From ae9a5af094b6924fb72e0f04b64d78835da78efb Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Tue, 20 Jan 2026 15:05:05 -0800 Subject: [PATCH 1/7] Samples --- .../sample_managed_credential.py | 2 +- .../sample_secret_credential.py | 2 +- .../samples/logs/sample_exception.py | 2 +- .../samples/metrics/sample_instruments.py | 6 ++--- .../traces/django/sample/example/admin.py | 2 +- .../traces/django/sample/example/models.py | 2 +- .../traces/django/sample/example/tests.py | 2 +- .../traces/django/sample/example/views.py | 2 +- .../samples/traces/django/sample/manage.py | 3 ++- .../traces/django/sample/sample/asgi.py | 3 ++- .../traces/django/sample/sample/wsgi.py | 3 ++- .../samples/traces/sample_app_config.py | 21 ++++++++------- .../samples/traces/sample_blob_checkpoint.py | 23 ++++++++-------- .../samples/traces/sample_comm_chat.py | 26 ++++++++++--------- .../samples/traces/sample_comm_phone.py | 24 ++++++++--------- .../samples/traces/sample_comm_sms.py | 24 ++++++++--------- .../samples/traces/sample_cosmos.py | 24 ++++++++--------- .../samples/traces/sample_event_grid.py | 25 +++++++++--------- .../samples/traces/sample_event_hub.py | 23 ++++++++-------- .../samples/traces/sample_fastapi.py | 5 ++-- .../samples/traces/sample_form_recognizer.py | 26 +++++++++---------- .../samples/traces/sample_jaeger.py | 3 ++- .../samples/traces/sample_key_cert.py | 25 +++++++++--------- .../samples/traces/sample_key_keys.py | 24 +++++++++-------- .../samples/traces/sample_key_secret.py | 23 +++++++++------- .../samples/traces/sample_metrics.py | 12 +++++---- .../samples/traces/sample_requests.py | 3 ++- .../traces/sample_servicebus_receive.py | 24 ++++++++--------- .../samples/traces/sample_servicebus_send.py | 24 ++++++++--------- .../samples/traces/sample_span_event.py | 4 +-- .../samples/traces/sample_storage_blob.py | 24 ++++++++--------- .../samples/traces/sample_text_analytics.py | 26 +++++++++---------- 32 files changed, 230 insertions(+), 212 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py index 757a4e9b3039..d9f87f425b44 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_managed_credential.py @@ -9,10 +9,10 @@ import os # You will need to install azure-identity -from azure.identity import ManagedIdentityCredential from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor +from azure.identity import ManagedIdentityCredential from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py index f1f52f242b30..257a8ed34996 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/authentication/sample_secret_credential.py @@ -9,10 +9,10 @@ import os # You will need to install azure-identity -from azure.identity import ClientSecretCredential from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor +from azure.identity import ClientSecretCredential from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py index 4f421348c343..81557a9c3a25 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py @@ -35,7 +35,7 @@ val = 1 / 0 print(val) except ZeroDivisionError: - logger.exception("Error: Division by zero") + logger.exception("Error: Division by zero") # pylint: disable=do-not-use-logging-exception try: val = 1 / 0 diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py index 9b51f8de7d4c..d391d8966cc9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/metrics/sample_instruments.py @@ -27,17 +27,17 @@ # Callback functions for observable instruments -def observable_counter_func(options: CallbackOptions) -> Iterable[Observation]: +def observable_counter_func(_options: CallbackOptions) -> Iterable[Observation]: yield Observation(1, {}) def observable_up_down_counter_func( - options: CallbackOptions, + _options: CallbackOptions, ) -> Iterable[Observation]: yield Observation(-10, {}) -def observable_gauge_func(options: CallbackOptions) -> Iterable[Observation]: +def observable_gauge_func(_options: CallbackOptions) -> Iterable[Observation]: yield Observation(9, {}) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py index 3f8b9caa30c7..855c2d3b0376 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py @@ -1,5 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from django.contrib import admin +from django.contrib import admin # pylint: disable=unused-import # Register your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py index 526ea7fddb97..163c27e604a6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py @@ -1,5 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from django.db import models +from django.db import models # pylint: disable=unused-import # Create your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py index 7705f147602a..47442e86431c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py @@ -1,5 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from django.test import TestCase +from django.test import TestCase # pylint: disable=unused-import # Create your tests here. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py index 723f6b599434..12cca0329873 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/views.py @@ -5,5 +5,5 @@ from django.http import HttpResponse -def index(request): +def index(_request): return HttpResponse("Hello, world.") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py index e3a87c01bdbd..5192827ad98a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/manage.py @@ -17,7 +17,8 @@ def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") - # Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, wsgi.py, or manage.py, depending on startup method. + # Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, + # wsgi.py, or manage.py, depending on startup method. # If using manage.py, please remove setup from asgi.py and wsgi.py # Enable instrumentation in the django library. DjangoInstrumentor().instrument() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py index f5030b6a14e3..344b712d77af 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/asgi.py @@ -22,7 +22,8 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") -# Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, wsgi.py, or manage.py, depending on startup method. +# Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, +# wsgi.py, or manage.py, depending on startup method. # If using manage.py, please remove setup from asgi.py and wsgi.py # Enable instrumentation in the django library. DjangoInstrumentor().instrument() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py index a34e435213b8..67bdcafa7470 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/sample/wsgi.py @@ -21,7 +21,8 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings") -# Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, wsgi.py, or manage.py, depending on startup method. +# Azure Monitor OpenTelemetry Exporters and Django Instrumentation should only be set up once in either asgi.py, +# wsgi.py, or manage.py, depending on startup method. # If using manage.py, please remove setup from asgi.py and wsgi.py # Enable instrumentation in the django library. DjangoInstrumentor().instrument() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py index 3fa3108b3f9a..e033d93f7187 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_app_config.py @@ -11,31 +11,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with App Configs SDKs -from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting connection_str = "" client = AzureAppConfigurationClient.from_connection_string(connection_str) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py index 003846444495..83ec19549580 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_blob_checkpoint.py @@ -11,32 +11,33 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +from azure.eventhub import EventHubConsumerClient +from azure.eventhub.extensions.checkpointstoreblob import BlobCheckpointStore + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with EventHub SDKs -from azure.eventhub import EventHubConsumerClient -from azure.eventhub.extensions.checkpointstoreblob import BlobCheckpointStore CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"] EVENTHUB_NAME = os.environ["EVENT_HUB_NAME"] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py index fcad00aa8fb4..17fa92e551fc 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_chat.py @@ -10,32 +10,35 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Authenticate with Communication Identity SDK +from azure.communication.identity import CommunicationIdentityClient + +from azure.communication.chat import ChatClient, CommunicationTokenCredential + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) # Example with Communication Chat SDKs -# Authenticate with Communication Identity SDK -from azure.communication.identity import CommunicationIdentityClient comm_connection_string = "" identity_client = CommunicationIdentityClient.from_connection_string(comm_connection_string) @@ -46,7 +49,6 @@ token = tokenresponse.token # Create a Chat Client -from azure.communication.chat import ChatClient, CommunicationTokenCredential # Your unique Azure Communication service endpoint endpoint = "https://.communcationservices.azure.com" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py index 37527ff9b018..9d163e29403c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_phone.py @@ -10,32 +10,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with Communication Phone SDKs +from azure.communication.phonenumbers import PhoneNumbersClient + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with Communication Phone SDKs -from azure.communication.phonenumbers import PhoneNumbersClient - # Create a Phone Client connection_str = "endpoint=ENDPOINT;accessKey=KEY" phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_str) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py index db95c0153cc6..bdef9936614a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_comm_sms.py @@ -10,32 +10,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with Communication SMS SDKs +from azure.communication.sms import SmsClient + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with Communication SMS SDKs -from azure.communication.sms import SmsClient - # Create a SMS Client connection_str = "endpoint=ENDPOINT;accessKey=KEY" sms_client = SmsClient.from_connection_string(connection_str) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py index ad9a8f037858..722c1041a4c2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_cosmos.py @@ -10,32 +10,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with CosmosDB SDKs +from azure.cosmos import exceptions, CosmosClient, PartitionKey + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with CosmosDB SDKs -from azure.cosmos import exceptions, CosmosClient, PartitionKey - url = os.environ["ACCOUNT_URI"] key = os.environ["ACCOUNT_KEY"] client = CosmosClient(url, key) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py index d3870db68993..cfd5b17ffac9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_grid.py @@ -10,32 +10,33 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with EventGrid SDKs +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid import EventGridPublisherClient, EventGridEvent + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with EventGrid SDKs -from azure.core.credentials import AzureKeyCredential -from azure.eventgrid import EventGridPublisherClient, EventGridEvent key = os.environ["EG_ACCESS_KEY"] endpoint = os.environ["EG_TOPIC_HOSTNAME"] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py index 767f69107171..976409c01d02 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_event_hub.py @@ -10,31 +10,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with EventHub SDKs +from azure.eventhub import EventHubProducerClient, EventData + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with EventHub SDKs -from azure.eventhub import EventHubProducerClient, EventData CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"] EVENTHUB_NAME = os.environ["EVENT_HUB_NAME"] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py index 011eddec5545..924386a2a169 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py @@ -12,11 +12,11 @@ import fastapi import uvicorn -from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter from opentelemetry import trace from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor +from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter # This method instruments all of the FastAPI module. # You can also use FastAPIInstrumentor().instrument_app(app) to instrument a specific app after it is created. @@ -40,8 +40,7 @@ async def test(): # Exceptions that are raised within the request are automatically captured @app.get("/exception") async def exception(): - raise Exception("Hit an exception") - + raise Exception("Hit an exception") # pylint: disable=broad-exception-raised # Set the OTEL_PYTHON_EXCLUDED_URLS environment variable to "http://127.0.0.1:8000/exclude" # Telemetry from this endpoint will not be captured due to excluded_urls config above diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py index c9c8884058a3..ceb1a58c58e4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_form_recognizer.py @@ -11,33 +11,33 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with Form Recognizer SDKs +from azure.core.credentials import AzureKeyCredential +from azure.ai.formrecognizer import DocumentAnalysisClient + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with Form Recognizer SDKs -from azure.core.credentials import AzureKeyCredential -from azure.ai.formrecognizer import DocumentAnalysisClient - endpoint = "https://.cognitiveservices.azure.com/" credential = AzureKeyCredential("") document_analysis_client = DocumentAnalysisClient(endpoint, credential) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py index 8070792702a1..cc7a92f7b2a2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_jaeger.py @@ -2,7 +2,8 @@ # Licensed under the MIT License. """ An example to show an application using Opentelemetry tracing api and sdk with multiple exporters. -Telemetry is exported to application insights with the AzureMonitorTraceExporter and Jaeger backend with the JaegerExporter. +Telemetry is exported to application insights with the AzureMonitorTraceExporter and +Jaeger backend with the JaegerExporter. """ # mypy: disable-error-code="attr-defined" import os diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py index 1b34dcbf908b..7add20337fe5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_cert.py @@ -10,33 +10,34 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor +# azure monitor trace exporter to send telemetry to appinsights +from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + +# Example with KeyVault Certificate SDKs +from azure.identity import ClientSecretCredential +from azure.keyvault.certificates import CertificateClient, CertificatePolicy + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) -# azure monitor trace exporter to send telemetry to appinsights -from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with KeyVault Certificate SDKs -from azure.identity import ClientSecretCredential -from azure.keyvault.certificates import CertificateClient, CertificatePolicy - tenant_id = "" client_id = "" client_secret = "" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py index 89e7e376770c..f6d67f7805d2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_keys.py @@ -10,33 +10,35 @@ # mypy: disable-error-code="attr-defined" import os +# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python +# for details +from opentelemetry import trace +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +# azure monitor trace exporter to send telemetry to appinsights +from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + +# Example with KeyVault Keys SDKs +from azure.identity import ClientSecretCredential +from azure.keyvault.keys import KeyClient + # Declare OpenTelemetry as enabled tracing plugin for Azure SDKs from azure.core.settings import settings from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan settings.tracing_implementation = OpenTelemetrySpan -# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python -# for details -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) -# azure monitor trace exporter to send telemetry to appinsights -from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with KeyVault Keys SDKs -from azure.identity import ClientSecretCredential -from azure.keyvault.keys import KeyClient - tenant_id = "" client_id = "" client_secret = "" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py index 40f4bcbb31b3..fa2ecb4fb029 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_key_secret.py @@ -10,32 +10,35 @@ # mypy: disable-error-code="attr-defined" import os +# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python +# for details +from opentelemetry import trace +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +# azure monitor trace exporter to send telemetry to appinsights +from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter + +# Example with KeyVault Secrets SDKs +from azure.identity import ClientSecretCredential +from azure.keyvault.secrets import SecretClient + # Declare OpenTelemetry as enabled tracing plugin for Azure SDKs from azure.core.settings import settings from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan settings.tracing_implementation = OpenTelemetrySpan -# Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python -# for details -from opentelemetry import trace -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor trace.set_tracer_provider(TracerProvider()) tracer = trace.get_tracer(__name__) -# azure monitor trace exporter to send telemetry to appinsights -from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with KeyVault Secrets SDKs -from azure.identity import ClientSecretCredential -from azure.keyvault.secrets import SecretClient tenant_id = "" client_id = "" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py index 863a0b99b894..08e446626fe5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_metrics.py @@ -2,15 +2,17 @@ # Licensed under the MIT License. """ An example to show an application instrumented with the OpenTelemetry instrumentations that collect metrics. -Only certain instrumentations support metrics collection, refer to https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/README.md +Only certain instrumentations support metrics collection, refer to - +https://github.com/open-telemetry/opentelemetry-python-contrib/blob/main/instrumentation/README.md for the full list. Calls made with the underlying instrumented libraries will track metrics information in the metrics explorer view in Application Insights. """ # mypy: disable-error-code="attr-defined" # mypy: disable-error-code="import-untyped" -import flask import os -import requests +import flask + +import requests # pylint: disable=networking-import-outside-azure-core-transport from opentelemetry import metrics, trace from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader @@ -50,8 +52,8 @@ @app.route("/") def test(): - success_response = requests.get("https://httpstat.us/200", timeout=5) - failure_response = requests.get("https://httpstat.us/404", timeout=5) + _success_response = requests.get("https://httpstat.us/200", timeout=5) + _failure_response = requests.get("https://httpstat.us/404", timeout=5) return "Test flask request" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py index d8eed04f46d7..e898eb872405 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_requests.py @@ -10,7 +10,8 @@ # mypy: disable-error-code="attr-defined" # mypy: disable-error-code="import-untyped" import os -import requests + +import requests # pylint: disable=networking-import-outside-azure-core-transport from opentelemetry import trace from opentelemetry.instrumentation.requests import RequestsInstrumentor from opentelemetry.sdk.trace import TracerProvider diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py index a2d78baaf588..85c76fb631bd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_receive.py @@ -12,32 +12,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Example with Servicebus SDKs +from azure.servicebus import ServiceBusClient, ServiceBusMessage + +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with Servicebus SDKs -from azure.servicebus import ServiceBusClient, ServiceBusMessage - connstr = os.environ["SERVICE_BUS_CONN_STR"] queue_name = os.environ["SERVICE_BUS_QUEUE_NAME"] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py index 110cdff2f68c..1e7d531d7a44 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_servicebus_send.py @@ -12,32 +12,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +# Example with Servicebus SDKs +from azure.servicebus import ServiceBusClient, ServiceBusMessage + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with Servicebus SDKs -from azure.servicebus import ServiceBusClient, ServiceBusMessage - connstr = os.environ["SERVICE_BUS_CONN_STR"] queue_name = os.environ["SERVICE_BUS_QUEUE_NAME"] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py index 8d83b9ffd0e8..0f33b9a20b3d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py @@ -27,6 +27,6 @@ # Exception events try: with tracer.start_as_current_span("hello") as span: - raise Exception("Custom exception message.") -except Exception: + raise Exception("Custom exception message.") # pylint: disable=broad-exception-raised +except Exception: # pylint: disable=broad-except print("Exception raised") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py index 5a6351afa4b1..42f4c5f050d9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_storage_blob.py @@ -10,32 +10,32 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan + +# Example with BlobStorage SDKs +from azure.storage.blob import BlobServiceClient + +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + span_processor = BatchSpanProcessor( AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) ) trace.get_tracer_provider().add_span_processor(span_processor) -# Example with BlobStorage SDKs -from azure.storage.blob import BlobServiceClient - connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"] container_name = os.environ["AZURE_STORAGE_BLOB_CONTAINER_NAME"] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py index 378ea645eabd..e55a37b4e158 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_text_analytics.py @@ -11,33 +11,33 @@ # mypy: disable-error-code="attr-defined" import os -# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs -from azure.core.settings import settings -from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan - -settings.tracing_implementation = OpenTelemetrySpan - # Regular open telemetry usage from here, see https://github.com/open-telemetry/opentelemetry-python # for details from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor -trace.set_tracer_provider(TracerProvider()) -tracer = trace.get_tracer(__name__) - # azure monitor trace exporter to send telemetry to appinsights from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter -span_processor = BatchSpanProcessor( - AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) -) -trace.get_tracer_provider().add_span_processor(span_processor) +# Declare OpenTelemetry as enabled tracing plugin for Azure SDKs +from azure.core.settings import settings +from azure.core.tracing.ext.opentelemetry_span import OpenTelemetrySpan # Example with Text Analytics SDKs from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalyticsClient +settings.tracing_implementation = OpenTelemetrySpan + +trace.set_tracer_provider(TracerProvider()) +tracer = trace.get_tracer(__name__) + +span_processor = BatchSpanProcessor( + AzureMonitorTraceExporter.from_connection_string(os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]) +) +trace.get_tracer_provider().add_span_processor(span_processor) + credential = AzureKeyCredential("") endpoint = "https://.cognitiveservices.azure.com/" From 82387cd68a07ed3cbac3bb02f291d318fb26c60e Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Tue, 20 Jan 2026 15:05:34 -0800 Subject: [PATCH 2/7] Utils and Manager --- .../exporter/_configuration/_utils.py | 14 ++++++------- .../exporter/_configuration/_worker.py | 2 +- .../_performance_counters/_manager.py | 20 +++++++++---------- .../exporter/_quickpulse/_manager.py | 2 +- .../exporter/statsbeat/_manager.py | 6 +++--- .../exporter/statsbeat/_utils.py | 4 ++-- .../exporter/statsbeat/customer/_utils.py | 2 +- 7 files changed, 25 insertions(+), 25 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py index 91c792861e23..0267cf0ba1a2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py @@ -6,7 +6,7 @@ import logging # mypy: disable-error-code="import-untyped" -import requests +import requests # pylint: disable=networking-import-outside-azure-core-transport from azure.monitor.opentelemetry.exporter._constants import ( _ONE_SETTINGS_DEFAULT_REFRESH_INTERVAL_SECONDS, @@ -124,16 +124,16 @@ def make_onesettings_request( return _parse_onesettings_response(result) except requests.exceptions.Timeout as ex: - logger.warning("OneSettings request timed out: %s", str(ex)) + logger.warning("OneSettings request timed out: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) except requests.exceptions.RequestException as ex: - logger.warning("Failed to fetch configuration from OneSettings: %s", str(ex)) + logger.warning("Failed to fetch configuration from OneSettings: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) except json.JSONDecodeError as ex: - logger.warning("Failed to parse OneSettings response: %s", str(ex)) + logger.warning("Failed to parse OneSettings response: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning("Unexpected error while fetching configuration: %s", str(ex)) + logger.warning("Unexpected error while fetching configuration: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) @@ -197,9 +197,9 @@ def _parse_onesettings_response(response: requests.Response) -> OneSettingsRespo if settings and settings.get(_ONE_SETTINGS_CHANGE_VERSION_KEY) is not None: version = int(settings.get(_ONE_SETTINGS_CHANGE_VERSION_KEY)) # type: ignore except (UnicodeDecodeError, json.JSONDecodeError) as ex: - logger.warning("Failed to decode OneSettings response content: %s", str(ex)) + logger.warning("Failed to decode OneSettings response content: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug except ValueError as ex: - logger.warning("Failed to parse OneSettings change version: %s", str(ex)) + logger.warning("Failed to parse OneSettings change version: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug elif status_code == 400: logger.warning("Bad request to OneSettings: %s", response.content) elif status_code == 404: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py index 19e7dc197ec2..aef055535432 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py @@ -141,7 +141,7 @@ def _get_configuration(self) -> None: # Capture interval while we have the lock interval = self._refresh_interval except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning("Configuration refresh failed: %s", ex) + logger.warning("Configuration refresh failed: %s", ex) # pylint: disable=do-not-log-exceptions-if-not-debug # Use current interval on error interval = self.get_refresh_interval() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py index beb9591e1fe1..3737661e9f29 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py @@ -79,7 +79,7 @@ def _get_process_cpu(options: CallbackOptions) -> Iterable[Observation]: cpu_percent = _PROCESS.cpu_percent(interval=None) yield Observation(cpu_percent, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting process CPU usage: %s", e) # pylint: disable=logging-not-lazy + _logger.exception("Error getting process CPU usage: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0.0, {}) @@ -110,7 +110,7 @@ def _get_process_cpu_normalized(options: CallbackOptions) -> Iterable[Observatio yield Observation(normalized_cpu_percent, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting normalized process CPU usage: %s", e) # pylint: disable=logging-not-lazy + _logger.exception("Error getting normalized process CPU usage: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0.0, {}) @@ -131,7 +131,7 @@ def _get_available_memory(options: CallbackOptions) -> Iterable[Observation]: available_memory = psutil.virtual_memory().available yield Observation(available_memory, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception("Error getting available memory: %s", e) # pylint: disable=logging-not-lazy + _logger.exception("Error getting available memory: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0, {}) @@ -152,7 +152,7 @@ def _get_process_memory(options: CallbackOptions) -> Iterable[Observation]: private_bytes = _PROCESS.memory_info().rss yield Observation(private_bytes, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting process memory: %s", e) # pylint: disable=logging-not-lazy + _logger.exception("Error getting process memory: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0, {}) @@ -186,7 +186,7 @@ def _get_process_io(options: CallbackOptions) -> Iterable[Observation]: io_rate = rw_diff / elapsed_time_s yield Observation(io_rate, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting process I/O rate: %s", e) + _logger.exception("Error getting process I/O rate: %s", e) # pylint: disable=do-not-use-logging-exception yield Observation(0, {}) @@ -245,7 +245,7 @@ def _get_processor_time(options: CallbackOptions) -> Iterable[Observation]: _LAST_CPU_TIMES = cpu_times yield Observation(utilization_percentage, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception("Error getting processor time: %s", e) + _logger.exception("Error getting processor time: %s", e) # pylint: disable=do-not-use-logging-exception yield Observation(0.0, {}) @@ -270,7 +270,7 @@ def _get_request_rate(options: CallbackOptions) -> Iterable[Observation]: _REQUESTS_COUNT = 0 yield Observation(request_rate, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception("Error getting request rate: %s", e) + _logger.exception("Error getting request rate: %s", e) # pylint: disable=do-not-use-logging-exception yield Observation(0.0, {}) @@ -295,7 +295,7 @@ def _get_exception_rate(options: CallbackOptions) -> Iterable[Observation]: _EXCEPTIONS_COUNT = 0 yield Observation(exception_rate, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception("Error getting exception rate: %s", e) + _logger.exception("Error getting exception rate: %s", e) # pylint: disable=do-not-use-logging-exception yield Observation(0.0, {}) @@ -603,10 +603,10 @@ def __init__(self, meter_provider=None): if metric_class == RequestExecutionTime: self._request_duration_histogram = performance_counter.gauge except Exception as e: # pylint: disable=broad-except - _logger.warning("Failed to initialize performance counter %s: %s", metric_class.NAME[0], e) + _logger.warning("Failed to initialize performance counter %s: %s", metric_class.NAME[0], e) # pylint: disable=do-not-log-exceptions-if-not-debug except Exception as e: # pylint: disable=broad-except - _logger.warning("Failed to setup performance counters: %s", e) + _logger.warning("Failed to setup performance counters: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug def _record_span(self, span: ReadableSpan) -> None: try: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py index 695dc0bdfd36..95fe423a7d44 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py @@ -202,7 +202,7 @@ def _do_initialize(self) -> bool: return True except Exception as e: # pylint: disable=broad-except - _logger.warning("Failed to initialize QuickpulseManager: %s", e) + _logger.warning("Failed to initialize QuickpulseManager: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug # Ensure cleanup happens and state is consistent self._cleanup() return False diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py index 602ba6f1dacc..bce536f4c573 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py @@ -251,7 +251,7 @@ def _do_initialize(self, config: StatsbeatConfig) -> bool: except Exception as e: # pylint: disable=broad-except # Log the error for debugging - logger.warning("Failed to initialize statsbeat: %s", e) + logger.warning("Failed to initialize statsbeat: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug # Clean up on failure self._cleanup() return False @@ -297,12 +297,12 @@ def _reconfigure(self, new_config: StatsbeatConfig) -> bool: # Force flush before shutdown to ensure data is sent self._meter_provider.force_flush(timeout_millis=5000) except Exception as e: # pylint: disable=broad-except - logger.warning("Failed to flush meter provider during reconfiguration: %s", e) + logger.warning("Failed to flush meter provider during reconfiguration: %s", e) # pylint:disable=do-not-log-exceptions-if-not-debug try: self._meter_provider.shutdown(timeout_millis=5000) except Exception as e: # pylint: disable=broad-except - logger.warning("Failed to shutdown meter provider during reconfiguration: %s", e) + logger.warning("Failed to shutdown meter provider during reconfiguration: %s", e) # pylint:disable=do-not-log-exceptions-if-not-debug # Reset state but keep initialized=True self._meter_provider = None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py index b94a8828a8ec..70bac7083c9e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py @@ -156,8 +156,8 @@ def _get_connection_string_for_region_from_config(target_region: str, settings: return None return default_connection_string except (ValueError, TypeError, KeyError) as ex: - logger.warning("Error parsing configuration for region '%s': %s", target_region, str(ex)) + logger.warning("Error parsing configuration for region '%s': %s", target_region, str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug return None except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning("Unexpected error getting stats connection string for region '%s': %s", target_region, str(ex)) + logger.warning("Unexpected error getting stats connection string for region '%s': %s", target_region, str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug return None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py index 3a0ca0285d47..16b275e968e0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py @@ -4,7 +4,7 @@ from typing import Optional, List, Tuple, Union, Any # mypy: disable-error-code="import-untyped" -from requests import ReadTimeout, Timeout +from requests import ReadTimeout, Timeout # pylint: disable=networking-import-outside-azure-core-transport from azure.core.exceptions import ServiceRequestTimeoutError from azure.monitor.opentelemetry.exporter._constants import ( _REQUEST, From 5a68a2aa5084bb4280bb3cb599946eb1397777c3 Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Thu, 22 Jan 2026 14:04:04 -0800 Subject: [PATCH 3/7] exporter and base --- .../exporter/_configuration/__init__.py | 2 +- .../exporter/_quickpulse/_exporter.py | 8 ++++---- .../opentelemetry/exporter/export/_base.py | 16 ++++++++-------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py index 99a9a1073ce0..e0c57ecc020c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py @@ -81,7 +81,7 @@ def _notify_callbacks(self, settings: Dict[str, str]): try: cb(settings) except Exception as ex: # pylint: disable=broad-except - logger.warning("Callback failed: %s", ex) + logger.warning("Callback failed: %s", ex) # pylint: disable=do-not-log-exceptions-if-not-debug def _is_transient_error(self, response: OneSettingsResponse) -> bool: """Check if the response indicates a transient error. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py index 21ada5cbeffc..d2295388759b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_exporter.py @@ -183,9 +183,9 @@ def export( try: _update_filter_configuration(etag, config) except Exception: # pylint: disable=broad-except - _logger.exception( + _logger.exception( # pylint: disable=C4769 "Exception occurred while updating filter config." - ) # pylint: disable=C4769 + ) result = MetricExportResult.FAILURE except Exception: # pylint: disable=broad-except _logger.exception("Exception occurred while publishing live metrics.") # pylint: disable=C4769 @@ -302,9 +302,9 @@ def _ticker(self) -> None: # Reset etag to default if not subscribed _set_quickpulse_etag("") except Exception: # pylint: disable=broad-except - _logger.exception( + _logger.exception( # pylint: disable=C4769 "Exception occurred while reading live metrics ping response." - ) # pylint: disable=C4769 + ) _set_quickpulse_etag("") # TODO: Implement redirect else: 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..3a13116120e3 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 @@ -200,7 +200,7 @@ def __init__(self, **kwargs: Any) -> None: collect_statsbeat_metrics(self) except Exception as e: # pylint: disable=broad-except - logger.warning("Failed to initialize statsbeat metrics: %s", e) + logger.warning("Failed to initialize statsbeat metrics: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug # customer sdkstats initialization if self._should_collect_customer_sdkstats(): @@ -439,14 +439,14 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: if self._should_collect_stats(): exc_type = request_error.exc_type - if exc_type is None or exc_type is type(None): + if exc_type is None or isinstance(exc_type, type(None)): exc_type = request_error.__class__.__name__ # type: ignore _update_requests_map(_REQ_EXCEPTION_NAME[1], value=exc_type) result = ExportResult.FAILED_RETRYABLE except Exception as ex: - logger.exception( + logger.exception( # pylint: disable=do-not-use-logging-exception "Envelopes could not be exported and are not retryable: %s.", ex - ) # pylint: disable=C4769 + ) # Track dropped items in customer sdkstats for general exceptions if self._should_collect_customer_sdkstats(): @@ -612,13 +612,13 @@ def _get_authentication_credential(**kwargs: Any) -> Optional[ManagedIdentityCre credential = ManagedIdentityCredential() return credential except ValueError as exc: - logger.error( + logger.error( # pylint: disable=do-not-log-exceptions-if-not-debug "APPLICATIONINSIGHTS_AUTHENTICATION_STRING, %s, has invalid format: %s", auth_string, exc - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) except Exception as e: - logger.error( + logger.error( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to get authentication credential and enable AAD: %s", e - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return None From d9de54264788de0958723d52f77fe20b53331b33 Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Fri, 23 Jan 2026 08:36:55 -0800 Subject: [PATCH 4/7] test files --- .../opentelemetry/exporter/export/_base.py | 2 +- .../tests/configuration/test_manager.py | 38 ++++---- .../tests/configuration/test_utils.py | 6 +- .../tests/configuration/test_worker.py | 14 +-- .../test_customer_sdkstats.py | 10 +-- .../tests/customer_sdk_stats/test_manager.py | 15 ++-- .../tests/customer_sdk_stats/test_utlities.py | 4 +- .../tests/logs/test_logs.py | 39 ++++++--- .../tests/logs/test_processor.py | 24 ++--- .../tests/metrics/test_metrics.py | 53 ++++++----- .../performance_counters/test_constants.py | 15 ++-- .../test_performance_counters.py | 32 +++---- .../performance_counters/test_processor.py | 4 +- .../tests/perfstress_tests/trace_exporter.py | 2 - .../tests/quickpulse/test_cpu.py | 2 +- .../tests/quickpulse/test_exporter.py | 28 +++--- .../tests/quickpulse/test_filter.py | 36 ++++++-- .../tests/quickpulse/test_live_metrics.py | 16 ++-- .../tests/quickpulse/test_manager.py | 21 +++-- .../tests/quickpulse/test_policy.py | 11 ++- .../tests/quickpulse/test_processor.py | 2 +- .../tests/quickpulse/test_types.py | 2 +- .../tests/quickpulse/test_utils.py | 4 +- .../tests/quickpulse/test_validate.py | 4 +- .../tests/statsbeat/test_manager.py | 64 ++++++++------ .../tests/statsbeat/test_metrics.py | 36 ++++---- .../tests/statsbeat/test_statsbeat.py | 41 +++++---- .../tests/test_base_customer_sdkstats.py | 87 ++++++++----------- .../tests/test_base_exporter.py | 74 ++++++++-------- .../tests/test_connection_string_parser.py | 34 ++++---- .../tests/test_storage.py | 68 +++++++-------- .../tests/test_utils.py | 77 ++++++++-------- .../tests/trace/test_rate_limited_sampling.py | 28 +++--- .../tests/trace/test_trace.py | 21 +++-- .../tests/trace/test_trace_utils.py | 5 +- 35 files changed, 469 insertions(+), 450 deletions(-) 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 3a13116120e3..1b822e602f0f 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 @@ -439,7 +439,7 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: if self._should_collect_stats(): exc_type = request_error.exc_type - if exc_type is None or isinstance(exc_type, type(None)): + if exc_type is None or exc_type is type(None): # pylint: disable=unidiomatic-typecheck exc_type = request_error.__class__.__name__ # type: ignore _update_requests_map(_REQ_EXCEPTION_NAME[1], value=exc_type) result = ExportResult.FAILED_RETRYABLE diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py index 1b4695611972..50fb4feac639 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py @@ -13,13 +13,11 @@ from azure.monitor.opentelemetry.exporter._constants import ( _ONE_SETTINGS_DEFAULT_REFRESH_INTERVAL_SECONDS, _ONE_SETTINGS_MAX_REFRESH_INTERVAL_SECONDS, - _ONE_SETTINGS_PYTHON_KEY, _ONE_SETTINGS_CHANGE_URL, _ONE_SETTINGS_CONFIG_URL, - _RETRYABLE_STATUS_CODES, ) - +# pylint: disable=protected-access, docstring-missing-param class TestConfigurationState(unittest.TestCase): """Test cases for _ConfigurationState immutable data class.""" @@ -137,7 +135,7 @@ def test_worker_initialization(self, mock_worker_class): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_get_configuration_basic_success(self, mock_worker_class, mock_request): + def test_get_configuration_basic_success(self, _mock_worker_class, mock_request): """Test basic successful configuration retrieval without CONFIG fetch.""" # Setup - Use version -1 to match initial state, no CONFIG fetch mock_response = OneSettingsResponse( @@ -166,7 +164,7 @@ def test_get_configuration_basic_success(self, mock_worker_class, mock_request): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_etag_headers_included(self, mock_worker_class, mock_request): + def test_etag_headers_included(self, _mock_worker_class, mock_request): """Test that etag is included in request headers.""" # Setup - first call sets etag mock_response1 = OneSettingsResponse(etag="test-etag", refresh_interval=1800, status_code=200) @@ -192,7 +190,7 @@ def test_etag_headers_included(self, mock_worker_class, mock_request): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_version_increase_triggers_config_fetch(self, mock_worker_class, mock_request): + def test_version_increase_triggers_config_fetch(self, _mock_worker_class, mock_request): #pylint: disable=name-too-long """Test that version increase triggers CONFIG endpoint fetch.""" manager = _ConfigurationManager() manager.initialize() @@ -204,10 +202,10 @@ def test_version_increase_triggers_config_fetch(self, mock_worker_class, mock_re config_response = OneSettingsResponse(settings={"key": "config_value"}, version=5, status_code=200) # Configure mock to return different responses for different URLs - def mock_request_side_effect(url, query_dict, headers=None): + def mock_request_side_effect(url, _query_dict, _headers=None): if url == _ONE_SETTINGS_CHANGE_URL: return change_response - elif url == _ONE_SETTINGS_CONFIG_URL: + if url == _ONE_SETTINGS_CONFIG_URL: return config_response return OneSettingsResponse() @@ -234,7 +232,7 @@ def mock_request_side_effect(url, query_dict, headers=None): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_version_same_no_config_fetch(self, mock_worker_class, mock_request): + def test_version_same_no_config_fetch(self, _mock_worker_class, mock_request): """Test that same version does not trigger CONFIG fetch.""" manager = _ConfigurationManager() manager.initialize() @@ -259,7 +257,7 @@ def test_version_same_no_config_fetch(self, mock_worker_class, mock_request): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") @patch("azure.monitor.opentelemetry.exporter._configuration.logger") - def test_version_decrease_warning(self, mock_logger, mock_worker_class, mock_request): + def test_version_decrease_warning(self, mock_logger, _mock_worker_class, mock_request): """Test warning when version decreases.""" manager = _ConfigurationManager() manager.initialize() @@ -294,7 +292,7 @@ def test_version_decrease_warning(self, mock_logger, mock_worker_class, mock_req @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_304_not_modified_response(self, mock_worker_class, mock_request): + def test_304_not_modified_response(self, _mock_worker_class, mock_request): """Test handling of 304 Not Modified response.""" manager = _ConfigurationManager() manager.initialize() @@ -305,10 +303,10 @@ def test_304_not_modified_response(self, mock_worker_class, mock_request): ) config_response = OneSettingsResponse(settings={"key": "config_value"}, version=2, status_code=200) - def first_call_side_effect(url, query_dict, headers=None): + def first_call_side_effect(url, _query_dict, _header=None): if url == _ONE_SETTINGS_CHANGE_URL: return first_response - elif url == _ONE_SETTINGS_CONFIG_URL: + if url == _ONE_SETTINGS_CONFIG_URL: return config_response return OneSettingsResponse() @@ -341,7 +339,7 @@ def first_call_side_effect(url, query_dict, headers=None): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") @patch("azure.monitor.opentelemetry.exporter._configuration.logger") - def test_transient_error_timeout(self, mock_logger, mock_worker_class, mock_request): + def test_transient_error_timeout(self, mock_logger, _mock_worker_class, mock_request): """Test transient error handling for timeout.""" manager = _ConfigurationManager() manager.initialize() @@ -375,7 +373,7 @@ def test_transient_error_timeout(self, mock_logger, mock_worker_class, mock_requ @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") @patch("azure.monitor.opentelemetry.exporter._configuration.logger") - def test_transient_error_network_exception(self, mock_logger, mock_worker_class, mock_request): + def test_transient_error_network_exception(self, mock_logger, _mock_worker_class, mock_request): """Test transient error handling for network exception.""" manager = _ConfigurationManager() manager.initialize() @@ -402,7 +400,7 @@ def test_transient_error_network_exception(self, mock_logger, mock_worker_class, @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") @patch("azure.monitor.opentelemetry.exporter._configuration.logger") - def test_transient_error_http_status_codes(self, mock_logger, mock_worker_class, mock_request): + def test_transient_error_http_status_codes(self, mock_logger, _mock_worker_class, mock_request): """Test transient error handling for various HTTP status codes.""" manager = _ConfigurationManager() manager.initialize() @@ -440,7 +438,7 @@ def test_transient_error_http_status_codes(self, mock_logger, mock_worker_class, @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") @patch("azure.monitor.opentelemetry.exporter._configuration.logger") - def test_transient_error_refresh_interval_cap(self, mock_logger, mock_worker_class, mock_request): + def test_transient_error_refresh_interval_cap(self, mock_logger, _mock_worker_class, mock_request): # pylint: disable=name-too-long """Test that refresh interval is capped at 24 hours for transient errors.""" manager = _ConfigurationManager() manager.initialize() @@ -468,7 +466,7 @@ def test_transient_error_refresh_interval_cap(self, mock_logger, mock_worker_cla @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_non_transient_error_no_backoff(self, mock_worker_class, mock_request): + def test_non_transient_error_no_backoff(self, _mock_worker_class, mock_request): """Test that non-transient errors don't trigger backoff.""" manager = _ConfigurationManager() manager.initialize() @@ -496,7 +494,7 @@ def test_non_transient_error_no_backoff(self, mock_worker_class, mock_request): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_successful_request_after_transient_error(self, mock_worker_class, mock_request): + def test_successful_request_after_transient_error(self, _mock_worker_class, mock_request): # pylint: disable=name-too-long """Test that successful requests don't double refresh interval.""" manager = _ConfigurationManager() manager.initialize() @@ -535,7 +533,7 @@ def test_configuration_manager_enabled(self): self.assertIsNotNone(manager) self.assertIsInstance(manager, _ConfigurationManager) - def test_configuration_manager_enabled_by_default(self): + def test_configuration_manager_enabled_by_default(self): # pylint: disable=name-too-long """Test that configuration manager is enabled by default when no environment variable is set.""" # Ensure env var is not set diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py index 4d97f41a62eb..012dc3db7aec 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py @@ -3,7 +3,7 @@ import json import unittest from unittest.mock import Mock, patch -import requests +import requests # pylint: disable=networking-import-outside-azure-core-transport from azure.monitor.opentelemetry.exporter._configuration._utils import ( _ConfigurationProfile, @@ -21,7 +21,7 @@ _ONE_SETTINGS_CHANGE_VERSION_KEY, ) - +# pylint: disable=docstring-missing-param class TestConfigurationProfile(unittest.TestCase): """Test cases for _ConfigurationProfile class.""" @@ -603,7 +603,7 @@ def test_response_error_combinations(self): (False, False, 429, "no error flags but error status"), ] - for has_timeout, has_exception, status_code, description in test_cases: + for _has_timeout, has_exception, status_code, description in test_cases: with self.subTest(description=description): response = OneSettingsResponse(has_exception=has_exception, status_code=status_code) self.assertEqual(response.has_exception, has_exception) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py index 8b2198e37d44..ff9b15eba12e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py @@ -3,12 +3,12 @@ import unittest import threading import time -from unittest.mock import Mock, patch, MagicMock +from unittest.mock import Mock, patch from azure.monitor.opentelemetry.exporter._configuration._worker import _ConfigurationWorker from azure.monitor.opentelemetry.exporter._constants import _ONE_SETTINGS_PYTHON_TARGETING - +# pylint: disable=protected-access, docstring-missing-param class TestConfigurationWorker(unittest.TestCase): """Test cases for _ConfigurationWorker class.""" @@ -17,11 +17,11 @@ def setUp(self): self.mock_configuration_manager = Mock() self.mock_configuration_manager.get_configuration_and_refresh_interval.return_value = 1800 - def tearDown(self): + def tearDown(self): # pylint: disable=docstring-missing-return, docstring-missing-rtype """Clean up after each test.""" # Ensure any workers created during tests are shut down # This prevents hanging tests and resource leaks - pass + pass # pylint: disable=unnecessary-pass def test_init_with_default_refresh_interval(self): """Test worker initialization with default refresh interval.""" @@ -213,7 +213,7 @@ def test_shutdown_idempotent(self): # Second shutdown should not cause errors try: worker.shutdown() - except Exception as e: + except Exception as e: # pylint: disable=broad-exception-caught self.fail(f"Second shutdown raised an exception: {e}") # State should remain shutdown @@ -253,7 +253,7 @@ def shutdown_worker(): try: worker.shutdown() shutdown_results.append("success") - except Exception as e: + except Exception as e: # pylint: disable=broad-exception-caught shutdown_results.append(f"error: {e}") threads = [threading.Thread(target=shutdown_worker) for _ in range(5)] @@ -346,7 +346,7 @@ def test_lock_protects_worker_state(self): finally: worker.shutdown() - def test_refresh_loop_continues_after_exception(self): + def test_refresh_loop_continues_after_exception(self): # pylint: disable=name-too-long """Test that refresh loop continues after exceptions.""" # First call raises exception, second succeeds self.mock_configuration_manager.get_configuration_and_refresh_interval.side_effect = [ diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py index 85e98347c502..c05396ad61ae 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py @@ -42,7 +42,7 @@ def test_collect_customer_sdkstats(self): """Test collecting customer SDK stats initializes the manager.""" # Create a mock exporter mock_exporter = mock.Mock() - mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" + mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access # Collect customer SDK stats collect_customer_sdkstats(mock_exporter) @@ -51,11 +51,11 @@ def test_collect_customer_sdkstats(self): manager = get_customer_stats_manager() self.assertTrue(manager.is_initialized) - def test_collect_customer_sdkstats_multiple_calls(self): + def test_collect_customer_sdkstats_multiple_calls(self): # pylint: disable=name-too-long """Test that multiple calls to collect_customer_sdkstats don't cause issues.""" # Create a mock exporter mock_exporter = mock.Mock() - mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" + mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access # Call collect multiple times collect_customer_sdkstats(mock_exporter) @@ -79,7 +79,7 @@ def test_shutdown_customer_sdkstats_metrics(self): # Verify shutdown self.assertFalse(manager.is_initialized) - def test_shutdown_customer_sdkstats_metrics_when_not_initialized(self): + def test_shutdown_customer_sdkstats_metrics_when_not_initialized(self): # pylint: disable=name-too-long """Test shutting down customer SDK stats when not initialized doesn't cause issues.""" # Ensure manager is not initialized manager = get_customer_stats_manager() @@ -96,7 +96,7 @@ def test_collect_and_shutdown_cycle(self): """Test a complete cycle of collect and shutdown operations.""" # Create a mock exporter mock_exporter = mock.Mock() - mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" + mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access # Collect customer SDK stats collect_customer_sdkstats(mock_exporter) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py index 24f5502c4010..0e33164a5ee1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py @@ -4,8 +4,7 @@ import os import threading import unittest -from unittest import mock -from unittest.mock import Mock, patch, MagicMock +from unittest.mock import Mock, patch from azure.monitor.opentelemetry.exporter._constants import ( DropCode, @@ -20,11 +19,9 @@ CustomerSdkStatsStatus, _CustomerSdkStatsTelemetryCounters, ) -from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( - get_customer_stats_manager, -) - +# pylint: disable=protected-access, docstring-missing-param +# pylint: disable=too-many-public-methods class TestCustomerSdkStatsManager(unittest.TestCase): """Test suite for CustomerSdkStatsManager.""" @@ -48,7 +45,7 @@ def tearDown(self): # Shutdown manager if needed try: self.manager.shutdown() - except: + except: # pylint: disable=bare-except pass # Reset singleton state - only clear CustomerSdkStatsManager instances @@ -270,7 +267,7 @@ def test_count_successful_items(self): self.assertEqual(self.manager._counters.total_item_success_count[_REQUEST], 7) self.assertEqual(self.manager._counters.total_item_success_count[_CUSTOM_EVENT], 3) - def test_count_successful_items_uninitialized(self): + def test_count_successful_items_uninitialized(self): # pylint: disable=name-too-long """Test that counting successful items does nothing when not initialized.""" self.manager.count_successful_items(5, _REQUEST) @@ -392,7 +389,7 @@ def test_threading_safety(self): # Define a function to run in threads def count_items(): - for i in range(100): + for _ in range(100): self.manager.count_successful_items(1, _REQUEST) self.manager.count_dropped_items(1, _REQUEST, DropCode.UNKNOWN, True) self.manager.count_retry_items(1, _REQUEST, RetryCode.CLIENT_TIMEOUT) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py index 8ee8634937ad..3ba29f61d9f4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py @@ -6,8 +6,8 @@ from unittest import mock from datetime import datetime +from requests.exceptions import ConnectionError, ReadTimeout, Timeout # pylint: disable=networking-import-outside-azure-core-transport from azure.core.exceptions import ServiceRequestTimeoutError, HttpResponseError -from requests.exceptions import ConnectionError, ReadTimeout, Timeout from azure.monitor.opentelemetry.exporter._generated.models import ( TelemetryItem, @@ -40,7 +40,7 @@ get_customer_stats_manager, ) - +# pylint: disable=protected-access, docstring-missing-param, name-too-long, too-many-public-methods class TestCustomerSdkStatsUtils(unittest.TestCase): """Test suite for customer SDK stats utility functions.""" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py index 67c769c1369b..68de220d4a8e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py @@ -53,9 +53,8 @@ def __str__(self) -> str: return "This class is not serializeable" -# pylint: disable=import-error -# pylint: disable=protected-access -# pylint: disable=too-many-lines +# pylint: disable=import-error, disable=protected-access +# pylint: disable=too-many-public-methods, disable=too-many-lines class TestAzureLogExporter(unittest.TestCase): _exporter_class = AzureMonitorLogExporter @@ -242,7 +241,10 @@ def setUpClass(cls): "test": "attribute", EXCEPTION_TYPE: "ZeroDivisionError", EXCEPTION_MESSAGE: "division by zero", - EXCEPTION_STACKTRACE: 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', + EXCEPTION_STACKTRACE: ( + "Traceback (most recent call last):\n File 'test.py', line 38, in \n" + " raise ZeroDivisionError()\nZeroDivisionError\n" + ), }, ), resource=Resource.create(attributes={"asd": "test_resource"}), @@ -259,7 +261,10 @@ def setUpClass(cls): "test": "attribute", EXCEPTION_TYPE: "ZeroDivisionError", EXCEPTION_MESSAGE: "division by zero", - EXCEPTION_STACKTRACE: 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', + EXCEPTION_STACKTRACE: ( + "Traceback (most recent call last):\n File 'test.py', line 38, in \n" + " raise ZeroDivisionError()\nZeroDivisionError\n" + ), }, ), resource=Resource.create(attributes={"asd": "test_resource"}), @@ -481,7 +486,7 @@ def test_log_to_envelope_log_empty(self): self.assertEqual(envelope.data.base_data.message, _DEFAULT_LOG_MESSAGE) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_NAME), "TestOperationName") - def test_log_to_envelope_log_empty_with_whitespaces(self): + def test_log_to_envelope_log_empty_with_whitespaces(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_empty_with_whitespaces) self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") @@ -499,7 +504,7 @@ def test_log_to_envelope_log_complex_body(self): ) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_NAME), "TestOperationName") - def test_log_to_envelope_log_complex_body_not_serializeable(self): + def test_log_to_envelope_log_complex_body_not_serializeable(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_complex_body_not_serializeable) self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") @@ -509,7 +514,7 @@ def test_log_to_envelope_log_complex_body_not_serializeable(self): str(self._log_data_complex_body_not_serializeable.log_record.body), ) - def test_log_to_envelope_exception_with_string_message(self): + def test_log_to_envelope_exception_with_string_message(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data) record = self._log_data.log_record @@ -524,10 +529,13 @@ def test_log_to_envelope_exception_with_string_message(self): self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack) self.assertEqual( envelope.data.base_data.exceptions[0].stack, - 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', + ( + "Traceback (most recent call last):\n File 'test.py', line 38, in \n" + " raise ZeroDivisionError()\nZeroDivisionError\n" + ), ) - def test_log_to_envelope_exception_with_exc_message(self): + def test_log_to_envelope_exception_with_exc_message(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_with_exc_body) record = self._log_data.log_record @@ -542,7 +550,10 @@ def test_log_to_envelope_exception_with_exc_message(self): self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack) self.assertEqual( envelope.data.base_data.exceptions[0].stack, - 'Traceback (most recent call last):\n File "test.py", line 38, in \n raise ZeroDivisionError()\nZeroDivisionError\n', + ( + "Traceback (most recent call last):\n File 'test.py', line 38, in \n" + " raise ZeroDivisionError()\nZeroDivisionError\n" + ), ) def test_log_to_envelope_exception_empty(self): @@ -560,7 +571,7 @@ def test_log_to_envelope_exception_empty(self): self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack) self.assertEqual(envelope.data.base_data.exceptions[0].stack, "") - def test_log_to_envelope_exception_with_blank_exception(self): + def test_log_to_envelope_exception_with_blank_exception(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_blank_exception) record = self._log_data.log_record @@ -595,7 +606,7 @@ def test_log_to_envelope_event_complex_body(self): self.assertEqual(envelope.data.base_data.name, json.dumps(record.body)) self.assertEqual(envelope.data.base_data.properties["event_key"], "event_attribute") - def test_log_to_envelope_event_complex_body_not_serializeable(self): + def test_log_to_envelope_event_complex_body_not_serializeable(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_event_complex_body_not_serializeable) record = self._log_data_event_complex_body_not_serializeable.log_record @@ -670,7 +681,7 @@ def test_log_to_envelope_synthetic_source(self): "testServiceInstanceId", ) - def test_log_to_envelope_synthetic_load_always_on(self): + def test_log_to_envelope_synthetic_load_always_on(self): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create( { diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py index 4de11902d279..2b10438a3241 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py @@ -1,3 +1,5 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. import os import unittest from unittest import mock @@ -28,24 +30,24 @@ def setUpClass(cls): os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "true" cls._exporter = AzureMonitorLogExporter() - def test_processor_initialization_without_trace_based_sampling(self): + def test_processor_initialization_without_trace_based_sampling(self): # pylint: disable=name-too-long """Test processor initialization without trace-based sampling enabled.""" processor = _AzureBatchLogRecordProcessor(self._exporter, options={}) self.assertFalse(processor._enable_trace_based_sampling_for_logs) - def test_processor_initialization_with_trace_based_sampling(self): + def test_processor_initialization_with_trace_based_sampling(self): # pylint: disable=name-too-long """Test processor initialization with trace-based sampling enabled.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} ) self.assertTrue(processor._enable_trace_based_sampling_for_logs) - def test_processor_initialization_without_options(self): + def test_processor_initialization_without_options(self): # pylint: disable=name-too-long """Test processor initialization without options.""" processor = _AzureBatchLogRecordProcessor(self._exporter) self.assertIsNone(processor._enable_trace_based_sampling_for_logs) - def test_on_emit_with_trace_based_sampling_disabled(self): + def test_on_emit_with_trace_based_sampling_disabled(self): # pylint: disable=name-too-long """Test on_emit does not filter logs when trace-based sampling is disabled.""" processor = _AzureBatchLogRecordProcessor(self._exporter, options={}) @@ -82,8 +84,8 @@ def test_on_emit_with_trace_based_sampling_disabled(self): # Parent on_emit should be called because trace-based sampling is disabled parent_on_emit_mock.assert_called_once() - def test_on_emit_with_trace_based_sampling_enabled_and_unsampled_trace(self): # cspell:disable-line - """Test on_emit filters logs when trace-based sampling is enabled and trace is unsampled.""" # cspell:disable-line + def test_on_emit_with_trace_based_sampling_enabled_and_unsampled_trace(self): # cspell:disable-line # pylint: disable=name-too-long + """Test on_emit filters logs when trace-based sampling is enabled and trace is unsampled.""" # cspell:disable-line # pylint: disable=line-too-long processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} ) @@ -121,10 +123,10 @@ def test_on_emit_with_trace_based_sampling_enabled_and_unsampled_trace(self): # # Mock only the parent class's on_emit method with mock.patch("opentelemetry.sdk._logs.export.BatchLogRecordProcessor.on_emit") as parent_on_emit_mock: processor.on_emit(log_record) - # Parent on_emit should NOT be called because trace is unsampled and filtering is enabled # cspell:disable-line + # Parent on_emit should NOT be called because trace is unsampled and filtering is enabled # cspell:disable-line # pylint: disable=line-too-long parent_on_emit_mock.assert_not_called() - def test_on_emit_with_trace_based_sampling_enabled_and_sampled_trace(self): + def test_on_emit_with_trace_based_sampling_enabled_and_sampled_trace(self): # pylint: disable=name-too-long """Test on_emit does not filter logs when trace-based sampling is enabled and trace is sampled.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -165,7 +167,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_sampled_trace(self): # Parent on_emit should be called because trace is sampled parent_on_emit_mock.assert_called_once() - def test_on_emit_with_trace_based_sampling_enabled_and_invalid_span_context(self): + def test_on_emit_with_trace_based_sampling_enabled_and_invalid_span_context(self): # pylint: disable=name-too-long """Test on_emit does not filter logs with invalid span context.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -205,7 +207,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_invalid_span_context(self # Parent on_emit should be called because span context is invalid parent_on_emit_mock.assert_called_once() - def test_on_emit_with_trace_based_sampling_enabled_and_no_context(self): + def test_on_emit_with_trace_based_sampling_enabled_and_no_context(self): # pylint: disable=name-too-long """Test on_emit does not filter logs when there is no log record context.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -227,7 +229,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_no_context(self): # Parent on_emit should be called because there's no context parent_on_emit_mock.assert_called_once() - def test_on_emit_integration_with_multiple_log_records(self): + def test_on_emit_integration_with_multiple_log_records(self): # pylint: disable=name-too-long """Integration test: verify processor handles multiple log records correctly with trace-based sampling.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py index ccfc3aaf3dad..0390111acec2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py @@ -40,9 +40,8 @@ def func(*_args, **_kwargs): return func -# pylint: disable=import-error -# pylint: disable=protected-access -# pylint: disable=too-many-lines +# pylint: disable=import-error, disable=protected-access +# pylint: disable=too-many-lines, too-many-public-methods class TestAzureMetricExporter(unittest.TestCase): @classmethod def setUpClass(cls): @@ -280,7 +279,7 @@ def test_point_to_envelope_histogram(self): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_aks_amw(self, attach_mock, aks_mock): + def test_point_to_envelope_aks_amw(self, _attach_mock, _aks_mock): exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") @@ -300,7 +299,7 @@ def test_point_to_envelope_aks_amw(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_statsbeat(self, attach_mock, aks_mock): + def test_point_to_envelope_statsbeat(self, _attach_mock, _aks_mock): exporter = AzureMonitorMetricExporter( is_sdkstats=True, ) @@ -320,7 +319,7 @@ def test_point_to_envelope_statsbeat(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_otlp_no_aks(self, attach_mock, aks_mock): + def test_point_to_envelope_otlp_no_aks(self, _attach_mock, _aks_mock): exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -339,7 +338,7 @@ def test_point_to_envelope_otlp_no_aks(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=False ) - def test_point_to_envelope_otlp_aks_no_attach(self, attach_mock, aks_mock): + def test_point_to_envelope_otlp_aks_no_attach(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -358,7 +357,7 @@ def test_point_to_envelope_otlp_aks_no_attach(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_aks_attach_no_otlp(self, attach_mock, aks_mock): + def test_point_to_envelope_aks_attach_no_otlp(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") @@ -377,7 +376,7 @@ def test_point_to_envelope_aks_attach_no_otlp(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_aks_attach_no_endpoint(self, attach_mock, aks_mock): + def test_point_to_envelope_aks_attach_no_endpoint(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -409,7 +408,7 @@ def test_point_to_envelope_metric_namespace(self): self.assertEqual(envelope.data.base_data.metrics[0].value, 10) self.assertEqual(envelope.data.base_data.metrics[0].count, 1) - def test_point_to_envelope_number_log_analytics_disabled(self): + def test_point_to_envelope_number_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter_log_analytics_disabled resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") @@ -417,7 +416,7 @@ def test_point_to_envelope_number_log_analytics_disabled(self): envelope = exporter._point_to_envelope(point, "test name", resource, scope) self.assertIsNone(envelope) - def test_point_to_envelope_histogram_log_analytics_disabled(self): + def test_point_to_envelope_histogram_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter_log_analytics_disabled resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -425,7 +424,7 @@ def test_point_to_envelope_histogram_log_analytics_disabled(self): self.assertIsNone(envelope) @mock.patch("azure.monitor.opentelemetry.exporter.export.trace._utils._get_target_and_path_for_http_dependency") - def test_point_to_envelope_std_metric_client_duration(self, target_mock): + def test_point_to_envelope_std_metric_client_duration(self, target_mock): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter resource = Resource( { @@ -501,7 +500,7 @@ def test_point_to_envelope_std_metric_client_duration(self, target_mock): self.assertEqual(envelope.data.base_data.metrics[0].name, "http.client.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_server_duration(self): + def test_point_to_envelope_std_metric_server_duration(self): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter resource = Resource( { @@ -577,7 +576,7 @@ def test_point_to_envelope_std_metric_server_duration(self): self.assertEqual(envelope.data.base_data.metrics[0].name, "http.server.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_unsupported(self): + def test_point_to_envelope_std_metric_unsupported(self): # pylint: disable=name-too-long exporter = self._exporter resource = Resource( { @@ -600,7 +599,7 @@ def test_point_to_envelope_std_metric_unsupported(self): self.assertIsNone(envelope) @mock.patch("azure.monitor.opentelemetry.exporter.export.trace._utils._get_target_and_path_for_http_dependency") - def test_point_to_envelope_std_metric_client_duration_log_analytics_disabled(self, target_mock): + def test_point_to_envelope_std_metric_client_duration_log_analytics_disabled(self, target_mock): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter_log_analytics_disabled resource = Resource( { @@ -674,7 +673,7 @@ def test_point_to_envelope_std_metric_client_duration_log_analytics_disabled(sel self.assertEqual(envelope.data.base_data.metrics[0].name, "http.client.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_server_duration_log_analytics_disabled(self): + def test_point_to_envelope_std_metric_server_duration_log_analytics_disabled(self): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter_log_analytics_disabled resource = Resource( { @@ -748,7 +747,7 @@ def test_point_to_envelope_std_metric_server_duration_log_analytics_disabled(sel self.assertEqual(envelope.data.base_data.metrics[0].name, "http.server.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_unsupported_log_analytics_disabled(self): + def test_point_to_envelope_std_metric_unsupported_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter_log_analytics_disabled resource = Resource( { @@ -770,7 +769,7 @@ def test_point_to_envelope_std_metric_unsupported_log_analytics_disabled(self): envelope = exporter._point_to_envelope(point, "http.server.request.size", resource) self.assertIsNone(envelope) - def test_point_to_envelope_std_metric_log_analytics_disabled(self): + def test_point_to_envelope_std_metric_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter resource = Resource( { @@ -796,7 +795,7 @@ def test_point_to_envelope_std_metric_log_analytics_disabled(self): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_enabled_default_aks(self, attach_mock, aks_mock): + def test_constructor_log_analytics_enabled_default_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -804,7 +803,7 @@ def test_constructor_log_analytics_enabled_default_aks(self, attach_mock, aks_mo @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_enabled_default_off_aks(self, attach_mock, aks_mock): + def test_constructor_log_analytics_enabled_default_off_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -813,7 +812,7 @@ def test_constructor_log_analytics_enabled_default_off_aks(self, attach_mock, ak @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_enabled_env_var(self, attach_mock, aks_mock): + def test_constructor_log_analytics_enabled_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -822,7 +821,7 @@ def test_constructor_log_analytics_enabled_env_var(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_disabled_env_var_off_aks(self, attach_mock, aks_mock): + def test_constructor_log_analytics_disabled_env_var_off_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() # APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED is currently only specified for AKS Attach self.assertTrue(exporter._metrics_to_log_analytics) @@ -832,7 +831,7 @@ def test_constructor_log_analytics_disabled_env_var_off_aks(self, attach_mock, a @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=False ) - def test_constructor_log_analytics_disabled_env_var_manual_aks(self, attach_mock, aks_mock): + def test_constructor_log_analytics_disabled_env_var_manual_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() # APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED is currently only specified for AKS Attach self.assertTrue(exporter._metrics_to_log_analytics) @@ -842,7 +841,7 @@ def test_constructor_log_analytics_disabled_env_var_manual_aks(self, attach_mock @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_disabled_env_var(self, attach_mock, aks_mock): + def test_constructor_log_analytics_disabled_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertFalse(exporter._metrics_to_log_analytics) @@ -851,7 +850,7 @@ def test_constructor_log_analytics_disabled_env_var(self, attach_mock, aks_mock) @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_statsbeat(self, attach_mock, aks_mock): + def test_constructor_log_analytics_statsbeat(self, _attach_mock, _aks_mock): exporter = AzureMonitorMetricExporter( is_sdkstats=True, ) @@ -862,7 +861,7 @@ def test_constructor_log_analytics_statsbeat(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_invalid_env_var(self, attach_mock, aks_mock): + def test_constructor_log_analytics_invalid_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -871,7 +870,7 @@ def test_constructor_log_analytics_invalid_env_var(self, attach_mock, aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_blank_env_var(self, attach_mock, aks_mock): + def test_constructor_log_analytics_blank_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py index f53dd2d85be9..c9e12122a700 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py @@ -86,7 +86,7 @@ def test_processor_time_constant(self): self.assertEqual(_PROCESSOR_TIME[0], "azuremonitor.performancecounter.processortotalprocessortime") self.assertEqual(_PROCESSOR_TIME[1], "\\Processor(_Total)\\% Processor Time") - def test_performance_counter_metric_name_mappings(self): + def test_performance_counter_metric_name_mappings(self): # pylint: disable=name-too-long """Test the performance counter metric name mappings dictionary.""" expected_mappings = [ _AVAILABLE_MEMORY, @@ -108,7 +108,7 @@ def test_performance_counter_metric_name_mappings(self): self.assertIn(otel_name, _PERFORMANCE_COUNTER_METRIC_NAME_MAPPINGS) self.assertEqual(_PERFORMANCE_COUNTER_METRIC_NAME_MAPPINGS[otel_name], quickpulse_name) - def test_all_constants_are_tuples_with_two_elements(self): + def test_all_constants_are_tuples_with_two_elements(self): # pylint: disable=name-too-long """Test that all metric constants are tuples with exactly two elements.""" constants = [ _AVAILABLE_MEMORY, @@ -129,7 +129,7 @@ def test_all_constants_are_tuples_with_two_elements(self): self.assertIsInstance(constant[0], str) self.assertIsInstance(constant[1], str) - def test_opentelemetry_metric_names_are_unique(self): + def test_opentelemetry_metric_names_are_unique(self): # pylint: disable=name-too-long """Test that all OpenTelemetry metric names are unique.""" constants = [ _AVAILABLE_MEMORY, @@ -148,13 +148,14 @@ def test_opentelemetry_metric_names_are_unique(self): self.assertEqual(len(otel_names), len(unique_names), "Duplicate OpenTelemetry metric names found") - def test_quickpulse_perf_counters_unique_otel(self): + def test_quickpulse_perf_counters_unique_otel(self): # pylint: disable=name-too-long """Test that all Quickpulse and Performance Counters metric names are unique.""" - # Note that the breeze names of Performance Counters and Quickpulse may overlap as they are sent to different endpoints + # Note that the breeze names of Performance Counters and Quickpulse may overlap + # as they are sent to different endpoints for perf_counter_otel in _PERFORMANCE_COUNTER_METRIC_NAME_MAPPINGS: self.assertNotIn(perf_counter_otel, _QUICKPULSE_METRIC_NAME_MAPPINGS) - def test_opentelemetry_metric_names_follow_convention(self): + def test_opentelemetry_metric_names_follow_convention(self): # pylint: disable=name-too-long """Test that all OpenTelemetry metric names follow the expected convention.""" constants = [ _AVAILABLE_MEMORY, @@ -180,7 +181,7 @@ def test_opentelemetry_metric_names_follow_convention(self): # Check that it doesn't end with the prefix (i.e., has additional content) self.assertGreater(len(otel_name), len(expected_prefix), f"Metric name '{otel_name}' is too short") - def test_quickpulse_metric_names_follow_convention(self): + def test_quickpulse_metric_names_follow_convention(self): # pylint: disable=name-too-long """Test that all Quickpulse metric names follow the expected Windows performance counter convention.""" constants = [ _AVAILABLE_MEMORY, diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py index 9fdbb1e36d62..ef60e2283b70 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py @@ -2,11 +2,11 @@ # Licensed under the MIT License. import collections -import psutil import unittest from datetime import datetime from unittest import mock from unittest.mock import MagicMock +import psutil from opentelemetry.semconv.attributes.exception_attributes import ( EXCEPTION_MESSAGE, @@ -44,6 +44,7 @@ from azure.monitor.opentelemetry.exporter._utils import Singleton +# pylint: disable=protected-access, docstring-missing-param class TestPerformanceCounterFunctions(unittest.TestCase): """Test individual performance counter callback functions.""" @@ -52,6 +53,7 @@ def setUp(self): # Import the module to reset globals import azure.monitor.opentelemetry.exporter._performance_counters._manager as manager_module + # pylint: disable=protected-access # TODO: _PROCESS.io_counters() is not available on Mac OS and some Linux distros. Find alternative. manager_module._IO_AVAILABLE = True manager_module._IO_LAST_COUNT = 0 @@ -308,7 +310,7 @@ def test_exception_rate_initialization(self): self.assertEqual(counter.NAME[0], "azuremonitor.performancecounter.exceptionssec") self.assertEqual(counter.NAME[1], "\\.NET CLR Exceptions(??APP_CLR_PROC??)\\# of Exceps Thrown / sec") - def test_request_execution_time_initialization(self): + def test_request_execution_time_initialization(self): # pylint: disable=name-too-long """Test RequestExecutionTime class initialization.""" counter = RequestExecutionTime(self.meter) @@ -332,7 +334,7 @@ def test_process_cpu_initialization(self): self.assertEqual(counter.NAME[0], "azuremonitor.performancecounter.processtime") self.assertEqual(counter.NAME[1], "\\Process(??APP_WIN32_PROC??)\\% Processor Time") - def test_process_cpu_normalized_initialization(self): + def test_process_cpu_normalized_initialization(self): # pylint: disable=name-too-long """Test ProcessCpuNormalized class initialization.""" counter = ProcessCpuNormalized(self.meter) @@ -348,7 +350,7 @@ def test_process_io_rate_initialization(self): self.assertEqual(counter.NAME[0], "azuremonitor.performancecounter.processiobytessec") self.assertEqual(counter.NAME[1], "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec") - def test_process_private_bytes_initialization(self): + def test_process_private_bytes_initialization(self): # pylint: disable=name-too-long """Test ProcessPrivateBytes class initialization.""" counter = ProcessPrivateBytes(self.meter) @@ -400,7 +402,7 @@ def test_manager_initialization_success(self, mock_get_meter_provider): @mock.patch("azure.monitor.opentelemetry.exporter._performance_counters._manager._IO_AVAILABLE", False) @mock.patch("azure.monitor.opentelemetry.exporter._performance_counters._manager.metrics.get_meter_provider") - def test_manager_initialization_success_no_io(self, mock_get_meter_provider): + def test_manager_initialization_success_no_io(self, mock_get_meter_provider): # pylint: disable=name-too-long """Test successful manager initialization.""" mock_meter_provider = MagicMock() mock_meter = MagicMock() @@ -417,7 +419,7 @@ def test_manager_initialization_success_no_io(self, mock_get_meter_provider): self.assertEqual(len(manager._performance_counters), len(PERFORMANCE_COUNTER_METRICS) - 1) mock_meter_provider.get_meter.assert_called_once() - def test_manager_initialization_with_custom_meter_provider(self): + def test_manager_initialization_with_custom_meter_provider(self): # pylint: disable=name-too-long """Test manager initialization with custom meter provider.""" mock_meter_provider = MagicMock() mock_meter = MagicMock() @@ -427,7 +429,7 @@ def test_manager_initialization_with_custom_meter_provider(self): mock_meter.create_observable_gauge.return_value = MagicMock() mock_meter.create_histogram.return_value = MagicMock() - manager = _PerformanceCountersManager(meter_provider=mock_meter_provider) + _manager = _PerformanceCountersManager(meter_provider=mock_meter_provider) mock_meter_provider.get_meter.assert_called_once() @@ -537,7 +539,7 @@ def test_record_span_with_exception(self, mock_get_meter_provider): # Check that exception was counted self.assertEqual(manager_module._EXCEPTIONS_COUNT, initial_exceptions + 1) - def test_record_span_non_server_consumer_kind(self): + def test_record_span_non_server_consumer_kind(self): # pylint: disable=name-too-long """Test recording span that's not a server/consumer kind.""" manager = _PerformanceCountersManager() @@ -617,7 +619,7 @@ def tearDown(self): if _PerformanceCountersManager in Singleton._instances: del Singleton._instances[_PerformanceCountersManager] - def test_enable_performance_counters_default_provider(self): + def test_enable_performance_counters_default_provider(self): # pylint: disable=name-too-long """Test enabling performance counters with default provider.""" # Create a proper meter provider for testing meter_provider = MeterProvider() @@ -632,7 +634,7 @@ def test_enable_performance_counters_default_provider(self): # self.assertIsNotNone(_PerformanceCountersManager._instance) self.assertIn(_PerformanceCountersManager, Singleton._instances) - def test_enable_performance_counters_custom_provider(self): + def test_enable_performance_counters_custom_provider(self): # pylint: disable=name-too-long """Test enabling performance counters with custom provider.""" # Create a proper meter provider for testing meter_provider = MeterProvider() @@ -679,7 +681,7 @@ def test_metric_name_constants(self): self.assertIsInstance(metric_class.NAME[1], str) -class TestPerformanceCountersMetricsIntegration(unittest.TestCase): +class TestPerformanceCountersMetricsIntegration(unittest.TestCase): # pylint: disable=name-too-long """Test actual metrics generation from performance counters.""" def setUp(self): @@ -697,7 +699,7 @@ def tearDown(self): if _PerformanceCountersManager in Singleton._instances: del Singleton._instances[_PerformanceCountersManager] - def _get_metric_names(self, metrics_data): + def _get_metric_names(self, metrics_data): # pylint: disable=docstring-missing-return, docstring-missing-rtype """Helper to extract metric names from metrics data.""" metric_names = [] for resource_metrics in metrics_data.resource_metrics: @@ -706,7 +708,7 @@ def _get_metric_names(self, metrics_data): metric_names.append(metric.name) return metric_names - def _get_metric_value(self, metrics_data, metric_name): + def _get_metric_value(self, metrics_data, metric_name): # pylint: disable=docstring-missing-return, docstring-missing-rtype """Helper to extract metric value from metrics data.""" for resource_metrics in metrics_data.resource_metrics: for scope_metrics in resource_metrics.scope_metrics: @@ -723,7 +725,7 @@ def test_available_memory_metric_generation(self, mock_virtual_memory): mock_virtual_memory.return_value.available = 2147483648 # 2GB # Initialize performance counters - use real meter provider, not mocked - manager = _PerformanceCountersManager(meter_provider=self.meter_provider) + _manager = _PerformanceCountersManager(meter_provider=self.meter_provider) # Force metrics collection metrics_data = self.reader.get_metrics_data() @@ -745,7 +747,7 @@ def test_process_memory_metric_generation(self, mock_process): mock_process.memory_info.return_value = mock_memory_info # Initialize performance counters - use real meter provider, not mocked - manager = _PerformanceCountersManager(meter_provider=self.meter_provider) + _manager = _PerformanceCountersManager(meter_provider=self.meter_provider) # Force metrics collection metrics_data = self.reader.get_metrics_data() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py index 1ce7492b20b6..a215aae241a9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py @@ -17,8 +17,8 @@ ) from azure.monitor.opentelemetry.exporter._utils import Singleton - -class TestPerformanceCountersLogRecordProcessor(unittest.TestCase): +# pylint: disable=protected-access, docstring-missing-param +class TestPerformanceCountersLogRecordProcessor(unittest.TestCase): # pylint: disable=name-too-long """Test performance counters log record processor.""" def setUp(self): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py index 9f87aaa27808..88b940ab95be 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/perfstress_tests/trace_exporter.py @@ -6,8 +6,6 @@ from devtools_testutils.perfstress_tests import PerfStressTest -from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter - from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider 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..52ed974ca1f7 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 @@ -2,10 +2,10 @@ # Licensed under the MIT License. # cSpell:disable import collections -import psutil import unittest from datetime import datetime, timedelta from unittest import mock +import psutil from azure.monitor.opentelemetry.exporter._quickpulse._cpu import ( _get_process_memory, diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py index 76231aa35c14..eea2ff064462 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py @@ -23,7 +23,6 @@ _POST_INTERVAL_SECONDS, _QuickpulseExporter, _QuickpulseMetricReader, - _QuickpulseState, _Response, _UnsuccessfulQuickPulsePostError, ) @@ -42,7 +41,7 @@ def func(*_args, **_kwargs): return func - +# pylint: disable=protected-access class TestQuickpulse(unittest.TestCase): @classmethod def setUpClass(cls): @@ -93,7 +92,10 @@ def setUpClass(cls): performance_collection_supported=True, ) cls._exporter = _QuickpulseExporter( - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" + connection_string=( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;" + "LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" + ) ) cls._reader = _QuickpulseMetricReader( cls._exporter, @@ -101,9 +103,12 @@ def setUpClass(cls): ) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient") - def test_init(self, client_mock): + def test_init(self, _client_mock): exporter = _QuickpulseExporter( - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" + connection_string=( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" + ) ) self.assertEqual(exporter._live_endpoint, "https://eastus.livediagnostics.monitor.azure.com/") self.assertEqual(exporter._instrumentation_key, "4321abcd-5678-4efa-8abc-1234567890ab") @@ -139,11 +144,6 @@ def test_export_subscribed_none(self, convert_mock, post_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._metric_to_quick_pulse_data_points") def test_export_exception(self, convert_mock): - post_response = _Response( - mock.Mock(), - None, - {}, - ) convert_mock.return_value = [self._data_point] with mock.patch( "azure.monitor.opentelemetry.exporter._quickpulse._generated._client.QuickpulseClient.publish", @@ -291,7 +291,7 @@ def test_quickpulsereader_ticker_ping_true(self, task_mock, ping_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock): + def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock): # pylint: disable=name-too-long task_inst_mock = mock.Mock() task_mock.return_value = task_inst_mock reader = _QuickpulseMetricReader( @@ -311,7 +311,7 @@ def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_ticker_erroneous_no_response_backoff(self, task_mock, ping_mock): + def test_ticker_erroneous_no_response_backoff(self, task_mock, ping_mock): # pylint: disable=name-too-long _set_global_quickpulse_state(_QuickpulseState.PING_SHORT) _set_quickpulse_etag("old-etag") task_inst_mock = mock.Mock() @@ -344,7 +344,7 @@ def test_ticker_post_state(self, task_mock, collect_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseMetricReader.collect") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_ticker_post_unsuccessful_backoff(self, task_mock, collect_mock): + def test_ticker_post_unsuccessful_backoff(self, task_mock, _collect_mock): _set_global_quickpulse_state(_QuickpulseState.POST_SHORT) task_inst_mock = mock.Mock() task_mock.return_value = task_inst_mock @@ -383,7 +383,7 @@ def test_quickpulsereader_receive_metrics(self, task_mock, export_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter.export") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_quickpulsereader_receive_metrics_exception(self, task_mock, export_mock): + def test_quickpulsereader_receive_metrics_exception(self, task_mock, export_mock): # pylint: disable=name-too-long task_inst_mock = mock.Mock() task_mock.return_value = task_inst_mock reader = _QuickpulseMetricReader( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py index 1e87e9036967..2d81afd8ab96 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py @@ -44,7 +44,10 @@ def test_update_filter_configuration(self, mock_set_etag, mock_parse_metric, moc def test_parse_metric_filter_configuration( self, dict_mock, validate_mock, rename_mock, init_projection_mock, set_metric_info_mock ): - test_config_bytes = '{"Metrics":[{"Id":"94.e4b85108","TelemetryType":"Request","FilterGroups":[{"Filters":[]}],"Projection":"Count()","Aggregation":"Sum","BackEndAggregation":"Sum"}]}'.encode() + test_config_bytes = ( + '{"Metrics":[{"Id":"94.e4b85108","TelemetryType":"Request","FilterGroups":[{"Filters":[]}],' + '"Projection":"Count()","Aggregation":"Sum","BackEndAggregation":"Sum"}]}' + ).encode() test_config_dict = json.loads(test_config_bytes.decode()) metric_info_mock = mock.Mock() filter_group_mock = mock.Mock() @@ -66,10 +69,13 @@ def test_parse_metric_filter_configuration( @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._rename_exception_fields_for_filtering") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._validate_derived_metric_info") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter.DerivedMetricInfo") - def test_parse_metric_filter_configuration_invalid( + def test_parse_metric_filter_configuration_invalid( # pylint: disable=name-too-long self, dict_mock, validate_mock, rename_mock, init_projection_mock, set_metric_info_mock ): - test_config_bytes = '{"Metrics":[{"Id":"94.e4b85108","TelemetryType":"Request","FilterGroups":[{"Filters":[]}],"Projection":"Count()","Aggregation":"Sum","BackEndAggregation":"Sum"}]}'.encode() + test_config_bytes = ( + '{"Metrics":[{"Id":"94.e4b85108","TelemetryType":"Request","FilterGroups":[{"Filters":[]}],' + '"Projection":"Count()","Aggregation":"Sum","BackEndAggregation":"Sum"}]}' + ).encode() test_config_dict = json.loads(test_config_bytes.decode()) metric_info_mock = mock.Mock() metric_info_mock.telemetry_type = TelemetryType.REQUEST @@ -88,7 +94,16 @@ def test_parse_metric_filter_configuration_invalid( @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._validate_document_filter_group_info") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter.DocumentStreamInfo") def test_parse_doc_filter_configuration(self, dict_mock, validate_mock, rename_mock, set_doc_info_mock): - test_config_bytes = '{"DocumentStreams": [ { "Id": "26a.7cf471b0", "DocumentFilterGroups": [ { "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, { "FieldName": "Url", "Predicate": "Contains", "Comparand": "privacy" } ] } }, { "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, { "TelemetryType": "Exception", "Filters": { "Filters": [] } }, { "TelemetryType": "Event", "Filters": { "Filters": [] } }, { "TelemetryType": "Trace", "Filters": { "Filters": [] } }, { "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}'.encode() + test_config_bytes = ( + '{"DocumentStreams": [ { "Id": "26a.7cf471b0", "DocumentFilterGroups": [ ' + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, ' # pylint: disable=line-too-long + '{ "FieldName": "Url", "Predicate": "Contains", "Comparand": "privacy" } ] } }, ' + '{ "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, ' # pylint: disable=line-too-long + '{ "TelemetryType": "Exception", "Filters": { "Filters": [] } }, ' + '{ "TelemetryType": "Event", "Filters": { "Filters": [] } }, ' + '{ "TelemetryType": "Trace", "Filters": { "Filters": [] } }, ' + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}' # pylint: disable=line-too-long + ).encode() test_config_dict = json.loads(test_config_bytes.decode()) doc_stream_mock = mock.Mock() doc_stream_mock.id = "26a.7cf471b0" @@ -110,8 +125,17 @@ def test_parse_doc_filter_configuration(self, dict_mock, validate_mock, rename_m @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._rename_exception_fields_for_filtering") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._validate_document_filter_group_info") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter.DocumentStreamInfo") - def test_parse_doc_filter_configuration_invalid(self, dict_mock, validate_mock, rename_mock, set_doc_info_mock): - test_config_bytes = '{"DocumentStreams": [ { "Id": "26a.7cf471b0", "DocumentFilterGroups": [ { "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, { "FieldName": "Url", "Predicate": "Contains", "Comparand": "privacy" } ] } }, { "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, { "TelemetryType": "Exception", "Filters": { "Filters": [] } }, { "TelemetryType": "Event", "Filters": { "Filters": [] } }, { "TelemetryType": "Trace", "Filters": { "Filters": [] } }, { "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}'.encode() + def test_parse_doc_filter_configuration_invalid(self, dict_mock, validate_mock, rename_mock, set_doc_info_mock): # pylint: disable=name-too-long + test_config_bytes = ( + '{"DocumentStreams": [ { "Id": "26a.7cf471b0", "DocumentFilterGroups": [ ' + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, ' # pylint: disable=line-too-long + '{ "FieldName": "Url", "Predicate": "Contains", "Comparand": "privacy" } ] } }, ' + '{ "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, ' # pylint: disable=line-too-long + '{ "TelemetryType": "Exception", "Filters": { "Filters": [] } }, ' + '{ "TelemetryType": "Event", "Filters": { "Filters": [] } }, ' + '{ "TelemetryType": "Trace", "Filters": { "Filters": [] } }, ' + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}' # pylint: disable=line-too-long + ).encode() test_config_dict = json.loads(test_config_bytes.decode()) doc_stream_mock = mock.Mock() doc_stream_mock.id = "26a.7cf471b0" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py index fbf1cfd44ffd..a4c1abd237f4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py @@ -10,7 +10,7 @@ from azure.monitor.opentelemetry.exporter._quickpulse._live_metrics import enable_live_metrics - +# pylint: disable=docstring-missing-param class TestLiveMetrics(unittest.TestCase): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") @@ -40,7 +40,7 @@ def test_enable_live_metrics_basic(self, manager_mock, statsbeat_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_initialization_fails(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_initialization_fails(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test enable_live_metrics when manager initialization fails.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = False @@ -59,7 +59,7 @@ def test_enable_live_metrics_initialization_fails(self, manager_mock, statsbeat_ @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_with_minimal_args(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_with_minimal_args(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test enable_live_metrics with minimal arguments.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True @@ -78,7 +78,7 @@ def test_enable_live_metrics_with_minimal_args(self, manager_mock, statsbeat_moc @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_with_all_parameters(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_with_all_parameters(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long, unused-argument """Test enable_live_metrics with all possible parameters.""" mock_resource = Resource.create( {"service.name": "test-service", "service.version": "1.0.0", "deployment.environment": "test"} @@ -108,7 +108,7 @@ def test_enable_live_metrics_with_all_parameters(self, manager_mock, statsbeat_m @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_with_none_values(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_with_none_values(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long, unused-argument """Test enable_live_metrics with None values for optional parameters.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True @@ -124,7 +124,7 @@ def test_enable_live_metrics_with_none_values(self, manager_mock, statsbeat_mock @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_empty_string_connection(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_empty_string_connection(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test enable_live_metrics with empty string connection string.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True @@ -143,7 +143,7 @@ def test_enable_live_metrics_empty_string_connection(self, manager_mock, statsbe @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_complex_resource(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_complex_resource(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test enable_live_metrics with complex resource attributes.""" mock_resource = Resource.create( { @@ -206,7 +206,7 @@ def test_enable_live_metrics_multiple_calls(self, manager_mock, statsbeat_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_kwargs_preservation(self, manager_mock, statsbeat_mock): + def test_enable_live_metrics_kwargs_preservation(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test that all kwargs are properly passed through to initialize.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py index 4fee6dc81eb3..f5edc8e30640 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py @@ -16,7 +16,6 @@ ) from opentelemetry.sdk.resources import Resource from opentelemetry.semconv.resource import ResourceAttributes -from opentelemetry.sdk.trace import ReadableSpan from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind @@ -66,7 +65,7 @@ _populate_part_a_fields, ) - +# pylint: disable=protected-access, docstring-missing-param, too-many-public-methods class TestQuickpulseManager(unittest.TestCase): def setUp(self): """Set up test fixtures.""" @@ -82,7 +81,7 @@ def tearDown(self): @classmethod def setUpClass(cls): _set_global_quickpulse_state(_QuickpulseState.PING_SHORT) - cls.connection_string = "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" + cls.connection_string = "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" # pylint: disable=line-too-long cls.resource = Resource.create( { ResourceAttributes.SERVICE_INSTANCE_ID: "test_instance", @@ -286,7 +285,7 @@ def test_shutdown_not_initialized(self): self.assertFalse(qpm.is_initialized()) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._logger") - def test_shutdown_meter_provider_exception(self, logger_mock): + def test_shutdown_meter_provider_exception(self, logger_mock): # pylint: disable=unused-argument """Test shutdown handling meter provider exception.""" qpm = _QuickpulseManager() @@ -683,7 +682,7 @@ def test_derive_metrics_from_telemetry_data(self, get_derived_mock, filter_mock, @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._create_projections") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_metric_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_derived_metric_infos") - def test_derive_metrics_from_telemetry_data_filter_false(self, get_derived_mock, filter_mock, projection_mock): + def test_derive_metrics_from_telemetry_data_filter_false(self, get_derived_mock, filter_mock, projection_mock): # pylint: disable=name-too-long metric_infos = [mock.Mock()] get_derived_mock.return_value = { TelemetryType.DEPENDENCY: metric_infos, @@ -708,7 +707,7 @@ def test_derive_metrics_from_telemetry_data_filter_false(self, get_derived_mock, @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_span_document") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_doc_stream_infos") - def test_apply_doc_filters_from_telemetry_data( + def test_apply_doc_filters_from_telemetry_data( # pylint: disable=name-too-long self, get_doc_stream_mock, filter_mock, @@ -744,7 +743,7 @@ def test_apply_doc_filters_from_telemetry_data( @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_span_document") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_doc_stream_infos") - def test_apply_doc_filters_from_telemetry_data_all_streams( + def test_apply_doc_filters_from_telemetry_data_all_streams( # pylint: disable=name-too-long self, get_doc_stream_mock, filter_mock, @@ -779,7 +778,7 @@ def test_apply_doc_filters_from_telemetry_data_all_streams( @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_span_document") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_doc_stream_infos") - def test_apply_doc_filters_from_telemetry_data_false_filter( + def test_apply_doc_filters_from_telemetry_data_false_filter( # pylint: disable=name-too-long self, get_doc_stream_mock, filter_mock, @@ -869,7 +868,7 @@ def test_record_span_not_initialized(self, post_state_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._TelemetryData") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._is_post_state") def test_record_span_exception_handling( - self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock + self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock # pylint: disable=unused-argument ): """Test _record_span exception handling.""" post_state_mock.return_value = True @@ -934,8 +933,8 @@ def test_record_log_record_not_initialized(self, post_state_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._derive_metrics_from_telemetry_data") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._TelemetryData") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._is_post_state") - def test_record_log_record_exception_handling( - self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock + def test_record_log_record_exception_handling( # pylint: disable=name-too-long + self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock # pylint: disable=unused-argument ): """Test _record_log_record exception handling.""" post_state_mock.return_value = True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py index 982ba2956e5f..cc4ff5636936 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py @@ -6,14 +6,16 @@ from azure.monitor.opentelemetry.exporter._quickpulse._policy import _QuickpulseRedirectPolicy - +# pylint: disable=protected-access class TestQuickpulseRedirectPolicy(unittest.TestCase): def test_get_redirect_location(self): policy = _QuickpulseRedirectPolicy() pipeline_resp_mock = mock.Mock() http_resp_mock = mock.Mock() headers = { - "x-ms-qps-service-endpoint-redirect-v2": "https://eastus.livediagnostics.monitor.azure.com/QuickPulseService.svc" + "x-ms-qps-service-endpoint-redirect-v2": ( + "https://eastus.livediagnostics.monitor.azure.com/QuickPulseService.svc" + ) } http_resp_mock.headers = headers pipeline_resp_mock.http_response = http_resp_mock @@ -43,7 +45,6 @@ def test_get_redirect_location_no_header(self): pipeline_resp_mock.http_response = http_resp_mock policy = _QuickpulseRedirectPolicy() self.assertIsNone(policy.get_redirect_location(pipeline_resp_mock)) - redirect_location = policy.get_redirect_location(pipeline_resp_mock) def test_get_redirect_location_invalid_url(self): policy = _QuickpulseRedirectPolicy() @@ -68,7 +69,9 @@ def test_get_redirect_location_no_client(self): pipeline_resp_mock = mock.Mock() http_resp_mock = mock.Mock() headers = { - "x-ms-qps-service-endpoint-redirect-v2": "https://eastus.livediagnostics.monitor.azure.com/QuickPulseService.svc" + "x-ms-qps-service-endpoint-redirect-v2": ( + "https://eastus.livediagnostics.monitor.azure.com/QuickPulseService.svc" + ) } http_resp_mock.headers = headers pipeline_resp_mock.http_response = http_resp_mock diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py index 89778cee063b..3345c067dc1c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py @@ -9,7 +9,7 @@ ) from azure.monitor.opentelemetry.exporter._quickpulse._manager import _QuickpulseManager - +# pylint: disable=protected-access class TestQuickpulseLogRecordProcessor(unittest.TestCase): @classmethod def setUpClass(cls): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py index e63251d9dbfe..f7dc34709e9b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py @@ -23,7 +23,7 @@ _TelemetryData, ) - +# pylint: disable=protected-access class TestTelemetryData(unittest.TestCase): @patch("azure.monitor.opentelemetry.exporter._quickpulse._types._RequestData") def test_from_span_server_kind_server(self, fn_mock): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py index bec2ac3bb935..aee760164dc4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py @@ -116,7 +116,7 @@ def test_metric_to_qp_data_point_num(self, datetime_mock): self.assertEqual(mdp.documents, documents) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._utils._get_metrics_from_projections") - def test_metric_to_qp_data_point_process_filtered_metrics(self, projection_mock): + def test_metric_to_qp_data_point_process_filtered_metrics(self, projection_mock): # pylint: disable=name-too-long metric_data = mock.Mock() metric_data.resource_metrics = [] projections = [("ID:1234", 5.0)] @@ -206,7 +206,7 @@ def test_get_metrics_from_projections(self, projection_map_mock): ], ) - def test_valid_time_stamp_with_decimal_seconds(self): + def test_valid_time_stamp_with_decimal_seconds(self): # pylint: disable=name-too-long time_stamp = "14.6:56:7.89" expected_ms = 1234567890 # Expected milliseconds self.assertEqual(_filter_time_stamp_to_ms(time_stamp), expected_ms) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py index aec50d51bab5..9d04f983fc58 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py @@ -13,12 +13,12 @@ def test_valid_telemetry_type(self): valid_metric_info = mock.Mock(telemetry_type="Request", projection=None, filter_groups=[]) self.assertTrue(_validate_derived_metric_info(valid_metric_info)) - def test_validate_info_invalid_telemetry_type(self): + def test_validate_info_invalid_telemetry_type(self): # pylint: disable=name-too-long invalid_metric_info = mock.Mock(telemetry_type="Request", projection=None, filter_groups=[]) invalid_metric_info.telemetry_type = "INVALID_TYPE" self.assertFalse(_validate_derived_metric_info(invalid_metric_info)) - def test_validate_info_custom_metric_projection(self): + def test_validate_info_custom_metric_projection(self): # pylint: disable=name-too-long valid_metric_info = mock.Mock(telemetry_type="Request", projection=None, filter_groups=[]) valid_metric_info.telemetry_type = "Request" valid_metric_info.projection = "CustomMetrics.MyMetric" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py index 30a9d6273816..127db95fbce3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py @@ -3,9 +3,8 @@ import os import unittest from unittest import mock -from unittest.mock import Mock, patch, MagicMock +from unittest.mock import Mock, patch -from azure.monitor.opentelemetry.exporter._connection_string_parser import ConnectionStringParser from azure.monitor.opentelemetry.exporter.statsbeat._manager import StatsbeatConfig, StatsbeatManager from azure.monitor.opentelemetry.exporter.statsbeat._state import ( _STATSBEAT_STATE, @@ -13,12 +12,10 @@ ) from azure.monitor.opentelemetry.exporter._constants import ( _APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL, - _DEFAULT_EU_STATS_CONNECTION_STRING, - _DEFAULT_NON_EU_STATS_CONNECTION_STRING, ) # cSpell:disable - +# pylint: disable=protected-access, docstring-missing-param class TestStatsbeatConfig(unittest.TestCase): def setUp(self): @@ -49,7 +46,10 @@ def test_init_with_all_parameters(self): disable_offline_storage=True, credential=mock.Mock(), distro_version="1.0.0", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" + ), ) self.assertEqual(config.endpoint, "https://westus-1.in.applicationinsights.azure.com/") @@ -60,11 +60,14 @@ def test_init_with_all_parameters(self): self.assertEqual(config.distro_version, "1.0.0") self.assertEqual( config.connection_string, - "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + ( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" + ), ) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager._get_stats_connection_string") - def test_init_invalid_connection_string_fallback(self, mock_get_stats_cs): + def test_init_invalid_connection_string_fallback(self, mock_get_stats_cs): # pylint: disable=name-too-long """Test that invalid connection string falls back to default.""" mock_get_stats_cs.return_value = "InstrumentationKey=fallback;IngestionEndpoint=https://fallback.com/" @@ -101,7 +104,7 @@ def test_from_exporter_valid(self): self.assertIsNotNone(config.credential) self.assertEqual(config.distro_version, "1.0.0") - def test_from_exporter_missing_instrumentation_key(self): + def test_from_exporter_missing_instrumentation_key(self): # pylint: disable=name-too-long """Test creating config from exporter missing instrumentation key.""" exporter = mock.Mock() exporter._endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -134,7 +137,10 @@ def test_from_exporter_missing_region(self): @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager._get_connection_string_for_region_from_config") def test_from_config_valid(self, mock_get_cs_for_region): """Test creating config from base config and dictionary.""" - mock_get_cs_for_region.return_value = "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" + mock_get_cs_for_region.return_value = ( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" + ) base_config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", @@ -159,11 +165,14 @@ def test_from_config_valid(self, mock_get_cs_for_region): self.assertEqual(new_config.distro_version, "1.0.0") self.assertEqual( new_config.connection_string, - "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + ( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" + ), ) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager._get_connection_string_for_region_from_config") - def test_from_config_fallback_connection_string(self, mock_get_cs_for_region): + def test_from_config_fallback_connection_string(self, mock_get_cs_for_region): # pylint: disable=name-too-long """Test that from_config falls back to base config connection string when needed.""" mock_get_cs_for_region.return_value = None @@ -182,7 +191,7 @@ def test_from_config_fallback_connection_string(self, mock_get_cs_for_region): if new_config: self.assertEqual(new_config.connection_string, base_config.connection_string) - def test_from_config_missing_instrumentation_key(self): + def test_from_config_missing_instrumentation_key(self): # pylint: disable=name-too-long """Test from_config with missing instrumentation key.""" base_config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", region="westus", instrumentation_key="" @@ -247,7 +256,7 @@ def test_hash(self): self.assertNotEqual(hash(config1), hash(config3)) -# pylint: disable=protected-access +# pylint: disable=protected-access, too-many-public-methods class TestStatsbeatManager(unittest.TestCase): def setUp(self): """Set up test fixtures.""" @@ -277,17 +286,19 @@ def tearDown(self): try: if hasattr(self, "manager"): self.manager.shutdown() - except Exception: + except Exception: # pylint: disable=broad-exception-caught pass os.environ.pop(_APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL, None) # Reset singleton state - only clear StatsbeatManager instances if StatsbeatManager in StatsbeatManager._instances: del StatsbeatManager._instances[StatsbeatManager] - def _create_valid_config( + def _create_valid_config( # pylint: disable=docstring-missing-return, docstring-missing-rtype self, - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", - disable_offline_storage=False, + connection_string=( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" + ), ): """Helper to create a valid StatsbeatConfig.""" return StatsbeatConfig( @@ -313,7 +324,7 @@ def test_validate_config_none(self): """Test _validate_config with None configuration.""" self.assertFalse(StatsbeatManager._validate_config(None)) # type: ignore - def test_validate_config_missing_instrumentation_key(self): + def test_validate_config_missing_instrumentation_key(self): # pylint: disable=name-too-long """Test _validate_config with missing instrumentation key.""" config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", region="westus", instrumentation_key="" @@ -332,7 +343,7 @@ def test_validate_config_missing_region(self): ) self.assertFalse(StatsbeatManager._validate_config(config)) - def test_validate_config_missing_connection_string(self): + def test_validate_config_missing_connection_string(self): # pylint: disable=name-too-long """Test _validate_config with missing connection string.""" config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", @@ -413,7 +424,7 @@ def test_initialize_success( @patch("azure.monitor.opentelemetry.exporter.export.metrics._exporter.AzureMonitorMetricExporter") @patch("azure.monitor.opentelemetry.exporter.statsbeat._state.is_statsbeat_enabled") def test_initialize_failure_exception( - self, mock_is_enabled, mock_exporter_class, mock_reader_class, mock_meter_provider_class + self, mock_is_enabled, mock_exporter_class, mock_reader_class, mock_meter_provider_class # pylint: disable=unused-argument ): """Test initialization failure due to exception.""" mock_is_enabled.return_value = True @@ -427,7 +438,7 @@ def test_initialize_failure_exception( self.assertFalse(self.manager._initialized) @patch("azure.monitor.opentelemetry.exporter.statsbeat._state.is_statsbeat_enabled") - def test_initialize_already_initialized_same_config(self, mock_is_enabled): + def test_initialize_already_initialized_same_config(self, mock_is_enabled): # pylint: disable=name-too-long """Test initialize when already initialized with same config.""" mock_is_enabled.return_value = True config = self._create_valid_config() @@ -441,7 +452,7 @@ def test_initialize_already_initialized_same_config(self, mock_is_enabled): self.assertTrue(result) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.is_statsbeat_enabled") - def test_initialize_already_initialized_different_config_cs(self, mock_is_enabled): + def test_initialize_already_initialized_different_config_cs(self, mock_is_enabled): # pylint: disable=name-too-long """Test initialize when already initialized with different config.""" mock_is_enabled.return_value = True @@ -450,7 +461,10 @@ def test_initialize_already_initialized_different_config_cs(self, mock_is_enable endpoint="https://eastus-1.in.applicationinsights.azure.com/", region="eastus", instrumentation_key="different-key", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://eastus-0.in.applicationinsights.azure.com/", + connection_string=( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://eastus-0.in.applicationinsights.azure.com/" + ), ) # Mock initialized state @@ -465,7 +479,7 @@ def test_initialize_already_initialized_different_config_cs(self, mock_is_enable mock_reconfigure.assert_called_once_with(new_config) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.is_statsbeat_enabled") - def test_initialize_already_initialized_different_config_storage(self, mock_is_enabled): + def test_initialize_already_initialized_different_config_storage(self, mock_is_enabled): # pylint: disable=name-too-long """Test initialize when already initialized with different config.""" mock_is_enabled.return_value = True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py index 6530a2da7c79..518fe92489cb 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py @@ -3,10 +3,10 @@ import json import os import platform -import requests import sys import unittest from unittest import mock +import requests # pylint: disable=networking-import-outside-azure-core-transport from opentelemetry.sdk.metrics import Meter, MeterProvider, ObservableGauge @@ -49,14 +49,14 @@ def func(*_args, **_kwargs): # cSpell:disable - +# pylint: disable=protected-access _StatsbeatMetrics_COMMON_ATTRS = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) _StatsbeatMetrics_NETWORK_ATTRS = dict(_StatsbeatMetrics._NETWORK_ATTRIBUTES) _StatsbeatMetrics_FEATURE_ATTRIBUTES = dict(_StatsbeatMetrics._FEATURE_ATTRIBUTES) _StatsbeatMetrics_INSTRUMENTATION_ATTRIBUTES = dict(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES) -# pylint: disable=protected-access +# pylint: disable=protected-access, too-many-public-methods class TestStatsbeatMetrics(unittest.TestCase): @classmethod def setUpClass(cls): @@ -127,7 +127,7 @@ def test_statsbeat_metric_init(self): self.assertEqual(metric._feature_metric.name, _FEATURE_METRIC_NAME[0]) @mock.patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled") - def test_statsbeat_metric_init_attach_enabled(self, attach_mock): + def test_statsbeat_metric_init_attach_enabled(self, attach_mock): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -180,7 +180,7 @@ def test_get_attach_metric_meet_threshold(self): self.assertEqual(metric._long_interval_count_map[_ATTACH_METRIC_NAME[0]], 0) # pylint: disable=protected-access - def test_get_attach_metric_does_not_meet_threshold(self): + def test_get_attach_metric_does_not_meet_threshold(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -206,10 +206,10 @@ def test_get_attach_metric_does_not_meet_threshold(self): }, ) @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long return_value=False, ) - def test_get_attach_metric_appsvc(self, metadata_mock): + def test_get_attach_metric_appsvc(self, _metadata_mock): attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) self.assertEqual(attributes["rp"], _RP_Names.UNKNOWN.value) attributes["rp"] = _RP_Names.APP_SERVICE.value @@ -231,10 +231,10 @@ def test_get_attach_metric_appsvc(self, metadata_mock): }, ) @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long return_value=False, ) - def test_get_attach_metric_functions(self, metadata_mock): + def test_get_attach_metric_functions(self, _metadata_mock): attributes = dict(_StatsbeatMetrics._COMMON_ATTRIBUTES) self.assertEqual(attributes["rp"], _RP_Names.UNKNOWN.value) attributes["rp"] = _RP_Names.FUNCTIONS.value @@ -283,7 +283,7 @@ def test_get_attach_metric_aks_manual(self): self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["rp"], _RP_Names.AKS.value) @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata" + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long ) def test_get_attach_metric_vm(self, metadata_mock): mp = MeterProvider() @@ -318,7 +318,7 @@ def test_get_attach_metric_vm(self, metadata_mock): self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["os"], "test_os") @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long return_value=False, ) def test_get_attach_metric_vm_no_os(self, metadata_mock): @@ -406,7 +406,7 @@ def test_get_azure_compute_metadata_not_vm(self): self.assertEqual(len(metric._vm_data), 0) self.assertFalse(metric._vm_retry) - def test_get_azure_compute_metadata_not_vm_timeout(self): + def test_get_azure_compute_metadata_not_vm_timeout(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -461,7 +461,7 @@ def test_get_feature_metric_meet_threshold(self): self.assertEqual(metric._long_interval_count_map[_FEATURE_METRIC_NAME[0]], 0) # pylint: disable=protected-access - def test_get_feature_metric_does_not_meet_threshold(self): + def test_get_feature_metric_does_not_meet_threshold(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -556,7 +556,7 @@ def test_get_feature_metric_custom_events(self, feature_mock): self.assertEqual(obs.attributes, attributes) # pylint: disable=protected-access - def test_get_feature_metric_custom_events_runtime(self): + def test_get_feature_metric_custom_events_runtime(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -610,7 +610,7 @@ def test_get_feature_metric_live_metrics(self, feature_mock): self.assertEqual(obs.attributes, attributes) # pylint: disable=protected-access - def test_get_feature_metric_live_metrics_runtime(self): + def test_get_feature_metric_live_metrics_runtime(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -641,7 +641,7 @@ def test_get_feature_metric_live_metrics_runtime(self): @mock.patch( "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics.get_statsbeat_customer_sdkstats_feature_set" ) - def test_get_feature_metric_customer_sdkstats(self, feature_mock): + def test_get_feature_metric_customer_sdkstats(self, feature_mock): # pylint: disable=name-too-long feature_mock.return_value = True mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" @@ -664,7 +664,7 @@ def test_get_feature_metric_customer_sdkstats(self, feature_mock): self.assertEqual(obs.attributes, attributes) # pylint: disable=protected-access - def test_get_feature_metric_customer_sdkstats_runtime(self): + def test_get_feature_metric_customer_sdkstats_runtime(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -734,7 +734,7 @@ def test_get_feature_metric_instrumentation(self): self.assertEqual(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES["feature"], 1026) # pylint: disable=protected-access - def test_get_feature_metric_instrumentation_none(self): + def test_get_feature_metric_instrumentation_none(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py index 406293cf212c..e39fd541a13f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py @@ -25,7 +25,7 @@ # cSpell:disable -# pylint: disable=protected-access +# pylint: disable=protected-access, docstring-missing-param class TestStatsbeat(unittest.TestCase): def setUp(self): os.environ[_APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL] = "false" @@ -102,7 +102,6 @@ def test_collect_statsbeat_metrics(self, mock_exporter, mock_reader, mock_meter_ self.assertEqual(config.distro_version, exporter._distro_version) # Verify statsbeat metrics creation - metrics = manager._metrics mock_statsbeat_metrics.assert_called_once_with( mock_meter_provider_instance, exporter._instrumentation_key, @@ -122,8 +121,8 @@ def test_collect_statsbeat_metrics(self, mock_exporter, mock_reader, mock_meter_ @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_registers_configuration_callback( - self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager, mock_get_configuration_manager + def test_collect_statsbeat_metrics_registers_configuration_callback( # pylint: disable=name-too-long + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager, mock_get_configuration_manager # pylint: disable=docstring-missing-param ): """Test that collect_statsbeat_metrics registers a configuration callback when initialized successfully.""" # Arrange @@ -169,8 +168,8 @@ def test_collect_statsbeat_metrics_registers_configuration_callback( @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_successful_update( - self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature + def test_get_statsbeat_configuration_callback_successful_update( # pylint: disable=name-too-long + self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature # pylint: disable=docstring-missing-param ): """Test that configuration callback successfully updates configuration when statsbeat is initialized.""" # Arrange @@ -204,7 +203,7 @@ def test_get_statsbeat_configuration_callback_successful_update( @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_disable_sdkstats( + def test_get_statsbeat_configuration_callback_disable_sdkstats( # pylint: disable=name-too-long self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature ): """Test that configuration callback successfully updates configuration when statsbeat is initialized.""" @@ -239,7 +238,7 @@ def test_get_statsbeat_configuration_callback_disable_sdkstats( @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_not_initialized( + def test_get_statsbeat_configuration_callback_not_initialized( # pylint: disable=name-too-long self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature ): """Test that configuration callback handles case when statsbeat is not initialized.""" @@ -264,7 +263,7 @@ def test_get_statsbeat_configuration_callback_not_initialized( @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_no_updated_config( + def test_get_statsbeat_configuration_callback_no_updated_config( # pylint: disable=name-too-long self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature ): """Test that configuration callback handles case when StatsbeatConfig.from_config returns None.""" @@ -297,8 +296,8 @@ def test_get_statsbeat_configuration_callback_no_updated_config( @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_no_callback_when_init_fails( - self, mock_exporter, mock_reader, mock_meter_provider, mock_statsbeat_metrics, mock_config_manager_cls + def test_collect_statsbeat_metrics_no_callback_when_init_fails( # pylint: disable=name-too-long + self, mock_exporter, mock_reader, mock_meter_provider, mock_statsbeat_metrics, mock_config_manager_cls # pylint: disable=unused-argument ): """Test that configuration callback is not registered when initialization fails.""" # Arrange @@ -332,7 +331,7 @@ def test_collect_statsbeat_metrics_no_callback_when_init_fails( def test_collect_statsbeat_metrics_exists( self, mock_exporter, mock_reader, mock_meter_provider, mock_statsbeat_metrics, mock_get_manager ): - """Test that collect_statsbeat_metrics reuses existing configuration when called multiple times with same config.""" + """Test that collect_statsbeat_metrics reuses existing configuration when called multiple times with same config.""" # pylint: disable=line-too-long # Arrange exporter = mock.Mock() exporter._endpoint = "test endpoint" @@ -435,7 +434,7 @@ def test_collect_statsbeat_metrics_non_eu(self, mock_exporter, mock_reader, mock call_args = mock_exporter.call_args # The connection string should be the non-EU default since the endpoint is non-EU expected_connection_string = call_args[1]["connection_string"] - self.assertIn(_DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(";")[0].split("=")[1], expected_connection_string) + self.assertIn(_DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(';', maxsplit=1)[0], expected_connection_string) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @@ -485,13 +484,13 @@ def test_collect_statsbeat_metrics_eu(self, mock_exporter, mock_reader, mock_met call_args = mock_exporter.call_args # The connection string should be the EU default since the endpoint is EU expected_connection_string = call_args[1]["connection_string"] - self.assertIn(_DEFAULT_EU_STATS_CONNECTION_STRING.split(";")[0].split("=")[1], expected_connection_string) + self.assertIn(_DEFAULT_EU_STATS_CONNECTION_STRING.split(';', maxsplit=1)[0], expected_connection_string) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_aad(self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager): + def test_collect_statsbeat_metrics_aad(self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager): # pylint: disable=unused-argument """Test collect_statsbeat_metrics with AAD credentials.""" # Arrange exporter = mock.Mock() @@ -521,7 +520,7 @@ def test_collect_statsbeat_metrics_aad(self, mock_exporter, mock_reader, mock_me @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_no_aad(self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager): + def test_collect_statsbeat_metrics_no_aad(self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager): # pylint: disable=line-too-long, unused-argument """Test collect_statsbeat_metrics without AAD credentials.""" # Arrange exporter = mock.Mock() @@ -551,8 +550,8 @@ def test_collect_statsbeat_metrics_no_aad(self, mock_exporter, mock_reader, mock @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_distro_version( - self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager + def test_collect_statsbeat_metrics_distro_version( # pylint: disable=name-too-long + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager # pylint: disable=unused-argument ): """Test collect_statsbeat_metrics with distribution version.""" # Arrange @@ -583,8 +582,8 @@ def test_collect_statsbeat_metrics_distro_version( @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_local_storage( - self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager + def test_collect_statsbeat_metrics_local_storage( # pylint: disable=name-too-long + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager # pylint: disable=unused-argument ): """Test collect_statsbeat_metrics with local storage.""" # Arrange @@ -667,7 +666,7 @@ def test_shutdown_statsbeat_metrics( assert mock_get_manager.call_count == 2 @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") - def test_shutdown_statsbeat_metrics_not_initialized(self, mock_get_manager): + def test_shutdown_statsbeat_metrics_not_initialized(self, mock_get_manager): # pylint: disable=name-too-long """Test shutdown when statsbeat is not initialized.""" # Arrange manager = StatsbeatManager() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py index 80fdd28be1ab..042f42de91c0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py @@ -2,13 +2,11 @@ # Licensed under the MIT License. import os -import shutil import unittest from unittest import mock from datetime import datetime -from azure.core.exceptions import HttpResponseError, ServiceRequestError -from requests.exceptions import ConnectionError +from azure.core.exceptions import HttpResponseError, ServiceRequestError # pylint: disable=networking-import-outside-azure-core-transport from azure.monitor.opentelemetry.exporter.export._base import ( BaseExporter, ExportResult, @@ -19,22 +17,11 @@ TrackResponse, TelemetryErrorDetails, ) -from azure.monitor.opentelemetry.exporter.statsbeat.customer._manager import ( - CustomerSdkStatsManager, -) -from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( - get_customer_stats_manager, -) from azure.monitor.opentelemetry.exporter._constants import ( - DropCode, - RetryCode, _exception_categories, ) from azure.monitor.opentelemetry.exporter.statsbeat.customer._utils import ( - track_successful_items, - track_dropped_items, - track_retry_items, track_dropped_items_from_storage, ) @@ -52,7 +39,7 @@ def __init__(self, status_code, content): self.reason = "Mock Reason" # Add the reason attribute self.url = "http://mock-url.com" # Add the url attribute - +# pylint: disable=protected-access class TestBaseExporterCustomerSdkStats(unittest.TestCase): """Test integration between BaseExporter and customer sdkstats tracking functions""" @@ -102,7 +89,7 @@ def tearDownClass(cls): os.environ.pop("APPLICATIONINSIGHTS_SDKSTATS_DISABLED", None) def _create_exporter_with_customer_sdkstats_enabled(self, disable_offline_storage=True): - """Helper method to create an exporter with customer sdkstats enabled""" + # Helper method to create an exporter with customer sdkstats enabled exporter = BaseExporter( connection_string="InstrumentationKey=12345678-1234-5678-abcd-12345678abcd", @@ -112,8 +99,8 @@ def _create_exporter_with_customer_sdkstats_enabled(self, disable_offline_storag return exporter @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_successful_items") - def test_transmit_200_customer_sdkstats_track_successful_items(self, track_successful_mock): - """Test that track_successful_items is called on 200 success response""" + def test_transmit_200_customer_sdkstats_track_successful_items(self, track_successful_mock): # pylint: disable=name-too-long + # Test that track_successful_items is called on 200 success response exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -130,8 +117,8 @@ def test_transmit_200_customer_sdkstats_track_successful_items(self, track_succe self.assertEqual(result, ExportResult.SUCCESS) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_206_customer_sdkstats_track_retry_items(self, track_retry_mock): - """Test that _track_retry_items is called on 206 partial success with retryable errors""" + def test_transmit_206_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + # Test that _track_retry_items is called on 206 partial success with retryable errors exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track") as track_mock: track_mock.return_value = TrackResponse( @@ -148,8 +135,8 @@ def test_transmit_206_customer_sdkstats_track_retry_items(self, track_retry_mock self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_206_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that _track_dropped_items is called on 206 partial success with non-retryable errors""" + def test_transmit_206_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that _track_dropped_items is called on 206 partial success with non-retryable errors exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track") as track_mock: track_mock.return_value = TrackResponse( @@ -165,8 +152,8 @@ def test_transmit_206_customer_sdkstats_track_dropped_items(self, track_dropped_ self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_retryable_http_error_customer_sdkstats_track_retry_items(self, track_retry_mock): - """Test that _track_retry_items is called on retryable HTTP errors (e.g., 408, 502, 503, 504)""" + def test_transmit_retryable_http_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + # Test that _track_retry_items is called on retryable HTTP errors (e.g., 408, 502, 503, 504) exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch("requests.Session.request") as request_mock: request_mock.return_value = MockResponse(408, "{}") @@ -176,8 +163,8 @@ def test_transmit_retryable_http_error_customer_sdkstats_track_retry_items(self, self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_throttle_http_error_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that _track_dropped_items is called on throttle HTTP errors (e.g., 402, 439)""" + def test_transmit_throttle_http_error_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that _track_dropped_items is called on throttle HTTP errors (e.g., 402, 439) exporter = self._create_exporter_with_customer_sdkstats_enabled() # Verify that _should_collect_customer_sdkstats is properly patched @@ -194,8 +181,8 @@ def test_transmit_throttle_http_error_customer_sdkstats_track_dropped_items(self self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_invalid_http_error_customer_sdkstats_track_dropped_items_and_shutdown(self, track_dropped_mock): - """Test that _track_dropped_items is called and customer sdkstats is shutdown on invalid HTTP errors (e.g., 400)""" + def test_transmit_invalid_http_error_customer_sdkstats_track_dropped_items_and_shutdown(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that _track_dropped_items is called and customer sdkstats is shutdown on invalid HTTP errors (e.g., 400) exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch("requests.Session.request") as request_mock, mock.patch( "azure.monitor.opentelemetry.exporter.statsbeat.customer.shutdown_customer_sdkstats_metrics" @@ -207,9 +194,9 @@ def test_transmit_invalid_http_error_customer_sdkstats_track_dropped_items_and_s shutdown_mock.assert_called_once() self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) - @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_service_request_error_customer_sdkstats_track_retry_items(self, track_retry_mock): - """Test that _track_retry_items is called on ServiceRequestError""" + @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") # pylint: disable=line-too-long + def test_transmit_service_request_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + # Test that _track_retry_items is called on ServiceRequestError exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track", side_effect=ServiceRequestError("Connection error")): result = exporter._transmit(self._envelopes_to_export) @@ -218,8 +205,8 @@ def test_transmit_service_request_error_customer_sdkstats_track_retry_items(self self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_general_exception_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that _track_dropped_items is called on general exceptions""" + def test_transmit_general_exception_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that _track_dropped_items is called on general exceptions exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object( AzureMonitorClient, "track", side_effect=Exception(_exception_categories.CLIENT_EXCEPTION.value) @@ -232,8 +219,8 @@ def test_transmit_general_exception_customer_sdkstats_track_dropped_items(self, self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_storage_disabled_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that _track_dropped_items is called when offline storage is disabled and items would be retried""" + def test_transmit_storage_disabled_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that _track_dropped_items is called when offline storage is disabled and items would be retried exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track") as track_mock: track_mock.return_value = TrackResponse( @@ -252,11 +239,9 @@ def test_transmit_storage_disabled_customer_sdkstats_track_dropped_items(self, t @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items_from_storage") - def test_transmit_from_storage_customer_sdkstats_track_dropped_items_from_storage( + def test_transmit_from_storage_customer_sdkstats_track_dropped_items_from_storage( # pylint: disable=name-too-long self, track_dropped_storage_mock, track_dropped_items_mock ): - """Test that _track_dropped_items_from_storage is called during storage operations""" - from azure.monitor.opentelemetry.exporter._storage import StorageExportResult exporter = self._create_exporter_with_customer_sdkstats_enabled(disable_offline_storage=False) @@ -285,7 +270,7 @@ def track_dropped_storage_side_effect(result_from_storage_put, envelopes): # Mock the storage to simulate storage operations - simulate storage error with mock.patch.object( exporter.storage, "put", return_value="storage_error" - ) as put_mock, mock.patch.object(exporter.storage, "gets", return_value=["stored_envelope"]) as gets_mock: + ) as _put_mock, mock.patch.object(exporter.storage, "gets", return_value=["stored_envelope"]) as _gets_mock: # We don't need to mock StorageExportResult anymore result = exporter._transmit(self._envelopes_to_export) @@ -295,8 +280,8 @@ def track_dropped_storage_side_effect(result_from_storage_put, envelopes): self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) # Storage makes it NOT_RETRYABLE @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_redirect_parsing_error_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that track_dropped_items is called on redirect errors with invalid headers/parsing errors""" + def test_transmit_redirect_parsing_error_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that track_dropped_items is called on redirect errors with invalid headers/parsing errors exporter = self._create_exporter_with_customer_sdkstats_enabled() # Simulate a redirect HTTP error using HttpResponseError without proper headers @@ -311,8 +296,8 @@ def test_transmit_redirect_parsing_error_customer_sdkstats_track_dropped_items(s self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_circular_redirect_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that track_dropped_items is called on circular redirect errors""" + def test_transmit_circular_redirect_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that track_dropped_items is called on circular redirect errors exporter = self._create_exporter_with_customer_sdkstats_enabled() # Mock the consecutive redirects counter to simulate exceeding max redirects @@ -330,8 +315,8 @@ def test_transmit_circular_redirect_customer_sdkstats_track_dropped_items(self, self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_403_forbidden_error_customer_sdkstats_track_retry_items(self, track_retry_mock): - """Test that track_retry_items is called on 403 Forbidden HTTP errors""" + def test_transmit_403_forbidden_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + # Test that track_retry_items is called on 403 Forbidden HTTP errors exporter = self._create_exporter_with_customer_sdkstats_enabled() # Simulate a 403 Forbidden HTTP error using HttpResponseError @@ -345,8 +330,8 @@ def test_transmit_403_forbidden_error_customer_sdkstats_track_retry_items(self, self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_401_unauthorized_error_customer_sdkstats_track_retry_items(self, track_retry_mock): - """Test that track_retry_items is called on 401 Unauthorized HTTP errors""" + def test_transmit_401_unauthorized_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + # Test that track_retry_items is called on 401 Unauthorized HTTP errors exporter = self._create_exporter_with_customer_sdkstats_enabled() # Simulate a 401 Unauthorized HTTP error using HttpResponseError @@ -360,8 +345,8 @@ def test_transmit_401_unauthorized_error_customer_sdkstats_track_retry_items(sel self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_redirect_invalid_location_header_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that track_dropped_items is called when redirect has invalid location header""" + def test_transmit_redirect_invalid_location_header_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + # Test that track_dropped_items is called when redirect has invalid location header exporter = self._create_exporter_with_customer_sdkstats_enabled() # Simulate a redirect HTTP error with invalid location header @@ -376,8 +361,8 @@ def test_transmit_redirect_invalid_location_header_customer_sdkstats_track_dropp self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_from_storage_failure_customer_sdkstats_track_dropped_items(self, track_dropped_mock): - """Test that track_dropped_items is called when _transmit_from_storage operations fail""" + def test_transmit_from_storage_failure_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long, unused-argument + # Test that track_dropped_items is called when _transmit_from_storage operations fail exporter = self._create_exporter_with_customer_sdkstats_enabled(disable_offline_storage=False) # Mock storage operations to simulate a successful initial transmit that triggers storage operations 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..ddd804f74c9d 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 @@ -8,8 +8,7 @@ from datetime import datetime from azure.core.exceptions import HttpResponseError, ServiceRequestError -from requests import ReadTimeout -from azure.core.pipeline.transport import HttpResponse +from azure.core.pipeline.transport import HttpResponse # pylint: disable=no-legacy-azure-core-http-response-import from azure.monitor.opentelemetry.exporter.export._base import ( _MONITOR_DOMAIN_MAPPING, _format_storage_telemetry_item, @@ -25,7 +24,6 @@ _STATSBEAT_STATE, ) from azure.monitor.opentelemetry.exporter.export.metrics._exporter import AzureMonitorMetricExporter -from azure.monitor.opentelemetry.exporter.export.trace._exporter import AzureMonitorTraceExporter from azure.monitor.opentelemetry.exporter._constants import ( _DEFAULT_AAD_SCOPE, _REQ_DURATION_NAME, @@ -34,9 +32,6 @@ _REQ_RETRY_NAME, _REQ_SUCCESS_NAME, _REQ_THROTTLE_NAME, - RetryCode, - _UNKNOWN, - _exception_categories, ) from azure.monitor.opentelemetry.exporter._generated import AzureMonitorClient from azure.monitor.opentelemetry.exporter._generated.models import ( @@ -57,6 +52,10 @@ TEST_AUTH_POLICY = "TEST_AUTH_POLICY" TEST_TEMP_DIR = "TEST_TEMP_DIR" TEST_USER_DIR = "test-user" +TEST_CONNECTION_STRING = ( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/" +) def throw(exc_type, *args, **kwargs): @@ -75,7 +74,7 @@ def clean_folder(folder): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) - except Exception as e: + except Exception as e: # pylint: disable=broad-exception-caught print("Failed to delete %s. Reason: %s" % (file_path, e)) @@ -122,7 +121,7 @@ def test_constructor(self): """Test the constructor.""" base = BaseExporter( api_version="2021-02-10_Preview", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=TEST_CONNECTION_STRING, disable_offline_storage=False, distro_version="1.0.0", storage_maintenance_period=30, @@ -154,7 +153,7 @@ def test_constructor_no_storage_directory(self, mock_get_temp_dir): mock_get_temp_dir.return_value = TEST_TEMP_DIR base = BaseExporter( api_version="2021-02-10_Preview", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=TEST_CONNECTION_STRING, disable_offline_storage=False, distro_version="1.0.0", storage_maintenance_period=30, @@ -182,11 +181,11 @@ def test_constructor_no_storage_directory(self, mock_get_temp_dir): self.assertEqual(base._storage_directory, storage_directory) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.tempfile.gettempdir") - def test_constructor_no_storage_directory_and_invalid_instrumentation_key(self, mock_get_temp_dir): + def test_constructor_no_storage_directory_and_invalid_instrumentation_key(self, mock_get_temp_dir): # pylint: disable=name-too-long mock_get_temp_dir.return_value = TEST_TEMP_DIR base = BaseExporter( api_version="2021-02-10_Preview", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=TEST_CONNECTION_STRING, disable_offline_storage=False, distro_version="1.0.0", storage_maintenance_period=30, @@ -215,12 +214,12 @@ def test_constructor_no_storage_directory_and_invalid_instrumentation_key(self, @mock.patch("azure.monitor.opentelemetry.exporter.export._base.getpass.getuser") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.tempfile.gettempdir") - def test_constructor_no_storage_directory_and_invalid_user_details(self, mock_get_temp_dir, mock_get_user): + def test_constructor_no_storage_directory_and_invalid_user_details(self, mock_get_temp_dir, mock_get_user): # pylint: disable=name-too-long mock_get_temp_dir.return_value = TEST_TEMP_DIR mock_get_user.side_effect = OSError("failed to resolve user") base = BaseExporter( api_version="2021-02-10_Preview", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=TEST_CONNECTION_STRING, disable_offline_storage=False, distro_version="1.0.0", storage_maintenance_period=30, @@ -253,7 +252,7 @@ def test_constructor_disable_offline_storage(self, mock_get_temp_dir): mock_get_temp_dir.side_effect = Exception() base = BaseExporter( api_version="2021-02-10_Preview", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=TEST_CONNECTION_STRING, disable_offline_storage=True, distro_version="1.0.0", storage_maintenance_period=30, @@ -279,11 +278,11 @@ def test_constructor_disable_offline_storage(self, mock_get_temp_dir): mock_get_temp_dir.assert_not_called() @mock.patch("azure.monitor.opentelemetry.exporter.export._base.tempfile.gettempdir") - def test_constructor_disable_offline_storage_with_storage_directory(self, mock_get_temp_dir): + def test_constructor_disable_offline_storage_with_storage_directory(self, mock_get_temp_dir): # pylint: disable=name-too-long mock_get_temp_dir.side_effect = Exception() base = BaseExporter( api_version="2021-02-10_Preview", - connection_string="InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com/", + connection_string=TEST_CONNECTION_STRING, disable_offline_storage=True, distro_version="1.0.0", storage_maintenance_period=30, @@ -369,7 +368,7 @@ def test_transmit_from_storage_lease_failure(self): blob_mock.lease.assert_called_once() blob_mock.delete.assert_not_called() - def test_transmit_from_storage_blob_get_returns_none(self): + def test_transmit_from_storage_blob_get_returns_none(self): # pylint: disable=name-too-long """Test that when blob.get() returns None, it's handled properly without TypeError.""" exporter = BaseExporter() exporter.storage = mock.Mock() @@ -392,6 +391,7 @@ def test_transmit_from_storage_blob_get_returns_none(self): transmit_mock.assert_not_called() # No transmission should occur def test_format_storage_telemetry_item(self): + # pylint: disable=too-many-statements time = datetime.now() base = MonitorBase(base_type="", base_data=None) ti = TelemetryItem( @@ -561,7 +561,7 @@ def test_format_storage_telemetry_item(self): self.assertEqual(format_ti.data.base_type, "RequestData") self.assertEqual(req_data.__dict__.items(), format_ti.data.base_data.__dict__.items()) - def test_handle_transmit_from_storage_success_result(self): + def test_handle_transmit_from_storage_success_result(self): # pylint: disable=name-too-long """Test that when storage.put() returns StorageExportResult.LOCAL_FILE_BLOB_SUCCESS, the method continues without any special handling.""" exporter = BaseExporter(disable_offline_storage=False) @@ -577,7 +577,7 @@ def test_handle_transmit_from_storage_success_result(self): # Verify storage.put was called with the serialized envelopes exporter.storage.put.assert_called_once_with(serialized_envelopes) - def test_handle_transmit_from_storage_success_triggers_transmit(self): + def test_handle_transmit_from_storage_success_triggers_transmit(self): # pylint: disable=name-too-long exporter = BaseExporter(disable_offline_storage=False) with mock.patch.object(exporter, "_transmit_from_storage") as mock_transmit_from_storage: @@ -587,7 +587,7 @@ def test_handle_transmit_from_storage_success_triggers_transmit(self): mock_transmit_from_storage.assert_called_once() - def test_handle_transmit_from_storage_no_storage(self): + def test_handle_transmit_from_storage_no_storage(self): # pylint: disable=name-too-long exporter = BaseExporter(disable_offline_storage=True) self.assertIsNone(exporter.storage) @@ -639,7 +639,7 @@ def test_transmit_http_error_redirect(self): self._base.client._config.redirect_policy.max_redirects = prev_redirects self._base.client._config.host = prev_host - def test_transmit_http_error_redirect_missing_headers(self): + def test_transmit_http_error_redirect_missing_headers(self): # pylint: disable=name-too-long response = HttpResponse(None, None) response.status_code = 307 response.headers = None @@ -652,7 +652,7 @@ def test_transmit_http_error_redirect_missing_headers(self): self.assertEqual(post.call_count, 1) self.assertEqual(self._base.client._config.host, prev_host) - def test_transmit_http_error_redirect_invalid_location_header(self): + def test_transmit_http_error_redirect_invalid_location_header(self): # pylint: disable=name-too-long response = HttpResponse(None, None) response.status_code = 307 response.headers = {"location": "123"} @@ -825,7 +825,7 @@ def test_transmit_request_exception(self): }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") - def test_transmit_request_exception_statsbeat(self, stats_mock): + def test_transmit_request_exception_statsbeat(self, stats_mock): # pylint: disable=name-too-long exporter = BaseExporter(disable_offline_storage=True) with mock.patch.object(AzureMonitorClient, "track", throw(Exception)): result = exporter._transmit(self._envelopes_to_export) @@ -1168,7 +1168,7 @@ def test_get_auth_policy_no_credential(self): def test_get_auth_policy_invalid_credential(self): class InvalidTestCredential: - def invalid_get_token(): + def invalid_get_token(self): return "TEST_TOKEN" self.assertRaises( @@ -1177,7 +1177,7 @@ def invalid_get_token(): def test_get_auth_policy_audience(self): class TestCredential: - def get_token(): + def get_token(self): return "TEST_TOKEN" credential = TestCredential() @@ -1196,7 +1196,7 @@ def test_get_authentication_credential_arg(self): @mock.patch.dict("os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "Authorization=AAD"}) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.logger") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_system_assigned(self, mock_managed_identity, mock_logger): + def test_get_authentication_credential_system_assigned(self, mock_managed_identity, mock_logger): # pylint: disable=name-too-long MOCK_MANAGED_IDENTITY_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CREDENTIAL" mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CREDENTIAL result = _get_authentication_credential(foo="bar") @@ -1209,8 +1209,8 @@ def test_get_authentication_credential_system_assigned(self, mock_managed_identi ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.logger") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_client_id(self, mock_managed_identity, mock_logger): - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" + def test_get_authentication_credential_client_id(self, mock_managed_identity, mock_logger): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") mock_logger.assert_not_called() @@ -1222,7 +1222,7 @@ def test_get_authentication_credential_client_id(self, mock_managed_identity, mo ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.logger") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_malformed(self, mock_managed_identity, mock_logger): + def test_get_authentication_credential_malformed(self, mock_managed_identity, mock_logger): # pylint: disable=name-too-long # Even a single malformed pair means Entra ID auth is skipped. MOCK_MANAGED_IDENTITY_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CREDENTIAL" mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CREDENTIAL @@ -1233,8 +1233,8 @@ def test_get_authentication_credential_malformed(self, mock_managed_identity, mo @mock.patch.dict("os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "ClientId=TEST_CLIENT_ID"}) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_no_auth(self, mock_managed_identity): - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" + def test_get_authentication_credential_no_auth(self, mock_managed_identity): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") self.assertIsNone(result) @@ -1244,8 +1244,8 @@ def test_get_authentication_credential_no_auth(self, mock_managed_identity): "os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "Authorization=foobar;ClientId=TEST_CLIENT_ID"} ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_no_aad(self, mock_managed_identity): - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" + def test_get_authentication_credential_no_aad(self, mock_managed_identity): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") self.assertIsNone(result) @@ -1255,8 +1255,8 @@ def test_get_authentication_credential_no_aad(self, mock_managed_identity): "os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "Authorization=AAD;ClientId=TEST_CLIENT_ID"} ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_error(self, mock_managed_identity): - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" + def test_get_authentication_credential_error(self, mock_managed_identity): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL mock_managed_identity.side_effect = ValueError("TEST ERROR") result = _get_authentication_credential(foo="bar") @@ -1283,10 +1283,10 @@ def validate_telemetry_item(item1, item2): class MockResponse: - def __init__(self, status_code, text, headers={}, reason="test", content="{}"): + def __init__(self, status_code, text, headers=None, reason="test", content="{}"): self.status_code = status_code self.text = text - self.headers = headers + self.headers = headers or {} self.reason = reason self.content = content self.raw = MockRaw() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py index 431f7c8533c1..b7a6f56cdc34 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py @@ -17,7 +17,7 @@ def setUp(self): def test_validate_connection_String(self): parser = ConnectionStringParser(connection_string=self._valid_connection_string) - self.assertEqual(parser._connection_string, self._valid_connection_string) + self.assertEqual(parser._connection_string, self._valid_connection_string) # pylint: disable=protected-access def test_invalid_key_empty(self): self.assertRaises(ValueError, lambda: ConnectionStringParser(connection_string="")) @@ -160,7 +160,7 @@ def test_process_options_endpoint_default(self): ) self.assertEqual(parser.endpoint, "https://dc.services.visualstudio.com") - def test_process_options_live_endpoint_code_cs(self): + def test_process_options_live_endpoint_code_cs(self): # pylint: disable=name-too-long os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key ) @@ -170,7 +170,7 @@ def test_process_options_live_endpoint_code_cs(self): self.assertEqual(parser.endpoint, "123") self.assertEqual(parser.live_endpoint, "111") - def test_process_options_live_endpoint_env_cs(self): + def test_process_options_live_endpoint_env_cs(self): # pylint: disable=name-too-long os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "Authorization=ikey;IngestionEndpoint=456;LiveEndpoint=111;InstrumentationKey=" + self._valid_instrumentation_key @@ -181,7 +181,7 @@ def test_process_options_live_endpoint_env_cs(self): self.assertEqual(parser.endpoint, "456") self.assertEqual(parser.live_endpoint, "111") - def test_process_options_live_endpoint_default(self): + def test_process_options_live_endpoint_default(self): # pylint: disable=name-too-long parser = ConnectionStringParser( connection_string=self._valid_connection_string, ) @@ -190,7 +190,7 @@ def test_process_options_live_endpoint_default(self): def test_parse_connection_string_invalid(self): self.assertRaises(ValueError, lambda: ConnectionStringParser(connection_string="asd")) - def test_parse_connection_string_invalid_auth(self): + def test_parse_connection_string_invalid_auth(self): # pylint: disable=name-too-long self.assertRaises( ValueError, lambda: ConnectionStringParser( @@ -205,7 +205,7 @@ def test_parse_connection_string_suffix(self): ) self.assertEqual(parser.endpoint, "https://US.dc.123") - def test_parse_connection_string_suffix_no_location(self): + def test_parse_connection_string_suffix_no_location(self): # pylint: disable=name-too-long parser = ConnectionStringParser( connection_string="Authorization=ikey;EndpointSuffix=123;InstrumentationKey=" + self._valid_instrumentation_key, @@ -213,7 +213,7 @@ def test_parse_connection_string_suffix_no_location(self): self.assertEqual(parser.endpoint, "https://dc.123") # Region extraction tests - def test_region_extraction_from_endpoint_with_number(self): + def test_region_extraction_from_endpoint_with_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL with number suffix.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -222,7 +222,7 @@ def test_region_extraction_from_endpoint_with_number(self): ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_from_endpoint_without_number(self): + def test_region_extraction_from_endpoint_without_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL without number suffix.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -231,7 +231,7 @@ def test_region_extraction_from_endpoint_without_number(self): ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_from_endpoint_two_digit_number(self): + def test_region_extraction_from_endpoint_two_digit_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL with two-digit number.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -240,7 +240,7 @@ def test_region_extraction_from_endpoint_two_digit_number(self): ) self.assertEqual(parser.region, "eastus") - def test_region_extraction_from_endpoint_three_digit_number(self): + def test_region_extraction_from_endpoint_three_digit_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL with three-digit number.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -269,7 +269,7 @@ def test_region_extraction_various_regions(self): ) self.assertEqual(parser.region, expected_region) - def test_region_extraction_no_region_global_endpoint(self): + def test_region_extraction_no_region_global_endpoint(self): # pylint: disable=name-too-long """Test that no region is extracted from global endpoints.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -278,12 +278,12 @@ def test_region_extraction_no_region_global_endpoint(self): ) self.assertIsNone(parser.region) - def test_region_extraction_no_region_default_endpoint(self): + def test_region_extraction_no_region_default_endpoint(self): # pylint: disable=name-too-long """Test that no region is extracted when using default endpoint.""" parser = ConnectionStringParser(connection_string="InstrumentationKey=" + self._valid_instrumentation_key) self.assertIsNone(parser.region) - def test_region_extraction_invalid_endpoint_format(self): + def test_region_extraction_invalid_endpoint_format(self): # pylint: disable=name-too-long """Test that no region is extracted from invalid endpoint formats.""" invalid_endpoints = [ "https://invalid.endpoint.com", @@ -301,7 +301,7 @@ def test_region_extraction_invalid_endpoint_format(self): ) self.assertIsNone(parser.region) - def test_region_extraction_from_environment_endpoint(self): + def test_region_extraction_from_environment_endpoint(self): # pylint: disable=name-too-long """Test region extraction from endpoint set via environment variable.""" os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "InstrumentationKey=" @@ -311,7 +311,7 @@ def test_region_extraction_from_environment_endpoint(self): parser = ConnectionStringParser(connection_string=None) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_code_endpoint_takes_priority(self): + def test_region_extraction_code_endpoint_takes_priority(self): # pylint: disable=name-too-long """Test that endpoint from code connection string takes priority over environment.""" os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "InstrumentationKey=" @@ -325,7 +325,7 @@ def test_region_extraction_code_endpoint_takes_priority(self): ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_with_trailing_slash(self): + def test_region_extraction_with_trailing_slash(self): # pylint: disable=name-too-long """Test region extraction works with and without trailing slash.""" test_cases = [ "https://westeurope-5.in.applicationinsights.azure.com/", @@ -341,7 +341,7 @@ def test_region_extraction_with_trailing_slash(self): ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_alphanumeric_regions(self): + def test_region_extraction_alphanumeric_regions(self): # pylint: disable=name-too-long """Test region extraction for regions with numbers in the name.""" test_cases = [ ("westus2-1.in.applicationinsights.azure.com", "westus2"), diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py index b7a6c56814ab..9fa38601c790 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py @@ -3,7 +3,6 @@ import os import shutil -import tempfile import unittest from unittest import mock @@ -39,11 +38,10 @@ def clean_folder(folder): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) - except Exception as e: + except Exception as e: # pylint: disable=broad-exception-caught print("Failed to delete %s. Reason: %s" % (file_path, e)) -# pylint: disable=no-self-use class TestLocalFileBlob(unittest.TestCase): @classmethod def setup_class(cls): @@ -69,7 +67,7 @@ def test_put_error(self): blob = LocalFileBlob(os.path.join(TEST_FOLDER, "foobar")) with mock.patch("os.rename", side_effect=throw(Exception)): result = blob.put([1, 2, 3]) - # self.assertIsInstance(result, str) + self.assertIsInstance(result, str) @unittest.skip("transient storage") def test_put_success_returns_self(self): @@ -100,7 +98,7 @@ def test_put_rename_error_returns_string(self): self.assertIsInstance(result, str) self.assertIn("File already exists", result) - def test_put_json_serialization_error_returns_string(self): + def test_put_json_serialization_error_returns_string(self): # pylint: disable=name-too-long blob = LocalFileBlob(os.path.join(TEST_FOLDER, "json_error_blob")) import datetime @@ -112,7 +110,7 @@ def test_put_json_serialization_error_returns_string(self): # Should contain JSON serialization error self.assertTrue("not JSON serializable" in result or "Object of type" in result) - def test_put_various_exceptions_return_strings(self): + def test_put_various_exceptions_return_strings(self): # pylint: disable=name-too-long blob = LocalFileBlob(os.path.join(TEST_FOLDER, "various_errors_blob")) test_input = [1, 2, 3] @@ -145,7 +143,7 @@ def test_put_with_lease_period_success(self): self.assertTrue(blob.fullpath.endswith(".lock")) @unittest.skip("transient storage") - def test_put_with_lease_period_error_returns_string(self): + def test_put_with_lease_period_error_returns_string(self): # pylint: disable=name-too-long blob = LocalFileBlob(os.path.join(TEST_FOLDER, "lease_error_blob")) test_input = [1, 2, 3] lease_period = 60 @@ -186,7 +184,7 @@ def test_put_return_type_consistency(self): # Test successful case result_success = blob.put(test_input) - self.assertTrue(isinstance(result_success, StorageExportResult) or isinstance(result_success, str)) + self.assertTrue(isinstance(result_success, (StorageExportResult, str))) # Test error case blob2 = LocalFileBlob(os.path.join(TEST_FOLDER, "consistency_blob2")) @@ -222,7 +220,7 @@ def test_lease_error(self): self.assertEqual(blob.lease(0.01), None) -# pylint: disable=protected-access +# pylint: disable=protected-access, too-many-public-methods class TestLocalFileStorage(unittest.TestCase): @classmethod def tearDownClass(cls): @@ -261,7 +259,7 @@ def test_put(self): with mock.patch("os.rename", side_effect=throw(Exception)): result = stor.put(test_input) # Should return an error string when os.rename fails - # self.assertIsInstance(result, None) + self.assertIsInstance(result, str) def test_put_max_size(self): test_input = (1, 2, 3) @@ -331,7 +329,7 @@ def test_put_storage_disabled_readonly(self): result = stor.put(test_input) self.assertEqual(result, StorageExportResult.CLIENT_READONLY) - def test_put_storage_disabled_with_exception_state(self): + def test_put_storage_disabled_with_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) exception_message = "Previous storage error occurred" with mock.patch( @@ -382,7 +380,7 @@ def test_put_blob_put_failure_returns_string(self): self.assertIsInstance(result, str) self.assertIn("Permission denied", result) - def test_put_exception_in_method_returns_string(self): + def test_put_exception_in_method_returns_string(self): # pylint: disable=name-too-long test_input = (1, 2, 3) with LocalFileStorage(os.path.join(TEST_FOLDER, "method_exception_test")) as stor: with mock.patch( @@ -429,7 +427,7 @@ def test_put_default_lease_period(self): # File should be created with lease (since default lease_period > 0) self.assertEqual(result, StorageExportResult.LOCAL_FILE_BLOB_SUCCESS) - def test_check_and_set_folder_permissions_oserror_sets_exception_state(self): + def test_check_and_set_folder_permissions_oserror_sets_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "OSError: Permission denied creating directory" @@ -461,7 +459,7 @@ def test_check_and_set_folder_permissions_oserror_sets_exception_state(self): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_generic_exception_sets_exception_state(self): + def test_check_and_set_folder_permissions_generic_exception_sets_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "RuntimeError: Unexpected error during setup" @@ -493,7 +491,7 @@ def test_check_and_set_folder_permissions_generic_exception_sets_exception_state # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_readonly_filesystem_sets_readonly_state(self): + def test_check_and_set_folder_permissions_readonly_filesystem_sets_readonly_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -529,7 +527,7 @@ def test_check_and_set_folder_permissions_readonly_filesystem_sets_readonly_stat # Clean up - note: cannot easily reset readonly state, but test isolation should handle this set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_windows_icacls_failure_sets_exception_state(self): + def test_check_and_set_folder_permissions_windows_icacls_failure_sets_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -573,11 +571,10 @@ def test_check_and_set_folder_permissions_windows_icacls_failure_sets_exception_ # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_windows_user_retrieval_failure(self): + def test_check_and_set_folder_permissions_windows_user_retrieval_failure(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( - get_local_storage_setup_state_exception, get_local_storage_setup_state_readonly, set_local_storage_setup_state_exception, ) @@ -608,7 +605,7 @@ def test_check_and_set_folder_permissions_windows_user_retrieval_failure(self): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_unix_chmod_exception_sets_exception_state(self): + def test_check_and_set_folder_permissions_unix_chmod_exception_sets_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "OSError: Operation not permitted" @@ -648,7 +645,7 @@ def test_check_and_set_folder_permissions_unix_chmod_exception_sets_exception_st # Clean up set_local_storage_setup_state_exception("") - def test_exception_state_persistence_across_storage_instances(self): + def test_exception_state_persistence_across_storage_instances(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "Persistent storage setup error" @@ -680,7 +677,7 @@ def test_exception_state_persistence_across_storage_instances(self): # Clean up set_local_storage_setup_state_exception("") - def test_exception_state_cleared_and_storage_recovery(self): + def test_exception_state_cleared_and_storage_recovery(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "Temporary storage setup error" @@ -712,7 +709,7 @@ def test_exception_state_cleared_and_storage_recovery(self): retrieved_data = stor2.get().get() self.assertEqual(retrieved_data, test_input) - def test_local_storage_state_readonly_get_set_operations(self): + def test_local_storage_state_readonly_get_set_operations(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_readonly, set_local_storage_setup_state_readonly, @@ -720,9 +717,6 @@ def test_local_storage_state_readonly_get_set_operations(self): _LOCAL_STORAGE_SETUP_STATE_LOCK, ) - # Save original state - original_readonly_state = _LOCAL_STORAGE_SETUP_STATE["READONLY"] - try: # Test 1: Initial state should be False # Note: Cannot easily reset readonly state, so we'll work with current state @@ -753,7 +747,7 @@ def test_local_storage_state_readonly_get_set_operations(self): # This is by design - once readonly is set, it stays set for the process pass - def test_readonly_state_interaction_with_storage_put_method(self): + def test_readonly_state_interaction_with_storage_put_method(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -791,7 +785,7 @@ def test_storage_put_invalid_return_type(self): f"Expected StorageExportResult or str, got {type(result)}", ) - def test_readonly_state_priority_over_exception_state(self): + def test_readonly_state_priority_over_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_exception_message = "Some storage exception" @@ -840,7 +834,7 @@ def readonly_operations(): time.sleep(0.01) # Small delay to encourage race conditions value = get_local_storage_setup_state_readonly() results.append(value) - except Exception as e: + except Exception as e: # pylint: disable=broad-exception-caught errors.append(str(e)) # Create multiple threads @@ -865,7 +859,7 @@ def readonly_operations(): for result in results: self.assertTrue(result) - def test_readonly_state_persistence_across_storage_instances(self): + def test_readonly_state_persistence_across_storage_instances(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -894,7 +888,7 @@ def test_readonly_state_persistence_across_storage_instances(self): # Verify readonly state is still set self.assertTrue(get_local_storage_setup_state_readonly()) - def test_readonly_state_direct_access_vs_function_access(self): + def test_readonly_state_direct_access_vs_function_access(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_readonly, set_local_storage_setup_state_readonly, @@ -914,15 +908,12 @@ def test_readonly_state_direct_access_vs_function_access(self): self.assertTrue(function_value) self.assertTrue(direct_value) - def test_readonly_state_idempotent_set_operations(self): + def test_readonly_state_idempotent_set_operations(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_readonly, set_local_storage_setup_state_readonly, ) - # Multiple set operations should be idempotent - initial_state = get_local_storage_setup_state_readonly() - for _ in range(5): set_local_storage_setup_state_readonly() self.assertTrue(get_local_storage_setup_state_readonly()) @@ -931,9 +922,8 @@ def test_readonly_state_idempotent_set_operations(self): final_state = get_local_storage_setup_state_readonly() self.assertTrue(final_state) - def test_check_and_set_folder_permissions_unix_multiuser_scenario(self): + def test_check_and_set_folder_permissions_unix_multiuser_scenario(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( - get_local_storage_setup_state_exception, set_local_storage_setup_state_exception, ) @@ -967,7 +957,7 @@ def mock_makedirs(path, mode=0o777, exist_ok=False): self.assertEqual( {(storage_abs_path, "0o700")}, - {(call_path, mode) for call_path, mode in chmod_calls}, + set(chmod_calls), f"Unexpected chmod calls: {chmod_calls}", ) @@ -976,7 +966,7 @@ def mock_makedirs(path, mode=0o777, exist_ok=False): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_unix_multiuser_parent_permission_failure(self): + def test_check_and_set_folder_permissions_unix_multiuser_parent_permission_failure(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_exception, set_local_storage_setup_state_exception, @@ -1007,7 +997,7 @@ def mock_makedirs(path, mode=0o777, exist_ok=False): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_unix_multiuser_storage_permission_failure(self): + def test_check_and_set_folder_permissions_unix_multiuser_storage_permission_failure(self): # pylint: disable=name-too-long test_error_message = "PermissionError: Operation not permitted on storage directory" from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py index e5b8b205d0ad..e4ac641128ff 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py @@ -2,15 +2,14 @@ # Licensed under the MIT License. import datetime -import os import platform import time import unittest +from unittest.mock import patch +from opentelemetry.sdk.resources import Resource from azure.monitor.opentelemetry.exporter import _utils from azure.monitor.opentelemetry.exporter._generated.models import TelemetryItem -from opentelemetry.sdk.resources import Resource -from unittest.mock import patch TEST_AI_DEVICE_ID = "TEST_AI_DEVICE_ID" @@ -30,12 +29,12 @@ TEST_KUBERNETES_SERVICE_HOST = "TEST_KUBERNETES_SERVICE_HOST" TEST_AKS_ARM_NAMESPACE_ID = "TEST_AKS_ARM_NAMESPACE_ID" - +# pylint: disable=protected-access, too-many-public-methods class TestUtils(unittest.TestCase): def setUp(self): self._valid_instrumentation_key = "1234abcd-5678-4efa-8abc-1234567890ab" - def test_filter_custom_properties_truncates_and_drops_invalid_entries(self): + def test_filter_custom_properties_truncates_and_drops_invalid_entries(self): # pylint: disable=name-too-long oversized_value = "v" * 9000 properties = { "valid_key": oversized_value, @@ -98,7 +97,7 @@ def test_populate_part_a_fields(self): self.assertEqual(tags.get("ai.application.ver"), "testApplicationVer") # Default service.name fields should be used when kubernetes values are not present - def test_populate_part_a_fields_unknown_service(self): + def test_populate_part_a_fields_unknown_service(self): # pylint: disable=name-too-long resource = Resource( { "service.name": "unknown_servicefoobar", @@ -222,7 +221,7 @@ def test_populate_part_a_fields_aks_daemon(self): self.assertEqual(tags.get("ai.internal.nodeName"), tags.get("ai.cloud.roleInstance")) # Test that undefined fields are ignored. - def test_populate_part_a_fields_aks_undefined(self): + def test_populate_part_a_fields_aks_undefined(self): # pylint: disable=name-too-long resource = Resource( { "k8s.deployment.name": "", @@ -240,7 +239,7 @@ def test_populate_part_a_fields_aks_undefined(self): self.assertEqual(tags.get("ai.cloud.roleInstance"), "testPodName") self.assertEqual(tags.get("ai.internal.nodeName"), tags.get("ai.cloud.roleInstance")) - def test_populate_part_a_fields_aks_with_service(self): + def test_populate_part_a_fields_aks_with_service(self): # pylint: disable=name-too-long resource = Resource( { "service.name": "testServiceName", @@ -261,7 +260,7 @@ def test_populate_part_a_fields_aks_with_service(self): self.assertEqual(tags.get("ai.internal.nodeName"), tags.get("ai.cloud.roleInstance")) # Default service.name fields should be ignored when kubernetes values are present - def test_populate_part_a_fields_aks_with_unknown_service(self): + def test_populate_part_a_fields_aks_with_unknown_service(self): # pylint: disable=name-too-long resource = Resource( { "service.name": "unknown_servicefoobar", @@ -288,7 +287,7 @@ def test_populate_part_a_fields_aks_with_unknown_service(self): "azure.monitor.opentelemetry.exporter._utils.azure_monitor_context", TEST_AZURE_MONITOR_CONTEXT, ) - def test_create_telemetry_item(self, mock_ns_to_iso_str): + def test_create_telemetry_item(self, _mock_ns_to_iso_str): result = _utils._create_telemetry_item(TEST_TIMESTAMP) expected_tags = dict(TEST_AZURE_MONITOR_CONTEXT) expected = TelemetryItem( @@ -306,7 +305,7 @@ def test_create_telemetry_item(self, mock_ns_to_iso_str): return_value=False, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix(self, _mock_system, _mock_isdir): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "uum_") @@ -318,7 +317,7 @@ def test_get_sdk_version_prefix(self, mock_system, mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_linux(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_linux(self, _mock_system, _mock_isdir): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "ulm_") @@ -330,7 +329,7 @@ def test_get_sdk_version_prefix_linux(self, mock_system, mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_windows(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_windows(self, _mock_system, _mock_isdir): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "uwm_") @@ -339,7 +338,7 @@ def test_get_sdk_version_prefix_windows(self, mock_system, mock_isdir): return_value=True, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_attach(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_attach(self, _mock_system, _mock_isdir): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "uui_") @@ -351,7 +350,7 @@ def test_get_sdk_version_prefix_attach(self, mock_system, mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_attach_linux(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_attach_linux(self, _mock_system, _mock_isdir): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "uli_") @@ -363,7 +362,7 @@ def test_get_sdk_version_prefix_attach_linux(self, mock_system, mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_attach_windows(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_attach_windows(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "uwi_") @@ -376,7 +375,7 @@ def test_get_sdk_version_prefix_attach_windows(self, mock_system, mock_isdir): ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=False) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_app_service(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_app_service(self, _mock_system, _mock_isdir): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "aum_") @@ -390,7 +389,7 @@ def test_get_sdk_version_prefix_app_service(self, mock_system, mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_app_service_linux(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_app_service_linux(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "alm_") @@ -404,7 +403,7 @@ def test_get_sdk_version_prefix_app_service_linux(self, mock_system, mock_isdir) "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_app_service_windows(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_app_service_windows(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "awm_") @@ -415,7 +414,7 @@ def test_get_sdk_version_prefix_app_service_windows(self, mock_system, mock_isdi ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_app_service_attach(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_app_service_attach(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "aui_") @@ -429,7 +428,7 @@ def test_get_sdk_version_prefix_app_service_attach(self, mock_system, mock_isdir "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_app_service_linux_attach(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_app_service_linux_attach(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "ali_") @@ -443,7 +442,7 @@ def test_get_sdk_version_prefix_app_service_linux_attach(self, mock_system, mock "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_app_service_windows_attach(self, mock_system, mock_isdir): + def test_get_sdk_version_prefix_app_service_windows_attach(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "awi_") @@ -458,7 +457,7 @@ def test_get_sdk_version_prefix_app_service_windows_attach(self, mock_system, mo clear=True, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_function(self, mock_system): + def test_get_sdk_version_prefix_function(self, _mock_system): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fum_") @@ -474,7 +473,7 @@ def test_get_sdk_version_prefix_function(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_function_linux(self, mock_system): + def test_get_sdk_version_prefix_function_linux(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "flm_") @@ -490,7 +489,7 @@ def test_get_sdk_version_prefix_function_linux(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_function_windows(self, mock_system): + def test_get_sdk_version_prefix_function_windows(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fwm_") @@ -504,7 +503,7 @@ def test_get_sdk_version_prefix_function_windows(self, mock_system): clear=True, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_function_attach(self, mock_system): + def test_get_sdk_version_prefix_function_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fui_") @@ -521,7 +520,7 @@ def test_get_sdk_version_prefix_function_attach(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_function_linux_attach(self, mock_system): + def test_get_sdk_version_prefix_function_linux_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fli_") @@ -538,7 +537,7 @@ def test_get_sdk_version_prefix_function_linux_attach(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_function_windows_attach(self, mock_system): + def test_get_sdk_version_prefix_function_windows_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fwi_") @@ -552,7 +551,7 @@ def test_get_sdk_version_prefix_function_windows_attach(self, mock_system): clear=True, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_aks(self, mock_system): + def test_get_sdk_version_prefix_aks(self, _mock_system): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kum_") @@ -567,7 +566,7 @@ def test_get_sdk_version_prefix_aks(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_aks_linux(self, mock_system): + def test_get_sdk_version_prefix_aks_linux(self, _mock_system): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "klm_") @@ -582,7 +581,7 @@ def test_get_sdk_version_prefix_aks_linux(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_aks_windows(self, mock_system): + def test_get_sdk_version_prefix_aks_windows(self, _mock_system): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kwm_") @@ -594,7 +593,7 @@ def test_get_sdk_version_prefix_aks_windows(self, mock_system): clear=True, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_aks_attach(self, mock_system): + def test_get_sdk_version_prefix_aks_attach(self, _mock_system): result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kui_") @@ -609,7 +608,7 @@ def test_get_sdk_version_prefix_aks_attach(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_aks_linux_attach(self, mock_system): + def test_get_sdk_version_prefix_aks_linux_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kli_") @@ -624,7 +623,7 @@ def test_get_sdk_version_prefix_aks_linux_attach(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_aks_windows_attach(self, mock_system): + def test_get_sdk_version_prefix_aks_windows_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kwi_") @@ -638,7 +637,7 @@ def test_get_sdk_version_prefix_aks_windows_attach(self, mock_system): "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, ) - def test_attach_enabled(self, mock_isdir): + def test_attach_enabled(self, _mock_isdir): self.assertEqual(_utils._is_attach_enabled(), True) @patch( @@ -649,7 +648,7 @@ def test_attach_enabled(self, mock_isdir): "azure.monitor.opentelemetry.exporter._utils.environ", {"WEBSITE_SITE_NAME": TEST_WEBSITE_SITE_NAME}, ) - def test_attach_app_service_disabled(self, mock_isdir): + def test_attach_app_service_disabled(self, _mock_isdir): self.assertEqual(_utils._is_attach_enabled(), False) @patch( @@ -657,7 +656,7 @@ def test_attach_app_service_disabled(self, mock_isdir): return_value=True, ) @patch.dict("azure.monitor.opentelemetry.exporter._utils.environ", {}, clear=True) - def test_attach_off_app_service_with_agent(self, mock_isdir): + def test_attach_off_app_service_with_agent(self, _mock_isdir): # This is not an expected scenario and just tests the default self.assertFalse(_utils._is_attach_enabled()) @@ -706,11 +705,11 @@ def test_is_synthetic_load_always_on_legacy(self): properties = {"http.user_agent": "Mozilla/5.0 AlwaysOn"} self.assertTrue(_utils._is_synthetic_load(properties)) - def test_is_synthetic_load_always_on_new_convention(self): + def test_is_synthetic_load_always_on_new_convention(self): # pylint: disable=name-too-long properties = {"user_agent.original": "Azure-Load-Testing/1.0 AlwaysOn"} self.assertTrue(_utils._is_synthetic_load(properties)) - def test_is_synthetic_load_always_on_case_sensitive(self): + def test_is_synthetic_load_always_on_case_sensitive(self): # pylint: disable=name-too-long properties = {"http.user_agent": "Mozilla/5.0 alwayson"} self.assertFalse(_utils._is_synthetic_load(properties)) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py index 0e6a6a967f6d..e1f18c5dc21d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py @@ -2,26 +2,24 @@ # Licensed under the MIT License. import random -import sys import threading import time import unittest -from typing import List, Optional +from typing import Optional from unittest.mock import patch, Mock -from opentelemetry.context import Context -from opentelemetry.trace import SpanContext, TraceFlags, set_span_in_context -from opentelemetry.trace.span import NonRecordingSpan +from opentelemetry.trace import SpanContext, TraceFlags from azure.monitor.opentelemetry.exporter.export.trace._rate_limited_sampling import ( Decision, - RateLimitedSamplingPercentage, RateLimitedSampler, SamplingResult, ) from azure.monitor.opentelemetry.exporter._constants import _SAMPLE_RATE_KEY +# pylint: disable=protected-access + def create_parent_span(sampled: bool, sample_rate: Optional[float] = None, is_remote: bool = False): trace_flags = TraceFlags(0x01) if sampled else TraceFlags(0x00) @@ -45,7 +43,7 @@ def create_parent_span(sampled: bool, sample_rate: Optional[float] = None, is_re return mock_span - +# pylint: disable=too-many-public-methods class TestRateLimitedSampler(unittest.TestCase): def setUp(self): # Use a mock for time.time_ns() instead of nano_time_supplier injection @@ -111,7 +109,6 @@ def test_high_volume_sampling(self): num_spans = 500 sampled_count = 0 - import random random.seed(42) trace_ids = [random.getrandbits(128) for _ in range(num_spans)] @@ -147,7 +144,6 @@ def test_rate_adaptation_increasing_load(self): sampled_phase1 = 0 sampled_phase2 = 0 - import random random.seed(123) trace_ids_phase1 = [random.getrandbits(128) for _ in range(phase1_spans)] @@ -272,7 +268,7 @@ def worker(): result = sampler.should_sample(None, i, f"thread-span-{i}") results.append(result) time.sleep(0.001) - except Exception as e: + except Exception as e: # pylint: disable=broad-exception-caught errors.append(e) threads = [threading.Thread(target=worker) for _ in range(5)] @@ -295,7 +291,7 @@ def worker(): self.assertIsInstance(sample_rate, (int, float)) # Test inheriting sampling decision from sampled parent span with sample rate - def test_parent_span_sampled_with_sample_rate(self): + def test_parent_span_sampled_with_sample_rate(self): # pylint: disable=name-too-long sampler = RateLimitedSampler(10.0) parent_span = create_parent_span(sampled=True, sample_rate=75.0, is_remote=False) @@ -311,7 +307,7 @@ def test_parent_span_sampled_with_sample_rate(self): self.assertEqual(result.attributes[_SAMPLE_RATE_KEY], 75.0) # Test inheriting sampling decision from non-sampled parent span with sample rate - def test_parent_span_not_sampled_with_sample_rate(self): + def test_parent_span_not_sampled_with_sample_rate(self): # pylint: disable=name-too-long sampler = RateLimitedSampler(10.0) parent_span = create_parent_span(sampled=False, sample_rate=25.0, is_remote=False) @@ -327,7 +323,7 @@ def test_parent_span_not_sampled_with_sample_rate(self): self.assertEqual(result.attributes[_SAMPLE_RATE_KEY], 0.0) # Test parent span with 100% sample rate maintains decision - def test_parent_span_sampled_with_100_percent_sample_rate(self): + def test_parent_span_sampled_with_100_percent_sample_rate(self): # pylint: disable=name-too-long sampler = RateLimitedSampler(5.0) parent_span = create_parent_span(sampled=True, sample_rate=100.0, is_remote=False) @@ -365,7 +361,7 @@ def test_parent_span_remote_ignored(self): self.assertNotEqual(result.attributes[_SAMPLE_RATE_KEY], 80.0) # Test parent span without sample rate attribute uses local sampling - def test_parent_span_no_sample_rate_attribute(self): + def test_parent_span_no_sample_rate_attribute(self): # pylint: disable=name-too-long sampler = RateLimitedSampler(5.0) parent_span = create_parent_span(sampled=True, sample_rate=None, is_remote=False) @@ -417,7 +413,7 @@ def test_parent_span_invalid_context(self): self.assertIsInstance(sample_rate, (int, float)) # Test sampling behavior when no parent context is provided - def test_no_parent_context_uses_local_sampling(self): + def test_no_parent_context_uses_local_sampling(self): # pylint: disable=name-too-long sampler = RateLimitedSampler(5.0) from azure.monitor.opentelemetry.exporter.export.trace._rate_limited_sampling import _State @@ -434,7 +430,7 @@ def test_no_parent_context_uses_local_sampling(self): self.assertIsInstance(sample_rate, (int, float)) # Test that original span attributes are preserved in sampling result - def test_parent_context_preserves_original_attributes(self): + def test_parent_context_preserves_original_attributes(self): # pylint: disable=name-too-long sampler = RateLimitedSampler(10.0) parent_span = create_parent_span(sampled=True, sample_rate=50.0, is_remote=False) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py index 31cd5b5ac031..a1fa14f2ecc4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py @@ -57,6 +57,7 @@ def func(*_args, **_kwargs): # pylint: disable=import-error # pylint: disable=protected-access # pylint: disable=too-many-lines +# pylint: disable=too-many-public-methods class TestAzureTraceExporter(unittest.TestCase): @classmethod def setUpClass(cls): @@ -362,6 +363,7 @@ def test_span_to_envelope_partA_default(self): envelope.tags.get(ContextTagKeys.AI_CLOUD_ROLE_INSTANCE), ) + # pylint: disable=too-many-statements def test_span_to_envelope_client_http(self): exporter = self._exporter start_time = 1575494316027613500 @@ -830,7 +832,7 @@ def test_span_to_envelope_client_gen_ai(self): self.assertEqual(envelope.data.base_data.target, "az.ai.inference") self.assertEqual(len(envelope.data.base_data.properties), 1) - def test_span_to_envelope_client_internal_gen_ai_type(self): + def test_span_to_envelope_client_internal_gen_ai_type(self): # pylint: disable=name-too-long exporter = self._exporter start_time = 1575494316027613500 end_time = start_time + 1001000000 @@ -853,7 +855,7 @@ def test_span_to_envelope_client_internal_gen_ai_type(self): envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.type, "GenAI | az.ai.inference") - def test_span_to_envelope_client_multiple_types_with_gen_ai(self): + def test_span_to_envelope_client_multiple_types_with_gen_ai(self): # pylint: disable=name-too-long exporter = self._exporter start_time = 1575494316027613500 end_time = start_time + 1001000000 @@ -1129,6 +1131,7 @@ def test_span_envelope_request_azure(self): envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.source, "Test_name//testdest") + # pylint: disable=too-many-statements def test_span_envelope_server_http(self): exporter = self._exporter start_time = 1575494316027613500 @@ -1502,7 +1505,7 @@ def test_span_to_envelope_properties_links(self): json_dict = json.loads(envelope.data.base_data.properties["_MS.links"])[0] self.assertEqual(json_dict["id"], "a6f5d48acb4d31da") - def test_span_to_envelope_properties_std_metrics(self): + def test_span_to_envelope_properties_std_metrics(self): # pylint: disable=name-too-long exporter = self._exporter start_time = 1575494316027613500 end_time = start_time + 1001000000 @@ -1665,7 +1668,7 @@ def test_span_events_to_envelopes_message(self): self.assertEqual(envelope.data.base_data.message, "test event") self.assertEqual(envelope.data.base_type, "MessageData") - def test_span_events_to_envelopes_sample_rate(self): + def test_span_events_to_envelopes_sample_rate(self): # pylint: disable=name-too-long exporter = self._exporter time = 1575494316027613500 @@ -1829,7 +1832,7 @@ def test_check_instrumentation_span(self): _check_instrumentation_span(span) add.assert_called_once_with("test") - def test_check_instrumentation_span_not_instrumentation(self): + def test_check_instrumentation_span_not_instrumentation(self): # pylint: disable=name-too-long span = mock.Mock() span.attributes = {} span.instrumentation_scope.name = "__main__" @@ -1837,7 +1840,7 @@ def test_check_instrumentation_span_not_instrumentation(self): _check_instrumentation_span(span) add.assert_not_called() - def test_check_instrumentation_span_azure_sdk(self): + def test_check_instrumentation_span_azure_sdk(self): # pylint: disable=name-too-long span = mock.Mock() span.attributes = {} span.instrumentation_scope.name = "azure.foo.bar.__init__" @@ -1847,7 +1850,7 @@ def test_check_instrumentation_span_azure_sdk(self): add.assert_called_once_with(_AZURE_SDK_OPENTELEMETRY_NAME) @mock.patch("opentelemetry.trace.get_tracer_provider") - def test_check_instrumentation_span_azure_sdk_otel_span(self, mock_get_tracer_provider): + def test_check_instrumentation_span_azure_sdk_otel_span(self, mock_get_tracer_provider): # pylint: disable=name-too-long mock_get_tracer_provider.return_value = self.get_tracer_provider() with OpenTelemetrySpan() as azure_sdk_span: @@ -1866,7 +1869,7 @@ def test_check_instrumentation_span_azure_sdk_otel_span(self, mock_get_tracer_pr add.assert_called_once_with(_AZURE_AI_SDK_NAME) @mock.patch("opentelemetry.trace.get_tracer_provider") - def test_check_instrumentation_span_azure_sdk_span_impl(self, mock_get_tracer_provider): + def test_check_instrumentation_span_azure_sdk_span_impl(self, mock_get_tracer_provider): #pylint: disable=name-too-long mock_get_tracer_provider.return_value = self.get_tracer_provider() settings.tracing_implementation = "opentelemetry" @@ -1891,7 +1894,7 @@ def test_check_instrumentation_span_azure_sdk_span_impl(self, mock_get_tracer_pr settings.tracing_implementation = None @mock.patch("opentelemetry.trace.get_tracer_provider") - def test_check_instrumentation_span_azure_sdk_get_tracer(self, mock_get_tracer_provider): + def test_check_instrumentation_span_azure_sdk_get_tracer(self, mock_get_tracer_provider): # pylint: disable=name-too-long mock_get_tracer_provider.return_value = self.get_tracer_provider() if not get_azure_sdk_tracer: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace_utils.py index 9fffe9089d21..764f113660a7 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace_utils.py @@ -2,14 +2,13 @@ # Licensed under the MIT License. import unittest -from unittest import mock + +from fixedint import Int32 # pylint: disable=no-name-in-module from azure.monitor.opentelemetry.exporter.export.trace._utils import ( _get_DJB2_sample_score, ) -# fixedint was removed as a source dependency. It is used as a dev requirement to test sample score -from fixedint import Int32 from azure.monitor.opentelemetry.exporter._constants import ( _SAMPLING_HASH, _INT32_MAX, From 14a55fff463d321e73200eeb0fdfe773a7fd2f19 Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Fri, 23 Jan 2026 11:29:00 -0800 Subject: [PATCH 5/7] Fix format errors --- .../exporter/_configuration/__init__.py | 2 +- .../exporter/_configuration/_utils.py | 26 +++++-- .../exporter/_configuration/_worker.py | 4 +- .../_performance_counters/_manager.py | 26 +++++-- .../exporter/_quickpulse/_manager.py | 4 +- .../opentelemetry/exporter/export/_base.py | 12 ++-- .../exporter/statsbeat/_manager.py | 12 +++- .../exporter/statsbeat/_utils.py | 8 ++- .../exporter/statsbeat/customer/_utils.py | 2 +- .../samples/logs/sample_exception.py | 2 +- .../traces/django/sample/example/admin.py | 2 +- .../traces/django/sample/example/models.py | 2 +- .../traces/django/sample/example/tests.py | 2 +- .../samples/traces/sample_fastapi.py | 3 +- .../samples/traces/sample_span_event.py | 2 +- .../tests/configuration/test_manager.py | 15 ++-- .../tests/configuration/test_utils.py | 3 +- .../tests/configuration/test_worker.py | 11 +-- .../test_customer_sdkstats.py | 16 +++-- .../tests/customer_sdk_stats/test_manager.py | 5 +- .../tests/customer_sdk_stats/test_utlities.py | 7 +- .../tests/logs/test_logs.py | 12 ++-- .../tests/logs/test_processor.py | 20 +++--- .../tests/metrics/test_metrics.py | 54 +++++++++------ .../performance_counters/test_constants.py | 8 +-- .../test_performance_counters.py | 24 ++++--- .../performance_counters/test_processor.py | 3 +- .../tests/quickpulse/test_exporter.py | 7 +- .../tests/quickpulse/test_filter.py | 18 ++--- .../tests/quickpulse/test_live_metrics.py | 25 +++++-- .../tests/quickpulse/test_manager.py | 21 +++--- .../tests/quickpulse/test_policy.py | 1 + .../tests/quickpulse/test_processor.py | 1 + .../tests/quickpulse/test_types.py | 1 + .../tests/quickpulse/test_utils.py | 4 +- .../tests/quickpulse/test_validate.py | 4 +- .../tests/statsbeat/test_manager.py | 31 +++++---- .../tests/statsbeat/test_metrics.py | 28 ++++---- .../tests/statsbeat/test_statsbeat.py | 55 +++++++++------ .../tests/test_base_customer_sdkstats.py | 68 ++++++++++++++----- .../tests/test_base_exporter.py | 64 +++++++++++------ .../tests/test_connection_string_parser.py | 34 +++++----- .../tests/test_storage.py | 60 +++++++++------- .../tests/test_utils.py | 49 +++++++------ .../tests/trace/test_rate_limited_sampling.py | 5 +- .../tests/trace/test_trace.py | 24 ++++--- 46 files changed, 495 insertions(+), 292 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py index e0c57ecc020c..999928856779 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/__init__.py @@ -81,7 +81,7 @@ def _notify_callbacks(self, settings: Dict[str, str]): try: cb(settings) except Exception as ex: # pylint: disable=broad-except - logger.warning("Callback failed: %s", ex) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning("Callback failed: %s", ex) # pylint: disable=do-not-log-exceptions-if-not-debug def _is_transient_error(self, response: OneSettingsResponse) -> bool: """Check if the response indicates a transient error. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py index 0267cf0ba1a2..7afc54ba04ab 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py @@ -6,7 +6,7 @@ import logging # mypy: disable-error-code="import-untyped" -import requests # pylint: disable=networking-import-outside-azure-core-transport +import requests # pylint: disable=networking-import-outside-azure-core-transport from azure.monitor.opentelemetry.exporter._constants import ( _ONE_SETTINGS_DEFAULT_REFRESH_INTERVAL_SECONDS, @@ -124,16 +124,24 @@ def make_onesettings_request( return _parse_onesettings_response(result) except requests.exceptions.Timeout as ex: - logger.warning("OneSettings request timed out: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "OneSettings request timed out: %s", str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) except requests.exceptions.RequestException as ex: - logger.warning("Failed to fetch configuration from OneSettings: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to fetch configuration from OneSettings: %s", str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) except json.JSONDecodeError as ex: - logger.warning("Failed to parse OneSettings response: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to parse OneSettings response: %s", str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning("Unexpected error while fetching configuration: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Unexpected error while fetching configuration: %s", str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug return OneSettingsResponse(has_exception=True) @@ -197,9 +205,13 @@ def _parse_onesettings_response(response: requests.Response) -> OneSettingsRespo if settings and settings.get(_ONE_SETTINGS_CHANGE_VERSION_KEY) is not None: version = int(settings.get(_ONE_SETTINGS_CHANGE_VERSION_KEY)) # type: ignore except (UnicodeDecodeError, json.JSONDecodeError) as ex: - logger.warning("Failed to decode OneSettings response content: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to decode OneSettings response content: %s", str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug except ValueError as ex: - logger.warning("Failed to parse OneSettings change version: %s", str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to parse OneSettings change version: %s", str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug elif status_code == 400: logger.warning("Bad request to OneSettings: %s", response.content) elif status_code == 404: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py index aef055535432..deafddf1e06f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py @@ -141,7 +141,9 @@ def _get_configuration(self) -> None: # Capture interval while we have the lock interval = self._refresh_interval except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning("Configuration refresh failed: %s", ex) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Configuration refresh failed: %s", ex + ) # pylint: disable=do-not-log-exceptions-if-not-debug # Use current interval on error interval = self.get_refresh_interval() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py index 3737661e9f29..b3f67d0e605f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py @@ -79,7 +79,9 @@ def _get_process_cpu(options: CallbackOptions) -> Iterable[Observation]: cpu_percent = _PROCESS.cpu_percent(interval=None) yield Observation(cpu_percent, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting process CPU usage: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + _logger.exception( + "Error getting process CPU usage: %s", e + ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0.0, {}) @@ -110,7 +112,9 @@ def _get_process_cpu_normalized(options: CallbackOptions) -> Iterable[Observatio yield Observation(normalized_cpu_percent, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting normalized process CPU usage: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + _logger.exception( + "Error getting normalized process CPU usage: %s", e + ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0.0, {}) @@ -131,7 +135,9 @@ def _get_available_memory(options: CallbackOptions) -> Iterable[Observation]: available_memory = psutil.virtual_memory().available yield Observation(available_memory, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception("Error getting available memory: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + _logger.exception( + "Error getting available memory: %s", e + ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0, {}) @@ -152,7 +158,9 @@ def _get_process_memory(options: CallbackOptions) -> Iterable[Observation]: private_bytes = _PROCESS.memory_info().rss yield Observation(private_bytes, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception("Error getting process memory: %s", e) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + _logger.exception( + "Error getting process memory: %s", e + ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception yield Observation(0, {}) @@ -245,7 +253,7 @@ def _get_processor_time(options: CallbackOptions) -> Iterable[Observation]: _LAST_CPU_TIMES = cpu_times yield Observation(utilization_percentage, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception("Error getting processor time: %s", e) # pylint: disable=do-not-use-logging-exception + _logger.exception("Error getting processor time: %s", e) # pylint: disable=do-not-use-logging-exception yield Observation(0.0, {}) @@ -603,10 +611,14 @@ def __init__(self, meter_provider=None): if metric_class == RequestExecutionTime: self._request_duration_histogram = performance_counter.gauge except Exception as e: # pylint: disable=broad-except - _logger.warning("Failed to initialize performance counter %s: %s", metric_class.NAME[0], e) # pylint: disable=do-not-log-exceptions-if-not-debug + _logger.warning( + "Failed to initialize performance counter %s: %s", metric_class.NAME[0], e + ) # pylint: disable=do-not-log-exceptions-if-not-debug except Exception as e: # pylint: disable=broad-except - _logger.warning("Failed to setup performance counters: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug + _logger.warning( + "Failed to setup performance counters: %s", e + ) # pylint: disable=do-not-log-exceptions-if-not-debug def _record_span(self, span: ReadableSpan) -> None: try: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py index 95fe423a7d44..a2ac444e6787 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py @@ -202,7 +202,9 @@ def _do_initialize(self) -> bool: return True except Exception as e: # pylint: disable=broad-except - _logger.warning("Failed to initialize QuickpulseManager: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug + _logger.warning( + "Failed to initialize QuickpulseManager: %s", e + ) # pylint: disable=do-not-log-exceptions-if-not-debug # Ensure cleanup happens and state is consistent self._cleanup() return False 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 1b822e602f0f..9ad096916c18 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 @@ -200,7 +200,9 @@ def __init__(self, **kwargs: Any) -> None: collect_statsbeat_metrics(self) except Exception as e: # pylint: disable=broad-except - logger.warning("Failed to initialize statsbeat metrics: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to initialize statsbeat metrics: %s", e + ) # pylint: disable=do-not-log-exceptions-if-not-debug # customer sdkstats initialization if self._should_collect_customer_sdkstats(): @@ -439,12 +441,12 @@ def _transmit(self, envelopes: List[TelemetryItem]) -> ExportResult: if self._should_collect_stats(): exc_type = request_error.exc_type - if exc_type is None or exc_type is type(None): # pylint: disable=unidiomatic-typecheck + if exc_type is None or exc_type is type(None): # pylint: disable=unidiomatic-typecheck exc_type = request_error.__class__.__name__ # type: ignore _update_requests_map(_REQ_EXCEPTION_NAME[1], value=exc_type) result = ExportResult.FAILED_RETRYABLE except Exception as ex: - logger.exception( # pylint: disable=do-not-use-logging-exception + logger.exception( # pylint: disable=do-not-use-logging-exception "Envelopes could not be exported and are not retryable: %s.", ex ) @@ -612,11 +614,11 @@ def _get_authentication_credential(**kwargs: Any) -> Optional[ManagedIdentityCre credential = ManagedIdentityCredential() return credential except ValueError as exc: - logger.error( # pylint: disable=do-not-log-exceptions-if-not-debug + logger.error( # pylint: disable=do-not-log-exceptions-if-not-debug "APPLICATIONINSIGHTS_AUTHENTICATION_STRING, %s, has invalid format: %s", auth_string, exc ) except Exception as e: - logger.error( # pylint: disable=do-not-log-exceptions-if-not-debug + logger.error( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to get authentication credential and enable AAD: %s", e ) return None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py index bce536f4c573..e61ff0dfafbd 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py @@ -251,7 +251,9 @@ def _do_initialize(self, config: StatsbeatConfig) -> bool: except Exception as e: # pylint: disable=broad-except # Log the error for debugging - logger.warning("Failed to initialize statsbeat: %s", e) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to initialize statsbeat: %s", e + ) # pylint: disable=do-not-log-exceptions-if-not-debug # Clean up on failure self._cleanup() return False @@ -297,12 +299,16 @@ def _reconfigure(self, new_config: StatsbeatConfig) -> bool: # Force flush before shutdown to ensure data is sent self._meter_provider.force_flush(timeout_millis=5000) except Exception as e: # pylint: disable=broad-except - logger.warning("Failed to flush meter provider during reconfiguration: %s", e) # pylint:disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to flush meter provider during reconfiguration: %s", e + ) # pylint:disable=do-not-log-exceptions-if-not-debug try: self._meter_provider.shutdown(timeout_millis=5000) except Exception as e: # pylint: disable=broad-except - logger.warning("Failed to shutdown meter provider during reconfiguration: %s", e) # pylint:disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Failed to shutdown meter provider during reconfiguration: %s", e + ) # pylint:disable=do-not-log-exceptions-if-not-debug # Reset state but keep initialized=True self._meter_provider = None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py index 70bac7083c9e..49332c8518ee 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py @@ -156,8 +156,12 @@ def _get_connection_string_for_region_from_config(target_region: str, settings: return None return default_connection_string except (ValueError, TypeError, KeyError) as ex: - logger.warning("Error parsing configuration for region '%s': %s", target_region, str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Error parsing configuration for region '%s': %s", target_region, str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug return None except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning("Unexpected error getting stats connection string for region '%s': %s", target_region, str(ex)) # pylint: disable=do-not-log-exceptions-if-not-debug + logger.warning( + "Unexpected error getting stats connection string for region '%s': %s", target_region, str(ex) + ) # pylint: disable=do-not-log-exceptions-if-not-debug return None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py index 16b275e968e0..0d4632c2b62f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/customer/_utils.py @@ -4,7 +4,7 @@ from typing import Optional, List, Tuple, Union, Any # mypy: disable-error-code="import-untyped" -from requests import ReadTimeout, Timeout # pylint: disable=networking-import-outside-azure-core-transport +from requests import ReadTimeout, Timeout # pylint: disable=networking-import-outside-azure-core-transport from azure.core.exceptions import ServiceRequestTimeoutError from azure.monitor.opentelemetry.exporter._constants import ( _REQUEST, diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py index 81557a9c3a25..4dfd7bc05635 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/logs/sample_exception.py @@ -35,7 +35,7 @@ val = 1 / 0 print(val) except ZeroDivisionError: - logger.exception("Error: Division by zero") # pylint: disable=do-not-use-logging-exception + logger.exception("Error: Division by zero") # pylint: disable=do-not-use-logging-exception try: val = 1 / 0 diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py index 855c2d3b0376..6ff2ff316ff1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/admin.py @@ -1,5 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from django.contrib import admin # pylint: disable=unused-import +from django.contrib import admin # pylint: disable=unused-import # Register your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py index 163c27e604a6..68a9a2a0dec9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/models.py @@ -1,5 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from django.db import models # pylint: disable=unused-import +from django.db import models # pylint: disable=unused-import # Create your models here. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py index 47442e86431c..039bae027b96 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/django/sample/example/tests.py @@ -1,5 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from django.test import TestCase # pylint: disable=unused-import +from django.test import TestCase # pylint: disable=unused-import # Create your tests here. diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py index 924386a2a169..861cf8628fd0 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_fastapi.py @@ -40,7 +40,8 @@ async def test(): # Exceptions that are raised within the request are automatically captured @app.get("/exception") async def exception(): - raise Exception("Hit an exception") # pylint: disable=broad-exception-raised + raise Exception("Hit an exception") # pylint: disable=broad-exception-raised + # Set the OTEL_PYTHON_EXCLUDED_URLS environment variable to "http://127.0.0.1:8000/exclude" # Telemetry from this endpoint will not be captured due to excluded_urls config above diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py index 0f33b9a20b3d..df8c88663a28 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/samples/traces/sample_span_event.py @@ -28,5 +28,5 @@ try: with tracer.start_as_current_span("hello") as span: raise Exception("Custom exception message.") # pylint: disable=broad-exception-raised -except Exception: # pylint: disable=broad-except +except Exception: # pylint: disable=broad-except print("Exception raised") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py index 50fb4feac639..98f225d96f8a 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_manager.py @@ -17,6 +17,7 @@ _ONE_SETTINGS_CONFIG_URL, ) + # pylint: disable=protected-access, docstring-missing-param class TestConfigurationState(unittest.TestCase): """Test cases for _ConfigurationState immutable data class.""" @@ -190,7 +191,9 @@ def test_etag_headers_included(self, _mock_worker_class, mock_request): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_version_increase_triggers_config_fetch(self, _mock_worker_class, mock_request): #pylint: disable=name-too-long + def test_version_increase_triggers_config_fetch( + self, _mock_worker_class, mock_request + ): # pylint: disable=name-too-long """Test that version increase triggers CONFIG endpoint fetch.""" manager = _ConfigurationManager() manager.initialize() @@ -438,7 +441,9 @@ def test_transient_error_http_status_codes(self, mock_logger, _mock_worker_class @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") @patch("azure.monitor.opentelemetry.exporter._configuration.logger") - def test_transient_error_refresh_interval_cap(self, mock_logger, _mock_worker_class, mock_request): # pylint: disable=name-too-long + def test_transient_error_refresh_interval_cap( + self, mock_logger, _mock_worker_class, mock_request + ): # pylint: disable=name-too-long """Test that refresh interval is capped at 24 hours for transient errors.""" manager = _ConfigurationManager() manager.initialize() @@ -494,7 +499,9 @@ def test_non_transient_error_no_backoff(self, _mock_worker_class, mock_request): @patch("azure.monitor.opentelemetry.exporter._configuration.make_onesettings_request") @patch("azure.monitor.opentelemetry.exporter._configuration._worker._ConfigurationWorker") - def test_successful_request_after_transient_error(self, _mock_worker_class, mock_request): # pylint: disable=name-too-long + def test_successful_request_after_transient_error( + self, _mock_worker_class, mock_request + ): # pylint: disable=name-too-long """Test that successful requests don't double refresh interval.""" manager = _ConfigurationManager() manager.initialize() @@ -533,7 +540,7 @@ def test_configuration_manager_enabled(self): self.assertIsNotNone(manager) self.assertIsInstance(manager, _ConfigurationManager) - def test_configuration_manager_enabled_by_default(self): # pylint: disable=name-too-long + def test_configuration_manager_enabled_by_default(self): # pylint: disable=name-too-long """Test that configuration manager is enabled by default when no environment variable is set.""" # Ensure env var is not set diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py index 012dc3db7aec..6431abec049b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_utils.py @@ -3,7 +3,7 @@ import json import unittest from unittest.mock import Mock, patch -import requests # pylint: disable=networking-import-outside-azure-core-transport +import requests # pylint: disable=networking-import-outside-azure-core-transport from azure.monitor.opentelemetry.exporter._configuration._utils import ( _ConfigurationProfile, @@ -21,6 +21,7 @@ _ONE_SETTINGS_CHANGE_VERSION_KEY, ) + # pylint: disable=docstring-missing-param class TestConfigurationProfile(unittest.TestCase): """Test cases for _ConfigurationProfile class.""" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py index ff9b15eba12e..e5e8dfdd06fa 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/configuration/test_worker.py @@ -8,6 +8,7 @@ from azure.monitor.opentelemetry.exporter._configuration._worker import _ConfigurationWorker from azure.monitor.opentelemetry.exporter._constants import _ONE_SETTINGS_PYTHON_TARGETING + # pylint: disable=protected-access, docstring-missing-param class TestConfigurationWorker(unittest.TestCase): """Test cases for _ConfigurationWorker class.""" @@ -17,11 +18,11 @@ def setUp(self): self.mock_configuration_manager = Mock() self.mock_configuration_manager.get_configuration_and_refresh_interval.return_value = 1800 - def tearDown(self): # pylint: disable=docstring-missing-return, docstring-missing-rtype + def tearDown(self): # pylint: disable=docstring-missing-return, docstring-missing-rtype """Clean up after each test.""" # Ensure any workers created during tests are shut down # This prevents hanging tests and resource leaks - pass # pylint: disable=unnecessary-pass + pass # pylint: disable=unnecessary-pass def test_init_with_default_refresh_interval(self): """Test worker initialization with default refresh interval.""" @@ -213,7 +214,7 @@ def test_shutdown_idempotent(self): # Second shutdown should not cause errors try: worker.shutdown() - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: # pylint: disable=broad-exception-caught self.fail(f"Second shutdown raised an exception: {e}") # State should remain shutdown @@ -253,7 +254,7 @@ def shutdown_worker(): try: worker.shutdown() shutdown_results.append("success") - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: # pylint: disable=broad-exception-caught shutdown_results.append(f"error: {e}") threads = [threading.Thread(target=shutdown_worker) for _ in range(5)] @@ -346,7 +347,7 @@ def test_lock_protects_worker_state(self): finally: worker.shutdown() - def test_refresh_loop_continues_after_exception(self): # pylint: disable=name-too-long + def test_refresh_loop_continues_after_exception(self): # pylint: disable=name-too-long """Test that refresh loop continues after exceptions.""" # First call raises exception, second succeeds self.mock_configuration_manager.get_configuration_and_refresh_interval.side_effect = [ diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py index c05396ad61ae..d24d2aaabe69 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py @@ -42,7 +42,9 @@ def test_collect_customer_sdkstats(self): """Test collecting customer SDK stats initializes the manager.""" # Create a mock exporter mock_exporter = mock.Mock() - mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access + mock_exporter._connection_string = ( + "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access + ) # Collect customer SDK stats collect_customer_sdkstats(mock_exporter) @@ -51,11 +53,13 @@ def test_collect_customer_sdkstats(self): manager = get_customer_stats_manager() self.assertTrue(manager.is_initialized) - def test_collect_customer_sdkstats_multiple_calls(self): # pylint: disable=name-too-long + def test_collect_customer_sdkstats_multiple_calls(self): # pylint: disable=name-too-long """Test that multiple calls to collect_customer_sdkstats don't cause issues.""" # Create a mock exporter mock_exporter = mock.Mock() - mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access + mock_exporter._connection_string = ( + "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access + ) # Call collect multiple times collect_customer_sdkstats(mock_exporter) @@ -79,7 +83,7 @@ def test_shutdown_customer_sdkstats_metrics(self): # Verify shutdown self.assertFalse(manager.is_initialized) - def test_shutdown_customer_sdkstats_metrics_when_not_initialized(self): # pylint: disable=name-too-long + def test_shutdown_customer_sdkstats_metrics_when_not_initialized(self): # pylint: disable=name-too-long """Test shutting down customer SDK stats when not initialized doesn't cause issues.""" # Ensure manager is not initialized manager = get_customer_stats_manager() @@ -96,7 +100,9 @@ def test_collect_and_shutdown_cycle(self): """Test a complete cycle of collect and shutdown operations.""" # Create a mock exporter mock_exporter = mock.Mock() - mock_exporter._connection_string = "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access + mock_exporter._connection_string = ( + "InstrumentationKey=12345678-1234-5678-abcd-12345678abcd" # pylint: disable=protected-access + ) # Collect customer SDK stats collect_customer_sdkstats(mock_exporter) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py index 0e33164a5ee1..c6e2526132d7 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_manager.py @@ -20,6 +20,7 @@ _CustomerSdkStatsTelemetryCounters, ) + # pylint: disable=protected-access, docstring-missing-param # pylint: disable=too-many-public-methods class TestCustomerSdkStatsManager(unittest.TestCase): @@ -45,7 +46,7 @@ def tearDown(self): # Shutdown manager if needed try: self.manager.shutdown() - except: # pylint: disable=bare-except + except: # pylint: disable=bare-except pass # Reset singleton state - only clear CustomerSdkStatsManager instances @@ -267,7 +268,7 @@ def test_count_successful_items(self): self.assertEqual(self.manager._counters.total_item_success_count[_REQUEST], 7) self.assertEqual(self.manager._counters.total_item_success_count[_CUSTOM_EVENT], 3) - def test_count_successful_items_uninitialized(self): # pylint: disable=name-too-long + def test_count_successful_items_uninitialized(self): # pylint: disable=name-too-long """Test that counting successful items does nothing when not initialized.""" self.manager.count_successful_items(5, _REQUEST) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py index 3ba29f61d9f4..f1a817543684 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py @@ -6,7 +6,11 @@ from unittest import mock from datetime import datetime -from requests.exceptions import ConnectionError, ReadTimeout, Timeout # pylint: disable=networking-import-outside-azure-core-transport +from requests.exceptions import ( + ConnectionError, + ReadTimeout, + Timeout, +) # pylint: disable=networking-import-outside-azure-core-transport from azure.core.exceptions import ServiceRequestTimeoutError, HttpResponseError from azure.monitor.opentelemetry.exporter._generated.models import ( @@ -40,6 +44,7 @@ get_customer_stats_manager, ) + # pylint: disable=protected-access, docstring-missing-param, name-too-long, too-many-public-methods class TestCustomerSdkStatsUtils(unittest.TestCase): """Test suite for customer SDK stats utility functions.""" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py index 68de220d4a8e..32382c17d3c8 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_logs.py @@ -486,7 +486,7 @@ def test_log_to_envelope_log_empty(self): self.assertEqual(envelope.data.base_data.message, _DEFAULT_LOG_MESSAGE) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_NAME), "TestOperationName") - def test_log_to_envelope_log_empty_with_whitespaces(self): # pylint: disable=name-too-long + def test_log_to_envelope_log_empty_with_whitespaces(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_empty_with_whitespaces) self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") @@ -504,7 +504,7 @@ def test_log_to_envelope_log_complex_body(self): ) self.assertEqual(envelope.tags.get(ContextTagKeys.AI_OPERATION_NAME), "TestOperationName") - def test_log_to_envelope_log_complex_body_not_serializeable(self): # pylint: disable=name-too-long + def test_log_to_envelope_log_complex_body_not_serializeable(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_complex_body_not_serializeable) self.assertEqual(envelope.name, "Microsoft.ApplicationInsights.Message") @@ -535,7 +535,7 @@ def test_log_to_envelope_exception_with_string_message(self): # pylint: disable ), ) - def test_log_to_envelope_exception_with_exc_message(self): # pylint: disable=name-too-long + def test_log_to_envelope_exception_with_exc_message(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_with_exc_body) record = self._log_data.log_record @@ -571,7 +571,7 @@ def test_log_to_envelope_exception_empty(self): self.assertTrue(envelope.data.base_data.exceptions[0].has_full_stack) self.assertEqual(envelope.data.base_data.exceptions[0].stack, "") - def test_log_to_envelope_exception_with_blank_exception(self): # pylint: disable=name-too-long + def test_log_to_envelope_exception_with_blank_exception(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._exc_data_blank_exception) record = self._log_data.log_record @@ -606,7 +606,7 @@ def test_log_to_envelope_event_complex_body(self): self.assertEqual(envelope.data.base_data.name, json.dumps(record.body)) self.assertEqual(envelope.data.base_data.properties["event_key"], "event_attribute") - def test_log_to_envelope_event_complex_body_not_serializeable(self): # pylint: disable=name-too-long + def test_log_to_envelope_event_complex_body_not_serializeable(self): # pylint: disable=name-too-long exporter = self._exporter envelope = exporter._log_to_envelope(self._log_data_event_complex_body_not_serializeable) record = self._log_data_event_complex_body_not_serializeable.log_record @@ -681,7 +681,7 @@ def test_log_to_envelope_synthetic_source(self): "testServiceInstanceId", ) - def test_log_to_envelope_synthetic_load_always_on(self): # pylint: disable=name-too-long + def test_log_to_envelope_synthetic_load_always_on(self): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create( { diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py index 2b10438a3241..c830385748ad 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/logs/test_processor.py @@ -30,24 +30,24 @@ def setUpClass(cls): os.environ["APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL"] = "true" cls._exporter = AzureMonitorLogExporter() - def test_processor_initialization_without_trace_based_sampling(self): # pylint: disable=name-too-long + def test_processor_initialization_without_trace_based_sampling(self): # pylint: disable=name-too-long """Test processor initialization without trace-based sampling enabled.""" processor = _AzureBatchLogRecordProcessor(self._exporter, options={}) self.assertFalse(processor._enable_trace_based_sampling_for_logs) - def test_processor_initialization_with_trace_based_sampling(self): # pylint: disable=name-too-long + def test_processor_initialization_with_trace_based_sampling(self): # pylint: disable=name-too-long """Test processor initialization with trace-based sampling enabled.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} ) self.assertTrue(processor._enable_trace_based_sampling_for_logs) - def test_processor_initialization_without_options(self): # pylint: disable=name-too-long + def test_processor_initialization_without_options(self): # pylint: disable=name-too-long """Test processor initialization without options.""" processor = _AzureBatchLogRecordProcessor(self._exporter) self.assertIsNone(processor._enable_trace_based_sampling_for_logs) - def test_on_emit_with_trace_based_sampling_disabled(self): # pylint: disable=name-too-long + def test_on_emit_with_trace_based_sampling_disabled(self): # pylint: disable=name-too-long """Test on_emit does not filter logs when trace-based sampling is disabled.""" processor = _AzureBatchLogRecordProcessor(self._exporter, options={}) @@ -84,7 +84,9 @@ def test_on_emit_with_trace_based_sampling_disabled(self): # pylint: disable=nam # Parent on_emit should be called because trace-based sampling is disabled parent_on_emit_mock.assert_called_once() - def test_on_emit_with_trace_based_sampling_enabled_and_unsampled_trace(self): # cspell:disable-line # pylint: disable=name-too-long + def test_on_emit_with_trace_based_sampling_enabled_and_unsampled_trace( + self, + ): # cspell:disable-line # pylint: disable=name-too-long """Test on_emit filters logs when trace-based sampling is enabled and trace is unsampled.""" # cspell:disable-line # pylint: disable=line-too-long processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -126,7 +128,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_unsampled_trace(self): # # Parent on_emit should NOT be called because trace is unsampled and filtering is enabled # cspell:disable-line # pylint: disable=line-too-long parent_on_emit_mock.assert_not_called() - def test_on_emit_with_trace_based_sampling_enabled_and_sampled_trace(self): # pylint: disable=name-too-long + def test_on_emit_with_trace_based_sampling_enabled_and_sampled_trace(self): # pylint: disable=name-too-long """Test on_emit does not filter logs when trace-based sampling is enabled and trace is sampled.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -167,7 +169,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_sampled_trace(self): # py # Parent on_emit should be called because trace is sampled parent_on_emit_mock.assert_called_once() - def test_on_emit_with_trace_based_sampling_enabled_and_invalid_span_context(self): # pylint: disable=name-too-long + def test_on_emit_with_trace_based_sampling_enabled_and_invalid_span_context(self): # pylint: disable=name-too-long """Test on_emit does not filter logs with invalid span context.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -207,7 +209,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_invalid_span_context(self # Parent on_emit should be called because span context is invalid parent_on_emit_mock.assert_called_once() - def test_on_emit_with_trace_based_sampling_enabled_and_no_context(self): # pylint: disable=name-too-long + def test_on_emit_with_trace_based_sampling_enabled_and_no_context(self): # pylint: disable=name-too-long """Test on_emit does not filter logs when there is no log record context.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} @@ -229,7 +231,7 @@ def test_on_emit_with_trace_based_sampling_enabled_and_no_context(self): # pylin # Parent on_emit should be called because there's no context parent_on_emit_mock.assert_called_once() - def test_on_emit_integration_with_multiple_log_records(self): # pylint: disable=name-too-long + def test_on_emit_integration_with_multiple_log_records(self): # pylint: disable=name-too-long """Integration test: verify processor handles multiple log records correctly with trace-based sampling.""" processor = _AzureBatchLogRecordProcessor( self._exporter, options={"enable_trace_based_sampling_for_logs": True} diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py index 0390111acec2..f7ea52aa1f76 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/metrics/test_metrics.py @@ -338,7 +338,7 @@ def test_point_to_envelope_otlp_no_aks(self, _attach_mock, _aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=False ) - def test_point_to_envelope_otlp_aks_no_attach(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_point_to_envelope_otlp_aks_no_attach(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -357,7 +357,7 @@ def test_point_to_envelope_otlp_aks_no_attach(self, _attach_mock, _aks_mock): # @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_aks_attach_no_otlp(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_point_to_envelope_aks_attach_no_otlp(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") @@ -376,7 +376,7 @@ def test_point_to_envelope_aks_attach_no_otlp(self, _attach_mock, _aks_mock): # @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_point_to_envelope_aks_attach_no_endpoint(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_point_to_envelope_aks_attach_no_endpoint(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = self._exporter resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -408,7 +408,7 @@ def test_point_to_envelope_metric_namespace(self): self.assertEqual(envelope.data.base_data.metrics[0].value, 10) self.assertEqual(envelope.data.base_data.metrics[0].count, 1) - def test_point_to_envelope_number_log_analytics_disabled(self): # pylint: disable=name-too-long + def test_point_to_envelope_number_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter_log_analytics_disabled resource = Resource.create(attributes={"asd": "test_resource"}) scope = InstrumentationScope("test_scope") @@ -416,7 +416,7 @@ def test_point_to_envelope_number_log_analytics_disabled(self): # pylint: disabl envelope = exporter._point_to_envelope(point, "test name", resource, scope) self.assertIsNone(envelope) - def test_point_to_envelope_histogram_log_analytics_disabled(self): # pylint: disable=name-too-long + def test_point_to_envelope_histogram_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter_log_analytics_disabled resource = Resource.create(attributes={"asd": "test_resource"}) point = self._histogram_data_point @@ -424,7 +424,9 @@ def test_point_to_envelope_histogram_log_analytics_disabled(self): # pylint: dis self.assertIsNone(envelope) @mock.patch("azure.monitor.opentelemetry.exporter.export.trace._utils._get_target_and_path_for_http_dependency") - def test_point_to_envelope_std_metric_client_duration(self, target_mock): # pylint: disable=name-too-long, too-many-statements + def test_point_to_envelope_std_metric_client_duration( + self, target_mock + ): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter resource = Resource( { @@ -500,7 +502,7 @@ def test_point_to_envelope_std_metric_client_duration(self, target_mock): # pyli self.assertEqual(envelope.data.base_data.metrics[0].name, "http.client.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_server_duration(self): # pylint: disable=name-too-long, too-many-statements + def test_point_to_envelope_std_metric_server_duration(self): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter resource = Resource( { @@ -576,7 +578,7 @@ def test_point_to_envelope_std_metric_server_duration(self): # pylint: disable=n self.assertEqual(envelope.data.base_data.metrics[0].name, "http.server.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_unsupported(self): # pylint: disable=name-too-long + def test_point_to_envelope_std_metric_unsupported(self): # pylint: disable=name-too-long exporter = self._exporter resource = Resource( { @@ -599,7 +601,9 @@ def test_point_to_envelope_std_metric_unsupported(self): # pylint: disable=name- self.assertIsNone(envelope) @mock.patch("azure.monitor.opentelemetry.exporter.export.trace._utils._get_target_and_path_for_http_dependency") - def test_point_to_envelope_std_metric_client_duration_log_analytics_disabled(self, target_mock): # pylint: disable=name-too-long, too-many-statements + def test_point_to_envelope_std_metric_client_duration_log_analytics_disabled( + self, target_mock + ): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter_log_analytics_disabled resource = Resource( { @@ -673,7 +677,9 @@ def test_point_to_envelope_std_metric_client_duration_log_analytics_disabled(sel self.assertEqual(envelope.data.base_data.metrics[0].name, "http.client.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_server_duration_log_analytics_disabled(self): # pylint: disable=name-too-long, too-many-statements + def test_point_to_envelope_std_metric_server_duration_log_analytics_disabled( + self, + ): # pylint: disable=name-too-long, too-many-statements exporter = self._exporter_log_analytics_disabled resource = Resource( { @@ -747,7 +753,7 @@ def test_point_to_envelope_std_metric_server_duration_log_analytics_disabled(sel self.assertEqual(envelope.data.base_data.metrics[0].name, "http.server.request.duration") self.assertEqual(envelope.data.base_data.metrics[0].value, 15.0) - def test_point_to_envelope_std_metric_unsupported_log_analytics_disabled(self): # pylint: disable=name-too-long + def test_point_to_envelope_std_metric_unsupported_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter_log_analytics_disabled resource = Resource( { @@ -769,7 +775,7 @@ def test_point_to_envelope_std_metric_unsupported_log_analytics_disabled(self): envelope = exporter._point_to_envelope(point, "http.server.request.size", resource) self.assertIsNone(envelope) - def test_point_to_envelope_std_metric_log_analytics_disabled(self): # pylint: disable=name-too-long + def test_point_to_envelope_std_metric_log_analytics_disabled(self): # pylint: disable=name-too-long exporter = self._exporter resource = Resource( { @@ -795,7 +801,9 @@ def test_point_to_envelope_std_metric_log_analytics_disabled(self): # pylint: di @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_enabled_default_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_enabled_default_aks( + self, _attach_mock, _aks_mock + ): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -803,7 +811,9 @@ def test_constructor_log_analytics_enabled_default_aks(self, _attach_mock, _aks_ @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_enabled_default_off_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_enabled_default_off_aks( + self, _attach_mock, _aks_mock + ): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -812,7 +822,7 @@ def test_constructor_log_analytics_enabled_default_off_aks(self, _attach_mock, _ @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_enabled_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_enabled_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -821,7 +831,9 @@ def test_constructor_log_analytics_enabled_env_var(self, _attach_mock, _aks_mock @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_disabled_env_var_off_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_disabled_env_var_off_aks( + self, _attach_mock, _aks_mock + ): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() # APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED is currently only specified for AKS Attach self.assertTrue(exporter._metrics_to_log_analytics) @@ -831,7 +843,9 @@ def test_constructor_log_analytics_disabled_env_var_off_aks(self, _attach_mock, @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=False ) - def test_constructor_log_analytics_disabled_env_var_manual_aks(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_disabled_env_var_manual_aks( + self, _attach_mock, _aks_mock + ): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() # APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED is currently only specified for AKS Attach self.assertTrue(exporter._metrics_to_log_analytics) @@ -841,7 +855,7 @@ def test_constructor_log_analytics_disabled_env_var_manual_aks(self, _attach_moc @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_disabled_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_disabled_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertFalse(exporter._metrics_to_log_analytics) @@ -861,7 +875,7 @@ def test_constructor_log_analytics_statsbeat(self, _attach_mock, _aks_mock): @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_invalid_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_invalid_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) @@ -870,7 +884,7 @@ def test_constructor_log_analytics_invalid_env_var(self, _attach_mock, _aks_mock @mock.patch( "azure.monitor.opentelemetry.exporter.export.metrics._exporter._utils._is_attach_enabled", return_value=True ) - def test_constructor_log_analytics_blank_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long + def test_constructor_log_analytics_blank_env_var(self, _attach_mock, _aks_mock): # pylint: disable=name-too-long exporter = AzureMonitorMetricExporter() self.assertTrue(exporter._metrics_to_log_analytics) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py index c9e12122a700..f30a0b683cb2 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_constants.py @@ -129,7 +129,7 @@ def test_all_constants_are_tuples_with_two_elements(self): # pylint: disable=na self.assertIsInstance(constant[0], str) self.assertIsInstance(constant[1], str) - def test_opentelemetry_metric_names_are_unique(self): # pylint: disable=name-too-long + def test_opentelemetry_metric_names_are_unique(self): # pylint: disable=name-too-long """Test that all OpenTelemetry metric names are unique.""" constants = [ _AVAILABLE_MEMORY, @@ -148,14 +148,14 @@ def test_opentelemetry_metric_names_are_unique(self): # pylint: disable=name-too self.assertEqual(len(otel_names), len(unique_names), "Duplicate OpenTelemetry metric names found") - def test_quickpulse_perf_counters_unique_otel(self): # pylint: disable=name-too-long + def test_quickpulse_perf_counters_unique_otel(self): # pylint: disable=name-too-long """Test that all Quickpulse and Performance Counters metric names are unique.""" # Note that the breeze names of Performance Counters and Quickpulse may overlap # as they are sent to different endpoints for perf_counter_otel in _PERFORMANCE_COUNTER_METRIC_NAME_MAPPINGS: self.assertNotIn(perf_counter_otel, _QUICKPULSE_METRIC_NAME_MAPPINGS) - def test_opentelemetry_metric_names_follow_convention(self): # pylint: disable=name-too-long + def test_opentelemetry_metric_names_follow_convention(self): # pylint: disable=name-too-long """Test that all OpenTelemetry metric names follow the expected convention.""" constants = [ _AVAILABLE_MEMORY, @@ -181,7 +181,7 @@ def test_opentelemetry_metric_names_follow_convention(self): # pylint: disable=n # Check that it doesn't end with the prefix (i.e., has additional content) self.assertGreater(len(otel_name), len(expected_prefix), f"Metric name '{otel_name}' is too short") - def test_quickpulse_metric_names_follow_convention(self): # pylint: disable=name-too-long + def test_quickpulse_metric_names_follow_convention(self): # pylint: disable=name-too-long """Test that all Quickpulse metric names follow the expected Windows performance counter convention.""" constants = [ _AVAILABLE_MEMORY, diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py index ef60e2283b70..3c084ecae6cf 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_performance_counters.py @@ -310,7 +310,7 @@ def test_exception_rate_initialization(self): self.assertEqual(counter.NAME[0], "azuremonitor.performancecounter.exceptionssec") self.assertEqual(counter.NAME[1], "\\.NET CLR Exceptions(??APP_CLR_PROC??)\\# of Exceps Thrown / sec") - def test_request_execution_time_initialization(self): # pylint: disable=name-too-long + def test_request_execution_time_initialization(self): # pylint: disable=name-too-long """Test RequestExecutionTime class initialization.""" counter = RequestExecutionTime(self.meter) @@ -334,7 +334,7 @@ def test_process_cpu_initialization(self): self.assertEqual(counter.NAME[0], "azuremonitor.performancecounter.processtime") self.assertEqual(counter.NAME[1], "\\Process(??APP_WIN32_PROC??)\\% Processor Time") - def test_process_cpu_normalized_initialization(self): # pylint: disable=name-too-long + def test_process_cpu_normalized_initialization(self): # pylint: disable=name-too-long """Test ProcessCpuNormalized class initialization.""" counter = ProcessCpuNormalized(self.meter) @@ -350,7 +350,7 @@ def test_process_io_rate_initialization(self): self.assertEqual(counter.NAME[0], "azuremonitor.performancecounter.processiobytessec") self.assertEqual(counter.NAME[1], "\\Process(??APP_WIN32_PROC??)\\IO Data Bytes/sec") - def test_process_private_bytes_initialization(self): # pylint: disable=name-too-long + def test_process_private_bytes_initialization(self): # pylint: disable=name-too-long """Test ProcessPrivateBytes class initialization.""" counter = ProcessPrivateBytes(self.meter) @@ -402,7 +402,7 @@ def test_manager_initialization_success(self, mock_get_meter_provider): @mock.patch("azure.monitor.opentelemetry.exporter._performance_counters._manager._IO_AVAILABLE", False) @mock.patch("azure.monitor.opentelemetry.exporter._performance_counters._manager.metrics.get_meter_provider") - def test_manager_initialization_success_no_io(self, mock_get_meter_provider): # pylint: disable=name-too-long + def test_manager_initialization_success_no_io(self, mock_get_meter_provider): # pylint: disable=name-too-long """Test successful manager initialization.""" mock_meter_provider = MagicMock() mock_meter = MagicMock() @@ -419,7 +419,7 @@ def test_manager_initialization_success_no_io(self, mock_get_meter_provider): # self.assertEqual(len(manager._performance_counters), len(PERFORMANCE_COUNTER_METRICS) - 1) mock_meter_provider.get_meter.assert_called_once() - def test_manager_initialization_with_custom_meter_provider(self): # pylint: disable=name-too-long + def test_manager_initialization_with_custom_meter_provider(self): # pylint: disable=name-too-long """Test manager initialization with custom meter provider.""" mock_meter_provider = MagicMock() mock_meter = MagicMock() @@ -539,7 +539,7 @@ def test_record_span_with_exception(self, mock_get_meter_provider): # Check that exception was counted self.assertEqual(manager_module._EXCEPTIONS_COUNT, initial_exceptions + 1) - def test_record_span_non_server_consumer_kind(self): # pylint: disable=name-too-long + def test_record_span_non_server_consumer_kind(self): # pylint: disable=name-too-long """Test recording span that's not a server/consumer kind.""" manager = _PerformanceCountersManager() @@ -619,7 +619,7 @@ def tearDown(self): if _PerformanceCountersManager in Singleton._instances: del Singleton._instances[_PerformanceCountersManager] - def test_enable_performance_counters_default_provider(self): # pylint: disable=name-too-long + def test_enable_performance_counters_default_provider(self): # pylint: disable=name-too-long """Test enabling performance counters with default provider.""" # Create a proper meter provider for testing meter_provider = MeterProvider() @@ -634,7 +634,7 @@ def test_enable_performance_counters_default_provider(self): # pylint: disable=n # self.assertIsNotNone(_PerformanceCountersManager._instance) self.assertIn(_PerformanceCountersManager, Singleton._instances) - def test_enable_performance_counters_custom_provider(self): # pylint: disable=name-too-long + def test_enable_performance_counters_custom_provider(self): # pylint: disable=name-too-long """Test enabling performance counters with custom provider.""" # Create a proper meter provider for testing meter_provider = MeterProvider() @@ -681,7 +681,7 @@ def test_metric_name_constants(self): self.assertIsInstance(metric_class.NAME[1], str) -class TestPerformanceCountersMetricsIntegration(unittest.TestCase): # pylint: disable=name-too-long +class TestPerformanceCountersMetricsIntegration(unittest.TestCase): # pylint: disable=name-too-long """Test actual metrics generation from performance counters.""" def setUp(self): @@ -699,7 +699,7 @@ def tearDown(self): if _PerformanceCountersManager in Singleton._instances: del Singleton._instances[_PerformanceCountersManager] - def _get_metric_names(self, metrics_data): # pylint: disable=docstring-missing-return, docstring-missing-rtype + def _get_metric_names(self, metrics_data): # pylint: disable=docstring-missing-return, docstring-missing-rtype """Helper to extract metric names from metrics data.""" metric_names = [] for resource_metrics in metrics_data.resource_metrics: @@ -708,7 +708,9 @@ def _get_metric_names(self, metrics_data): # pylint: disable=docstring-missing-r metric_names.append(metric.name) return metric_names - def _get_metric_value(self, metrics_data, metric_name): # pylint: disable=docstring-missing-return, docstring-missing-rtype + def _get_metric_value( + self, metrics_data, metric_name + ): # pylint: disable=docstring-missing-return, docstring-missing-rtype """Helper to extract metric value from metrics data.""" for resource_metrics in metrics_data.resource_metrics: for scope_metrics in resource_metrics.scope_metrics: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py index a215aae241a9..8268e9b2af96 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/performance_counters/test_processor.py @@ -17,8 +17,9 @@ ) from azure.monitor.opentelemetry.exporter._utils import Singleton + # pylint: disable=protected-access, docstring-missing-param -class TestPerformanceCountersLogRecordProcessor(unittest.TestCase): # pylint: disable=name-too-long +class TestPerformanceCountersLogRecordProcessor(unittest.TestCase): # pylint: disable=name-too-long """Test performance counters log record processor.""" def setUp(self): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py index eea2ff064462..5737b517e2a4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_exporter.py @@ -41,6 +41,7 @@ def func(*_args, **_kwargs): return func + # pylint: disable=protected-access class TestQuickpulse(unittest.TestCase): @classmethod @@ -291,7 +292,7 @@ def test_quickpulsereader_ticker_ping_true(self, task_mock, ping_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock): # pylint: disable=name-too-long + def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock): # pylint: disable=name-too-long task_inst_mock = mock.Mock() task_mock.return_value = task_inst_mock reader = _QuickpulseMetricReader( @@ -311,7 +312,7 @@ def test_quickpulsereader_ticker_ping_false_backoff(self, task_mock, ping_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter._ping") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_ticker_erroneous_no_response_backoff(self, task_mock, ping_mock): # pylint: disable=name-too-long + def test_ticker_erroneous_no_response_backoff(self, task_mock, ping_mock): # pylint: disable=name-too-long _set_global_quickpulse_state(_QuickpulseState.PING_SHORT) _set_quickpulse_etag("old-etag") task_inst_mock = mock.Mock() @@ -383,7 +384,7 @@ def test_quickpulsereader_receive_metrics(self, task_mock, export_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter._QuickpulseExporter.export") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._exporter.PeriodicTask") - def test_quickpulsereader_receive_metrics_exception(self, task_mock, export_mock): # pylint: disable=name-too-long + def test_quickpulsereader_receive_metrics_exception(self, task_mock, export_mock): # pylint: disable=name-too-long task_inst_mock = mock.Mock() task_mock.return_value = task_inst_mock reader = _QuickpulseMetricReader( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py index 2d81afd8ab96..26495128771f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_filter.py @@ -69,7 +69,7 @@ def test_parse_metric_filter_configuration( @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._rename_exception_fields_for_filtering") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._validate_derived_metric_info") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter.DerivedMetricInfo") - def test_parse_metric_filter_configuration_invalid( # pylint: disable=name-too-long + def test_parse_metric_filter_configuration_invalid( # pylint: disable=name-too-long self, dict_mock, validate_mock, rename_mock, init_projection_mock, set_metric_info_mock ): test_config_bytes = ( @@ -96,13 +96,13 @@ def test_parse_metric_filter_configuration_invalid( # pylint: disable=name-too-l def test_parse_doc_filter_configuration(self, dict_mock, validate_mock, rename_mock, set_doc_info_mock): test_config_bytes = ( '{"DocumentStreams": [ { "Id": "26a.7cf471b0", "DocumentFilterGroups": [ ' - '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, ' # pylint: disable=line-too-long + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, ' # pylint: disable=line-too-long '{ "FieldName": "Url", "Predicate": "Contains", "Comparand": "privacy" } ] } }, ' - '{ "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, ' # pylint: disable=line-too-long + '{ "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, ' # pylint: disable=line-too-long '{ "TelemetryType": "Exception", "Filters": { "Filters": [] } }, ' '{ "TelemetryType": "Event", "Filters": { "Filters": [] } }, ' '{ "TelemetryType": "Trace", "Filters": { "Filters": [] } }, ' - '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}' # pylint: disable=line-too-long + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}' # pylint: disable=line-too-long ).encode() test_config_dict = json.loads(test_config_bytes.decode()) doc_stream_mock = mock.Mock() @@ -125,16 +125,18 @@ def test_parse_doc_filter_configuration(self, dict_mock, validate_mock, rename_m @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._rename_exception_fields_for_filtering") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter._validate_document_filter_group_info") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._filter.DocumentStreamInfo") - def test_parse_doc_filter_configuration_invalid(self, dict_mock, validate_mock, rename_mock, set_doc_info_mock): # pylint: disable=name-too-long + def test_parse_doc_filter_configuration_invalid( + self, dict_mock, validate_mock, rename_mock, set_doc_info_mock + ): # pylint: disable=name-too-long test_config_bytes = ( '{"DocumentStreams": [ { "Id": "26a.7cf471b0", "DocumentFilterGroups": [ ' - '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, ' # pylint: disable=line-too-long + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" }, ' # pylint: disable=line-too-long '{ "FieldName": "Url", "Predicate": "Contains", "Comparand": "privacy" } ] } }, ' - '{ "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, ' # pylint: disable=line-too-long + '{ "TelemetryType": "Dependency", "Filters": { "Filters": [ { "FieldName": "Success", "Predicate": "Equal", "Comparand": "true" } ] } }, ' # pylint: disable=line-too-long '{ "TelemetryType": "Exception", "Filters": { "Filters": [] } }, ' '{ "TelemetryType": "Event", "Filters": { "Filters": [] } }, ' '{ "TelemetryType": "Trace", "Filters": { "Filters": [] } }, ' - '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}' # pylint: disable=line-too-long + '{ "TelemetryType": "Request", "Filters": { "Filters": [ { "FieldName": "Duration", "Predicate": "LessThan", "Comparand": "0.0:0:0.015" } ] } } ] } ]}' # pylint: disable=line-too-long ).encode() test_config_dict = json.loads(test_config_bytes.decode()) doc_stream_mock = mock.Mock() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py index a4c1abd237f4..48a25fab3b80 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_live_metrics.py @@ -10,6 +10,7 @@ from azure.monitor.opentelemetry.exporter._quickpulse._live_metrics import enable_live_metrics + # pylint: disable=docstring-missing-param class TestLiveMetrics(unittest.TestCase): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @@ -40,7 +41,9 @@ def test_enable_live_metrics_basic(self, manager_mock, statsbeat_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_initialization_fails(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long + def test_enable_live_metrics_initialization_fails( + self, manager_mock, statsbeat_mock + ): # pylint: disable=name-too-long """Test enable_live_metrics when manager initialization fails.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = False @@ -59,7 +62,7 @@ def test_enable_live_metrics_initialization_fails(self, manager_mock, statsbeat_ @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_with_minimal_args(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long + def test_enable_live_metrics_with_minimal_args(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test enable_live_metrics with minimal arguments.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True @@ -78,7 +81,9 @@ def test_enable_live_metrics_with_minimal_args(self, manager_mock, statsbeat_moc @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_with_all_parameters(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long, unused-argument + def test_enable_live_metrics_with_all_parameters( + self, manager_mock, statsbeat_mock + ): # pylint: disable=name-too-long, unused-argument """Test enable_live_metrics with all possible parameters.""" mock_resource = Resource.create( {"service.name": "test-service", "service.version": "1.0.0", "deployment.environment": "test"} @@ -108,7 +113,9 @@ def test_enable_live_metrics_with_all_parameters(self, manager_mock, statsbeat_m @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_with_none_values(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long, unused-argument + def test_enable_live_metrics_with_none_values( + self, manager_mock, statsbeat_mock + ): # pylint: disable=name-too-long, unused-argument """Test enable_live_metrics with None values for optional parameters.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True @@ -124,7 +131,9 @@ def test_enable_live_metrics_with_none_values(self, manager_mock, statsbeat_mock @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_empty_string_connection(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long + def test_enable_live_metrics_empty_string_connection( + self, manager_mock, statsbeat_mock + ): # pylint: disable=name-too-long """Test enable_live_metrics with empty string connection string.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True @@ -143,7 +152,7 @@ def test_enable_live_metrics_empty_string_connection(self, manager_mock, statsbe @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_complex_resource(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long + def test_enable_live_metrics_complex_resource(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long """Test enable_live_metrics with complex resource attributes.""" mock_resource = Resource.create( { @@ -206,7 +215,9 @@ def test_enable_live_metrics_multiple_calls(self, manager_mock, statsbeat_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.set_statsbeat_live_metrics_feature_set") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._live_metrics.get_quickpulse_manager") - def test_enable_live_metrics_kwargs_preservation(self, manager_mock, statsbeat_mock): # pylint: disable=name-too-long + def test_enable_live_metrics_kwargs_preservation( + self, manager_mock, statsbeat_mock + ): # pylint: disable=name-too-long """Test that all kwargs are properly passed through to initialize.""" mock_manager_instance = mock.Mock() mock_manager_instance.initialize.return_value = True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py index f5edc8e30640..b6d01df204d5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_manager.py @@ -65,6 +65,7 @@ _populate_part_a_fields, ) + # pylint: disable=protected-access, docstring-missing-param, too-many-public-methods class TestQuickpulseManager(unittest.TestCase): def setUp(self): @@ -81,7 +82,7 @@ def tearDown(self): @classmethod def setUpClass(cls): _set_global_quickpulse_state(_QuickpulseState.PING_SHORT) - cls.connection_string = "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" # pylint: disable=line-too-long + cls.connection_string = "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ac;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/" # pylint: disable=line-too-long cls.resource = Resource.create( { ResourceAttributes.SERVICE_INSTANCE_ID: "test_instance", @@ -285,7 +286,7 @@ def test_shutdown_not_initialized(self): self.assertFalse(qpm.is_initialized()) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._logger") - def test_shutdown_meter_provider_exception(self, logger_mock): # pylint: disable=unused-argument + def test_shutdown_meter_provider_exception(self, logger_mock): # pylint: disable=unused-argument """Test shutdown handling meter provider exception.""" qpm = _QuickpulseManager() @@ -682,7 +683,9 @@ def test_derive_metrics_from_telemetry_data(self, get_derived_mock, filter_mock, @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._create_projections") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_metric_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_derived_metric_infos") - def test_derive_metrics_from_telemetry_data_filter_false(self, get_derived_mock, filter_mock, projection_mock): # pylint: disable=name-too-long + def test_derive_metrics_from_telemetry_data_filter_false( + self, get_derived_mock, filter_mock, projection_mock + ): # pylint: disable=name-too-long metric_infos = [mock.Mock()] get_derived_mock.return_value = { TelemetryType.DEPENDENCY: metric_infos, @@ -707,7 +710,7 @@ def test_derive_metrics_from_telemetry_data_filter_false(self, get_derived_mock, @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_span_document") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_doc_stream_infos") - def test_apply_doc_filters_from_telemetry_data( # pylint: disable=name-too-long + def test_apply_doc_filters_from_telemetry_data( # pylint: disable=name-too-long self, get_doc_stream_mock, filter_mock, @@ -743,7 +746,7 @@ def test_apply_doc_filters_from_telemetry_data( # pylint: disable=name-too-long @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_span_document") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_doc_stream_infos") - def test_apply_doc_filters_from_telemetry_data_all_streams( # pylint: disable=name-too-long + def test_apply_doc_filters_from_telemetry_data_all_streams( # pylint: disable=name-too-long self, get_doc_stream_mock, filter_mock, @@ -778,7 +781,7 @@ def test_apply_doc_filters_from_telemetry_data_all_streams( # pylint: disable=na @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_span_document") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._check_filters") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._get_quickpulse_doc_stream_infos") - def test_apply_doc_filters_from_telemetry_data_false_filter( # pylint: disable=name-too-long + def test_apply_doc_filters_from_telemetry_data_false_filter( # pylint: disable=name-too-long self, get_doc_stream_mock, filter_mock, @@ -868,7 +871,7 @@ def test_record_span_not_initialized(self, post_state_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._TelemetryData") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._is_post_state") def test_record_span_exception_handling( - self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock # pylint: disable=unused-argument + self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock # pylint: disable=unused-argument ): """Test _record_span exception handling.""" post_state_mock.return_value = True @@ -933,8 +936,8 @@ def test_record_log_record_not_initialized(self, post_state_mock): @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._derive_metrics_from_telemetry_data") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._TelemetryData") @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._manager._is_post_state") - def test_record_log_record_exception_handling( # pylint: disable=name-too-long - self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock # pylint: disable=unused-argument + def test_record_log_record_exception_handling( # pylint: disable=name-too-long + self, post_state_mock, data_mock, metric_derive_mock, doc_mock, logger_mock # pylint: disable=unused-argument ): """Test _record_log_record exception handling.""" post_state_mock.return_value = True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py index cc4ff5636936..c9c43a12ed18 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_policy.py @@ -6,6 +6,7 @@ from azure.monitor.opentelemetry.exporter._quickpulse._policy import _QuickpulseRedirectPolicy + # pylint: disable=protected-access class TestQuickpulseRedirectPolicy(unittest.TestCase): def test_get_redirect_location(self): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py index 3345c067dc1c..ead5746a562b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_processor.py @@ -9,6 +9,7 @@ ) from azure.monitor.opentelemetry.exporter._quickpulse._manager import _QuickpulseManager + # pylint: disable=protected-access class TestQuickpulseLogRecordProcessor(unittest.TestCase): @classmethod diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py index f7dc34709e9b..27eedbeb116e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_types.py @@ -23,6 +23,7 @@ _TelemetryData, ) + # pylint: disable=protected-access class TestTelemetryData(unittest.TestCase): @patch("azure.monitor.opentelemetry.exporter._quickpulse._types._RequestData") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py index aee760164dc4..34b670789de5 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_utils.py @@ -116,7 +116,7 @@ def test_metric_to_qp_data_point_num(self, datetime_mock): self.assertEqual(mdp.documents, documents) @mock.patch("azure.monitor.opentelemetry.exporter._quickpulse._utils._get_metrics_from_projections") - def test_metric_to_qp_data_point_process_filtered_metrics(self, projection_mock): # pylint: disable=name-too-long + def test_metric_to_qp_data_point_process_filtered_metrics(self, projection_mock): # pylint: disable=name-too-long metric_data = mock.Mock() metric_data.resource_metrics = [] projections = [("ID:1234", 5.0)] @@ -206,7 +206,7 @@ def test_get_metrics_from_projections(self, projection_map_mock): ], ) - def test_valid_time_stamp_with_decimal_seconds(self): # pylint: disable=name-too-long + def test_valid_time_stamp_with_decimal_seconds(self): # pylint: disable=name-too-long time_stamp = "14.6:56:7.89" expected_ms = 1234567890 # Expected milliseconds self.assertEqual(_filter_time_stamp_to_ms(time_stamp), expected_ms) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py index 9d04f983fc58..fc2caf3a5c14 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/quickpulse/test_validate.py @@ -13,12 +13,12 @@ def test_valid_telemetry_type(self): valid_metric_info = mock.Mock(telemetry_type="Request", projection=None, filter_groups=[]) self.assertTrue(_validate_derived_metric_info(valid_metric_info)) - def test_validate_info_invalid_telemetry_type(self): # pylint: disable=name-too-long + def test_validate_info_invalid_telemetry_type(self): # pylint: disable=name-too-long invalid_metric_info = mock.Mock(telemetry_type="Request", projection=None, filter_groups=[]) invalid_metric_info.telemetry_type = "INVALID_TYPE" self.assertFalse(_validate_derived_metric_info(invalid_metric_info)) - def test_validate_info_custom_metric_projection(self): # pylint: disable=name-too-long + def test_validate_info_custom_metric_projection(self): # pylint: disable=name-too-long valid_metric_info = mock.Mock(telemetry_type="Request", projection=None, filter_groups=[]) valid_metric_info.telemetry_type = "Request" valid_metric_info.projection = "CustomMetrics.MyMetric" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py index 127db95fbce3..05a6f2c34df4 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py @@ -17,6 +17,7 @@ # cSpell:disable # pylint: disable=protected-access, docstring-missing-param + class TestStatsbeatConfig(unittest.TestCase): def setUp(self): os.environ.pop(_APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL, None) @@ -67,7 +68,7 @@ def test_init_with_all_parameters(self): ) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager._get_stats_connection_string") - def test_init_invalid_connection_string_fallback(self, mock_get_stats_cs): # pylint: disable=name-too-long + def test_init_invalid_connection_string_fallback(self, mock_get_stats_cs): # pylint: disable=name-too-long """Test that invalid connection string falls back to default.""" mock_get_stats_cs.return_value = "InstrumentationKey=fallback;IngestionEndpoint=https://fallback.com/" @@ -104,7 +105,7 @@ def test_from_exporter_valid(self): self.assertIsNotNone(config.credential) self.assertEqual(config.distro_version, "1.0.0") - def test_from_exporter_missing_instrumentation_key(self): # pylint: disable=name-too-long + def test_from_exporter_missing_instrumentation_key(self): # pylint: disable=name-too-long """Test creating config from exporter missing instrumentation key.""" exporter = mock.Mock() exporter._endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -172,7 +173,7 @@ def test_from_config_valid(self, mock_get_cs_for_region): ) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager._get_connection_string_for_region_from_config") - def test_from_config_fallback_connection_string(self, mock_get_cs_for_region): # pylint: disable=name-too-long + def test_from_config_fallback_connection_string(self, mock_get_cs_for_region): # pylint: disable=name-too-long """Test that from_config falls back to base config connection string when needed.""" mock_get_cs_for_region.return_value = None @@ -191,7 +192,7 @@ def test_from_config_fallback_connection_string(self, mock_get_cs_for_region): # if new_config: self.assertEqual(new_config.connection_string, base_config.connection_string) - def test_from_config_missing_instrumentation_key(self): # pylint: disable=name-too-long + def test_from_config_missing_instrumentation_key(self): # pylint: disable=name-too-long """Test from_config with missing instrumentation key.""" base_config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", region="westus", instrumentation_key="" @@ -286,14 +287,14 @@ def tearDown(self): try: if hasattr(self, "manager"): self.manager.shutdown() - except Exception: # pylint: disable=broad-exception-caught + except Exception: # pylint: disable=broad-exception-caught pass os.environ.pop(_APPLICATIONINSIGHTS_STATSBEAT_DISABLED_ALL, None) # Reset singleton state - only clear StatsbeatManager instances if StatsbeatManager in StatsbeatManager._instances: del StatsbeatManager._instances[StatsbeatManager] - def _create_valid_config( # pylint: disable=docstring-missing-return, docstring-missing-rtype + def _create_valid_config( # pylint: disable=docstring-missing-return, docstring-missing-rtype self, connection_string=( "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" @@ -324,7 +325,7 @@ def test_validate_config_none(self): """Test _validate_config with None configuration.""" self.assertFalse(StatsbeatManager._validate_config(None)) # type: ignore - def test_validate_config_missing_instrumentation_key(self): # pylint: disable=name-too-long + def test_validate_config_missing_instrumentation_key(self): # pylint: disable=name-too-long """Test _validate_config with missing instrumentation key.""" config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", region="westus", instrumentation_key="" @@ -343,7 +344,7 @@ def test_validate_config_missing_region(self): ) self.assertFalse(StatsbeatManager._validate_config(config)) - def test_validate_config_missing_connection_string(self): # pylint: disable=name-too-long + def test_validate_config_missing_connection_string(self): # pylint: disable=name-too-long """Test _validate_config with missing connection string.""" config = StatsbeatConfig( endpoint="https://westus-1.in.applicationinsights.azure.com/", @@ -424,7 +425,11 @@ def test_initialize_success( @patch("azure.monitor.opentelemetry.exporter.export.metrics._exporter.AzureMonitorMetricExporter") @patch("azure.monitor.opentelemetry.exporter.statsbeat._state.is_statsbeat_enabled") def test_initialize_failure_exception( - self, mock_is_enabled, mock_exporter_class, mock_reader_class, mock_meter_provider_class # pylint: disable=unused-argument + self, + mock_is_enabled, + mock_exporter_class, + mock_reader_class, + mock_meter_provider_class, # pylint: disable=unused-argument ): """Test initialization failure due to exception.""" mock_is_enabled.return_value = True @@ -438,7 +443,7 @@ def test_initialize_failure_exception( self.assertFalse(self.manager._initialized) @patch("azure.monitor.opentelemetry.exporter.statsbeat._state.is_statsbeat_enabled") - def test_initialize_already_initialized_same_config(self, mock_is_enabled): # pylint: disable=name-too-long + def test_initialize_already_initialized_same_config(self, mock_is_enabled): # pylint: disable=name-too-long """Test initialize when already initialized with same config.""" mock_is_enabled.return_value = True config = self._create_valid_config() @@ -452,7 +457,7 @@ def test_initialize_already_initialized_same_config(self, mock_is_enabled): # py self.assertTrue(result) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.is_statsbeat_enabled") - def test_initialize_already_initialized_different_config_cs(self, mock_is_enabled): # pylint: disable=name-too-long + def test_initialize_already_initialized_different_config_cs(self, mock_is_enabled): # pylint: disable=name-too-long """Test initialize when already initialized with different config.""" mock_is_enabled.return_value = True @@ -479,7 +484,9 @@ def test_initialize_already_initialized_different_config_cs(self, mock_is_enable mock_reconfigure.assert_called_once_with(new_config) @patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.is_statsbeat_enabled") - def test_initialize_already_initialized_different_config_storage(self, mock_is_enabled): # pylint: disable=name-too-long + def test_initialize_already_initialized_different_config_storage( + self, mock_is_enabled + ): # pylint: disable=name-too-long """Test initialize when already initialized with different config.""" mock_is_enabled.return_value = True diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py index 518fe92489cb..f171f53ff960 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_metrics.py @@ -6,7 +6,7 @@ import sys import unittest from unittest import mock -import requests # pylint: disable=networking-import-outside-azure-core-transport +import requests # pylint: disable=networking-import-outside-azure-core-transport from opentelemetry.sdk.metrics import Meter, MeterProvider, ObservableGauge @@ -127,7 +127,7 @@ def test_statsbeat_metric_init(self): self.assertEqual(metric._feature_metric.name, _FEATURE_METRIC_NAME[0]) @mock.patch("azure.monitor.opentelemetry.exporter._utils._is_attach_enabled") - def test_statsbeat_metric_init_attach_enabled(self, attach_mock): # pylint: disable=name-too-long + def test_statsbeat_metric_init_attach_enabled(self, attach_mock): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -180,7 +180,7 @@ def test_get_attach_metric_meet_threshold(self): self.assertEqual(metric._long_interval_count_map[_ATTACH_METRIC_NAME[0]], 0) # pylint: disable=protected-access - def test_get_attach_metric_does_not_meet_threshold(self): # pylint: disable=name-too-long + def test_get_attach_metric_does_not_meet_threshold(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -206,7 +206,7 @@ def test_get_attach_metric_does_not_meet_threshold(self): # pylint: disable=name }, ) @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long return_value=False, ) def test_get_attach_metric_appsvc(self, _metadata_mock): @@ -231,7 +231,7 @@ def test_get_attach_metric_appsvc(self, _metadata_mock): }, ) @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long return_value=False, ) def test_get_attach_metric_functions(self, _metadata_mock): @@ -283,7 +283,7 @@ def test_get_attach_metric_aks_manual(self): self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["rp"], _RP_Names.AKS.value) @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long ) def test_get_attach_metric_vm(self, metadata_mock): mp = MeterProvider() @@ -318,7 +318,7 @@ def test_get_attach_metric_vm(self, metadata_mock): self.assertEqual(_StatsbeatMetrics._COMMON_ATTRIBUTES["os"], "test_os") @mock.patch( - "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long + "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics._StatsbeatMetrics._get_azure_compute_metadata", # pylint: disable=line-too-long return_value=False, ) def test_get_attach_metric_vm_no_os(self, metadata_mock): @@ -406,7 +406,7 @@ def test_get_azure_compute_metadata_not_vm(self): self.assertEqual(len(metric._vm_data), 0) self.assertFalse(metric._vm_retry) - def test_get_azure_compute_metadata_not_vm_timeout(self): # pylint: disable=name-too-long + def test_get_azure_compute_metadata_not_vm_timeout(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -461,7 +461,7 @@ def test_get_feature_metric_meet_threshold(self): self.assertEqual(metric._long_interval_count_map[_FEATURE_METRIC_NAME[0]], 0) # pylint: disable=protected-access - def test_get_feature_metric_does_not_meet_threshold(self): # pylint: disable=name-too-long + def test_get_feature_metric_does_not_meet_threshold(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -556,7 +556,7 @@ def test_get_feature_metric_custom_events(self, feature_mock): self.assertEqual(obs.attributes, attributes) # pylint: disable=protected-access - def test_get_feature_metric_custom_events_runtime(self): # pylint: disable=name-too-long + def test_get_feature_metric_custom_events_runtime(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -610,7 +610,7 @@ def test_get_feature_metric_live_metrics(self, feature_mock): self.assertEqual(obs.attributes, attributes) # pylint: disable=protected-access - def test_get_feature_metric_live_metrics_runtime(self): # pylint: disable=name-too-long + def test_get_feature_metric_live_metrics_runtime(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -641,7 +641,7 @@ def test_get_feature_metric_live_metrics_runtime(self): # pylint: disable=name-t @mock.patch( "azure.monitor.opentelemetry.exporter.statsbeat._statsbeat_metrics.get_statsbeat_customer_sdkstats_feature_set" ) - def test_get_feature_metric_customer_sdkstats(self, feature_mock): # pylint: disable=name-too-long + def test_get_feature_metric_customer_sdkstats(self, feature_mock): # pylint: disable=name-too-long feature_mock.return_value = True mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" @@ -664,7 +664,7 @@ def test_get_feature_metric_customer_sdkstats(self, feature_mock): # pylint: dis self.assertEqual(obs.attributes, attributes) # pylint: disable=protected-access - def test_get_feature_metric_customer_sdkstats_runtime(self): # pylint: disable=name-too-long + def test_get_feature_metric_customer_sdkstats_runtime(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" @@ -734,7 +734,7 @@ def test_get_feature_metric_instrumentation(self): self.assertEqual(_StatsbeatMetrics._INSTRUMENTATION_ATTRIBUTES["feature"], 1026) # pylint: disable=protected-access - def test_get_feature_metric_instrumentation_none(self): # pylint: disable=name-too-long + def test_get_feature_metric_instrumentation_none(self): # pylint: disable=name-too-long mp = MeterProvider() ikey = "1aa11111-bbbb-1ccc-8ddd-eeeeffff3334" endpoint = "https://westus-1.in.applicationinsights.azure.com/" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py index e39fd541a13f..15cbc70814d6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py @@ -121,8 +121,13 @@ def test_collect_statsbeat_metrics(self, mock_exporter, mock_reader, mock_meter_ @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_registers_configuration_callback( # pylint: disable=name-too-long - self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager, mock_get_configuration_manager # pylint: disable=docstring-missing-param + def test_collect_statsbeat_metrics_registers_configuration_callback( # pylint: disable=name-too-long + self, + mock_exporter, + mock_reader, + mock_meter_provider, + mock_get_manager, + mock_get_configuration_manager, # pylint: disable=docstring-missing-param ): """Test that collect_statsbeat_metrics registers a configuration callback when initialized successfully.""" # Arrange @@ -168,8 +173,11 @@ def test_collect_statsbeat_metrics_registers_configuration_callback( # pylint: d @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_successful_update( # pylint: disable=name-too-long - self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature # pylint: disable=docstring-missing-param + def test_get_statsbeat_configuration_callback_successful_update( # pylint: disable=name-too-long + self, + mock_statsbeat_config_cls, + mock_get_manager, + mock_evaluate_feature, # pylint: disable=docstring-missing-param ): """Test that configuration callback successfully updates configuration when statsbeat is initialized.""" # Arrange @@ -203,7 +211,7 @@ def test_get_statsbeat_configuration_callback_successful_update( # pylint: disab @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_disable_sdkstats( # pylint: disable=name-too-long + def test_get_statsbeat_configuration_callback_disable_sdkstats( # pylint: disable=name-too-long self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature ): """Test that configuration callback successfully updates configuration when statsbeat is initialized.""" @@ -238,7 +246,7 @@ def test_get_statsbeat_configuration_callback_disable_sdkstats( # pylint: disabl @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_not_initialized( # pylint: disable=name-too-long + def test_get_statsbeat_configuration_callback_not_initialized( # pylint: disable=name-too-long self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature ): """Test that configuration callback handles case when statsbeat is not initialized.""" @@ -263,7 +271,7 @@ def test_get_statsbeat_configuration_callback_not_initialized( # pylint: disable @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.evaluate_feature") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.StatsbeatConfig") - def test_get_statsbeat_configuration_callback_no_updated_config( # pylint: disable=name-too-long + def test_get_statsbeat_configuration_callback_no_updated_config( # pylint: disable=name-too-long self, mock_statsbeat_config_cls, mock_get_manager, mock_evaluate_feature ): """Test that configuration callback handles case when StatsbeatConfig.from_config returns None.""" @@ -296,8 +304,13 @@ def test_get_statsbeat_configuration_callback_no_updated_config( # pylint: disab @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_no_callback_when_init_fails( # pylint: disable=name-too-long - self, mock_exporter, mock_reader, mock_meter_provider, mock_statsbeat_metrics, mock_config_manager_cls # pylint: disable=unused-argument + def test_collect_statsbeat_metrics_no_callback_when_init_fails( # pylint: disable=name-too-long + self, + mock_exporter, + mock_reader, + mock_meter_provider, + mock_statsbeat_metrics, + mock_config_manager_cls, # pylint: disable=unused-argument ): """Test that configuration callback is not registered when initialization fails.""" # Arrange @@ -331,7 +344,7 @@ def test_collect_statsbeat_metrics_no_callback_when_init_fails( # pylint: disabl def test_collect_statsbeat_metrics_exists( self, mock_exporter, mock_reader, mock_meter_provider, mock_statsbeat_metrics, mock_get_manager ): - """Test that collect_statsbeat_metrics reuses existing configuration when called multiple times with same config.""" # pylint: disable=line-too-long + """Test that collect_statsbeat_metrics reuses existing configuration when called multiple times with same config.""" # pylint: disable=line-too-long # Arrange exporter = mock.Mock() exporter._endpoint = "test endpoint" @@ -434,7 +447,7 @@ def test_collect_statsbeat_metrics_non_eu(self, mock_exporter, mock_reader, mock call_args = mock_exporter.call_args # The connection string should be the non-EU default since the endpoint is non-EU expected_connection_string = call_args[1]["connection_string"] - self.assertIn(_DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(';', maxsplit=1)[0], expected_connection_string) + self.assertIn(_DEFAULT_NON_EU_STATS_CONNECTION_STRING.split(";", maxsplit=1)[0], expected_connection_string) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @@ -484,13 +497,15 @@ def test_collect_statsbeat_metrics_eu(self, mock_exporter, mock_reader, mock_met call_args = mock_exporter.call_args # The connection string should be the EU default since the endpoint is EU expected_connection_string = call_args[1]["connection_string"] - self.assertIn(_DEFAULT_EU_STATS_CONNECTION_STRING.split(';', maxsplit=1)[0], expected_connection_string) + self.assertIn(_DEFAULT_EU_STATS_CONNECTION_STRING.split(";", maxsplit=1)[0], expected_connection_string) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_aad(self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager): # pylint: disable=unused-argument + def test_collect_statsbeat_metrics_aad( + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager + ): # pylint: disable=unused-argument """Test collect_statsbeat_metrics with AAD credentials.""" # Arrange exporter = mock.Mock() @@ -520,7 +535,9 @@ def test_collect_statsbeat_metrics_aad(self, mock_exporter, mock_reader, mock_me @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_no_aad(self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager): # pylint: disable=line-too-long, unused-argument + def test_collect_statsbeat_metrics_no_aad( + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager + ): # pylint: disable=line-too-long, unused-argument """Test collect_statsbeat_metrics without AAD credentials.""" # Arrange exporter = mock.Mock() @@ -550,8 +567,8 @@ def test_collect_statsbeat_metrics_no_aad(self, mock_exporter, mock_reader, mock @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_distro_version( # pylint: disable=name-too-long - self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager # pylint: disable=unused-argument + def test_collect_statsbeat_metrics_distro_version( # pylint: disable=name-too-long + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager # pylint: disable=unused-argument ): """Test collect_statsbeat_metrics with distribution version.""" # Arrange @@ -582,8 +599,8 @@ def test_collect_statsbeat_metrics_distro_version( # pylint: disable=name-too-lo @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.MeterProvider") @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._manager.PeriodicExportingMetricReader") @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") - def test_collect_statsbeat_metrics_local_storage( # pylint: disable=name-too-long - self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager # pylint: disable=unused-argument + def test_collect_statsbeat_metrics_local_storage( # pylint: disable=name-too-long + self, mock_exporter, mock_reader, mock_meter_provider, mock_get_manager # pylint: disable=unused-argument ): """Test collect_statsbeat_metrics with local storage.""" # Arrange @@ -666,7 +683,7 @@ def test_shutdown_statsbeat_metrics( assert mock_get_manager.call_count == 2 @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.get_statsbeat_manager") - def test_shutdown_statsbeat_metrics_not_initialized(self, mock_get_manager): # pylint: disable=name-too-long + def test_shutdown_statsbeat_metrics_not_initialized(self, mock_get_manager): # pylint: disable=name-too-long """Test shutdown when statsbeat is not initialized.""" # Arrange manager = StatsbeatManager() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py index 042f42de91c0..8e2369f60752 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_base_customer_sdkstats.py @@ -6,7 +6,10 @@ from unittest import mock from datetime import datetime -from azure.core.exceptions import HttpResponseError, ServiceRequestError # pylint: disable=networking-import-outside-azure-core-transport +from azure.core.exceptions import ( + HttpResponseError, + ServiceRequestError, +) # pylint: disable=networking-import-outside-azure-core-transport from azure.monitor.opentelemetry.exporter.export._base import ( BaseExporter, ExportResult, @@ -39,6 +42,7 @@ def __init__(self, status_code, content): self.reason = "Mock Reason" # Add the reason attribute self.url = "http://mock-url.com" # Add the url attribute + # pylint: disable=protected-access class TestBaseExporterCustomerSdkStats(unittest.TestCase): """Test integration between BaseExporter and customer sdkstats tracking functions""" @@ -99,7 +103,9 @@ def _create_exporter_with_customer_sdkstats_enabled(self, disable_offline_storag return exporter @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_successful_items") - def test_transmit_200_customer_sdkstats_track_successful_items(self, track_successful_mock): # pylint: disable=name-too-long + def test_transmit_200_customer_sdkstats_track_successful_items( + self, track_successful_mock + ): # pylint: disable=name-too-long # Test that track_successful_items is called on 200 success response exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -117,7 +123,7 @@ def test_transmit_200_customer_sdkstats_track_successful_items(self, track_succe self.assertEqual(result, ExportResult.SUCCESS) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_206_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + def test_transmit_206_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long # Test that _track_retry_items is called on 206 partial success with retryable errors exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track") as track_mock: @@ -135,7 +141,9 @@ def test_transmit_206_customer_sdkstats_track_retry_items(self, track_retry_mock self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_206_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_206_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that _track_dropped_items is called on 206 partial success with non-retryable errors exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track") as track_mock: @@ -152,7 +160,9 @@ def test_transmit_206_customer_sdkstats_track_dropped_items(self, track_dropped_ self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_retryable_http_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + def test_transmit_retryable_http_error_customer_sdkstats_track_retry_items( + self, track_retry_mock + ): # pylint: disable=name-too-long # Test that _track_retry_items is called on retryable HTTP errors (e.g., 408, 502, 503, 504) exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch("requests.Session.request") as request_mock: @@ -163,7 +173,9 @@ def test_transmit_retryable_http_error_customer_sdkstats_track_retry_items(self, self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_throttle_http_error_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_throttle_http_error_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that _track_dropped_items is called on throttle HTTP errors (e.g., 402, 439) exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -181,7 +193,9 @@ def test_transmit_throttle_http_error_customer_sdkstats_track_dropped_items(self self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_invalid_http_error_customer_sdkstats_track_dropped_items_and_shutdown(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_invalid_http_error_customer_sdkstats_track_dropped_items_and_shutdown( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that _track_dropped_items is called and customer sdkstats is shutdown on invalid HTTP errors (e.g., 400) exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch("requests.Session.request") as request_mock, mock.patch( @@ -194,8 +208,10 @@ def test_transmit_invalid_http_error_customer_sdkstats_track_dropped_items_and_s shutdown_mock.assert_called_once() self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) - @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") # pylint: disable=line-too-long - def test_transmit_service_request_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") # pylint: disable=line-too-long + def test_transmit_service_request_error_customer_sdkstats_track_retry_items( + self, track_retry_mock + ): # pylint: disable=name-too-long # Test that _track_retry_items is called on ServiceRequestError exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track", side_effect=ServiceRequestError("Connection error")): @@ -205,7 +221,9 @@ def test_transmit_service_request_error_customer_sdkstats_track_retry_items(self self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_general_exception_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_general_exception_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that _track_dropped_items is called on general exceptions exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object( @@ -219,7 +237,9 @@ def test_transmit_general_exception_customer_sdkstats_track_dropped_items(self, self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_storage_disabled_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_storage_disabled_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that _track_dropped_items is called when offline storage is disabled and items would be retried exporter = self._create_exporter_with_customer_sdkstats_enabled() with mock.patch.object(AzureMonitorClient, "track") as track_mock: @@ -239,7 +259,7 @@ def test_transmit_storage_disabled_customer_sdkstats_track_dropped_items(self, t @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items_from_storage") - def test_transmit_from_storage_customer_sdkstats_track_dropped_items_from_storage( # pylint: disable=name-too-long + def test_transmit_from_storage_customer_sdkstats_track_dropped_items_from_storage( # pylint: disable=name-too-long self, track_dropped_storage_mock, track_dropped_items_mock ): @@ -280,7 +300,9 @@ def track_dropped_storage_side_effect(result_from_storage_put, envelopes): self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) # Storage makes it NOT_RETRYABLE @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_redirect_parsing_error_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_redirect_parsing_error_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that track_dropped_items is called on redirect errors with invalid headers/parsing errors exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -296,7 +318,9 @@ def test_transmit_redirect_parsing_error_customer_sdkstats_track_dropped_items(s self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_circular_redirect_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_circular_redirect_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that track_dropped_items is called on circular redirect errors exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -315,7 +339,9 @@ def test_transmit_circular_redirect_customer_sdkstats_track_dropped_items(self, self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_403_forbidden_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + def test_transmit_403_forbidden_error_customer_sdkstats_track_retry_items( + self, track_retry_mock + ): # pylint: disable=name-too-long # Test that track_retry_items is called on 403 Forbidden HTTP errors exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -330,7 +356,9 @@ def test_transmit_403_forbidden_error_customer_sdkstats_track_retry_items(self, self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_retry_items") - def test_transmit_401_unauthorized_error_customer_sdkstats_track_retry_items(self, track_retry_mock): # pylint: disable=name-too-long + def test_transmit_401_unauthorized_error_customer_sdkstats_track_retry_items( + self, track_retry_mock + ): # pylint: disable=name-too-long # Test that track_retry_items is called on 401 Unauthorized HTTP errors exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -345,7 +373,9 @@ def test_transmit_401_unauthorized_error_customer_sdkstats_track_retry_items(sel self.assertEqual(result, ExportResult.FAILED_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_redirect_invalid_location_header_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long + def test_transmit_redirect_invalid_location_header_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long # Test that track_dropped_items is called when redirect has invalid location header exporter = self._create_exporter_with_customer_sdkstats_enabled() @@ -361,7 +391,9 @@ def test_transmit_redirect_invalid_location_header_customer_sdkstats_track_dropp self.assertEqual(result, ExportResult.FAILED_NOT_RETRYABLE) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.track_dropped_items") - def test_transmit_from_storage_failure_customer_sdkstats_track_dropped_items(self, track_dropped_mock): # pylint: disable=name-too-long, unused-argument + def test_transmit_from_storage_failure_customer_sdkstats_track_dropped_items( + self, track_dropped_mock + ): # pylint: disable=name-too-long, unused-argument # Test that track_dropped_items is called when _transmit_from_storage operations fail exporter = self._create_exporter_with_customer_sdkstats_enabled(disable_offline_storage=False) 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 ddd804f74c9d..db48435d9aaf 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 @@ -8,7 +8,7 @@ from datetime import datetime from azure.core.exceptions import HttpResponseError, ServiceRequestError -from azure.core.pipeline.transport import HttpResponse # pylint: disable=no-legacy-azure-core-http-response-import +from azure.core.pipeline.transport import HttpResponse # pylint: disable=no-legacy-azure-core-http-response-import from azure.monitor.opentelemetry.exporter.export._base import ( _MONITOR_DOMAIN_MAPPING, _format_storage_telemetry_item, @@ -74,7 +74,7 @@ def clean_folder(folder): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: # pylint: disable=broad-exception-caught print("Failed to delete %s. Reason: %s" % (file_path, e)) @@ -181,7 +181,9 @@ def test_constructor_no_storage_directory(self, mock_get_temp_dir): self.assertEqual(base._storage_directory, storage_directory) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.tempfile.gettempdir") - def test_constructor_no_storage_directory_and_invalid_instrumentation_key(self, mock_get_temp_dir): # pylint: disable=name-too-long + def test_constructor_no_storage_directory_and_invalid_instrumentation_key( + self, mock_get_temp_dir + ): # pylint: disable=name-too-long mock_get_temp_dir.return_value = TEST_TEMP_DIR base = BaseExporter( api_version="2021-02-10_Preview", @@ -214,7 +216,9 @@ def test_constructor_no_storage_directory_and_invalid_instrumentation_key(self, @mock.patch("azure.monitor.opentelemetry.exporter.export._base.getpass.getuser") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.tempfile.gettempdir") - def test_constructor_no_storage_directory_and_invalid_user_details(self, mock_get_temp_dir, mock_get_user): # pylint: disable=name-too-long + def test_constructor_no_storage_directory_and_invalid_user_details( + self, mock_get_temp_dir, mock_get_user + ): # pylint: disable=name-too-long mock_get_temp_dir.return_value = TEST_TEMP_DIR mock_get_user.side_effect = OSError("failed to resolve user") base = BaseExporter( @@ -278,7 +282,9 @@ def test_constructor_disable_offline_storage(self, mock_get_temp_dir): mock_get_temp_dir.assert_not_called() @mock.patch("azure.monitor.opentelemetry.exporter.export._base.tempfile.gettempdir") - def test_constructor_disable_offline_storage_with_storage_directory(self, mock_get_temp_dir): # pylint: disable=name-too-long + def test_constructor_disable_offline_storage_with_storage_directory( + self, mock_get_temp_dir + ): # pylint: disable=name-too-long mock_get_temp_dir.side_effect = Exception() base = BaseExporter( api_version="2021-02-10_Preview", @@ -368,7 +374,7 @@ def test_transmit_from_storage_lease_failure(self): blob_mock.lease.assert_called_once() blob_mock.delete.assert_not_called() - def test_transmit_from_storage_blob_get_returns_none(self): # pylint: disable=name-too-long + def test_transmit_from_storage_blob_get_returns_none(self): # pylint: disable=name-too-long """Test that when blob.get() returns None, it's handled properly without TypeError.""" exporter = BaseExporter() exporter.storage = mock.Mock() @@ -561,7 +567,7 @@ def test_format_storage_telemetry_item(self): self.assertEqual(format_ti.data.base_type, "RequestData") self.assertEqual(req_data.__dict__.items(), format_ti.data.base_data.__dict__.items()) - def test_handle_transmit_from_storage_success_result(self): # pylint: disable=name-too-long + def test_handle_transmit_from_storage_success_result(self): # pylint: disable=name-too-long """Test that when storage.put() returns StorageExportResult.LOCAL_FILE_BLOB_SUCCESS, the method continues without any special handling.""" exporter = BaseExporter(disable_offline_storage=False) @@ -577,7 +583,7 @@ def test_handle_transmit_from_storage_success_result(self): # pylint: disable=na # Verify storage.put was called with the serialized envelopes exporter.storage.put.assert_called_once_with(serialized_envelopes) - def test_handle_transmit_from_storage_success_triggers_transmit(self): # pylint: disable=name-too-long + def test_handle_transmit_from_storage_success_triggers_transmit(self): # pylint: disable=name-too-long exporter = BaseExporter(disable_offline_storage=False) with mock.patch.object(exporter, "_transmit_from_storage") as mock_transmit_from_storage: @@ -587,7 +593,7 @@ def test_handle_transmit_from_storage_success_triggers_transmit(self): # pylint: mock_transmit_from_storage.assert_called_once() - def test_handle_transmit_from_storage_no_storage(self): # pylint: disable=name-too-long + def test_handle_transmit_from_storage_no_storage(self): # pylint: disable=name-too-long exporter = BaseExporter(disable_offline_storage=True) self.assertIsNone(exporter.storage) @@ -639,7 +645,7 @@ def test_transmit_http_error_redirect(self): self._base.client._config.redirect_policy.max_redirects = prev_redirects self._base.client._config.host = prev_host - def test_transmit_http_error_redirect_missing_headers(self): # pylint: disable=name-too-long + def test_transmit_http_error_redirect_missing_headers(self): # pylint: disable=name-too-long response = HttpResponse(None, None) response.status_code = 307 response.headers = None @@ -652,7 +658,7 @@ def test_transmit_http_error_redirect_missing_headers(self): # pylint: disable=n self.assertEqual(post.call_count, 1) self.assertEqual(self._base.client._config.host, prev_host) - def test_transmit_http_error_redirect_invalid_location_header(self): # pylint: disable=name-too-long + def test_transmit_http_error_redirect_invalid_location_header(self): # pylint: disable=name-too-long response = HttpResponse(None, None) response.status_code = 307 response.headers = {"location": "123"} @@ -825,7 +831,7 @@ def test_transmit_request_exception(self): }, ) @mock.patch("azure.monitor.opentelemetry.exporter.statsbeat._statsbeat.collect_statsbeat_metrics") - def test_transmit_request_exception_statsbeat(self, stats_mock): # pylint: disable=name-too-long + def test_transmit_request_exception_statsbeat(self, stats_mock): # pylint: disable=name-too-long exporter = BaseExporter(disable_offline_storage=True) with mock.patch.object(AzureMonitorClient, "track", throw(Exception)): result = exporter._transmit(self._envelopes_to_export) @@ -1196,7 +1202,9 @@ def test_get_authentication_credential_arg(self): @mock.patch.dict("os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "Authorization=AAD"}) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.logger") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_system_assigned(self, mock_managed_identity, mock_logger): # pylint: disable=name-too-long + def test_get_authentication_credential_system_assigned( + self, mock_managed_identity, mock_logger + ): # pylint: disable=name-too-long MOCK_MANAGED_IDENTITY_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CREDENTIAL" mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CREDENTIAL result = _get_authentication_credential(foo="bar") @@ -1209,8 +1217,12 @@ def test_get_authentication_credential_system_assigned(self, mock_managed_identi ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.logger") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_client_id(self, mock_managed_identity, mock_logger): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + def test_get_authentication_credential_client_id( + self, mock_managed_identity, mock_logger + ): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") mock_logger.assert_not_called() @@ -1222,7 +1234,9 @@ def test_get_authentication_credential_client_id(self, mock_managed_identity, mo ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.logger") @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_malformed(self, mock_managed_identity, mock_logger): # pylint: disable=name-too-long + def test_get_authentication_credential_malformed( + self, mock_managed_identity, mock_logger + ): # pylint: disable=name-too-long # Even a single malformed pair means Entra ID auth is skipped. MOCK_MANAGED_IDENTITY_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CREDENTIAL" mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CREDENTIAL @@ -1233,8 +1247,10 @@ def test_get_authentication_credential_malformed(self, mock_managed_identity, mo @mock.patch.dict("os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "ClientId=TEST_CLIENT_ID"}) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_no_auth(self, mock_managed_identity): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + def test_get_authentication_credential_no_auth(self, mock_managed_identity): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") self.assertIsNone(result) @@ -1244,8 +1260,10 @@ def test_get_authentication_credential_no_auth(self, mock_managed_identity): # p "os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "Authorization=foobar;ClientId=TEST_CLIENT_ID"} ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_no_aad(self, mock_managed_identity): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + def test_get_authentication_credential_no_aad(self, mock_managed_identity): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") self.assertIsNone(result) @@ -1255,8 +1273,10 @@ def test_get_authentication_credential_no_aad(self, mock_managed_identity): # py "os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "Authorization=AAD;ClientId=TEST_CLIENT_ID"} ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") - def test_get_authentication_credential_error(self, mock_managed_identity): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + def test_get_authentication_credential_error(self, mock_managed_identity): # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL mock_managed_identity.side_effect = ValueError("TEST ERROR") result = _get_authentication_credential(foo="bar") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py index b7a6f56cdc34..4c9cf5ea9fde 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py @@ -17,7 +17,7 @@ def setUp(self): def test_validate_connection_String(self): parser = ConnectionStringParser(connection_string=self._valid_connection_string) - self.assertEqual(parser._connection_string, self._valid_connection_string) # pylint: disable=protected-access + self.assertEqual(parser._connection_string, self._valid_connection_string) # pylint: disable=protected-access def test_invalid_key_empty(self): self.assertRaises(ValueError, lambda: ConnectionStringParser(connection_string="")) @@ -160,7 +160,7 @@ def test_process_options_endpoint_default(self): ) self.assertEqual(parser.endpoint, "https://dc.services.visualstudio.com") - def test_process_options_live_endpoint_code_cs(self): # pylint: disable=name-too-long + def test_process_options_live_endpoint_code_cs(self): # pylint: disable=name-too-long os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "Authorization=ikey;IngestionEndpoint=456;InstrumentationKey=" + self._valid_instrumentation_key ) @@ -170,7 +170,7 @@ def test_process_options_live_endpoint_code_cs(self): # pylint: disable=name-too self.assertEqual(parser.endpoint, "123") self.assertEqual(parser.live_endpoint, "111") - def test_process_options_live_endpoint_env_cs(self): # pylint: disable=name-too-long + def test_process_options_live_endpoint_env_cs(self): # pylint: disable=name-too-long os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "Authorization=ikey;IngestionEndpoint=456;LiveEndpoint=111;InstrumentationKey=" + self._valid_instrumentation_key @@ -181,7 +181,7 @@ def test_process_options_live_endpoint_env_cs(self): # pylint: disable=name-too- self.assertEqual(parser.endpoint, "456") self.assertEqual(parser.live_endpoint, "111") - def test_process_options_live_endpoint_default(self): # pylint: disable=name-too-long + def test_process_options_live_endpoint_default(self): # pylint: disable=name-too-long parser = ConnectionStringParser( connection_string=self._valid_connection_string, ) @@ -190,7 +190,7 @@ def test_process_options_live_endpoint_default(self): # pylint: disable=name-too def test_parse_connection_string_invalid(self): self.assertRaises(ValueError, lambda: ConnectionStringParser(connection_string="asd")) - def test_parse_connection_string_invalid_auth(self): # pylint: disable=name-too-long + def test_parse_connection_string_invalid_auth(self): # pylint: disable=name-too-long self.assertRaises( ValueError, lambda: ConnectionStringParser( @@ -205,7 +205,7 @@ def test_parse_connection_string_suffix(self): ) self.assertEqual(parser.endpoint, "https://US.dc.123") - def test_parse_connection_string_suffix_no_location(self): # pylint: disable=name-too-long + def test_parse_connection_string_suffix_no_location(self): # pylint: disable=name-too-long parser = ConnectionStringParser( connection_string="Authorization=ikey;EndpointSuffix=123;InstrumentationKey=" + self._valid_instrumentation_key, @@ -213,7 +213,7 @@ def test_parse_connection_string_suffix_no_location(self): # pylint: disable=nam self.assertEqual(parser.endpoint, "https://dc.123") # Region extraction tests - def test_region_extraction_from_endpoint_with_number(self): # pylint: disable=name-too-long + def test_region_extraction_from_endpoint_with_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL with number suffix.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -222,7 +222,7 @@ def test_region_extraction_from_endpoint_with_number(self): # pylint: disable=na ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_from_endpoint_without_number(self): # pylint: disable=name-too-long + def test_region_extraction_from_endpoint_without_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL without number suffix.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -231,7 +231,7 @@ def test_region_extraction_from_endpoint_without_number(self): # pylint: disable ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_from_endpoint_two_digit_number(self): # pylint: disable=name-too-long + def test_region_extraction_from_endpoint_two_digit_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL with two-digit number.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -240,7 +240,7 @@ def test_region_extraction_from_endpoint_two_digit_number(self): # pylint: disab ) self.assertEqual(parser.region, "eastus") - def test_region_extraction_from_endpoint_three_digit_number(self): # pylint: disable=name-too-long + def test_region_extraction_from_endpoint_three_digit_number(self): # pylint: disable=name-too-long """Test region extraction from endpoint URL with three-digit number.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -269,7 +269,7 @@ def test_region_extraction_various_regions(self): ) self.assertEqual(parser.region, expected_region) - def test_region_extraction_no_region_global_endpoint(self): # pylint: disable=name-too-long + def test_region_extraction_no_region_global_endpoint(self): # pylint: disable=name-too-long """Test that no region is extracted from global endpoints.""" parser = ConnectionStringParser( connection_string="InstrumentationKey=" @@ -278,12 +278,12 @@ def test_region_extraction_no_region_global_endpoint(self): # pylint: disable=na ) self.assertIsNone(parser.region) - def test_region_extraction_no_region_default_endpoint(self): # pylint: disable=name-too-long + def test_region_extraction_no_region_default_endpoint(self): # pylint: disable=name-too-long """Test that no region is extracted when using default endpoint.""" parser = ConnectionStringParser(connection_string="InstrumentationKey=" + self._valid_instrumentation_key) self.assertIsNone(parser.region) - def test_region_extraction_invalid_endpoint_format(self): # pylint: disable=name-too-long + def test_region_extraction_invalid_endpoint_format(self): # pylint: disable=name-too-long """Test that no region is extracted from invalid endpoint formats.""" invalid_endpoints = [ "https://invalid.endpoint.com", @@ -301,7 +301,7 @@ def test_region_extraction_invalid_endpoint_format(self): # pylint: disable=name ) self.assertIsNone(parser.region) - def test_region_extraction_from_environment_endpoint(self): # pylint: disable=name-too-long + def test_region_extraction_from_environment_endpoint(self): # pylint: disable=name-too-long """Test region extraction from endpoint set via environment variable.""" os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "InstrumentationKey=" @@ -311,7 +311,7 @@ def test_region_extraction_from_environment_endpoint(self): # pylint: disable=na parser = ConnectionStringParser(connection_string=None) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_code_endpoint_takes_priority(self): # pylint: disable=name-too-long + def test_region_extraction_code_endpoint_takes_priority(self): # pylint: disable=name-too-long """Test that endpoint from code connection string takes priority over environment.""" os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = ( "InstrumentationKey=" @@ -325,7 +325,7 @@ def test_region_extraction_code_endpoint_takes_priority(self): # pylint: disable ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_with_trailing_slash(self): # pylint: disable=name-too-long + def test_region_extraction_with_trailing_slash(self): # pylint: disable=name-too-long """Test region extraction works with and without trailing slash.""" test_cases = [ "https://westeurope-5.in.applicationinsights.azure.com/", @@ -341,7 +341,7 @@ def test_region_extraction_with_trailing_slash(self): # pylint: disable=name-too ) self.assertEqual(parser.region, "westeurope") - def test_region_extraction_alphanumeric_regions(self): # pylint: disable=name-too-long + def test_region_extraction_alphanumeric_regions(self): # pylint: disable=name-too-long """Test region extraction for regions with numbers in the name.""" test_cases = [ ("westus2-1.in.applicationinsights.azure.com", "westus2"), diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py index 9fa38601c790..1c95ce020172 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_storage.py @@ -38,7 +38,7 @@ def clean_folder(folder): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: # pylint: disable=broad-exception-caught print("Failed to delete %s. Reason: %s" % (file_path, e)) @@ -98,7 +98,7 @@ def test_put_rename_error_returns_string(self): self.assertIsInstance(result, str) self.assertIn("File already exists", result) - def test_put_json_serialization_error_returns_string(self): # pylint: disable=name-too-long + def test_put_json_serialization_error_returns_string(self): # pylint: disable=name-too-long blob = LocalFileBlob(os.path.join(TEST_FOLDER, "json_error_blob")) import datetime @@ -110,7 +110,7 @@ def test_put_json_serialization_error_returns_string(self): # pylint: disable=na # Should contain JSON serialization error self.assertTrue("not JSON serializable" in result or "Object of type" in result) - def test_put_various_exceptions_return_strings(self): # pylint: disable=name-too-long + def test_put_various_exceptions_return_strings(self): # pylint: disable=name-too-long blob = LocalFileBlob(os.path.join(TEST_FOLDER, "various_errors_blob")) test_input = [1, 2, 3] @@ -143,7 +143,7 @@ def test_put_with_lease_period_success(self): self.assertTrue(blob.fullpath.endswith(".lock")) @unittest.skip("transient storage") - def test_put_with_lease_period_error_returns_string(self): # pylint: disable=name-too-long + def test_put_with_lease_period_error_returns_string(self): # pylint: disable=name-too-long blob = LocalFileBlob(os.path.join(TEST_FOLDER, "lease_error_blob")) test_input = [1, 2, 3] lease_period = 60 @@ -329,7 +329,7 @@ def test_put_storage_disabled_readonly(self): result = stor.put(test_input) self.assertEqual(result, StorageExportResult.CLIENT_READONLY) - def test_put_storage_disabled_with_exception_state(self): # pylint: disable=name-too-long + def test_put_storage_disabled_with_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) exception_message = "Previous storage error occurred" with mock.patch( @@ -380,7 +380,7 @@ def test_put_blob_put_failure_returns_string(self): self.assertIsInstance(result, str) self.assertIn("Permission denied", result) - def test_put_exception_in_method_returns_string(self): # pylint: disable=name-too-long + def test_put_exception_in_method_returns_string(self): # pylint: disable=name-too-long test_input = (1, 2, 3) with LocalFileStorage(os.path.join(TEST_FOLDER, "method_exception_test")) as stor: with mock.patch( @@ -427,7 +427,7 @@ def test_put_default_lease_period(self): # File should be created with lease (since default lease_period > 0) self.assertEqual(result, StorageExportResult.LOCAL_FILE_BLOB_SUCCESS) - def test_check_and_set_folder_permissions_oserror_sets_exception_state(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_oserror_sets_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "OSError: Permission denied creating directory" @@ -459,7 +459,9 @@ def test_check_and_set_folder_permissions_oserror_sets_exception_state(self): # # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_generic_exception_sets_exception_state(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_generic_exception_sets_exception_state( + self, + ): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "RuntimeError: Unexpected error during setup" @@ -491,7 +493,9 @@ def test_check_and_set_folder_permissions_generic_exception_sets_exception_state # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_readonly_filesystem_sets_readonly_state(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_readonly_filesystem_sets_readonly_state( + self, + ): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -527,7 +531,9 @@ def test_check_and_set_folder_permissions_readonly_filesystem_sets_readonly_stat # Clean up - note: cannot easily reset readonly state, but test isolation should handle this set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_windows_icacls_failure_sets_exception_state(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_windows_icacls_failure_sets_exception_state( + self, + ): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -571,7 +577,7 @@ def test_check_and_set_folder_permissions_windows_icacls_failure_sets_exception_ # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_windows_user_retrieval_failure(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_windows_user_retrieval_failure(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -605,7 +611,9 @@ def test_check_and_set_folder_permissions_windows_user_retrieval_failure(self): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_unix_chmod_exception_sets_exception_state(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_unix_chmod_exception_sets_exception_state( + self, + ): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "OSError: Operation not permitted" @@ -645,7 +653,7 @@ def test_check_and_set_folder_permissions_unix_chmod_exception_sets_exception_st # Clean up set_local_storage_setup_state_exception("") - def test_exception_state_persistence_across_storage_instances(self): # pylint: disable=name-too-long + def test_exception_state_persistence_across_storage_instances(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "Persistent storage setup error" @@ -677,7 +685,7 @@ def test_exception_state_persistence_across_storage_instances(self): # pylint: d # Clean up set_local_storage_setup_state_exception("") - def test_exception_state_cleared_and_storage_recovery(self): # pylint: disable=name-too-long + def test_exception_state_cleared_and_storage_recovery(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_error_message = "Temporary storage setup error" @@ -709,7 +717,7 @@ def test_exception_state_cleared_and_storage_recovery(self): # pylint: disable=n retrieved_data = stor2.get().get() self.assertEqual(retrieved_data, test_input) - def test_local_storage_state_readonly_get_set_operations(self): # pylint: disable=name-too-long + def test_local_storage_state_readonly_get_set_operations(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_readonly, set_local_storage_setup_state_readonly, @@ -747,7 +755,7 @@ def test_local_storage_state_readonly_get_set_operations(self): # pylint: disabl # This is by design - once readonly is set, it stays set for the process pass - def test_readonly_state_interaction_with_storage_put_method(self): # pylint: disable=name-too-long + def test_readonly_state_interaction_with_storage_put_method(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -785,7 +793,7 @@ def test_storage_put_invalid_return_type(self): f"Expected StorageExportResult or str, got {type(result)}", ) - def test_readonly_state_priority_over_exception_state(self): # pylint: disable=name-too-long + def test_readonly_state_priority_over_exception_state(self): # pylint: disable=name-too-long test_input = (1, 2, 3) test_exception_message = "Some storage exception" @@ -834,7 +842,7 @@ def readonly_operations(): time.sleep(0.01) # Small delay to encourage race conditions value = get_local_storage_setup_state_readonly() results.append(value) - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: # pylint: disable=broad-exception-caught errors.append(str(e)) # Create multiple threads @@ -859,7 +867,7 @@ def readonly_operations(): for result in results: self.assertTrue(result) - def test_readonly_state_persistence_across_storage_instances(self): # pylint: disable=name-too-long + def test_readonly_state_persistence_across_storage_instances(self): # pylint: disable=name-too-long test_input = (1, 2, 3) from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( @@ -888,7 +896,7 @@ def test_readonly_state_persistence_across_storage_instances(self): # pylint: di # Verify readonly state is still set self.assertTrue(get_local_storage_setup_state_readonly()) - def test_readonly_state_direct_access_vs_function_access(self): # pylint: disable=name-too-long + def test_readonly_state_direct_access_vs_function_access(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_readonly, set_local_storage_setup_state_readonly, @@ -908,7 +916,7 @@ def test_readonly_state_direct_access_vs_function_access(self): # pylint: disabl self.assertTrue(function_value) self.assertTrue(direct_value) - def test_readonly_state_idempotent_set_operations(self): # pylint: disable=name-too-long + def test_readonly_state_idempotent_set_operations(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_readonly, set_local_storage_setup_state_readonly, @@ -922,7 +930,7 @@ def test_readonly_state_idempotent_set_operations(self): # pylint: disable=name- final_state = get_local_storage_setup_state_readonly() self.assertTrue(final_state) - def test_check_and_set_folder_permissions_unix_multiuser_scenario(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_unix_multiuser_scenario(self): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( set_local_storage_setup_state_exception, ) @@ -966,7 +974,9 @@ def mock_makedirs(path, mode=0o777, exist_ok=False): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_unix_multiuser_parent_permission_failure(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_unix_multiuser_parent_permission_failure( + self, + ): # pylint: disable=name-too-long from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( get_local_storage_setup_state_exception, set_local_storage_setup_state_exception, @@ -997,7 +1007,9 @@ def mock_makedirs(path, mode=0o777, exist_ok=False): # Clean up set_local_storage_setup_state_exception("") - def test_check_and_set_folder_permissions_unix_multiuser_storage_permission_failure(self): # pylint: disable=name-too-long + def test_check_and_set_folder_permissions_unix_multiuser_storage_permission_failure( + self, + ): # pylint: disable=name-too-long test_error_message = "PermissionError: Operation not permitted on storage directory" from azure.monitor.opentelemetry.exporter.statsbeat.customer._state import ( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py index e4ac641128ff..fce04dd84756 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_utils.py @@ -29,12 +29,13 @@ TEST_KUBERNETES_SERVICE_HOST = "TEST_KUBERNETES_SERVICE_HOST" TEST_AKS_ARM_NAMESPACE_ID = "TEST_AKS_ARM_NAMESPACE_ID" + # pylint: disable=protected-access, too-many-public-methods class TestUtils(unittest.TestCase): def setUp(self): self._valid_instrumentation_key = "1234abcd-5678-4efa-8abc-1234567890ab" - def test_filter_custom_properties_truncates_and_drops_invalid_entries(self): # pylint: disable=name-too-long + def test_filter_custom_properties_truncates_and_drops_invalid_entries(self): # pylint: disable=name-too-long oversized_value = "v" * 9000 properties = { "valid_key": oversized_value, @@ -97,7 +98,7 @@ def test_populate_part_a_fields(self): self.assertEqual(tags.get("ai.application.ver"), "testApplicationVer") # Default service.name fields should be used when kubernetes values are not present - def test_populate_part_a_fields_unknown_service(self): # pylint: disable=name-too-long + def test_populate_part_a_fields_unknown_service(self): # pylint: disable=name-too-long resource = Resource( { "service.name": "unknown_servicefoobar", @@ -221,7 +222,7 @@ def test_populate_part_a_fields_aks_daemon(self): self.assertEqual(tags.get("ai.internal.nodeName"), tags.get("ai.cloud.roleInstance")) # Test that undefined fields are ignored. - def test_populate_part_a_fields_aks_undefined(self): # pylint: disable=name-too-long + def test_populate_part_a_fields_aks_undefined(self): # pylint: disable=name-too-long resource = Resource( { "k8s.deployment.name": "", @@ -239,7 +240,7 @@ def test_populate_part_a_fields_aks_undefined(self): # pylint: disable=name-too- self.assertEqual(tags.get("ai.cloud.roleInstance"), "testPodName") self.assertEqual(tags.get("ai.internal.nodeName"), tags.get("ai.cloud.roleInstance")) - def test_populate_part_a_fields_aks_with_service(self): # pylint: disable=name-too-long + def test_populate_part_a_fields_aks_with_service(self): # pylint: disable=name-too-long resource = Resource( { "service.name": "testServiceName", @@ -260,7 +261,7 @@ def test_populate_part_a_fields_aks_with_service(self): # pylint: disable=name-t self.assertEqual(tags.get("ai.internal.nodeName"), tags.get("ai.cloud.roleInstance")) # Default service.name fields should be ignored when kubernetes values are present - def test_populate_part_a_fields_aks_with_unknown_service(self): # pylint: disable=name-too-long + def test_populate_part_a_fields_aks_with_unknown_service(self): # pylint: disable=name-too-long resource = Resource( { "service.name": "unknown_servicefoobar", @@ -362,7 +363,7 @@ def test_get_sdk_version_prefix_attach_linux(self, _mock_system, _mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_attach_windows(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_attach_windows(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "uwi_") @@ -389,7 +390,7 @@ def test_get_sdk_version_prefix_app_service(self, _mock_system, _mock_isdir): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_app_service_linux(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_app_service_linux(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "alm_") @@ -403,7 +404,9 @@ def test_get_sdk_version_prefix_app_service_linux(self, _mock_system, _mock_isdi "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_app_service_windows(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_app_service_windows( + self, _mock_system, _mock_isdir + ): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "awm_") @@ -414,7 +417,9 @@ def test_get_sdk_version_prefix_app_service_windows(self, _mock_system, _mock_is ) @patch("azure.monitor.opentelemetry.exporter._utils.isdir", return_value=True) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_app_service_attach(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_app_service_attach( + self, _mock_system, _mock_isdir + ): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "aui_") @@ -428,7 +433,9 @@ def test_get_sdk_version_prefix_app_service_attach(self, _mock_system, _mock_isd "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_app_service_linux_attach(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_app_service_linux_attach( + self, _mock_system, _mock_isdir + ): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "ali_") @@ -442,7 +449,9 @@ def test_get_sdk_version_prefix_app_service_linux_attach(self, _mock_system, _mo "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_app_service_windows_attach(self, _mock_system, _mock_isdir): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_app_service_windows_attach( + self, _mock_system, _mock_isdir + ): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "awi_") @@ -473,7 +482,7 @@ def test_get_sdk_version_prefix_function(self, _mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_function_linux(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_function_linux(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "flm_") @@ -489,7 +498,7 @@ def test_get_sdk_version_prefix_function_linux(self, _mock_system): # pylint: di "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_function_windows(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_function_windows(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fwm_") @@ -503,7 +512,7 @@ def test_get_sdk_version_prefix_function_windows(self, _mock_system): # pylint: clear=True, ) @patch("azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="") - def test_get_sdk_version_prefix_function_attach(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_function_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fui_") @@ -520,7 +529,7 @@ def test_get_sdk_version_prefix_function_attach(self, _mock_system): # pylint: d "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_function_linux_attach(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_function_linux_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fli_") @@ -537,7 +546,7 @@ def test_get_sdk_version_prefix_function_linux_attach(self, _mock_system): # pyl "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_function_windows_attach(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_function_windows_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "fwi_") @@ -608,7 +617,7 @@ def test_get_sdk_version_prefix_aks_attach(self, _mock_system): "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Linux", ) - def test_get_sdk_version_prefix_aks_linux_attach(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_aks_linux_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kli_") @@ -623,7 +632,7 @@ def test_get_sdk_version_prefix_aks_linux_attach(self, _mock_system): # pylint: "azure.monitor.opentelemetry.exporter._utils.platform.system", return_value="Windows", ) - def test_get_sdk_version_prefix_aks_windows_attach(self, _mock_system): # pylint: disable=name-too-long + def test_get_sdk_version_prefix_aks_windows_attach(self, _mock_system): # pylint: disable=name-too-long result = _utils._get_sdk_version_prefix() self.assertEqual(result, "kwi_") @@ -705,11 +714,11 @@ def test_is_synthetic_load_always_on_legacy(self): properties = {"http.user_agent": "Mozilla/5.0 AlwaysOn"} self.assertTrue(_utils._is_synthetic_load(properties)) - def test_is_synthetic_load_always_on_new_convention(self): # pylint: disable=name-too-long + def test_is_synthetic_load_always_on_new_convention(self): # pylint: disable=name-too-long properties = {"user_agent.original": "Azure-Load-Testing/1.0 AlwaysOn"} self.assertTrue(_utils._is_synthetic_load(properties)) - def test_is_synthetic_load_always_on_case_sensitive(self): # pylint: disable=name-too-long + def test_is_synthetic_load_always_on_case_sensitive(self): # pylint: disable=name-too-long properties = {"http.user_agent": "Mozilla/5.0 alwayson"} self.assertFalse(_utils._is_synthetic_load(properties)) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py index e1f18c5dc21d..e63a03157120 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_rate_limited_sampling.py @@ -43,6 +43,7 @@ def create_parent_span(sampled: bool, sample_rate: Optional[float] = None, is_re return mock_span + # pylint: disable=too-many-public-methods class TestRateLimitedSampler(unittest.TestCase): def setUp(self): @@ -109,7 +110,6 @@ def test_high_volume_sampling(self): num_spans = 500 sampled_count = 0 - random.seed(42) trace_ids = [random.getrandbits(128) for _ in range(num_spans)] @@ -144,7 +144,6 @@ def test_rate_adaptation_increasing_load(self): sampled_phase1 = 0 sampled_phase2 = 0 - random.seed(123) trace_ids_phase1 = [random.getrandbits(128) for _ in range(phase1_spans)] trace_ids_phase2 = [random.getrandbits(128) for _ in range(phase2_spans)] @@ -268,7 +267,7 @@ def worker(): result = sampler.should_sample(None, i, f"thread-span-{i}") results.append(result) time.sleep(0.001) - except Exception as e: # pylint: disable=broad-exception-caught + except Exception as e: # pylint: disable=broad-exception-caught errors.append(e) threads = [threading.Thread(target=worker) for _ in range(5)] diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py index a1fa14f2ecc4..c9dc88c03a9b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py @@ -832,7 +832,7 @@ def test_span_to_envelope_client_gen_ai(self): self.assertEqual(envelope.data.base_data.target, "az.ai.inference") self.assertEqual(len(envelope.data.base_data.properties), 1) - def test_span_to_envelope_client_internal_gen_ai_type(self): # pylint: disable=name-too-long + def test_span_to_envelope_client_internal_gen_ai_type(self): # pylint: disable=name-too-long exporter = self._exporter start_time = 1575494316027613500 end_time = start_time + 1001000000 @@ -855,7 +855,7 @@ def test_span_to_envelope_client_internal_gen_ai_type(self): # pylint: disable=n envelope = exporter._span_to_envelope(span) self.assertEqual(envelope.data.base_data.type, "GenAI | az.ai.inference") - def test_span_to_envelope_client_multiple_types_with_gen_ai(self): # pylint: disable=name-too-long + def test_span_to_envelope_client_multiple_types_with_gen_ai(self): # pylint: disable=name-too-long exporter = self._exporter start_time = 1575494316027613500 end_time = start_time + 1001000000 @@ -1505,7 +1505,7 @@ def test_span_to_envelope_properties_links(self): json_dict = json.loads(envelope.data.base_data.properties["_MS.links"])[0] self.assertEqual(json_dict["id"], "a6f5d48acb4d31da") - def test_span_to_envelope_properties_std_metrics(self): # pylint: disable=name-too-long + def test_span_to_envelope_properties_std_metrics(self): # pylint: disable=name-too-long exporter = self._exporter start_time = 1575494316027613500 end_time = start_time + 1001000000 @@ -1668,7 +1668,7 @@ def test_span_events_to_envelopes_message(self): self.assertEqual(envelope.data.base_data.message, "test event") self.assertEqual(envelope.data.base_type, "MessageData") - def test_span_events_to_envelopes_sample_rate(self): # pylint: disable=name-too-long + def test_span_events_to_envelopes_sample_rate(self): # pylint: disable=name-too-long exporter = self._exporter time = 1575494316027613500 @@ -1832,7 +1832,7 @@ def test_check_instrumentation_span(self): _check_instrumentation_span(span) add.assert_called_once_with("test") - def test_check_instrumentation_span_not_instrumentation(self): # pylint: disable=name-too-long + def test_check_instrumentation_span_not_instrumentation(self): # pylint: disable=name-too-long span = mock.Mock() span.attributes = {} span.instrumentation_scope.name = "__main__" @@ -1840,7 +1840,7 @@ def test_check_instrumentation_span_not_instrumentation(self): # pylint: disable _check_instrumentation_span(span) add.assert_not_called() - def test_check_instrumentation_span_azure_sdk(self): # pylint: disable=name-too-long + def test_check_instrumentation_span_azure_sdk(self): # pylint: disable=name-too-long span = mock.Mock() span.attributes = {} span.instrumentation_scope.name = "azure.foo.bar.__init__" @@ -1850,7 +1850,9 @@ def test_check_instrumentation_span_azure_sdk(self): # pylint: disable=name-too- add.assert_called_once_with(_AZURE_SDK_OPENTELEMETRY_NAME) @mock.patch("opentelemetry.trace.get_tracer_provider") - def test_check_instrumentation_span_azure_sdk_otel_span(self, mock_get_tracer_provider): # pylint: disable=name-too-long + def test_check_instrumentation_span_azure_sdk_otel_span( + self, mock_get_tracer_provider + ): # pylint: disable=name-too-long mock_get_tracer_provider.return_value = self.get_tracer_provider() with OpenTelemetrySpan() as azure_sdk_span: @@ -1869,7 +1871,9 @@ def test_check_instrumentation_span_azure_sdk_otel_span(self, mock_get_tracer_pr add.assert_called_once_with(_AZURE_AI_SDK_NAME) @mock.patch("opentelemetry.trace.get_tracer_provider") - def test_check_instrumentation_span_azure_sdk_span_impl(self, mock_get_tracer_provider): #pylint: disable=name-too-long + def test_check_instrumentation_span_azure_sdk_span_impl( + self, mock_get_tracer_provider + ): # pylint: disable=name-too-long mock_get_tracer_provider.return_value = self.get_tracer_provider() settings.tracing_implementation = "opentelemetry" @@ -1894,7 +1898,9 @@ def test_check_instrumentation_span_azure_sdk_span_impl(self, mock_get_tracer_pr settings.tracing_implementation = None @mock.patch("opentelemetry.trace.get_tracer_provider") - def test_check_instrumentation_span_azure_sdk_get_tracer(self, mock_get_tracer_provider): # pylint: disable=name-too-long + def test_check_instrumentation_span_azure_sdk_get_tracer( + self, mock_get_tracer_provider + ): # pylint: disable=name-too-long mock_get_tracer_provider.return_value = self.get_tracer_provider() if not get_azure_sdk_tracer: From facf97f84c9f72a7d5c8b5dc7f9b203b0e64f5b7 Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Mon, 26 Jan 2026 13:33:53 -0800 Subject: [PATCH 6/7] fix pylint --- .../exporter/_configuration/_utils.py | 24 +++++++++---------- .../exporter/_configuration/_worker.py | 4 ++-- .../_performance_counters/_manager.py | 24 +++++++++---------- .../exporter/_quickpulse/_manager.py | 4 ++-- .../opentelemetry/exporter/export/_base.py | 4 ++-- .../exporter/statsbeat/_manager.py | 12 +++++----- .../exporter/statsbeat/_utils.py | 8 +++---- .../test_customer_sdkstats.py | 1 + .../tests/customer_sdk_stats/test_utlities.py | 4 ++-- .../tests/statsbeat/test_manager.py | 2 +- .../tests/statsbeat/test_statsbeat.py | 8 +++---- .../tests/test_base_exporter.py | 12 +++++----- .../tests/test_connection_string_parser.py | 6 ++--- .../tests/trace/test_trace.py | 8 +++++-- 14 files changed, 63 insertions(+), 58 deletions(-) diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py index 7afc54ba04ab..0a88e99deb1f 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_utils.py @@ -124,24 +124,24 @@ def make_onesettings_request( return _parse_onesettings_response(result) except requests.exceptions.Timeout as ex: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "OneSettings request timed out: %s", str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return OneSettingsResponse(has_exception=True) except requests.exceptions.RequestException as ex: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to fetch configuration from OneSettings: %s", str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return OneSettingsResponse(has_exception=True) except json.JSONDecodeError as ex: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to parse OneSettings response: %s", str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return OneSettingsResponse(has_exception=True) except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Unexpected error while fetching configuration: %s", str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return OneSettingsResponse(has_exception=True) @@ -205,13 +205,13 @@ def _parse_onesettings_response(response: requests.Response) -> OneSettingsRespo if settings and settings.get(_ONE_SETTINGS_CHANGE_VERSION_KEY) is not None: version = int(settings.get(_ONE_SETTINGS_CHANGE_VERSION_KEY)) # type: ignore except (UnicodeDecodeError, json.JSONDecodeError) as ex: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to decode OneSettings response content: %s", str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) except ValueError as ex: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to parse OneSettings change version: %s", str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) elif status_code == 400: logger.warning("Bad request to OneSettings: %s", response.content) elif status_code == 404: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py index deafddf1e06f..6c3b8bb9763d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_configuration/_worker.py @@ -141,9 +141,9 @@ def _get_configuration(self) -> None: # Capture interval while we have the lock interval = self._refresh_interval except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Configuration refresh failed: %s", ex - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) # Use current interval on error interval = self.get_refresh_interval() diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py index b3f67d0e605f..ecfae706e8be 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_performance_counters/_manager.py @@ -79,9 +79,9 @@ def _get_process_cpu(options: CallbackOptions) -> Iterable[Observation]: cpu_percent = _PROCESS.cpu_percent(interval=None) yield Observation(cpu_percent, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception( + _logger.exception( # pylint: disable=do-not-use-logging-exception "Error getting process CPU usage: %s", e - ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + ) # pylint: disable=logging-not-lazy yield Observation(0.0, {}) @@ -112,9 +112,9 @@ def _get_process_cpu_normalized(options: CallbackOptions) -> Iterable[Observatio yield Observation(normalized_cpu_percent, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception( + _logger.exception( # pylint: disable=do-not-use-logging-exception "Error getting normalized process CPU usage: %s", e - ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + ) # pylint: disable=logging-not-lazy yield Observation(0.0, {}) @@ -135,9 +135,9 @@ def _get_available_memory(options: CallbackOptions) -> Iterable[Observation]: available_memory = psutil.virtual_memory().available yield Observation(available_memory, {}) except Exception as e: # pylint: disable=broad-except - _logger.exception( + _logger.exception( # pylint: disable=do-not-use-logging-exception "Error getting available memory: %s", e - ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + ) # pylint: disable=logging-not-lazy yield Observation(0, {}) @@ -158,9 +158,9 @@ def _get_process_memory(options: CallbackOptions) -> Iterable[Observation]: private_bytes = _PROCESS.memory_info().rss yield Observation(private_bytes, {}) except (psutil.NoSuchProcess, psutil.AccessDenied, Exception) as e: # pylint: disable=broad-except - _logger.exception( + _logger.exception( # pylint: disable=do-not-use-logging-exception "Error getting process memory: %s", e - ) # pylint: disable=logging-not-lazy, do-not-use-logging-exception + ) # pylint: disable=logging-not-lazy yield Observation(0, {}) @@ -611,14 +611,14 @@ def __init__(self, meter_provider=None): if metric_class == RequestExecutionTime: self._request_duration_histogram = performance_counter.gauge except Exception as e: # pylint: disable=broad-except - _logger.warning( + _logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to initialize performance counter %s: %s", metric_class.NAME[0], e - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) except Exception as e: # pylint: disable=broad-except - _logger.warning( + _logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to setup performance counters: %s", e - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) def _record_span(self, span: ReadableSpan) -> None: try: diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py index a2ac444e6787..0dbbef15bc74 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/_quickpulse/_manager.py @@ -202,9 +202,9 @@ def _do_initialize(self) -> bool: return True except Exception as e: # pylint: disable=broad-except - _logger.warning( + _logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to initialize QuickpulseManager: %s", e - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) # Ensure cleanup happens and state is consistent self._cleanup() return False 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 9ad096916c18..f77d7bd553e8 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 @@ -200,9 +200,9 @@ def __init__(self, **kwargs: Any) -> None: collect_statsbeat_metrics(self) except Exception as e: # pylint: disable=broad-except - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to initialize statsbeat metrics: %s", e - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) # customer sdkstats initialization if self._should_collect_customer_sdkstats(): diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py index e61ff0dfafbd..44bff4c85580 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_manager.py @@ -251,9 +251,9 @@ def _do_initialize(self, config: StatsbeatConfig) -> bool: except Exception as e: # pylint: disable=broad-except # Log the error for debugging - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to initialize statsbeat: %s", e - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) # Clean up on failure self._cleanup() return False @@ -299,16 +299,16 @@ def _reconfigure(self, new_config: StatsbeatConfig) -> bool: # Force flush before shutdown to ensure data is sent self._meter_provider.force_flush(timeout_millis=5000) except Exception as e: # pylint: disable=broad-except - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to flush meter provider during reconfiguration: %s", e - ) # pylint:disable=do-not-log-exceptions-if-not-debug + ) try: self._meter_provider.shutdown(timeout_millis=5000) except Exception as e: # pylint: disable=broad-except - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Failed to shutdown meter provider during reconfiguration: %s", e - ) # pylint:disable=do-not-log-exceptions-if-not-debug + ) # Reset state but keep initialized=True self._meter_provider = None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py index 49332c8518ee..07ed150cd33d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/azure/monitor/opentelemetry/exporter/statsbeat/_utils.py @@ -156,12 +156,12 @@ def _get_connection_string_for_region_from_config(target_region: str, settings: return None return default_connection_string except (ValueError, TypeError, KeyError) as ex: - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Error parsing configuration for region '%s': %s", target_region, str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return None except Exception as ex: # pylint: disable=broad-exception-caught - logger.warning( + logger.warning( # pylint: disable=do-not-log-exceptions-if-not-debug "Unexpected error getting stats connection string for region '%s': %s", target_region, str(ex) - ) # pylint: disable=do-not-log-exceptions-if-not-debug + ) return None diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py index d24d2aaabe69..8834fb756196 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_customer_sdkstats.py @@ -17,6 +17,7 @@ ) +# pylint: disable=protected-access class TestCustomerSdkStats(unittest.TestCase): """Test suite for customer SDK stats core functionality.""" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py index f1a817543684..21af15a20a80 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/customer_sdk_stats/test_utlities.py @@ -6,11 +6,11 @@ from unittest import mock from datetime import datetime -from requests.exceptions import ( +from requests.exceptions import ( # pylint: disable=networking-import-outside-azure-core-transport ConnectionError, ReadTimeout, Timeout, -) # pylint: disable=networking-import-outside-azure-core-transport +) from azure.core.exceptions import ServiceRequestTimeoutError, HttpResponseError from azure.monitor.opentelemetry.exporter._generated.models import ( diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py index 05a6f2c34df4..43a9f3893c35 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_manager.py @@ -428,7 +428,7 @@ def test_initialize_failure_exception( self, mock_is_enabled, mock_exporter_class, - mock_reader_class, + mock_reader_class, # pylint: disable=unused-argument mock_meter_provider_class, # pylint: disable=unused-argument ): """Test initialization failure due to exception.""" diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py index 15cbc70814d6..2013ce297866 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/statsbeat/test_statsbeat.py @@ -306,10 +306,10 @@ def test_get_statsbeat_configuration_callback_no_updated_config( # pylint: disa @mock.patch("azure.monitor.opentelemetry.exporter.AzureMonitorMetricExporter") def test_collect_statsbeat_metrics_no_callback_when_init_fails( # pylint: disable=name-too-long self, - mock_exporter, - mock_reader, - mock_meter_provider, - mock_statsbeat_metrics, + mock_exporter, # pylint: disable=unused-argument + mock_reader, # pylint: disable=unused-argument + mock_meter_provider, # pylint: disable=unused-argument + mock_statsbeat_metrics, # pylint: disable=unused-argument mock_config_manager_cls, # pylint: disable=unused-argument ): """Test that configuration callback is not registered when initialization fails.""" 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 db48435d9aaf..e6db79f20140 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 @@ -1248,8 +1248,8 @@ def test_get_authentication_credential_malformed( @mock.patch.dict("os.environ", {"APPLICATIONINSIGHTS_AUTHENTICATION_STRING": "ClientId=TEST_CLIENT_ID"}) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") def test_get_authentication_credential_no_auth(self, mock_managed_identity): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( - "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( # pylint: disable=name-too-long + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") @@ -1261,8 +1261,8 @@ def test_get_authentication_credential_no_auth(self, mock_managed_identity): # ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") def test_get_authentication_credential_no_aad(self, mock_managed_identity): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( - "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( # pylint: disable=name-too-long + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL result = _get_authentication_credential(foo="bar") @@ -1274,8 +1274,8 @@ def test_get_authentication_credential_no_aad(self, mock_managed_identity): # p ) @mock.patch("azure.monitor.opentelemetry.exporter.export._base.ManagedIdentityCredential") def test_get_authentication_credential_error(self, mock_managed_identity): # pylint: disable=name-too-long - MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( - "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" # pylint: disable=name-too-long + MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL = ( # pylint: disable=name-too-long + "MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL" ) mock_managed_identity.return_value = MOCK_MANAGED_IDENTITY_CLIENT_ID_CREDENTIAL mock_managed_identity.side_effect = ValueError("TEST ERROR") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py index 4c9cf5ea9fde..6a59941e072b 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/test_connection_string_parser.py @@ -358,16 +358,16 @@ def test_region_extraction_alphanumeric_regions(self): # pylint: disable=name-t ) self.assertEqual(parser.region, expected_region) - def test_application_id_extraction_from_connection_string(self): + def test_application_id_extraction_from_connection_string(self): # pylint: disable=name-too-long parser = ConnectionStringParser( connection_string="InstrumentationKey=" + self._valid_instrumentation_key + ";IngestionEndpoint=https://northeurope-999.in.applicationinsights.azure.com/" - + ";LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=3cd3dd3f-64cc-4d7c-9303-8d69a4bb8558" + + ";LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=3cd3dd3f-64cc-4d7c-9303-8d69a4bb8558" # pylint: disable=line-too-long ) self.assertEqual(parser.application_id, "3cd3dd3f-64cc-4d7c-9303-8d69a4bb8558") - def test_application_id_extraction_from_no_application_id(self): + def test_application_id_extraction_from_no_application_id(self): # pylint: disable=name-too-long parser = ConnectionStringParser( connection_string="InstrumentationKey=" + self._valid_instrumentation_key diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py index c9dc88c03a9b..3ea11551c16c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/tests/trace/test_trace.py @@ -41,7 +41,6 @@ _AZURE_SDK_NAMESPACE_NAME, _AZURE_SDK_OPENTELEMETRY_NAME, _AZURE_AI_SDK_NAME, - _APPLICATION_ID_RESOURCE_KEY, ) from azure.monitor.opentelemetry.exporter._generated.models import ContextTagKeys from azure.monitor.opentelemetry.exporter._utils import azure_monitor_context @@ -135,7 +134,12 @@ def test_export_failure(self): transmit.return_value = ExportResult.FAILED_RETRYABLE storage_mock = mock.Mock() exporter.storage.put = storage_mock - exporter._connection_string = "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=4321abcd-5678-4efa-8abc-1234567890ab" + exporter._connection_string = ( + "InstrumentationKey=4321abcd-5678-4efa-8abc-1234567890ab;" + "IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;" + "LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;" + "ApplicationId=4321abcd-5678-4efa-8abc-1234567890ab" + ) result = exporter.export([test_span]) self.assertEqual(result, SpanExportResult.FAILURE) self.assertEqual(storage_mock.call_count, 1) From 574f4a5d7515b565adf6b757f8cd65d53d9a2eda Mon Sep 17 00:00:00 2001 From: Radhika Gupta Date: Tue, 27 Jan 2026 11:51:07 -0800 Subject: [PATCH 7/7] Retrigger CI/CD pipeline