From cc35508054e6b61a977245947d4c3eca9d4da0f7 Mon Sep 17 00:00:00 2001 From: Aaron Abbott Date: Thu, 28 Mar 2024 16:47:29 +0000 Subject: [PATCH 1/5] Use ruff instead of black/isort for autoformatting --- .isort.cfg | 19 ----- dev-requirements.txt | 3 +- docs/conf.py | 4 +- docs/examples/auto-instrumentation/client.py | 1 - docs/examples/django/client.py | 1 - .../django/instrumentation_example/urls.py | 1 + docs/examples/django/manage.py | 1 + .../src/error_handler_0/__init__.py | 1 - .../src/error_handler_1/__init__.py | 1 - docs/examples/opentracing/rediscache.py | 1 - .../opencensus/trace_exporter/__init__.py | 9 ++- .../otlp/proto/common/_internal/__init__.py | 22 +++--- .../common/_internal/_log_encoder/__init__.py | 9 ++- .../_internal/metrics_encoder/__init__.py | 63 +++++++---------- .../_internal/trace_encoder/__init__.py | 15 ++-- .../tests/test_metrics_encoder.py | 13 ++-- .../exporter/otlp/proto/grpc/__init__.py | 1 + .../otlp/proto/grpc/_log_exporter/__init__.py | 8 +-- .../exporter/otlp/proto/grpc/exporter.py | 15 ++-- .../proto/grpc/metric_exporter/__init__.py | 23 +++---- .../proto/grpc/trace_exporter/__init__.py | 13 ++-- .../tests/logs/test_otlp_logs_exporter.py | 6 +- .../tests/test_otlp_metrics_exporter.py | 10 --- .../tests/test_otlp_trace_exporter.py | 17 +++-- .../exporter/otlp/proto/http/__init__.py | 2 +- .../otlp/proto/http/_log_exporter/__init__.py | 29 ++++---- .../proto/http/metric_exporter/__init__.py | 52 +++++++------- .../proto/http/trace_exporter/__init__.py | 22 +++--- .../http/trace_exporter/encoder/__init__.py | 20 +++--- .../metrics/test_otlp_metrics_exporter.py | 14 ---- .../tests/test_proto_log_exporter.py | 2 - .../tests/test_proto_span_exporter.py | 5 -- .../exporter/prometheus/__init__.py | 55 +++++++-------- .../tests/test_prometheus_exporter.py | 2 - .../exporter/zipkin/json/v1/__init__.py | 3 +- .../exporter/zipkin/json/v2/__init__.py | 4 +- .../tests/encoder/test_v1_json.py | 1 - .../exporter/zipkin/proto/http/__init__.py | 2 +- .../exporter/zipkin/proto/http/v2/__init__.py | 3 +- .../src/opentelemetry/context/__init__.py | 1 - .../src/opentelemetry/metrics/__init__.py | 8 +-- .../metrics/_internal/__init__.py | 1 - .../src/opentelemetry/propagate/__init__.py | 1 - .../src/opentelemetry/trace/__init__.py | 1 - .../src/opentelemetry/trace/span.py | 1 - .../src/opentelemetry/util/_decorator.py | 3 +- .../src/opentelemetry/util/_providers.py | 4 +- .../tests/logs/test_logger_provider.py | 1 - .../tests/metrics/test_instruments.py | 2 - opentelemetry-api/tests/metrics/test_meter.py | 1 - .../tests/metrics/test_meter_provider.py | 1 - .../tests/propagators/test_propagators.py | 3 - .../propagators/test_w3cbaggagepropagator.py | 3 - .../test_tracecontexthttptextformat.py | 1 - opentelemetry-api/tests/trace/test_globals.py | 1 - opentelemetry-api/tests/trace/test_status.py | 4 +- .../tests/util/test__importlib_metadata.py | 1 - .../tests/util/test__providers.py | 1 - opentelemetry-proto/tests/test_proto.py | 1 - .../sdk/_configuration/__init__.py | 27 +++++--- .../sdk/_logs/_internal/__init__.py | 1 - .../sdk/_logs/_internal/export/__init__.py | 8 +-- .../sdk/error_handler/__init__.py | 8 --- .../src/opentelemetry/sdk/metrics/__init__.py | 4 +- .../sdk/metrics/_internal/__init__.py | 13 ---- .../_internal/_view_instrument_match.py | 3 - .../sdk/metrics/_internal/aggregation.py | 21 +----- .../exponential_histogram/buckets.py | 4 -- .../exponential_histogram/mapping/__init__.py | 1 - .../exponential_histogram/mapping/ieee_754.py | 3 +- .../mapping/logarithm_mapping.py | 1 - .../sdk/metrics/_internal/export/__init__.py | 69 +++++++++---------- .../sdk/metrics/_internal/instrument.py | 3 - .../metrics/_internal/measurement_consumer.py | 3 - .../_internal/metric_reader_storage.py | 17 ++--- .../sdk/metrics/_internal/view.py | 2 - .../opentelemetry/sdk/resources/__init__.py | 3 +- .../src/opentelemetry/sdk/trace/__init__.py | 12 ++-- .../sdk/trace/export/__init__.py | 17 ++--- .../src/opentelemetry/sdk/trace/sampling.py | 1 + .../src/opentelemetry/sdk/util/__init__.pyi | 2 +- .../tests/error_handler/test_error_handler.py | 2 - opentelemetry-sdk/tests/logs/test_handler.py | 1 - .../test_exponent_mapping.py | 6 -- ...xponential_bucket_histogram_aggregation.py | 19 ----- .../test_logarithm_mapping.py | 6 -- .../integration_test/test_console_exporter.py | 2 - .../metrics/integration_test/test_cpu_time.py | 6 +- ...t_explicit_bucket_histogram_aggregation.py | 10 --- .../integration_test/test_histogram_export.py | 1 - .../integration_test/test_sum_aggregation.py | 14 ---- .../tests/metrics/test_aggregation.py | 7 -- .../metrics/test_in_memory_metric_reader.py | 1 - .../metrics/test_measurement_consumer.py | 1 - .../tests/metrics/test_metric_reader.py | 2 - .../metrics/test_metric_reader_storage.py | 7 +- .../tests/metrics/test_metrics.py | 4 -- .../test_periodic_exporting_metric_reader.py | 1 - opentelemetry-sdk/tests/metrics/test_point.py | 10 --- opentelemetry-sdk/tests/metrics/test_view.py | 9 --- .../metrics/test_view_instrument_match.py | 1 - .../tests/resources/test_resources.py | 6 +- opentelemetry-sdk/tests/test_configurator.py | 2 - .../tests/trace/export/test_export.py | 3 - .../tests/trace/test_sampling.py | 1 - opentelemetry-sdk/tests/trace/test_trace.py | 2 - .../tests/test_semconv.py | 1 - .../tests/test_b3_format.py | 1 - .../propagators/jaeger/__init__.py | 1 - .../tests/test_jaeger_propagator.py | 13 ++-- pyproject.toml | 67 +++++++++++++----- scripts/check_for_valid_readme.py | 2 +- scripts/eachdist.py | 22 +++--- scripts/public_symbols_checker.py | 12 ++-- .../shim/opencensus/_shim_span.py | 12 ++-- .../shim/opencensus/_shim_tracer.py | 2 +- .../shim/opentracing_shim/__init__.py | 8 ++- .../tests/test_shim.py | 7 +- .../test_asyncio.py | 1 - .../test_threads.py | 1 - .../src/opentelemetry/test/__init__.py | 6 +- .../src/opentelemetry/test/wsgitestutil.py | 4 +- .../tests/test_utils.py | 13 ---- 123 files changed, 367 insertions(+), 666 deletions(-) delete mode 100644 .isort.cfg diff --git a/.isort.cfg b/.isort.cfg deleted file mode 100644 index ab1ab74ee59..00000000000 --- a/.isort.cfg +++ /dev/null @@ -1,19 +0,0 @@ -[settings] -include_trailing_comma=True -force_grid_wrap=0 -use_parentheses=True -line_length=79 -profile=black - -; 3 stands for Vertical Hanging Indent, e.g. -; from third_party import ( -; lib1, -; lib2, -; lib3, -; ) -; docs: https://github.com/timothycrosley/isort#multi-line-output-modes -multi_line_output=3 -skip=target -skip_glob=**/gen/*,.venv*/*,venv*/*,**/proto/*,.tox/* -known_first_party=opentelemetry,opentelemetry_example_app -known_third_party=psutil,pytest,redis,redis_opentracing diff --git a/dev-requirements.txt b/dev-requirements.txt index 01f46ae87e9..298dad5fd1b 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,7 +1,5 @@ pylint==3.0.2 flake8==6.1.0 -isort==5.12.0 -black==22.3.0 httpretty==1.1.4 mypy==1.9.0 sphinx==7.1.2 @@ -19,3 +17,4 @@ asgiref==3.7.2 psutil==5.9.6 GitPython==3.1.41 flaky==3.7.0 +ruff==0.3.4 diff --git a/docs/conf.py b/docs/conf.py index 352cf927cd4..fbe5165f2d7 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -169,9 +169,7 @@ .. |SCM_WEB| replace:: {s} .. |SCM_RAW_WEB| replace:: {sr} .. |SCM_BRANCH| replace:: {b} -""".format( - s=scm_web, sr=scm_raw_web, b=branch -) +""".format(s=scm_web, sr=scm_raw_web, b=branch) # used to have links to repo files extlinks = { diff --git a/docs/examples/auto-instrumentation/client.py b/docs/examples/auto-instrumentation/client.py index 4f70e2b9333..0320493f94a 100644 --- a/docs/examples/auto-instrumentation/client.py +++ b/docs/examples/auto-instrumentation/client.py @@ -35,7 +35,6 @@ assert len(argv) == 2 with tracer.start_as_current_span("client"): - with tracer.start_as_current_span("client-server"): headers = {} inject(headers) diff --git a/docs/examples/django/client.py b/docs/examples/django/client.py index 859fe4a9da7..d8d476902e8 100644 --- a/docs/examples/django/client.py +++ b/docs/examples/django/client.py @@ -33,7 +33,6 @@ with tracer.start_as_current_span("client"): - with tracer.start_as_current_span("client-server"): headers = {} inject(headers) diff --git a/docs/examples/django/instrumentation_example/urls.py b/docs/examples/django/instrumentation_example/urls.py index 292467155f8..fcdb2e09be8 100644 --- a/docs/examples/django/instrumentation_example/urls.py +++ b/docs/examples/django/instrumentation_example/urls.py @@ -26,6 +26,7 @@ 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path("blog/", include("blog.urls")) """ + from django.contrib import admin from django.urls import include, path diff --git a/docs/examples/django/manage.py b/docs/examples/django/manage.py index bc2d44886b4..0a6f51e2596 100755 --- a/docs/examples/django/manage.py +++ b/docs/examples/django/manage.py @@ -14,6 +14,7 @@ # limitations under the License. """Django"s command-line utility for administrative tasks.""" + import os import sys diff --git a/docs/examples/error_handler/error_handler_0/src/error_handler_0/__init__.py b/docs/examples/error_handler/error_handler_0/src/error_handler_0/__init__.py index 8b42b7c70eb..ef3034bc6b9 100644 --- a/docs/examples/error_handler/error_handler_0/src/error_handler_0/__init__.py +++ b/docs/examples/error_handler/error_handler_0/src/error_handler_0/__init__.py @@ -21,5 +21,4 @@ class ErrorHandler0(ErrorHandler, ZeroDivisionError): def _handle(self, error: Exception, *args, **kwargs): - logger.exception("ErrorHandler0 handling a ZeroDivisionError") diff --git a/docs/examples/error_handler/error_handler_1/src/error_handler_1/__init__.py b/docs/examples/error_handler/error_handler_1/src/error_handler_1/__init__.py index cc63465617f..1f210a384f6 100644 --- a/docs/examples/error_handler/error_handler_1/src/error_handler_1/__init__.py +++ b/docs/examples/error_handler/error_handler_1/src/error_handler_1/__init__.py @@ -22,7 +22,6 @@ # pylint: disable=too-many-ancestors class ErrorHandler1(ErrorHandler, IndexError, KeyError): def _handle(self, error: Exception, *args, **kwargs): - if isinstance(error, IndexError): logger.exception("ErrorHandler1 handling an IndexError") diff --git a/docs/examples/opentracing/rediscache.py b/docs/examples/opentracing/rediscache.py index 9d2a51aab87..61025eac725 100644 --- a/docs/examples/opentracing/rediscache.py +++ b/docs/examples/opentracing/rediscache.py @@ -30,7 +30,6 @@ def __call__(self, func): @wraps(func) def inner(*args, **kwargs): with self.tracer.start_active_span("Caching decorator") as scope1: - # Pickle the call args to get a canonical key. Don't do this in # prod! key = pickle.dumps((func.__qualname__, args, kwargs)) diff --git a/exporter/opentelemetry-exporter-opencensus/src/opentelemetry/exporter/opencensus/trace_exporter/__init__.py b/exporter/opentelemetry-exporter-opencensus/src/opentelemetry/exporter/opencensus/trace_exporter/__init__.py index b855728cad5..0b79bbb2073 100644 --- a/exporter/opentelemetry-exporter-opencensus/src/opentelemetry/exporter/opencensus/trace_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-opencensus/src/opentelemetry/exporter/opencensus/trace_exporter/__init__.py @@ -133,24 +133,23 @@ def translate_to_collector(spans: Sequence[ReadableSpan]): collector_span.parent_span_id = parent_id.to_bytes(8, "big") if span.context.trace_state is not None: - for (key, value) in span.context.trace_state.items(): + for key, value in span.context.trace_state.items(): collector_span.tracestate.entries.add(key=key, value=value) if span.attributes: - for (key, value) in span.attributes.items(): + for key, value in span.attributes.items(): utils.add_proto_attribute_value( collector_span.attributes, key, value ) if span.events: for event in span.events: - collector_annotation = trace_pb2.Span.TimeEvent.Annotation( description=trace_pb2.TruncatableString(value=event.name) ) if event.attributes: - for (key, value) in event.attributes.items(): + for key, value in event.attributes.items(): utils.add_proto_attribute_value( collector_annotation.attributes, key, value ) @@ -183,7 +182,7 @@ def translate_to_collector(spans: Sequence[ReadableSpan]): ) if link.attributes: - for (key, value) in link.attributes.items(): + for key, value in link.attributes.items(): utils.add_proto_attribute_value( collector_span_link.attributes, key, value ) diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py index 6593d89fd87..da297f1d55f 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/__init__.py @@ -18,31 +18,31 @@ from itertools import count from typing import ( Any, - Mapping, - Optional, - List, Callable, - TypeVar, Dict, Iterator, + List, + Mapping, + Optional, + TypeVar, ) -from opentelemetry.sdk.util.instrumentation import InstrumentationScope +from opentelemetry.proto.common.v1.common_pb2 import AnyValue as PB2AnyValue from opentelemetry.proto.common.v1.common_pb2 import ( - InstrumentationScope as PB2InstrumentationScope, + ArrayValue as PB2ArrayValue, ) -from opentelemetry.proto.resource.v1.resource_pb2 import ( - Resource as PB2Resource, +from opentelemetry.proto.common.v1.common_pb2 import ( + InstrumentationScope as PB2InstrumentationScope, ) -from opentelemetry.proto.common.v1.common_pb2 import AnyValue as PB2AnyValue from opentelemetry.proto.common.v1.common_pb2 import KeyValue as PB2KeyValue from opentelemetry.proto.common.v1.common_pb2 import ( KeyValueList as PB2KeyValueList, ) -from opentelemetry.proto.common.v1.common_pb2 import ( - ArrayValue as PB2ArrayValue, +from opentelemetry.proto.resource.v1.resource_pb2 import ( + Resource as PB2Resource, ) from opentelemetry.sdk.trace import Resource +from opentelemetry.sdk.util.instrumentation import InstrumentationScope from opentelemetry.util.types import Attributes _logger = logging.getLogger(__name__) diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/_log_encoder/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/_log_encoder/__init__.py index c664e3ba883..d6909b45173 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/_log_encoder/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/_log_encoder/__init__.py @@ -12,25 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. from collections import defaultdict -from typing import Sequence, List +from typing import List, Sequence from opentelemetry.exporter.otlp.proto.common._internal import ( + _encode_attributes, _encode_instrumentation_scope, _encode_resource, _encode_span_id, _encode_trace_id, _encode_value, - _encode_attributes, ) from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ( ExportLogsServiceRequest, ) +from opentelemetry.proto.logs.v1.logs_pb2 import LogRecord as PB2LogRecord from opentelemetry.proto.logs.v1.logs_pb2 import ( - ScopeLogs, ResourceLogs, + ScopeLogs, ) -from opentelemetry.proto.logs.v1.logs_pb2 import LogRecord as PB2LogRecord - from opentelemetry.sdk._logs import LogData diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/metrics_encoder/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/metrics_encoder/__init__.py index 0d66fd28b70..dde34e4da64 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/metrics_encoder/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/metrics_encoder/__init__.py @@ -12,12 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. import logging +from os import environ +from typing import Dict -from opentelemetry.sdk.metrics.export import ( - MetricExporter, +from opentelemetry.exporter.otlp.proto.common._internal import ( + _encode_attributes, +) +from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ( + ExportMetricsServiceRequest, +) +from opentelemetry.proto.common.v1.common_pb2 import InstrumentationScope +from opentelemetry.proto.metrics.v1 import metrics_pb2 as pb2 +from opentelemetry.proto.resource.v1.resource_pb2 import ( + Resource as PB2Resource, +) +from opentelemetry.sdk.environment_variables import ( + OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION, + OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE, ) -from opentelemetry.sdk.metrics.view import Aggregation -from os import environ from opentelemetry.sdk.metrics import ( Counter, Histogram, @@ -26,37 +38,23 @@ ObservableUpDownCounter, UpDownCounter, ) -from opentelemetry.exporter.otlp.proto.common._internal import ( - _encode_attributes, -) -from opentelemetry.sdk.environment_variables import ( - OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE, -) from opentelemetry.sdk.metrics.export import ( AggregationTemporality, -) -from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ( - ExportMetricsServiceRequest, -) -from opentelemetry.proto.common.v1.common_pb2 import InstrumentationScope -from opentelemetry.proto.metrics.v1 import metrics_pb2 as pb2 -from opentelemetry.sdk.metrics.export import ( - MetricsData, Gauge, - Histogram as HistogramType, + MetricExporter, + MetricsData, Sum, - ExponentialHistogram as ExponentialHistogramType, ) -from typing import Dict -from opentelemetry.proto.resource.v1.resource_pb2 import ( - Resource as PB2Resource, +from opentelemetry.sdk.metrics.export import ( + ExponentialHistogram as ExponentialHistogramType, ) -from opentelemetry.sdk.environment_variables import ( - OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION, +from opentelemetry.sdk.metrics.export import ( + Histogram as HistogramType, ) from opentelemetry.sdk.metrics.view import ( - ExponentialBucketHistogramAggregation, + Aggregation, ExplicitBucketHistogramAggregation, + ExponentialBucketHistogramAggregation, ) _logger = logging.getLogger(__name__) @@ -68,7 +66,6 @@ def _common_configuration( preferred_temporality: Dict[type, AggregationTemporality] = None, preferred_aggregation: Dict[type, Aggregation] = None, ) -> None: - MetricExporter.__init__( self, preferred_temporality=self._get_temporality(preferred_temporality), @@ -78,7 +75,6 @@ def _common_configuration( def _get_temporality( self, preferred_temporality: Dict[type, AggregationTemporality] ) -> Dict[type, AggregationTemporality]: - otel_exporter_otlp_metrics_temporality_preference = ( environ.get( OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE, @@ -135,7 +131,6 @@ def _get_aggregation( self, preferred_aggregation: Dict[type, Aggregation], ) -> Dict[type, Aggregation]: - otel_exporter_otlp_metrics_default_histogram_aggregation = environ.get( OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION, "explicit_bucket_histogram", @@ -144,17 +139,14 @@ def _get_aggregation( if otel_exporter_otlp_metrics_default_histogram_aggregation == ( "base2_exponential_bucket_histogram" ): - instrument_class_aggregation = { Histogram: ExponentialBucketHistogramAggregation(), } else: - if otel_exporter_otlp_metrics_default_histogram_aggregation != ( "explicit_bucket_histogram" ): - _logger.warning( ( "Invalid value for %s: %s, using explicit bucket " @@ -177,7 +169,6 @@ def encode_metrics(data: MetricsData) -> ExportMetricsServiceRequest: resource_metrics_dict = {} for resource_metrics in data.resource_metrics: - resource = resource_metrics.resource # It is safe to assume that each entry in data.resource_metrics is @@ -187,7 +178,6 @@ def encode_metrics(data: MetricsData) -> ExportMetricsServiceRequest: resource_metrics_dict[resource] = scope_metrics_dict for scope_metrics in resource_metrics.scope_metrics: - instrumentation_scope = scope_metrics.scope # The SDK groups metrics in instrumentation scopes already so @@ -271,7 +261,6 @@ def encode_metrics(data: MetricsData) -> ExportMetricsServiceRequest: elif isinstance(metric.data, ExponentialHistogramType): for data_point in metric.data.data_points: - if data_point.positive.bucket_counts: positive = pb2.ExponentialHistogramDataPoint.Buckets( offset=data_point.positive.offset, @@ -306,9 +295,7 @@ def encode_metrics(data: MetricsData) -> ExportMetricsServiceRequest: max=data_point.max, min=data_point.min, ) - pb2_metric.exponential_histogram.aggregation_temporality = ( - metric.data.aggregation_temporality - ) + pb2_metric.exponential_histogram.aggregation_temporality = metric.data.aggregation_temporality pb2_metric.exponential_histogram.data_points.append(pt) else: diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/trace_encoder/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/trace_encoder/__init__.py index 99498c93ef7..3a62916bc20 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/trace_encoder/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/trace_encoder/__init__.py @@ -17,27 +17,26 @@ from typing import List, Optional, Sequence from opentelemetry.exporter.otlp.proto.common._internal import ( - _encode_trace_id, - _encode_span_id, - _encode_instrumentation_scope, _encode_attributes, + _encode_instrumentation_scope, _encode_resource, + _encode_span_id, + _encode_trace_id, ) from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ( ExportTraceServiceRequest as PB2ExportTraceServiceRequest, ) from opentelemetry.proto.trace.v1.trace_pb2 import ( - ScopeSpans as PB2ScopeSpans, + ResourceSpans as PB2ResourceSpans, ) from opentelemetry.proto.trace.v1.trace_pb2 import ( - ResourceSpans as PB2ResourceSpans, + ScopeSpans as PB2ScopeSpans, ) from opentelemetry.proto.trace.v1.trace_pb2 import Span as PB2SPan from opentelemetry.proto.trace.v1.trace_pb2 import Status as PB2Status from opentelemetry.sdk.trace import Event, ReadableSpan -from opentelemetry.trace import Link -from opentelemetry.trace import SpanKind -from opentelemetry.trace.span import SpanContext, TraceState, Status +from opentelemetry.trace import Link, SpanKind +from opentelemetry.trace.span import SpanContext, Status, TraceState # pylint: disable=E1101 _SPAN_KIND_MAP = { diff --git a/exporter/opentelemetry-exporter-otlp-proto-common/tests/test_metrics_encoder.py b/exporter/opentelemetry-exporter-otlp-proto-common/tests/test_metrics_encoder.py index 70863bb44a7..880ea69de6e 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-common/tests/test_metrics_encoder.py +++ b/exporter/opentelemetry-exporter-otlp-proto-common/tests/test_metrics_encoder.py @@ -30,19 +30,20 @@ from opentelemetry.proto.resource.v1.resource_pb2 import ( Resource as OTLPResource, ) -from opentelemetry.sdk.metrics.export import AggregationTemporality, Buckets -from opentelemetry.sdk.metrics.export import ( - ExponentialHistogram as ExponentialHistogramType, -) -from opentelemetry.sdk.metrics.export import ExponentialHistogramDataPoint -from opentelemetry.sdk.metrics.export import Histogram as HistogramType from opentelemetry.sdk.metrics.export import ( + AggregationTemporality, + Buckets, + ExponentialHistogramDataPoint, HistogramDataPoint, Metric, MetricsData, ResourceMetrics, ScopeMetrics, ) +from opentelemetry.sdk.metrics.export import ( + ExponentialHistogram as ExponentialHistogramType, +) +from opentelemetry.sdk.metrics.export import Histogram as HistogramType from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.util.instrumentation import ( InstrumentationScope as SDKInstrumentationScope, diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/__init__.py index 07553d69d03..31976a43dac 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/__init__.py @@ -69,6 +69,7 @@ API --- """ + from .version import __version__ _USER_AGENT_HEADER_VALUE = "OTel-OTLP-Exporter-Python/" + __version__ diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/_log_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/_log_exporter/__init__.py index 3a87ef1223c..039fb392116 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/_log_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/_log_exporter/__init__.py @@ -12,10 +12,10 @@ # limitations under the License. from os import environ -from typing import Dict, Optional, Tuple, Union, Sequence +from typing import Dict, Optional, Sequence, Tuple, Union from typing import Sequence as TypingSequence -from grpc import ChannelCredentials, Compression +from grpc import ChannelCredentials, Compression from opentelemetry.exporter.otlp.proto.common._log_encoder import encode_logs from opentelemetry.exporter.otlp.proto.grpc.exporter import ( OTLPExporterMixin, @@ -28,10 +28,9 @@ from opentelemetry.proto.collector.logs.v1.logs_service_pb2_grpc import ( LogsServiceStub, ) -from opentelemetry.sdk._logs import LogRecord as SDKLogRecord from opentelemetry.sdk._logs import LogData +from opentelemetry.sdk._logs import LogRecord as SDKLogRecord from opentelemetry.sdk._logs.export import LogExporter, LogExportResult - from opentelemetry.sdk.environment_variables import ( OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE, OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, @@ -46,7 +45,6 @@ class OTLPLogExporter( LogExporter, OTLPExporterMixin[SDKLogRecord, ExportLogsServiceRequest, LogExportResult], ): - _result = LogExportResult _stub = LogsServiceStub diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/exporter.py index b4226828280..a43d7e9d648 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/exporter.py @@ -28,19 +28,15 @@ List, Optional, Tuple, + TypeVar, Union, ) from typing import Sequence as TypingSequence -from typing import TypeVar from urllib.parse import urlparse from deprecated import deprecated - -from opentelemetry.exporter.otlp.proto.common._internal import ( - _get_resource_data, - _create_exp_backoff_generator, -) from google.rpc.error_details_pb2 import RetryInfo + from grpc import ( ChannelCredentials, Compression, @@ -50,7 +46,10 @@ secure_channel, ssl_channel_credentials, ) - +from opentelemetry.exporter.otlp.proto.common._internal import ( + _create_exp_backoff_generator, + _get_resource_data, +) from opentelemetry.exporter.otlp.proto.grpc import ( _OTLP_GRPC_HEADERS, ) @@ -268,7 +267,6 @@ def _export( return self._result.SUCCESS except RpcError as error: - if error.code() in [ StatusCode.CANCELLED, StatusCode.DEADLINE_EXCEEDED, @@ -278,7 +276,6 @@ def _export( StatusCode.UNAVAILABLE, StatusCode.DATA_LOSS, ]: - retry_info_bin = dict(error.trailing_metadata()).get( "google.rpc.retryinfo-bin" ) diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/metric_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/metric_exporter/__init__.py index 0ceca25c867..859f2ea15dc 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/metric_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/metric_exporter/__init__.py @@ -16,18 +16,18 @@ from os import environ from typing import Dict, Iterable, List, Optional, Tuple, Union from typing import Sequence as TypingSequence -from grpc import ChannelCredentials, Compression +from grpc import ChannelCredentials, Compression +from opentelemetry.exporter.otlp.proto.common._internal.metrics_encoder import ( + OTLPMetricExporterMixin, +) from opentelemetry.exporter.otlp.proto.common.metrics_encoder import ( encode_metrics, ) -from opentelemetry.sdk.metrics._internal.aggregation import Aggregation -from opentelemetry.exporter.otlp.proto.grpc.exporter import ( +from opentelemetry.exporter.otlp.proto.grpc.exporter import ( # noqa: F401 OTLPExporterMixin, _get_credentials, environ_to_compression, -) -from opentelemetry.exporter.otlp.proto.grpc.exporter import ( # noqa: F401 get_resource_data, ) from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ( @@ -48,24 +48,24 @@ OTEL_EXPORTER_OTLP_METRICS_INSECURE, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, ) -from opentelemetry.sdk.metrics.export import ( +from opentelemetry.sdk.metrics._internal.aggregation import Aggregation +from opentelemetry.sdk.metrics.export import ( # noqa: F401 AggregationTemporality, DataPointT, + Gauge, Metric, MetricExporter, MetricExportResult, MetricsData, ResourceMetrics, ScopeMetrics, + Sum, ) from opentelemetry.sdk.metrics.export import ( # noqa: F401 - Gauge, - Histogram as HistogramType, - Sum, ExponentialHistogram as ExponentialHistogramType, ) -from opentelemetry.exporter.otlp.proto.common._internal.metrics_encoder import ( - OTLPMetricExporterMixin, +from opentelemetry.sdk.metrics.export import ( # noqa: F401 + Histogram as HistogramType, ) _logger = getLogger(__name__) @@ -102,7 +102,6 @@ def __init__( preferred_aggregation: Dict[type, Aggregation] = None, max_export_batch_size: Optional[int] = None, ): - if insecure is None: insecure = environ.get(OTEL_EXPORTER_OTLP_METRICS_INSECURE) if insecure is not None: diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/trace_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/trace_exporter/__init__.py index bd120ac7874..07473458ac3 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/trace_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/trace_exporter/__init__.py @@ -18,18 +18,14 @@ from typing import Dict, Optional, Sequence, Tuple, Union from typing import Sequence as TypingSequence - from grpc import ChannelCredentials, Compression - from opentelemetry.exporter.otlp.proto.common.trace_encoder import ( encode_spans, ) -from opentelemetry.exporter.otlp.proto.grpc.exporter import ( +from opentelemetry.exporter.otlp.proto.grpc.exporter import ( # noqa: F401 OTLPExporterMixin, _get_credentials, environ_to_compression, -) -from opentelemetry.exporter.otlp.proto.grpc.exporter import ( # noqa: F401 get_resource_data, ) from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ( @@ -42,11 +38,13 @@ InstrumentationScope, ) from opentelemetry.proto.trace.v1.trace_pb2 import ( # noqa: F401 - ScopeSpans, ResourceSpans, + ScopeSpans, + Status, +) +from opentelemetry.proto.trace.v1.trace_pb2 import ( # noqa: F401 Span as CollectorSpan, ) -from opentelemetry.proto.trace.v1.trace_pb2 import Status # noqa: F401 from opentelemetry.sdk.environment_variables import ( OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, @@ -94,7 +92,6 @@ def __init__( timeout: Optional[int] = None, compression: Optional[Compression] = None, ): - if insecure is None: insecure = environ.get(OTEL_EXPORTER_OTLP_TRACES_INSECURE) if insecure is not None: diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/logs/test_otlp_logs_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/logs/test_otlp_logs_exporter.py index a6479a14741..a3e3e45497b 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/logs/test_otlp_logs_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/logs/test_otlp_logs_exporter.py @@ -36,11 +36,10 @@ LogsServiceServicer, add_LogsServiceServicer_to_server, ) -from opentelemetry.proto.common.v1.common_pb2 import AnyValue +from opentelemetry.proto.common.v1.common_pb2 import AnyValue, KeyValue from opentelemetry.proto.common.v1.common_pb2 import ( InstrumentationScope as PB2InstrumentationScope, ) -from opentelemetry.proto.common.v1.common_pb2 import KeyValue from opentelemetry.proto.logs.v1.logs_pb2 import LogRecord as PB2LogRecord from opentelemetry.proto.logs.v1.logs_pb2 import ResourceLogs, ScopeLogs from opentelemetry.proto.resource.v1.resource_pb2 import ( @@ -297,7 +296,6 @@ def test_otlp_headers_from_env(self): ) @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") def test_unavailable(self, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_LogsServiceServicer_to_server( @@ -313,7 +311,6 @@ def test_unavailable(self, mock_sleep, mock_expo): ) @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") def test_unavailable_delay(self, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_LogsServiceServicer_to_server( @@ -341,7 +338,6 @@ def test_failure(self): ) def test_translate_log_data(self): - expected = ExportLogsServiceRequest( resource_logs=[ ResourceLogs( diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_metrics_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_metrics_exporter.py index 95733b917bf..a7756725be2 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_metrics_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_metrics_exporter.py @@ -140,7 +140,6 @@ class TestOTLPMetricExporter(TestCase): # pylint: disable=too-many-public-methods def setUp(self): - self.exporter = OTLPMetricExporter() self.server = server(ThreadPoolExecutor(max_workers=10)) @@ -420,7 +419,6 @@ def test_otlp_exporter_otlp_compression_unspecified( ) @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") def test_unavailable(self, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_MetricsServiceServicer_to_server( @@ -437,7 +435,6 @@ def test_unavailable(self, mock_sleep, mock_expo): ) @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") def test_unavailable_delay(self, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_MetricsServiceServicer_to_server( @@ -455,7 +452,6 @@ def test_unavailable_delay(self, mock_sleep, mock_expo): @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.logger.error") def test_unknown_logs(self, mock_logger_error, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_MetricsServiceServicer_to_server( @@ -825,7 +821,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "CUMULATIVE"}, ): - otlp_metric_exporter = OTLPMetricExporter() for ( @@ -838,7 +833,6 @@ def test_aggregation_temporality(self): with patch.dict( environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "ABC"} ): - with self.assertLogs(level=WARNING): otlp_metric_exporter = OTLPMetricExporter() @@ -853,7 +847,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "DELTA"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -887,7 +880,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "LOWMEMORY"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -918,7 +910,6 @@ def test_aggregation_temporality(self): ) def test_exponential_explicit_bucket_histogram(self): - self.assertIsInstance( # pylint: disable=protected-access OTLPMetricExporter()._preferred_aggregation[Histogram], @@ -969,7 +960,6 @@ def test_exponential_explicit_bucket_histogram(self): ) def test_preferred_aggregation_override(self): - histogram_aggregation = ExplicitBucketHistogramAggregation( boundaries=[0.05, 0.1, 0.5, 1, 5, 10], ) diff --git a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py index bb17e35b7b7..8c27fbe63a3 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-grpc/tests/test_otlp_trace_exporter.py @@ -40,17 +40,23 @@ TraceServiceServicer, add_TraceServiceServicer_to_server, ) -from opentelemetry.proto.common.v1.common_pb2 import AnyValue, ArrayValue +from opentelemetry.proto.common.v1.common_pb2 import ( + AnyValue, + ArrayValue, + KeyValue, +) from opentelemetry.proto.common.v1.common_pb2 import ( InstrumentationScope as PB2InstrumentationScope, ) -from opentelemetry.proto.common.v1.common_pb2 import KeyValue from opentelemetry.proto.resource.v1.resource_pb2 import ( Resource as OTLPResource, ) -from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans, ScopeSpans +from opentelemetry.proto.trace.v1.trace_pb2 import ( + ResourceSpans, + ScopeSpans, + Status, +) from opentelemetry.proto.trace.v1.trace_pb2 import Span as OTLPSpan -from opentelemetry.proto.trace.v1.trace_pb2 import Status from opentelemetry.sdk.environment_variables import ( OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE, @@ -463,7 +469,6 @@ def test_otlp_headers(self, mock_ssl_channel, mock_secure): ) @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") def test_unavailable(self, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_TraceServiceServicer_to_server( @@ -478,7 +483,6 @@ def test_unavailable(self, mock_sleep, mock_expo): ) @patch("opentelemetry.exporter.otlp.proto.grpc.exporter.sleep") def test_unavailable_delay(self, mock_sleep, mock_expo): - mock_expo.configure_mock(**{"return_value": [1]}) add_TraceServiceServicer_to_server( @@ -506,7 +510,6 @@ def test_failure(self): ) def test_translate_spans(self): - expected = ExportTraceServiceRequest( resource_spans=[ ResourceSpans( diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/__init__.py index 2c40b39590b..b8f92bd9a87 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/__init__.py @@ -69,11 +69,11 @@ API --- """ + import enum from .version import __version__ - _OTLP_HTTP_HEADERS = { "Content-Type": "application/x-protobuf", "User-Agent": "OTel-OTLP-Exporter-Python/" + __version__, diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/_log_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/_log_exporter/__init__.py index 902ac5f2429..51aea1a3935 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/_log_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/_log_exporter/__init__.py @@ -17,8 +17,8 @@ import zlib from io import BytesIO from os import environ -from typing import Dict, Optional, Sequence from time import sleep +from typing import Dict, Optional, Sequence import requests @@ -26,30 +26,29 @@ _create_exp_backoff_generator, ) from opentelemetry.exporter.otlp.proto.common._log_encoder import encode_logs +from opentelemetry.exporter.otlp.proto.http import ( + _OTLP_HTTP_HEADERS, + Compression, +) +from opentelemetry.sdk._logs import LogData +from opentelemetry.sdk._logs.export import ( + LogExporter, + LogExportResult, +) from opentelemetry.sdk.environment_variables import ( OTEL_EXPORTER_OTLP_CERTIFICATE, OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS, - OTEL_EXPORTER_OTLP_TIMEOUT, - OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE, + OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_LOGS_HEADERS, OTEL_EXPORTER_OTLP_LOGS_TIMEOUT, - OTEL_EXPORTER_OTLP_LOGS_COMPRESSION, -) -from opentelemetry.sdk._logs import LogData -from opentelemetry.sdk._logs.export import ( - LogExporter, - LogExportResult, -) -from opentelemetry.exporter.otlp.proto.http import ( - _OTLP_HTTP_HEADERS, - Compression, + OTEL_EXPORTER_OTLP_TIMEOUT, ) from opentelemetry.util.re import parse_env_headers - _logger = logging.getLogger(__name__) @@ -60,7 +59,6 @@ class OTLPLogExporter(LogExporter): - _MAX_RETRY_TIMEOUT = 64 def __init__( @@ -140,7 +138,6 @@ def export(self, batch: Sequence[LogData]) -> LogExportResult: for delay in _create_exp_backoff_generator( max_value=self._MAX_RETRY_TIMEOUT ): - if delay == self._MAX_RETRY_TIMEOUT: return LogExportResult.FAILURE diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/metric_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/metric_exporter/__init__.py index 57e030bd549..fbd6a6b05aa 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/metric_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/metric_exporter/__init__.py @@ -14,17 +14,25 @@ import gzip import logging import zlib -from os import environ -from typing import Dict, Optional, Any, Callable, List -from typing import Sequence, Mapping # noqa: F401 - from io import BytesIO +from os import environ from time import sleep +from typing import ( # noqa: F401 + Any, + Callable, + Dict, + List, + Mapping, + Optional, + Sequence, +) + +import requests from deprecated import deprecated from opentelemetry.exporter.otlp.proto.common._internal import ( - _get_resource_data, _create_exp_backoff_generator, + _get_resource_data, ) from opentelemetry.exporter.otlp.proto.common._internal.metrics_encoder import ( OTLPMetricExporterMixin, @@ -33,52 +41,48 @@ encode_metrics, ) from opentelemetry.exporter.otlp.proto.http import Compression -from opentelemetry.sdk.metrics._internal.aggregation import Aggregation from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ( # noqa: F401 ExportMetricsServiceRequest, ) from opentelemetry.proto.common.v1.common_pb2 import ( # noqa: F401 AnyValue, ArrayValue, + InstrumentationScope, KeyValue, KeyValueList, ) -from opentelemetry.proto.common.v1.common_pb2 import ( # noqa: F401 - InstrumentationScope, -) -from opentelemetry.proto.resource.v1.resource_pb2 import Resource # noqa: F401 from opentelemetry.proto.metrics.v1 import metrics_pb2 as pb2 # noqa: F401 +from opentelemetry.proto.resource.v1.resource_pb2 import Resource # noqa: F401 +from opentelemetry.proto.resource.v1.resource_pb2 import ( + Resource as PB2Resource, +) from opentelemetry.sdk.environment_variables import ( - OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_CERTIFICATE, - OTEL_EXPORTER_OTLP_HEADERS, - OTEL_EXPORTER_OTLP_TIMEOUT, OTEL_EXPORTER_OTLP_COMPRESSION, - OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, + OTEL_EXPORTER_OTLP_ENDPOINT, + OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE, + OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, + OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_HEADERS, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, - OTEL_EXPORTER_OTLP_METRICS_COMPRESSION, + OTEL_EXPORTER_OTLP_TIMEOUT, ) -from opentelemetry.sdk.metrics.export import ( +from opentelemetry.sdk.metrics._internal.aggregation import Aggregation +from opentelemetry.sdk.metrics.export import ( # noqa: F401 AggregationTemporality, + Gauge, MetricExporter, MetricExportResult, MetricsData, + Sum, ) from opentelemetry.sdk.metrics.export import ( # noqa: F401 - Gauge, Histogram as HistogramType, - Sum, ) from opentelemetry.sdk.resources import Resource as SDKResource from opentelemetry.util.re import parse_env_headers -import requests -from opentelemetry.proto.resource.v1.resource_pb2 import ( - Resource as PB2Resource, -) - _logger = logging.getLogger(__name__) @@ -89,7 +93,6 @@ class OTLPMetricExporter(MetricExporter, OTLPMetricExporterMixin): - _MAX_RETRY_TIMEOUT = 64 def __init__( @@ -174,7 +177,6 @@ def export( for delay in _create_exp_backoff_generator( max_value=self._MAX_RETRY_TIMEOUT ): - if delay == self._MAX_RETRY_TIMEOUT: return MetricExportResult.FAILURE diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py index ea21cc664bc..6b4f36fbe8c 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py @@ -17,8 +17,8 @@ import zlib from io import BytesIO from os import environ -from typing import Dict, Optional from time import sleep +from typing import Dict, Optional import requests @@ -28,26 +28,25 @@ from opentelemetry.exporter.otlp.proto.common.trace_encoder import ( encode_spans, ) +from opentelemetry.exporter.otlp.proto.http import ( + _OTLP_HTTP_HEADERS, + Compression, +) from opentelemetry.sdk.environment_variables import ( - OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE, - OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, - OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, - OTEL_EXPORTER_OTLP_TRACES_HEADERS, - OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, OTEL_EXPORTER_OTLP_CERTIFICATE, OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_TIMEOUT, + OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE, + OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, + OTEL_EXPORTER_OTLP_TRACES_HEADERS, + OTEL_EXPORTER_OTLP_TRACES_TIMEOUT, ) from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult -from opentelemetry.exporter.otlp.proto.http import ( - _OTLP_HTTP_HEADERS, - Compression, -) from opentelemetry.util.re import parse_env_headers - _logger = logging.getLogger(__name__) @@ -58,7 +57,6 @@ class OTLPSpanExporter(SpanExporter): - _MAX_RETRY_TIMEOUT = 64 def __init__( diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__init__.py b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__init__.py index a0036ecd24a..764be1c58c2 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__init__.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__init__.py @@ -35,10 +35,10 @@ Resource as PB2Resource, ) from opentelemetry.proto.trace.v1.trace_pb2 import ( # noqa: F401 - ScopeSpans as PB2ScopeSpans, + ResourceSpans as PB2ResourceSpans, ) from opentelemetry.proto.trace.v1.trace_pb2 import ( # noqa: F401 - ResourceSpans as PB2ResourceSpans, + ScopeSpans as PB2ScopeSpans, ) from opentelemetry.proto.trace.v1.trace_pb2 import ( # noqa: F401 Span as PB2SPan, @@ -46,17 +46,21 @@ from opentelemetry.proto.trace.v1.trace_pb2 import ( # noqa: F401 Status as PB2Status, ) -from opentelemetry.sdk.trace import Event # noqa: F401 +from opentelemetry.sdk.trace import ( # noqa: F401 + Event, + Resource, +) +from opentelemetry.sdk.trace import Span as SDKSpan # noqa: F401 from opentelemetry.sdk.util.instrumentation import ( # noqa: F401 InstrumentationScope, ) -from opentelemetry.sdk.trace import Resource # noqa: F401 -from opentelemetry.sdk.trace import Span as SDKSpan # noqa: F401 -from opentelemetry.trace import Link # noqa: F401 -from opentelemetry.trace import SpanKind # noqa: F401 +from opentelemetry.trace import ( # noqa: F401 + Link, + SpanKind, +) from opentelemetry.trace.span import ( # noqa: F401 SpanContext, - TraceState, Status, + TraceState, ) from opentelemetry.util.types import Attributes # noqa: F401 diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/tests/metrics/test_otlp_metrics_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-http/tests/metrics/test_otlp_metrics_exporter.py index 674785056a5..fccfd4f52d2 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/tests/metrics/test_otlp_metrics_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/tests/metrics/test_otlp_metrics_exporter.py @@ -80,7 +80,6 @@ # pylint: disable=protected-access class TestOTLPMetricExporter(TestCase): def setUp(self): - self.metrics = { "sum_int": MetricsData( resource_metrics=[ @@ -107,7 +106,6 @@ def setUp(self): } def test_constructor_default(self): - exporter = OTLPMetricExporter() self.assertEqual( @@ -192,7 +190,6 @@ def test_exporter_constructor_take_priority(self): }, ) def test_exporter_env(self): - exporter = OTLPMetricExporter() self.assertEqual(exporter._certificate_file, OS_ENV_CERTIFICATE) @@ -207,7 +204,6 @@ def test_exporter_env(self): {OTEL_EXPORTER_OTLP_ENDPOINT: OS_ENV_ENDPOINT}, ) def test_exporter_env_endpoint_without_slash(self): - exporter = OTLPMetricExporter() self.assertEqual( @@ -220,7 +216,6 @@ def test_exporter_env_endpoint_without_slash(self): {OTEL_EXPORTER_OTLP_ENDPOINT: OS_ENV_ENDPOINT + "/"}, ) def test_exporter_env_endpoint_with_slash(self): - exporter = OTLPMetricExporter() self.assertEqual( @@ -235,7 +230,6 @@ def test_exporter_env_endpoint_with_slash(self): }, ) def test_headers_parse_from_env(self): - with self.assertLogs(level="WARNING") as cm: _ = OTLPMetricExporter() @@ -276,7 +270,6 @@ def test_failure(self, mock_post): @patch.object(Session, "post") def test_serialization(self, mock_post): - resp = Response() resp.status_code = 200 mock_post.return_value = resp @@ -318,7 +311,6 @@ def test_exponential_backoff(self, mock_sleep): ) def test_aggregation_temporality(self): - otlp_metric_exporter = OTLPMetricExporter() for ( @@ -330,7 +322,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "CUMULATIVE"}, ): - otlp_metric_exporter = OTLPMetricExporter() for ( @@ -343,7 +334,6 @@ def test_aggregation_temporality(self): with patch.dict( environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "ABC"} ): - with self.assertLogs(level=WARNING): otlp_metric_exporter = OTLPMetricExporter() @@ -358,7 +348,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "DELTA"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -392,7 +381,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "LOWMEMORY"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -423,7 +411,6 @@ def test_aggregation_temporality(self): ) def test_exponential_explicit_bucket_histogram(self): - self.assertIsInstance( OTLPMetricExporter()._preferred_aggregation[Histogram], ExplicitBucketHistogramAggregation, @@ -481,7 +468,6 @@ def test_2xx_status_code(self, mock_otlp_metric_exporter): ) def test_preferred_aggregation_override(self): - histogram_aggregation = ExplicitBucketHistogramAggregation( boundaries=[0.05, 0.1, 0.5, 1, 5, 10], ) diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_log_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_log_exporter.py index 6b6aafd465f..33ccbf90818 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_log_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_log_exporter.py @@ -58,7 +58,6 @@ class TestOTLPHTTPLogExporter(unittest.TestCase): def test_constructor_default(self): - exporter = OTLPLogExporter() self.assertEqual( @@ -153,7 +152,6 @@ def test_exporter_constructor_take_priority(self): }, ) def test_exporter_env(self): - exporter = OTLPLogExporter() self.assertEqual( diff --git a/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_span_exporter.py b/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_span_exporter.py index 69874664c7a..eefe5601dd0 100644 --- a/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_span_exporter.py +++ b/exporter/opentelemetry-exporter-otlp-proto-http/tests/test_proto_span_exporter.py @@ -51,7 +51,6 @@ # pylint: disable=protected-access class TestOTLPSpanExporter(unittest.TestCase): def test_constructor_default(self): - exporter = OTLPSpanExporter() self.assertEqual( @@ -145,7 +144,6 @@ def test_exporter_constructor_take_priority(self): }, ) def test_exporter_env(self): - exporter = OTLPSpanExporter() self.assertEqual(exporter._certificate_file, OS_ENV_CERTIFICATE) @@ -160,7 +158,6 @@ def test_exporter_env(self): {OTEL_EXPORTER_OTLP_ENDPOINT: OS_ENV_ENDPOINT}, ) def test_exporter_env_endpoint_without_slash(self): - exporter = OTLPSpanExporter() self.assertEqual( @@ -173,7 +170,6 @@ def test_exporter_env_endpoint_without_slash(self): {OTEL_EXPORTER_OTLP_ENDPOINT: OS_ENV_ENDPOINT + "/"}, ) def test_exporter_env_endpoint_with_slash(self): - exporter = OTLPSpanExporter() self.assertEqual( @@ -188,7 +184,6 @@ def test_exporter_env_endpoint_with_slash(self): }, ) def test_headers_parse_from_env(self): - with self.assertLogs(level="WARNING") as cm: _ = OTLPSpanExporter() diff --git a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py index b1a8d668c46..f700ec9ba8a 100644 --- a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py +++ b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py @@ -84,14 +84,14 @@ OTEL_EXPORTER_PROMETHEUS_HOST, OTEL_EXPORTER_PROMETHEUS_PORT, ) -from opentelemetry.sdk.metrics import Counter -from opentelemetry.sdk.metrics import Histogram as HistogramInstrument from opentelemetry.sdk.metrics import ( + Counter, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter, ) +from opentelemetry.sdk.metrics import Histogram as HistogramInstrument from opentelemetry.sdk.metrics.export import ( AggregationTemporality, Gauge, @@ -196,9 +196,9 @@ def collect(self) -> None: self._target_info = self._create_info_metric( _TARGET_INFO_NAME, _TARGET_INFO_DESCRIPTION, attributes ) - metric_family_id_metric_family[ - _TARGET_INFO_NAME - ] = self._target_info + metric_family_id_metric_family[_TARGET_INFO_NAME] = ( + self._target_info + ) while self._metrics_datas: self._translate_to_prometheus( @@ -288,19 +288,18 @@ def _translate_to_prometheus( isinstance(metric.data, Sum) and not should_convert_sum_to_gauge ): - metric_family_id = "|".join( [pre_metric_family_id, CounterMetricFamily.__name__] ) if metric_family_id not in metric_family_id_metric_family: - metric_family_id_metric_family[ - metric_family_id - ] = CounterMetricFamily( - name=metric_name, - documentation=metric_description, - labels=label_keys, - unit=metric.unit, + metric_family_id_metric_family[metric_family_id] = ( + CounterMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + unit=metric.unit, + ) ) metric_family_id_metric_family[ metric_family_id @@ -309,7 +308,6 @@ def _translate_to_prometheus( isinstance(metric.data, Gauge) or should_convert_sum_to_gauge ): - metric_family_id = "|".join( [pre_metric_family_id, GaugeMetricFamily.__name__] ) @@ -318,19 +316,18 @@ def _translate_to_prometheus( metric_family_id not in metric_family_id_metric_family.keys() ): - metric_family_id_metric_family[ - metric_family_id - ] = GaugeMetricFamily( - name=metric_name, - documentation=metric_description, - labels=label_keys, - unit=metric.unit, + metric_family_id_metric_family[metric_family_id] = ( + GaugeMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + unit=metric.unit, + ) ) metric_family_id_metric_family[ metric_family_id ].add_metric(labels=label_values, value=value) elif isinstance(metric.data, Histogram): - metric_family_id = "|".join( [pre_metric_family_id, HistogramMetricFamily.__name__] ) @@ -339,13 +336,13 @@ def _translate_to_prometheus( metric_family_id not in metric_family_id_metric_family.keys() ): - metric_family_id_metric_family[ - metric_family_id - ] = HistogramMetricFamily( - name=metric_name, - documentation=metric_description, - labels=label_keys, - unit=metric.unit, + metric_family_id_metric_family[metric_family_id] = ( + HistogramMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + unit=metric.unit, + ) ) metric_family_id_metric_family[ metric_family_id diff --git a/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py b/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py index 6d9126c815f..745355ec445 100644 --- a/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py +++ b/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py @@ -321,7 +321,6 @@ def test_list_labels(self): self.assertEqual(prometheus_metric.samples[0].labels["os"], "Unix") def test_check_value(self): - collector = _CustomCollector() self.assertEqual(collector._check_value(1), "1") @@ -335,7 +334,6 @@ def test_check_value(self): self.assertEqual(collector._check_value(None), "null") def test_multiple_collection_calls(self): - metric_reader = PrometheusMetricReader() provider = MeterProvider(metric_readers=[metric_reader]) meter = provider.get_meter("getting-started", "0.1.2") diff --git a/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v1/__init__.py b/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v1/__init__.py index 5272173f315..c44a2dd0af2 100644 --- a/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v1/__init__.py +++ b/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v1/__init__.py @@ -12,8 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Zipkin Export Encoders for JSON formats -""" +"""Zipkin Export Encoders for JSON formats""" from typing import Dict, List diff --git a/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v2/__init__.py b/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v2/__init__.py index ec6e53382b6..579087c4516 100644 --- a/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v2/__init__.py +++ b/exporter/opentelemetry-exporter-zipkin-json/src/opentelemetry/exporter/zipkin/json/v2/__init__.py @@ -12,8 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Zipkin Export Encoders for JSON formats -""" +"""Zipkin Export Encoders for JSON formats""" + from typing import Dict from opentelemetry.exporter.zipkin.encoder import JsonEncoder diff --git a/exporter/opentelemetry-exporter-zipkin-json/tests/encoder/test_v1_json.py b/exporter/opentelemetry-exporter-zipkin-json/tests/encoder/test_v1_json.py index 778ed74e8d7..7ff4e9b276e 100644 --- a/exporter/opentelemetry-exporter-zipkin-json/tests/encoder/test_v1_json.py +++ b/exporter/opentelemetry-exporter-zipkin-json/tests/encoder/test_v1_json.py @@ -41,7 +41,6 @@ def get_encoder(*args, **kwargs) -> JsonV1Encoder: return JsonV1Encoder(*args, **kwargs) def test_encode(self): - local_endpoint = {"serviceName": TEST_SERVICE_NAME} otel_spans = self.get_exhaustive_otel_span_list() diff --git a/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/__init__.py b/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/__init__.py index 8177efc07bc..dcb092c9cec 100644 --- a/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/__init__.py +++ b/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/__init__.py @@ -77,8 +77,8 @@ import requests -from opentelemetry.exporter.zipkin.proto.http.v2 import ProtobufEncoder from opentelemetry.exporter.zipkin.node_endpoint import IpInput, NodeEndpoint +from opentelemetry.exporter.zipkin.proto.http.v2 import ProtobufEncoder from opentelemetry.sdk.environment_variables import ( OTEL_EXPORTER_ZIPKIN_ENDPOINT, OTEL_EXPORTER_ZIPKIN_TIMEOUT, diff --git a/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/v2/__init__.py b/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/v2/__init__.py index 308abde01f8..d7ca3b88d27 100644 --- a/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/v2/__init__.py +++ b/exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/v2/__init__.py @@ -16,11 +16,12 @@ API spec: https://github.com/openzipkin/zipkin-api/blob/master/zipkin.proto """ + from typing import List, Optional, Sequence from opentelemetry.exporter.zipkin.encoder import Encoder -from opentelemetry.exporter.zipkin.proto.http.v2.gen import zipkin_pb2 from opentelemetry.exporter.zipkin.node_endpoint import NodeEndpoint +from opentelemetry.exporter.zipkin.proto.http.v2.gen import zipkin_pb2 from opentelemetry.sdk.trace import Event from opentelemetry.trace import Span, SpanKind diff --git a/opentelemetry-api/src/opentelemetry/context/__init__.py b/opentelemetry-api/src/opentelemetry/context/__init__.py index 91133884f68..f801e7d3f40 100644 --- a/opentelemetry-api/src/opentelemetry/context/__init__.py +++ b/opentelemetry-api/src/opentelemetry/context/__init__.py @@ -56,7 +56,6 @@ def wrapper( OTEL_PYTHON_CONTEXT, default_context ) # type: str try: - _RUNTIME_CONTEXT = next( # type: ignore iter( # type: ignore entry_points( # type: ignore diff --git a/opentelemetry-api/src/opentelemetry/metrics/__init__.py b/opentelemetry-api/src/opentelemetry/metrics/__init__.py index 56ffabee6cd..74284ad6e3f 100644 --- a/opentelemetry-api/src/opentelemetry/metrics/__init__.py +++ b/opentelemetry-api/src/opentelemetry/metrics/__init__.py @@ -53,15 +53,9 @@ CallbackOptions, CallbackT, Counter, -) -from opentelemetry.metrics._internal.instrument import Gauge as _Gauge -from opentelemetry.metrics._internal.instrument import ( Histogram, Instrument, NoOpCounter, -) -from opentelemetry.metrics._internal.instrument import NoOpGauge as _NoOpGauge -from opentelemetry.metrics._internal.instrument import ( NoOpHistogram, NoOpObservableCounter, NoOpObservableGauge, @@ -73,6 +67,8 @@ Synchronous, UpDownCounter, ) +from opentelemetry.metrics._internal.instrument import Gauge as _Gauge +from opentelemetry.metrics._internal.instrument import NoOpGauge as _NoOpGauge from opentelemetry.metrics._internal.observation import Observation for obj in [ diff --git a/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py b/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py index 9cbf14d2edc..1b09f02eeb6 100644 --- a/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py +++ b/opentelemetry-api/src/opentelemetry/metrics/_internal/__init__.py @@ -40,7 +40,6 @@ .. versionadded:: 1.10.0 """ - import warnings from abc import ABC, abstractmethod from logging import getLogger diff --git a/opentelemetry-api/src/opentelemetry/propagate/__init__.py b/opentelemetry-api/src/opentelemetry/propagate/__init__.py index 90f9e617448..109ae3992f1 100644 --- a/opentelemetry-api/src/opentelemetry/propagate/__init__.py +++ b/opentelemetry-api/src/opentelemetry/propagate/__init__.py @@ -133,7 +133,6 @@ def inject( propagator = propagator.strip() try: - propagators.append( # type: ignore next( # type: ignore iter( # type: ignore diff --git a/opentelemetry-api/src/opentelemetry/trace/__init__.py b/opentelemetry-api/src/opentelemetry/trace/__init__.py index 3b6295e259d..52403cf6b91 100644 --- a/opentelemetry-api/src/opentelemetry/trace/__init__.py +++ b/opentelemetry-api/src/opentelemetry/trace/__init__.py @@ -73,7 +73,6 @@ `set_tracer_provider`. """ - import os import typing from abc import ABC, abstractmethod diff --git a/opentelemetry-api/src/opentelemetry/trace/span.py b/opentelemetry-api/src/opentelemetry/trace/span.py index 5d46ffcb4a9..b612c7e9486 100644 --- a/opentelemetry-api/src/opentelemetry/trace/span.py +++ b/opentelemetry-api/src/opentelemetry/trace/span.py @@ -45,7 +45,6 @@ def _is_valid_pair(key: str, value: str) -> bool: - return ( isinstance(key, str) and _KEY_PATTERN.fullmatch(key) is not None diff --git a/opentelemetry-api/src/opentelemetry/util/_decorator.py b/opentelemetry-api/src/opentelemetry/util/_decorator.py index 870c97bd989..f585078bba6 100644 --- a/opentelemetry-api/src/opentelemetry/util/_decorator.py +++ b/opentelemetry-api/src/opentelemetry/util/_decorator.py @@ -30,7 +30,8 @@ class _AgnosticContextManager( - contextlib._GeneratorContextManager, Generic[R] # type: ignore # FIXME use contextlib._GeneratorContextManager[R] when we drop the python 3.8 support + contextlib._GeneratorContextManager, + Generic[R], # type: ignore # FIXME use contextlib._GeneratorContextManager[R] when we drop the python 3.8 support ): # pylint: disable=protected-access """Context manager that can decorate both async and sync functions. diff --git a/opentelemetry-api/src/opentelemetry/util/_providers.py b/opentelemetry-api/src/opentelemetry/util/_providers.py index 307650bb1d2..dfe08d106ab 100644 --- a/opentelemetry-api/src/opentelemetry/util/_providers.py +++ b/opentelemetry-api/src/opentelemetry/util/_providers.py @@ -29,10 +29,8 @@ def _load_provider( provider_environment_variable: str, provider: str -) -> Provider: # type: ignore[type-var] - +) -> Provider: try: - provider_name = cast( str, environ.get(provider_environment_variable, f"default_{provider}"), diff --git a/opentelemetry-api/tests/logs/test_logger_provider.py b/opentelemetry-api/tests/logs/test_logger_provider.py index 84f3f13e9c3..63a4889908a 100644 --- a/opentelemetry-api/tests/logs/test_logger_provider.py +++ b/opentelemetry-api/tests/logs/test_logger_provider.py @@ -53,7 +53,6 @@ def test_get_logger_provider(self): "os.environ", {_OTEL_PYTHON_LOGGER_PROVIDER: "test_logger_provider"}, ): - with patch("opentelemetry._logs._internal._load_provider", Mock()): with patch( "opentelemetry._logs._internal.cast", diff --git a/opentelemetry-api/tests/metrics/test_instruments.py b/opentelemetry-api/tests/metrics/test_instruments.py index 12267433af0..2e07e19ebd1 100644 --- a/opentelemetry-api/tests/metrics/test_instruments.py +++ b/opentelemetry-api/tests/metrics/test_instruments.py @@ -675,7 +675,6 @@ def test_name_check(self): ) def test_unit_check(self): - instrument = ChildInstrument("name") self.assertEqual( @@ -709,7 +708,6 @@ def test_unit_check(self): ) def test_description_check(self): - instrument = ChildInstrument("name") self.assertEqual( diff --git a/opentelemetry-api/tests/metrics/test_meter.py b/opentelemetry-api/tests/metrics/test_meter.py index 2226965521e..a6aff3e5bc3 100644 --- a/opentelemetry-api/tests/metrics/test_meter.py +++ b/opentelemetry-api/tests/metrics/test_meter.py @@ -59,7 +59,6 @@ def create_observable_up_down_counter( class TestMeter(TestCase): def test_repeated_instrument_names(self): - try: test_meter = NoOpMeter("name") diff --git a/opentelemetry-api/tests/metrics/test_meter_provider.py b/opentelemetry-api/tests/metrics/test_meter_provider.py index 559b56205ec..046584a3f05 100644 --- a/opentelemetry-api/tests/metrics/test_meter_provider.py +++ b/opentelemetry-api/tests/metrics/test_meter_provider.py @@ -95,7 +95,6 @@ def test_get_meter_provider(reset_meter_provider): with patch.dict( "os.environ", {OTEL_PYTHON_METER_PROVIDER: "test_meter_provider"} ): - with patch("opentelemetry.metrics._internal._load_provider", Mock()): with patch( "opentelemetry.metrics._internal.cast", diff --git a/opentelemetry-api/tests/propagators/test_propagators.py b/opentelemetry-api/tests/propagators/test_propagators.py index 29065b8cb3e..f0554ad2812 100644 --- a/opentelemetry-api/tests/propagators/test_propagators.py +++ b/opentelemetry-api/tests/propagators/test_propagators.py @@ -32,7 +32,6 @@ class TestPropagators(TestCase): @patch("opentelemetry.propagators.composite.CompositePropagator") def test_default_composite_propagators(self, mock_compositehttppropagator): def test_propagators(propagators): - propagators = {propagator.__class__ for propagator in propagators} self.assertEqual(len(propagators), 2) @@ -56,7 +55,6 @@ def test_propagators(propagators): def test_non_default_propagators( self, mock_entry_points, mock_compositehttppropagator ): - mock_entry_points.configure_mock( **{ "side_effect": [ @@ -107,7 +105,6 @@ def test_propagators(propagators): environ, {OTEL_PROPAGATORS: "tracecontext , unknown , baggage"} ) def test_composite_propagators_error(self): - with self.assertRaises(ValueError) as cm: # pylint: disable=import-outside-toplevel import opentelemetry.propagate diff --git a/opentelemetry-api/tests/propagators/test_w3cbaggagepropagator.py b/opentelemetry-api/tests/propagators/test_w3cbaggagepropagator.py index ccc4b3cb2d0..7666b39cbbb 100644 --- a/opentelemetry-api/tests/propagators/test_w3cbaggagepropagator.py +++ b/opentelemetry-api/tests/propagators/test_w3cbaggagepropagator.py @@ -128,7 +128,6 @@ def test_extract_unquote_plus(self): ) def test_header_max_entries_skip_invalid_entry(self): - with self.assertLogs(level=WARNING) as warning: self.assertEqual( self._extract( @@ -221,7 +220,6 @@ def test_inject_non_string_values(self): @patch("opentelemetry.baggage.propagation.get_all") @patch("opentelemetry.baggage.propagation._format_baggage") def test_fields(self, mock_format_baggage, mock_baggage): - mock_setter = Mock() self.propagator.inject({}, setter=mock_setter) @@ -244,7 +242,6 @@ def test__format_baggage(self): @patch("opentelemetry.baggage._BAGGAGE_KEY", new="abc") def test_inject_extract(self): - carrier = {} context = set_baggage( diff --git a/opentelemetry-api/tests/trace/propagation/test_tracecontexthttptextformat.py b/opentelemetry-api/tests/trace/propagation/test_tracecontexthttptextformat.py index 7fefd8dea67..150982cab4a 100644 --- a/opentelemetry-api/tests/trace/propagation/test_tracecontexthttptextformat.py +++ b/opentelemetry-api/tests/trace/propagation/test_tracecontexthttptextformat.py @@ -245,7 +245,6 @@ def test_tracestate_keys(self): @patch("opentelemetry.trace.INVALID_SPAN_CONTEXT") @patch("opentelemetry.trace.get_current_span") def test_fields(self, mock_get_current_span, mock_invalid_span_context): - mock_get_current_span.configure_mock( return_value=Mock( **{ diff --git a/opentelemetry-api/tests/trace/test_globals.py b/opentelemetry-api/tests/trace/test_globals.py index c2cc80db82e..cdeeed246a3 100644 --- a/opentelemetry-api/tests/trace/test_globals.py +++ b/opentelemetry-api/tests/trace/test_globals.py @@ -109,7 +109,6 @@ def test_use_span(self): self.assertEqual(trace.get_current_span(), trace.INVALID_SPAN) def test_use_span_end_on_exit(self): - test_span = TestSpan(trace.INVALID_SPAN_CONTEXT) with trace.use_span(test_span): diff --git a/opentelemetry-api/tests/trace/test_status.py b/opentelemetry-api/tests/trace/test_status.py index 6388ae98049..f670bdb44b7 100644 --- a/opentelemetry-api/tests/trace/test_status.py +++ b/opentelemetry-api/tests/trace/test_status.py @@ -30,7 +30,9 @@ def test_constructor(self): def test_invalid_description(self): with self.assertLogs(level=WARNING) as warning: - status = Status(status_code=StatusCode.ERROR, description={"test": "val"}) # type: ignore + status = Status( + status_code=StatusCode.ERROR, description={"test": "val"} + ) # type: ignore self.assertIs(status.status_code, StatusCode.ERROR) self.assertEqual(status.description, None) self.assertIn( diff --git a/opentelemetry-api/tests/util/test__importlib_metadata.py b/opentelemetry-api/tests/util/test__importlib_metadata.py index 92a4e7dd62a..406f8ce5277 100644 --- a/opentelemetry-api/tests/util/test__importlib_metadata.py +++ b/opentelemetry-api/tests/util/test__importlib_metadata.py @@ -23,7 +23,6 @@ class TestEntryPoints(TestCase): def test_entry_points(self): - self.assertIsInstance( next( iter( diff --git a/opentelemetry-api/tests/util/test__providers.py b/opentelemetry-api/tests/util/test__providers.py index f7b21ebacf1..988b6afdae8 100644 --- a/opentelemetry-api/tests/util/test__providers.py +++ b/opentelemetry-api/tests/util/test__providers.py @@ -29,7 +29,6 @@ class Test_Providers(TestCase): ) @patch("opentelemetry.util._importlib_metadata.entry_points") def test__providers(self, mock_entry_points): - reload(_providers) mock_entry_points.configure_mock( diff --git a/opentelemetry-proto/tests/test_proto.py b/opentelemetry-proto/tests/test_proto.py index 9670be46276..5c041162437 100644 --- a/opentelemetry-proto/tests/test_proto.py +++ b/opentelemetry-proto/tests/test_proto.py @@ -19,6 +19,5 @@ class TestInstrumentor(TestCase): def test_proto(self): - if find_spec("opentelemetry.proto") is None: self.fail("opentelemetry-proto not installed") diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py index 33c5147a599..9038f3675e2 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py @@ -91,7 +91,6 @@ def _import_config_components( selected_components: List[str], entry_point_name: str ) -> Sequence[Tuple[str, object]]: - component_implementations = [] for selected_component in selected_components: @@ -109,13 +108,11 @@ def _import_config_components( ) ) except KeyError: - raise RuntimeError( f"Requested entry point '{entry_point_name}' not found" ) except StopIteration: - raise RuntimeError( f"Requested component '{selected_component}' not found in " f"entry point '{entry_point_name}'" @@ -177,7 +174,7 @@ def _get_exporter_entry_point( def _get_exporter_names( - signal_type: Literal["traces", "metrics", "logs"] + signal_type: Literal["traces", "metrics", "logs"], ) -> Sequence[str]: names = environ.get(_EXPORTER_ENV_BY_SIGNAL_TYPE.get(signal_type, "")) @@ -265,7 +262,10 @@ def _import_exporters( metric_exporters = {} log_exporters = {} - for (exporter_name, exporter_impl,) in _import_config_components( + for ( + exporter_name, + exporter_impl, + ) in _import_config_components( trace_exporter_names, "opentelemetry_traces_exporter" ): if issubclass(exporter_impl, SpanExporter): @@ -273,7 +273,10 @@ def _import_exporters( else: raise RuntimeError(f"{exporter_name} is not a trace exporter") - for (exporter_name, exporter_impl,) in _import_config_components( + for ( + exporter_name, + exporter_impl, + ) in _import_config_components( metric_exporter_names, "opentelemetry_metrics_exporter" ): # The metric exporter components may be push MetricExporter or pull exporters which @@ -283,7 +286,10 @@ def _import_exporters( else: raise RuntimeError(f"{exporter_name} is not a metric exporter") - for (exporter_name, exporter_impl,) in _import_config_components( + for ( + exporter_name, + exporter_impl, + ) in _import_config_components( log_exporter_names, "opentelemetry_logs_exporter" ): if issubclass(exporter_impl, LogExporter): @@ -360,9 +366,9 @@ def _initialize_components(auto_instrumentation_version): auto_resource = {} # populate version if using auto-instrumentation if auto_instrumentation_version: - auto_resource[ - ResourceAttributes.TELEMETRY_AUTO_VERSION - ] = auto_instrumentation_version + auto_resource[ResourceAttributes.TELEMETRY_AUTO_VERSION] = ( + auto_instrumentation_version + ) resource = Resource.create(auto_resource) _init_tracing( @@ -391,7 +397,6 @@ class _BaseConfigurator(ABC): _is_instrumented = False def __new__(cls, *args, **kwargs): - if cls._instance is None: cls._instance = object.__new__(cls, *args, **kwargs) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py index 8ba0dae6f2e..4b407353ab9 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py @@ -94,7 +94,6 @@ def __init__( max_attributes: Optional[int] = None, max_attribute_length: Optional[int] = None, ): - # attribute count global_max_attributes = self._from_env_if_absent( max_attributes, OTEL_ATTRIBUTE_COUNT_LIMIT diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py index 597c55a6725..79c3ffc1198 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py @@ -135,9 +135,7 @@ def shutdown(self): self._shutdown = True self._exporter.shutdown() - def force_flush( - self, timeout_millis: int = 30000 - ) -> bool: # pylint: disable=no-self-use + def force_flush(self, timeout_millis: int = 30000) -> bool: # pylint: disable=no-self-use return True @@ -217,9 +215,7 @@ def __init__( self._log_records = [None] * self._max_export_batch_size self._worker_thread.start() if hasattr(os, "register_at_fork"): - os.register_at_fork( - after_in_child=self._at_fork_reinit - ) # pylint: disable=protected-access + os.register_at_fork(after_in_child=self._at_fork_reinit) # pylint: disable=protected-access self._pid = os.getpid() def _at_fork_reinit(self): diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/error_handler/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/error_handler/__init__.py index 7b21d92d2af..a5930dbd5af 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/error_handler/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/error_handler/__init__.py @@ -84,7 +84,6 @@ class _DefaultErrorHandler(ErrorHandler): # pylint: disable=useless-return def _handle(self, error: Exception, *args, **kwargs): - logger.exception("Error handled by default error handler: ") return None @@ -111,9 +110,7 @@ def __enter__(self): # pylint: disable=no-self-use def __exit__(self, exc_type, exc_value, traceback): - if exc_value is None: - return None plugin_handled = False @@ -123,19 +120,15 @@ def __exit__(self, exc_type, exc_value, traceback): ) for error_handler_entry_point in error_handler_entry_points: - error_handler_class = error_handler_entry_point.load() if issubclass(error_handler_class, exc_value.__class__): - try: - error_handler_class()._handle(exc_value) plugin_handled = True # pylint: disable=broad-except except Exception as error_handling_error: - logger.exception( "%s error while handling error" " %s by error handler %s", @@ -145,7 +138,6 @@ def __exit__(self, exc_type, exc_value, traceback): ) if not plugin_handled: - _DefaultErrorHandler()._handle(exc_value) return True diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py index a907a289760..96bb54f61fb 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py @@ -15,15 +15,15 @@ from opentelemetry.sdk.metrics._internal import Meter, MeterProvider from opentelemetry.sdk.metrics._internal.exceptions import MetricsTimeoutError -from opentelemetry.sdk.metrics._internal.instrument import Counter -from opentelemetry.sdk.metrics._internal.instrument import Gauge as _Gauge from opentelemetry.sdk.metrics._internal.instrument import ( + Counter, Histogram, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter, ) +from opentelemetry.sdk.metrics._internal.instrument import Gauge as _Gauge __all__ = [ "Meter", diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py index 908d8f81cf8..1e70021fa97 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py @@ -77,7 +77,6 @@ def __init__( self._instrument_id_instrument_lock = Lock() def create_counter(self, name, unit="", description="") -> APICounter: - ( is_instrument_registered, instrument_id, @@ -113,7 +112,6 @@ def create_counter(self, name, unit="", description="") -> APICounter: def create_up_down_counter( self, name, unit="", description="" ) -> APIUpDownCounter: - ( is_instrument_registered, instrument_id, @@ -151,7 +149,6 @@ def create_up_down_counter( def create_observable_counter( self, name, callbacks=None, unit="", description="" ) -> APIObservableCounter: - ( is_instrument_registered, instrument_id, @@ -190,7 +187,6 @@ def create_observable_counter( return instrument def create_histogram(self, name, unit="", description="") -> APIHistogram: - ( is_instrument_registered, instrument_id, @@ -223,7 +219,6 @@ def create_histogram(self, name, unit="", description="") -> APIHistogram: return instrument def create_gauge(self, name, unit="", description="") -> APIGauge: - ( is_instrument_registered, instrument_id, @@ -259,7 +254,6 @@ def create_gauge(self, name, unit="", description="") -> APIGauge: def create_observable_gauge( self, name, callbacks=None, unit="", description="" ) -> APIObservableGauge: - ( is_instrument_registered, instrument_id, @@ -300,7 +294,6 @@ def create_observable_gauge( def create_observable_up_down_counter( self, name, callbacks=None, unit="", description="" ) -> APIObservableUpDownCounter: - ( is_instrument_registered, instrument_id, @@ -407,7 +400,6 @@ def __init__( self._shutdown = False for metric_reader in self._sdk_config.metric_readers: - with self._all_metric_readers_lock: if metric_reader in self._all_metric_readers: raise Exception( @@ -439,11 +431,9 @@ def force_flush(self, timeout_millis: float = 10_000) -> bool: # pylint: disable=broad-except except Exception as error: - metric_reader_error[metric_reader] = error if metric_reader_error: - metric_reader_error_string = "\n".join( [ f"{metric_reader.__class__.__name__}: {repr(error)}" @@ -485,7 +475,6 @@ def _shutdown(): # pylint: disable=broad-except except Exception as error: - metric_reader_error[metric_reader] = error if self._atexit_handler is not None: @@ -493,7 +482,6 @@ def _shutdown(): self._atexit_handler = None if metric_reader_error: - metric_reader_error_string = "\n".join( [ f"{metric_reader.__class__.__name__}: {repr(error)}" @@ -515,7 +503,6 @@ def get_meter( version: Optional[str] = None, schema_url: Optional[str] = None, ) -> Meter: - if self._disabled: _logger.warning("SDK is disabled.") return NoOpMeter(name, version=version, schema_url=schema_url) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py index 7dd7f58f272..36c302abc6f 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/_view_instrument_match.py @@ -82,9 +82,7 @@ def conflicts(self, other: "_ViewInstrumentMatch") -> bool: # pylint: disable=protected-access def consume_measurement(self, measurement: Measurement) -> None: - if self._view._attribute_keys is not None: - attributes = {} for key, value in (measurement.attributes or {}).items(): @@ -127,7 +125,6 @@ def collect( collection_aggregation_temporality: AggregationTemporality, collection_start_nanos: int, ) -> Optional[Sequence[DataPointT]]: - data_points: List[DataPointT] = [] with self._lock: for aggregation in self._attributes_aggregation.values(): diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py index 3ec37473f60..cd2fbb5092d 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py @@ -47,16 +47,14 @@ from opentelemetry.sdk.metrics._internal.point import Buckets as BucketsPoint from opentelemetry.sdk.metrics._internal.point import ( ExponentialHistogramDataPoint, + HistogramDataPoint, + NumberDataPoint, + Sum, ) from opentelemetry.sdk.metrics._internal.point import Gauge as GaugePoint from opentelemetry.sdk.metrics._internal.point import ( Histogram as HistogramPoint, ) -from opentelemetry.sdk.metrics._internal.point import ( - HistogramDataPoint, - NumberDataPoint, - Sum, -) from opentelemetry.util.types import Attributes _DataPointVarT = TypeVar("_DataPointVarT", NumberDataPoint, HistogramDataPoint) @@ -274,7 +272,6 @@ def collect( collection_aggregation_temporality is AggregationTemporality.DELTA ): - if current_value is None: return None @@ -467,7 +464,6 @@ def collect( collection_aggregation_temporality is AggregationTemporality.DELTA ): - if current_value is None: return None @@ -609,7 +605,6 @@ def aggregate(self, measurement: Measurement) -> None: # pylint: disable=too-many-branches,too-many-statements, too-many-locals with self._lock: - value = measurement.value # 0. Set the following attributes: @@ -677,7 +672,6 @@ def aggregate(self, measurement: Measurement) -> None: # 4. Rescale the mapping if needed. if is_rescaling_needed: - self._downscale( self._get_scale_change(low, high), self._positive, @@ -823,7 +817,6 @@ def collect( collection_aggregation_temporality is AggregationTemporality.CUMULATIVE ): - start_time_unix_nano = self._previous_start_time_unix_nano sum_ = current_sum + self._previous_sum # Only update min/max on delta -> cumulative @@ -899,7 +892,6 @@ def collect( def _get_low_high_previous_current( self, previous_point_buckets, current_point_buckets, min_scale ): - (previous_point_low, previous_point_high) = self._get_low_high( previous_point_buckets, min_scale ) @@ -930,7 +922,6 @@ def _get_low_high(self, buckets, min_scale): return buckets.index_start >> shift, buckets.index_end >> shift def _get_scale_change(self, low, high): - change = 0 while high - low >= self._max_size: @@ -942,7 +933,6 @@ def _get_scale_change(self, low, high): return change def _downscale(self, change: int, positive, negative): - if change == 0: return @@ -969,13 +959,11 @@ def _merge( min_scale, aggregation_temporality, ): - current_change = current_scale - min_scale for current_bucket_index, current_bucket in enumerate( current_buckets.counts ): - if current_bucket == 0: continue @@ -1062,7 +1050,6 @@ def _create_aggregation( attributes: Attributes, start_time_unix_nano: int, ) -> _Aggregation: - # pylint: disable=too-many-return-statements if isinstance(instrument, Counter): return _SumAggregation( @@ -1188,7 +1175,6 @@ def _create_aggregation( attributes: Attributes, start_time_unix_nano: int, ) -> _Aggregation: - instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED if isinstance(instrument, Synchronous): instrument_aggregation_temporality = AggregationTemporality.DELTA @@ -1218,7 +1204,6 @@ def _create_aggregation( attributes: Attributes, start_time_unix_nano: int, ) -> _Aggregation: - instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED if isinstance(instrument, Synchronous): instrument_aggregation_temporality = AggregationTemporality.DELTA diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/buckets.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/buckets.py index 5c6b04bd39b..a538221189f 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/buckets.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/buckets.py @@ -16,7 +16,6 @@ class Buckets: - # No method of this class is protected by locks because instances of this # class are only used in methods that are protected by locks themselves. @@ -74,7 +73,6 @@ def counts(self): return self._counts def grow(self, needed: int, max_size: int) -> None: - size = len(self._counts) bias = self.__index_base - self.__index_start old_positive_limit = size - bias @@ -129,7 +127,6 @@ def downscale(self, amount: int) -> None: bias = self.__index_base - self.__index_start if bias != 0: - self.__index_base = self.__index_start # [0, 1, 2, 3, 4] Original backing array @@ -157,7 +154,6 @@ def downscale(self, amount: int) -> None: index = mod while index < each and inpos < size: - if outpos != inpos: self._counts[outpos] += self._counts[inpos] self._counts[inpos] = 0 diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/__init__.py index d8c780cf404..96709ccee57 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/__init__.py @@ -22,7 +22,6 @@ class Mapping(ABC): # pylint: disable=no-member def __new__(cls, scale: int): - with cls._mappings_lock: # cls._mappings and cls._mappings_lock are implemented in each of # the child classes as a dictionary and a lock, respectively. They diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/ieee_754.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/ieee_754.py index 9503b57c0e0..d4b7e86148a 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/ieee_754.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/ieee_754.py @@ -82,8 +82,7 @@ def get_ieee_754_exponent(value: float) -> int: # # This step isolates the exponent bits, turning every bit outside # of the exponent field (sign and mantissa bits) to 0. - c_uint64.from_buffer(c_double(value)).value - & EXPONENT_MASK + c_uint64.from_buffer(c_double(value)).value & EXPONENT_MASK # For the example this means: # 18442240474082181119 & EXPONENT_MASK == 9214364837600034816 # bin(9214364837600034816) == '0b111111111100000000000000000000000000000000000000000000000000000' diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/logarithm_mapping.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/logarithm_mapping.py index 5abf9238b9b..e73f3a81e23 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/logarithm_mapping.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/exponential_histogram/mapping/logarithm_mapping.py @@ -115,7 +115,6 @@ def map_to_index(self, value: float) -> int: ) def get_lower_boundary(self, index: int) -> float: - if index >= self._max_normal_lower_boundary_index: if index == self._max_normal_lower_boundary_index: return 2 * exp( diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/__init__.py index 14546636a94..bb91e803b3f 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/export/__init__.py @@ -142,8 +142,7 @@ def __init__( out: IO = stdout, formatter: Callable[ ["opentelemetry.sdk.metrics.export.MetricsData"], str - ] = lambda metrics_data: metrics_data.to_json() - + linesep, + ] = lambda metrics_data: metrics_data.to_json() + linesep, preferred_temporality: Dict[type, AggregationTemporality] = None, preferred_aggregation: Dict[ type, "opentelemetry.sdk.metrics.view.Aggregation" @@ -247,27 +246,27 @@ def __init__( if typ is Counter: self._instrument_class_temporality[_Counter] = temporality elif typ is UpDownCounter: - self._instrument_class_temporality[ - _UpDownCounter - ] = temporality + self._instrument_class_temporality[_UpDownCounter] = ( + temporality + ) elif typ is Histogram: - self._instrument_class_temporality[ - _Histogram - ] = temporality + self._instrument_class_temporality[_Histogram] = ( + temporality + ) elif typ is Gauge: self._instrument_class_temporality[_Gauge] = temporality elif typ is ObservableCounter: - self._instrument_class_temporality[ - _ObservableCounter - ] = temporality + self._instrument_class_temporality[_ObservableCounter] = ( + temporality + ) elif typ is ObservableUpDownCounter: self._instrument_class_temporality[ _ObservableUpDownCounter ] = temporality elif typ is ObservableGauge: - self._instrument_class_temporality[ - _ObservableGauge - ] = temporality + self._instrument_class_temporality[_ObservableGauge] = ( + temporality + ) else: raise Exception(f"Invalid instrument class found {typ}") @@ -287,27 +286,27 @@ def __init__( if typ is Counter: self._instrument_class_aggregation[_Counter] = aggregation elif typ is UpDownCounter: - self._instrument_class_aggregation[ - _UpDownCounter - ] = aggregation + self._instrument_class_aggregation[_UpDownCounter] = ( + aggregation + ) elif typ is Histogram: - self._instrument_class_aggregation[ - _Histogram - ] = aggregation + self._instrument_class_aggregation[_Histogram] = ( + aggregation + ) elif typ is Gauge: self._instrument_class_aggregation[_Gauge] = aggregation elif typ is ObservableCounter: - self._instrument_class_aggregation[ - _ObservableCounter - ] = aggregation + self._instrument_class_aggregation[_ObservableCounter] = ( + aggregation + ) elif typ is ObservableUpDownCounter: self._instrument_class_aggregation[ _ObservableUpDownCounter ] = aggregation elif typ is ObservableGauge: - self._instrument_class_aggregation[ - _ObservableGauge - ] = aggregation + self._instrument_class_aggregation[_ObservableGauge] = ( + aggregation + ) else: raise Exception(f"Invalid instrument class found {typ}") @@ -333,7 +332,6 @@ def collect(self, timeout_millis: float = 10_000) -> None: metrics = self._collect(self, timeout_millis=timeout_millis) if metrics is not None: - self._receive_metrics( metrics, timeout_millis=timeout_millis, @@ -398,13 +396,13 @@ def __init__( preferred_aggregation=preferred_aggregation, ) self._lock = RLock() - self._metrics_data: ( - "opentelemetry.sdk.metrics.export.MetricsData" - ) = None + self._metrics_data: "opentelemetry.sdk.metrics.export.MetricsData" = ( + None + ) def get_metrics_data( self, - ) -> ("opentelemetry.sdk.metrics.export.MetricsData"): + ) -> "opentelemetry.sdk.metrics.export.MetricsData": """Reads and returns current metrics from the SDK""" with self._lock: self.collect() @@ -490,9 +488,7 @@ def __init__( ) self._daemon_thread.start() if hasattr(os, "register_at_fork"): - os.register_at_fork( - after_in_child=self._at_fork_reinit - ) # pylint: disable=protected-access + os.register_at_fork(after_in_child=self._at_fork_reinit) # pylint: disable=protected-access elif self._export_interval_millis <= 0: raise ValueError( f"interval value {self._export_interval_millis} is invalid \ @@ -527,7 +523,6 @@ def _receive_metrics( timeout_millis: float = 10_000, **kwargs, ) -> None: - token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)) try: with self._export_lock: @@ -551,9 +546,7 @@ def _shutdown(): self._shutdown_event.set() if self._daemon_thread: - self._daemon_thread.join( - timeout=(deadline_ns - time_ns()) / 10**9 - ) + self._daemon_thread.join(timeout=(deadline_ns - time_ns()) / 10**9) self._exporter.shutdown(timeout=(deadline_ns - time_ns()) / 10**6) def force_flush(self, timeout_millis: float = 10_000) -> bool: diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py index 11dd8499341..538be42ace2 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py @@ -104,11 +104,8 @@ def __init__( self._callbacks: List[CallbackT] = [] if callbacks is not None: - for callback in callbacks: - if isinstance(callback, Generator): - # advance generator to it's first yield next(callback) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement_consumer.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement_consumer.py index c5e81678dcb..6d4e5f6be21 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement_consumer.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement_consumer.py @@ -95,7 +95,6 @@ def collect( metric_reader: "opentelemetry.sdk.metrics.MetricReader", timeout_millis: float = 10_000, ) -> Optional[Iterable[Metric]]: - with self._lock: metric_reader_storage = self._reader_storages[metric_reader] # for now, just use the defaults @@ -105,11 +104,9 @@ def collect( default_timeout_millis = 10000 * 10**6 for async_instrument in self._async_instruments: - remaining_time = deadline_ns - time_ns() if remaining_time < default_timeout_millis: - callback_options = CallbackOptions( timeout_millis=remaining_time ) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/metric_reader_storage.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/metric_reader_storage.py index 700ace87204..fdd9a13ec49 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/metric_reader_storage.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/metric_reader_storage.py @@ -107,9 +107,9 @@ def _get_or_init_view_instrument_match( ), ) ) - self._instrument_view_instrument_matches[ - instrument - ] = view_instrument_matches + self._instrument_view_instrument_matches[instrument] = ( + view_instrument_matches + ) return view_instrument_matches @@ -135,10 +135,9 @@ def collect(self) -> Optional[MetricsData]: collection_start_nanos = time_ns() with self._lock: - - instrumentation_scope_scope_metrics: ( - Dict[InstrumentationScope, ScopeMetrics] - ) = {} + instrumentation_scope_scope_metrics: Dict[ + InstrumentationScope, ScopeMetrics + ] = {} for ( instrument, @@ -151,7 +150,6 @@ def collect(self) -> Optional[MetricsData]: metrics: List[Metric] = [] for view_instrument_match in view_instrument_matches: - data_points = view_instrument_match.collect( aggregation_temporality, collection_start_nanos ) @@ -214,7 +212,6 @@ def collect(self) -> Optional[MetricsData]: ) if metrics: - if instrument.instrumentation_scope not in ( instrumentation_scope_scope_metrics ): @@ -231,7 +228,6 @@ def collect(self) -> Optional[MetricsData]: ].metrics.extend(metrics) if instrumentation_scope_scope_metrics: - return MetricsData( resource_metrics=[ ResourceMetrics( @@ -276,7 +272,6 @@ def _handle_view_instrument_match( if existing_view_instrument_match.conflicts( new_view_instrument_match ): - _logger.warning( "Views %s and %s will cause conflicting " "metrics identities", diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/view.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/view.py index 5b548a5e05c..575136258d1 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/view.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/view.py @@ -113,7 +113,6 @@ def __init__( and instrument_name is not None and ("*" in instrument_name or "?" in instrument_name) ): - raise Exception( f"View {name} declared with wildcard " "characters in instrument_name" @@ -136,7 +135,6 @@ def __init__( # pylint: disable=too-many-return-statements # pylint: disable=too-many-branches def _match(self, instrument: Instrument) -> bool: - if self._instrument_type is not None: if not isinstance(instrument, self._instrument_type): return False diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py index 852b23f5002..118288608fe 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py @@ -53,7 +53,7 @@ `_ that have prescribed semantic meanings, for example ``service.name`` in the above example. - """ +""" import abc import concurrent.futures @@ -305,7 +305,6 @@ def detect(self) -> "Resource": class OTELResourceDetector(ResourceDetector): # pylint: disable=no-self-use def detect(self) -> "Resource": - env_resources_items = environ.get(OTEL_RESOURCE_ATTRIBUTES) env_resource_map = {} diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py index 0110a5c0e05..0c673d286ae 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py @@ -601,7 +601,6 @@ def __init__( max_attribute_length: Optional[int] = None, max_span_attribute_length: Optional[int] = None, ): - # span events and links count self.max_events = self._from_env_if_absent( max_events, @@ -702,12 +701,10 @@ def _from_env_if_absent( ) # not removed for backward compat. please use SpanLimits instead. -SPAN_ATTRIBUTE_COUNT_LIMIT = ( - SpanLimits._from_env_if_absent( # pylint: disable=protected-access - None, - OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, - _DEFAULT_OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, - ) +SPAN_ATTRIBUTE_COUNT_LIMIT = SpanLimits._from_env_if_absent( # pylint: disable=protected-access + None, + OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, + _DEFAULT_OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, ) @@ -1081,7 +1078,6 @@ def start_span( # pylint: disable=too-many-locals record_exception: bool = True, set_status_on_exception: bool = True, ) -> trace_api.Span: - parent_span_context = trace_api.get_current_span( context ).get_span_context() diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py index a4a9958343e..83a5b54415d 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py @@ -183,9 +183,7 @@ def __init__( ) self.span_exporter = span_exporter - self.queue = collections.deque( - [], max_queue_size - ) # type: typing.Deque[Span] + self.queue = collections.deque([], max_queue_size) # type: typing.Deque[Span] self.worker_thread = threading.Thread( name="OtelBatchSpanProcessor", target=self.worker, daemon=True ) @@ -199,14 +197,10 @@ def __init__( # flag that indicates that spans are being dropped self._spans_dropped = False # precallocated list to send spans to exporter - self.spans_list = [ - None - ] * self.max_export_batch_size # type: typing.List[typing.Optional[Span]] + self.spans_list = [None] * self.max_export_batch_size # type: typing.List[typing.Optional[Span]] self.worker_thread.start() if hasattr(os, "register_at_fork"): - os.register_at_fork( - after_in_child=self._at_fork_reinit - ) # pylint: disable=protected-access + os.register_at_fork(after_in_child=self._at_fork_reinit) # pylint: disable=protected-access self._pid = os.getpid() def on_start( @@ -259,7 +253,6 @@ def worker(self): len(self.queue) < self.max_export_batch_size and flush_request is None ): - self.condition.wait(timeout) flush_request = self._get_and_unset_flush_request() if not self.queue: @@ -384,7 +377,6 @@ def _drain_queue(self): self._export_batch() def force_flush(self, timeout_millis: int = None) -> bool: - if timeout_millis is None: timeout_millis = self.export_timeout_millis @@ -509,8 +501,7 @@ def __init__( out: typing.IO = sys.stdout, formatter: typing.Callable[ [ReadableSpan], str - ] = lambda span: span.to_json() - + linesep, + ] = lambda span: span.to_json() + linesep, ): self.out = out self.formatter = formatter diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py index 40e142ea1a9..5a73e84130f 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py @@ -131,6 +131,7 @@ class CustomSamplerFactory: In order to configure you application with a custom sampler's entry point, set the ``OTEL_TRACES_SAMPLER`` environment variable to the key name of the entry point. For example, to configured the above sampler, set ``OTEL_TRACES_SAMPLER=custom_sampler_name`` and ``OTEL_TRACES_SAMPLER_ARG=0.5``. """ + import abc import enum import os diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi index d42e0f018fa..d7c2f209e41 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi +++ b/opentelemetry-sdk/src/opentelemetry/sdk/util/__init__.pyi @@ -30,7 +30,7 @@ _VT = TypeVar("_VT") def ns_to_iso_str(nanoseconds: int) -> str: ... def get_dict_as_key( - labels: Mapping[str, AttributeValue] + labels: Mapping[str, AttributeValue], ) -> AttributesAsKey: ... class BoundedList(Sequence[_T]): diff --git a/opentelemetry-sdk/tests/error_handler/test_error_handler.py b/opentelemetry-sdk/tests/error_handler/test_error_handler.py index 116771dc9a1..31a07315ae6 100644 --- a/opentelemetry-sdk/tests/error_handler/test_error_handler.py +++ b/opentelemetry-sdk/tests/error_handler/test_error_handler.py @@ -27,7 +27,6 @@ class TestErrorHandler(TestCase): @patch("opentelemetry.sdk.error_handler.entry_points") def test_default_error_handler(self, mock_entry_points): - with self.assertLogs(logger, ERROR): with GlobalErrorHandler(): raise Exception("some exception") @@ -104,7 +103,6 @@ def _handle(self, error: Exception): # pylint: disable=no-self-use @patch("opentelemetry.sdk.error_handler.entry_points") def test_plugin_error_handler_context_manager(self, mock_entry_points): - mock_error_handler_instance = Mock() class MockErrorHandlerClass(IndexError): diff --git a/opentelemetry-sdk/tests/logs/test_handler.py b/opentelemetry-sdk/tests/logs/test_handler.py index 0f96361712b..866e5d05d7b 100644 --- a/opentelemetry-sdk/tests/logs/test_handler.py +++ b/opentelemetry-sdk/tests/logs/test_handler.py @@ -80,7 +80,6 @@ def test_log_record_emit_noop(self): handler_mock._translate.assert_not_called() def test_log_flush_noop(self): - no_op_logger_provider = NoOpLoggerProvider() no_op_logger_provider.force_flush = Mock() diff --git a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py index 96ba3991819..1232aa6376f 100644 --- a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py +++ b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py @@ -47,7 +47,6 @@ def right_boundary(scale: int, index: int) -> float: class TestExponentMapping(TestCase): def test_singleton(self): - self.assertIs(ExponentMapping(-3), ExponentMapping(-3)) self.assertIsNot(ExponentMapping(-3), ExponentMapping(-5)) @@ -61,19 +60,16 @@ def test_singleton(self): "exponent_mapping.ExponentMapping._init" ) def test_init_called_once(self, mock_init): - ExponentMapping(-3) ExponentMapping(-3) mock_init.assert_called_once() def test_exponent_mapping_0(self): - with self.assertNotRaises(Exception): ExponentMapping(0) def test_exponent_mapping_zero(self): - exponent_mapping = ExponentMapping(0) # This is the equivalent to 1.1 in hexadecimal @@ -133,7 +129,6 @@ def test_exponent_mapping_zero(self): ) def test_exponent_mapping_min_scale(self): - exponent_mapping = ExponentMapping(ExponentMapping._min_scale) self.assertEqual(exponent_mapping.map_to_index(1.000001), 0) self.assertEqual(exponent_mapping.map_to_index(1), -1) @@ -306,7 +301,6 @@ def test_exponent_mapping_neg_four(self): self.assertEqual(exponent_mapping.map_to_index(2**-975), -61) def test_exponent_index_max(self): - for scale in range( ExponentMapping._min_scale, ExponentMapping._max_scale ): diff --git a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponential_bucket_histogram_aggregation.py b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponential_bucket_histogram_aggregation.py index 311f00a0b00..d208f214c1d 100644 --- a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponential_bucket_histogram_aggregation.py +++ b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponential_bucket_histogram_aggregation.py @@ -44,7 +44,6 @@ def get_counts(buckets: Buckets) -> int: - counts = [] for index in range(len(buckets)): @@ -64,7 +63,6 @@ def swap( first: _ExponentialBucketHistogramAggregation, second: _ExponentialBucketHistogramAggregation, ): - for attribute in [ "_positive", "_negative", @@ -119,7 +117,6 @@ def assertInEpsilon(self, first, second, epsilon): self.assertGreaterEqual(first, (second * (1 - epsilon))) def require_equal(self, a, b): - if a._sum == 0 or b._sum == 0: self.assertAlmostEqual(a._sum, b._sum, 1e-6) else: @@ -234,9 +231,7 @@ def test_permutations(self): }, ], ]: - for permutation in permutations(test_values): - exponential_histogram_aggregation = ( _ExponentialBucketHistogramAggregation( Mock(), Mock(), max_size=2 @@ -244,7 +239,6 @@ def test_permutations(self): ) for value in permutation: - exponential_histogram_aggregation.aggregate( Measurement(value, Mock()) ) @@ -271,7 +265,6 @@ def test_permutations(self): ) def test_ascending_sequence(self): - for max_size in [3, 4, 6, 9]: for offset in range(-5, 6): for init_scale in [0, 4]: @@ -280,9 +273,7 @@ def test_ascending_sequence(self): def ascending_sequence_test( self, max_size: int, offset: int, init_scale: int ): - for step in range(max_size, max_size * 4): - exponential_histogram_aggregation = ( _ExponentialBucketHistogramAggregation( Mock(), Mock(), max_size=max_size @@ -375,7 +366,6 @@ def ascending_sequence_test( ) def test_reset(self): - for increment in [0x1, 0x100, 0x10000, 0x100000000, 0x200000000]: def mock_increment(self, bucket_index: int) -> None: @@ -441,7 +431,6 @@ def mock_increment(self, bucket_index: int) -> None: ) def test_move_into(self): - exponential_histogram_aggregation_0 = ( _ExponentialBucketHistogramAggregation( Mock(), Mock(), max_size=256 @@ -495,7 +484,6 @@ def test_move_into(self): ) def test_very_large_numbers(self): - exponential_histogram_aggregation = ( _ExponentialBucketHistogramAggregation(Mock(), Mock(), max_size=2) ) @@ -571,7 +559,6 @@ def expect_balanced(count: int): expect_balanced(3) def test_full_range(self): - exponential_histogram_aggregation = ( _ExponentialBucketHistogramAggregation(Mock(), Mock(), max_size=2) ) @@ -604,7 +591,6 @@ def test_full_range(self): self.assertLessEqual(exponential_histogram_aggregation._positive[1], 1) def test_aggregator_min_max(self): - exponential_histogram_aggregation = ( _ExponentialBucketHistogramAggregation(Mock(), Mock()) ) @@ -630,7 +616,6 @@ def test_aggregator_min_max(self): self.assertEqual(-1, exponential_histogram_aggregation._max) def test_aggregator_copy_swap(self): - exponential_histogram_aggregation_0 = ( _ExponentialBucketHistogramAggregation(Mock(), Mock()) ) @@ -687,7 +672,6 @@ def test_aggregator_copy_swap(self): ) def test_zero_count_by_increment(self): - exponential_histogram_aggregation_0 = ( _ExponentialBucketHistogramAggregation(Mock(), Mock()) ) @@ -730,7 +714,6 @@ def mock_increment(self, bucket_index: int) -> None: ) def test_one_count_by_increment(self): - exponential_histogram_aggregation_0 = ( _ExponentialBucketHistogramAggregation(Mock(), Mock()) ) @@ -773,13 +756,11 @@ def mock_increment(self, bucket_index: int) -> None: ) def test_boundary_statistics(self): - total = MAX_NORMAL_EXPONENT - MIN_NORMAL_EXPONENT + 1 for scale in range( LogarithmMapping._min_scale, LogarithmMapping._max_scale + 1 ): - above = 0 below = 0 diff --git a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py index 1fd18845bb6..d4001263d29 100644 --- a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py +++ b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py @@ -32,7 +32,6 @@ def left_boundary(scale: int, index: int) -> float: - # This is implemented in this way to avoid using a third-party bigfloat # package. The Go implementation uses a bigfloat package that is part of # their standard library. The assumption here is that the smallest float @@ -67,7 +66,6 @@ def assertInEpsilon(self, first, second, epsilon): "logarithm_mapping.LogarithmMapping._init" ) def test_init_called_once(self, mock_init): - LogarithmMapping(3) LogarithmMapping(3) @@ -78,7 +76,6 @@ def test_invalid_scale(self): LogarithmMapping(-1) def test_logarithm_mapping_scale_one(self): - # The exponentiation factor for this logarithm exponent histogram # mapping is square_root(2). # Scale 1 means 1 division between every power of two, having @@ -130,12 +127,10 @@ def test_logarithm_mapping_scale_one(self): ) def test_logarithm_boundary(self): - for scale in [1, 2, 3, 4, 10, 15]: logarithm_exponent_histogram_mapping = LogarithmMapping(scale) for index in [-100, -10, -1, 0, 1, 10, 100]: - lower_boundary = ( logarithm_exponent_histogram_mapping.get_lower_boundary( index @@ -156,7 +151,6 @@ def test_logarithm_boundary(self): ) def test_logarithm_index_max(self): - for scale in range( LogarithmMapping._min_scale, LogarithmMapping._max_scale + 1 ): diff --git a/opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py b/opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py index 1b3283717ae..13b15f3bd23 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py @@ -33,7 +33,6 @@ def tearDown(self): reset_metrics_globals() def test_console_exporter(self): - output = StringIO() exporter = ConsoleMetricExporter(out=output) reader = PeriodicExportingMetricReader( @@ -74,7 +73,6 @@ def test_console_exporter(self): self.assertEqual(metrics["value"], 1) def test_console_exporter_no_export(self): - output = StringIO() exporter = ConsoleMetricExporter(out=output) reader = PeriodicExportingMetricReader( diff --git a/opentelemetry-sdk/tests/metrics/integration_test/test_cpu_time.py b/opentelemetry-sdk/tests/metrics/integration_test/test_cpu_time.py index 7b440c0332a..18b8cbdcea0 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_cpu_time.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_cpu_time.py @@ -188,9 +188,9 @@ def cpu_time_callback( ) def test_cpu_time_generator(self): - def cpu_time_generator() -> Generator[ - Iterable[Observation], None, None - ]: + def cpu_time_generator() -> ( + Generator[Iterable[Observation], None, None] + ): options = yield while True: self.assertIsInstance(options, CallbackOptions) diff --git a/opentelemetry-sdk/tests/metrics/integration_test/test_explicit_bucket_histogram_aggregation.py b/opentelemetry-sdk/tests/metrics/integration_test/test_explicit_bucket_histogram_aggregation.py index 6db35fd4c0a..f46e04ee9bf 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_explicit_bucket_histogram_aggregation.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_explicit_bucket_histogram_aggregation.py @@ -26,7 +26,6 @@ class TestExplicitBucketHistogramAggregation(TestCase): - test_values = [1, 6, 11, 26, 51, 76, 101, 251, 501, 751] @mark.skipif( @@ -38,7 +37,6 @@ class TestExplicitBucketHistogramAggregation(TestCase): ), ) def test_synchronous_delta_temporality(self): - aggregation = ExplicitBucketHistogramAggregation() reader = InMemoryMetricReader( @@ -54,7 +52,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -120,7 +117,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) provider.shutdown() @@ -137,7 +133,6 @@ def test_synchronous_delta_temporality(self): ), ) def test_synchronous_cumulative_temporality(self): - aggregation = ExplicitBucketHistogramAggregation() reader = InMemoryMetricReader( @@ -155,7 +150,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -164,7 +158,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for test_value in self.test_values: - histogram.record(test_value) results.append(reader.get_metrics_data()) @@ -178,7 +171,6 @@ def test_synchronous_cumulative_temporality(self): ) for index, metrics_data in enumerate(results): - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -209,7 +201,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) provider.shutdown() @@ -224,7 +215,6 @@ def test_synchronous_cumulative_temporality(self): ) for metrics_data in results: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] diff --git a/opentelemetry-sdk/tests/metrics/integration_test/test_histogram_export.py b/opentelemetry-sdk/tests/metrics/integration_test/test_histogram_export.py index eaf590219ba..6e1213a377c 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_histogram_export.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_histogram_export.py @@ -21,7 +21,6 @@ class TestHistogramExport(TestCase): def test_histogram_counter_collection(self): - in_memory_metric_reader = InMemoryMetricReader() provider = MeterProvider( diff --git a/opentelemetry-sdk/tests/metrics/integration_test/test_sum_aggregation.py b/opentelemetry-sdk/tests/metrics/integration_test/test_sum_aggregation.py index 708b44f5fef..bc7322fccb4 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_sum_aggregation.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_sum_aggregation.py @@ -38,7 +38,6 @@ class TestSumAggregation(TestCase): ), ) def test_asynchronous_delta_temporality(self): - eight_multiple_generator = count(start=8, step=8) counter = 0 @@ -124,7 +123,6 @@ def observable_counter_callback(callback_options): ) for metrics_data in results[1:]: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -163,7 +161,6 @@ def observable_counter_callback(callback_options): ), ) def test_asynchronous_cumulative_temporality(self): - eight_multiple_generator = count(start=8, step=8) counter = 0 @@ -225,7 +222,6 @@ def observable_counter_callback(callback_options): ) for index, metrics_data in enumerate(results): - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -260,7 +256,6 @@ def observable_counter_callback(callback_options): ), ) def test_synchronous_delta_temporality(self): - aggregation = SumAggregation() reader = InMemoryMetricReader( @@ -276,7 +271,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -322,7 +316,6 @@ def test_synchronous_delta_temporality(self): ) for metrics_data in results[1:]: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -342,7 +335,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) provider.shutdown() @@ -359,7 +351,6 @@ def test_synchronous_delta_temporality(self): ), ) def test_synchronous_cumulative_temporality(self): - aggregation = SumAggregation() reader = InMemoryMetricReader( @@ -375,7 +366,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -384,7 +374,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - counter.add(8) results.append(reader.get_metrics_data()) @@ -398,7 +387,6 @@ def test_synchronous_cumulative_temporality(self): ) for index, metrics_data in enumerate(results): - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -414,7 +402,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) provider.shutdown() @@ -429,7 +416,6 @@ def test_synchronous_cumulative_temporality(self): ) for metrics_data in results: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] diff --git a/opentelemetry-sdk/tests/metrics/test_aggregation.py b/opentelemetry-sdk/tests/metrics/test_aggregation.py index 37656b0a34c..4fd942b5684 100644 --- a/opentelemetry-sdk/tests/metrics/test_aggregation.py +++ b/opentelemetry-sdk/tests/metrics/test_aggregation.py @@ -481,7 +481,6 @@ def setUpClass(cls): cls.default_aggregation = DefaultAggregation() def test_counter(self): - aggregation = self.default_aggregation._create_aggregation( _Counter("name", Mock(), Mock()), Mock(), 0 ) @@ -493,7 +492,6 @@ def test_counter(self): ) def test_up_down_counter(self): - aggregation = self.default_aggregation._create_aggregation( _UpDownCounter("name", Mock(), Mock()), Mock(), 0 ) @@ -505,7 +503,6 @@ def test_up_down_counter(self): ) def test_observable_counter(self): - aggregation = self.default_aggregation._create_aggregation( _ObservableCounter("name", Mock(), Mock(), callbacks=[Mock()]), Mock(), @@ -519,7 +516,6 @@ def test_observable_counter(self): ) def test_observable_up_down_counter(self): - aggregation = self.default_aggregation._create_aggregation( _ObservableUpDownCounter( "name", Mock(), Mock(), callbacks=[Mock()] @@ -535,7 +531,6 @@ def test_observable_up_down_counter(self): ) def test_histogram(self): - aggregation = self.default_aggregation._create_aggregation( _Histogram( "name", @@ -548,7 +543,6 @@ def test_histogram(self): self.assertIsInstance(aggregation, _ExplicitBucketHistogramAggregation) def test_gauge(self): - aggregation = self.default_aggregation._create_aggregation( _Gauge( "name", @@ -561,7 +555,6 @@ def test_gauge(self): self.assertIsInstance(aggregation, _LastValueAggregation) def test_observable_gauge(self): - aggregation = self.default_aggregation._create_aggregation( _ObservableGauge( "name", diff --git a/opentelemetry-sdk/tests/metrics/test_in_memory_metric_reader.py b/opentelemetry-sdk/tests/metrics/test_in_memory_metric_reader.py index 68c81e8b7ef..04d648c772c 100644 --- a/opentelemetry-sdk/tests/metrics/test_in_memory_metric_reader.py +++ b/opentelemetry-sdk/tests/metrics/test_in_memory_metric_reader.py @@ -109,7 +109,6 @@ def test_integration(self): ) def test_cumulative_multiple_collect(self): - reader = InMemoryMetricReader( preferred_temporality={Counter: AggregationTemporality.CUMULATIVE} ) diff --git a/opentelemetry-sdk/tests/metrics/test_measurement_consumer.py b/opentelemetry-sdk/tests/metrics/test_measurement_consumer.py index b1f3dc2a385..f9d4c26f01c 100644 --- a/opentelemetry-sdk/tests/metrics/test_measurement_consumer.py +++ b/opentelemetry-sdk/tests/metrics/test_measurement_consumer.py @@ -32,7 +32,6 @@ ) class TestSynchronousMeasurementConsumer(TestCase): def test_parent(self, _): - self.assertIsInstance( SynchronousMeasurementConsumer(MagicMock()), MeasurementConsumer ) diff --git a/opentelemetry-sdk/tests/metrics/test_metric_reader.py b/opentelemetry-sdk/tests/metrics/test_metric_reader.py index fff645e36d9..a3eb5fa71c1 100644 --- a/opentelemetry-sdk/tests/metrics/test_metric_reader.py +++ b/opentelemetry-sdk/tests/metrics/test_metric_reader.py @@ -74,7 +74,6 @@ def shutdown(self, timeout_millis: float = 30_000, **kwargs) -> None: class TestMetricReader(TestCase): def test_configure_temporality(self): - dummy_metric_reader = DummyMetricReader( preferred_temporality={ Histogram: AggregationTemporality.DELTA, @@ -147,7 +146,6 @@ def test_configure_aggregation(self): ) def test_force_flush(self): - with patch.object(DummyMetricReader, "collect") as mock_collect: DummyMetricReader().force_flush(timeout_millis=10) mock_collect.assert_called_with(timeout_millis=10) diff --git a/opentelemetry-sdk/tests/metrics/test_metric_reader_storage.py b/opentelemetry-sdk/tests/metrics/test_metric_reader_storage.py index 5bcf07f6b68..fe48818272d 100644 --- a/opentelemetry-sdk/tests/metrics/test_metric_reader_storage.py +++ b/opentelemetry-sdk/tests/metrics/test_metric_reader_storage.py @@ -294,7 +294,6 @@ def test_default_view_enabled(self, MockViewInstrumentMatch: Mock): self.assertEqual(len(MockViewInstrumentMatch.call_args_list), 1) def test_drop_aggregation(self): - counter = _Counter("name", Mock(), Mock()) metric_reader_storage = MetricReaderStorage( SdkConfiguration( @@ -318,7 +317,6 @@ def test_drop_aggregation(self): self.assertIsNone(metric_reader_storage.collect()) def test_same_collection_start(self): - counter = _Counter("name", Mock(), Mock()) up_down_counter = _UpDownCounter("name", Mock(), Mock()) @@ -359,7 +357,6 @@ def test_same_collection_start(self): ) def test_conflicting_view_configuration(self): - observable_counter = _ObservableCounter( "observable_counter", Mock(), @@ -515,9 +512,7 @@ def test_view_instrument_match_conflict_1(self): log.records[0].message, ) - for ( - view_instrument_matches - ) in ( + for view_instrument_matches in ( metric_reader_storage._instrument_view_instrument_matches.values() ): for view_instrument_match in view_instrument_matches: diff --git a/opentelemetry-sdk/tests/metrics/test_metrics.py b/opentelemetry-sdk/tests/metrics/test_metrics.py index 199305005b3..621a96b9414 100644 --- a/opentelemetry-sdk/tests/metrics/test_metrics.py +++ b/opentelemetry-sdk/tests/metrics/test_metrics.py @@ -63,7 +63,6 @@ def shutdown(self, timeout_millis: float = 30_000, **kwargs) -> None: class TestMeterProvider(ConcurrencyTestBase, TestCase): def tearDown(self): - MeterProvider._all_metric_readers = set() @patch.object(Resource, "create") @@ -181,7 +180,6 @@ def test_get_meter_duplicate(self): self.assertIsNot(meter1, meter3) def test_shutdown(self): - mock_metric_reader_0 = MagicMock( **{ "shutdown.side_effect": ZeroDivisionError(), @@ -289,7 +287,6 @@ def test_creates_sync_measurement_consumer( def test_register_asynchronous_instrument( self, mock_sync_measurement_consumer ): - meter_provider = MeterProvider() meter_provider._measurement_consumer.register_asynchronous_instrument.assert_called_with( @@ -497,7 +494,6 @@ def force_flush(self, timeout_millis: float = 10_000) -> bool: class TestDuplicateInstrumentAggregateData(TestCase): def test_duplicate_instrument_aggregate_data(self): - exporter = InMemoryMetricExporter() reader = PeriodicExportingMetricReader( exporter, export_interval_millis=500 diff --git a/opentelemetry-sdk/tests/metrics/test_periodic_exporting_metric_reader.py b/opentelemetry-sdk/tests/metrics/test_periodic_exporting_metric_reader.py index 98f59526ef6..648b1c8aac1 100644 --- a/opentelemetry-sdk/tests/metrics/test_periodic_exporting_metric_reader.py +++ b/opentelemetry-sdk/tests/metrics/test_periodic_exporting_metric_reader.py @@ -134,7 +134,6 @@ def test_defaults(self): def _create_periodic_reader( self, metrics, exporter, collect_wait=0, interval=60000, timeout=30000 ): - pmr = PeriodicExportingMetricReader( exporter, export_interval_millis=interval, diff --git a/opentelemetry-sdk/tests/metrics/test_point.py b/opentelemetry-sdk/tests/metrics/test_point.py index 20dd0e72384..13343fd4704 100644 --- a/opentelemetry-sdk/tests/metrics/test_point.py +++ b/opentelemetry-sdk/tests/metrics/test_point.py @@ -36,7 +36,6 @@ class TestToJson(TestCase): @classmethod def setUpClass(cls): - cls.attributes_0 = { "a": "b", "b": True, @@ -215,7 +214,6 @@ def setUpClass(cls): cls.metrics_data_0_str = f'{{"resource_metrics": [{cls.resource_metrics_0_str}, {cls.resource_metrics_1_str}]}}' def test_number_data_point(self): - self.assertEqual( self.number_data_point_0.to_json(indent=None), self.number_data_point_0_str, @@ -226,7 +224,6 @@ def test_number_data_point(self): ) def test_histogram_data_point(self): - self.assertEqual( self.histogram_data_point_0.to_json(indent=None), self.histogram_data_point_0_str, @@ -246,17 +243,14 @@ def test_exp_histogram_data_point(self): ) def test_sum(self): - self.assertEqual(self.sum_0.to_json(indent=None), self.sum_0_str) def test_gauge(self): - self.maxDiff = None self.assertEqual(self.gauge_0.to_json(indent=None), self.gauge_0_str) def test_histogram(self): - self.assertEqual( self.histogram_0.to_json(indent=None), self.histogram_0_str ) @@ -270,7 +264,6 @@ def test_exp_histogram(self): ) def test_metric(self): - self.assertEqual(self.metric_0.to_json(indent=None), self.metric_0_str) self.assertEqual(self.metric_1.to_json(indent=None), self.metric_1_str) @@ -278,7 +271,6 @@ def test_metric(self): self.assertEqual(self.metric_2.to_json(indent=None), self.metric_2_str) def test_scope_metrics(self): - self.assertEqual( self.scope_metrics_0.to_json(indent=None), self.scope_metrics_0_str ) @@ -287,7 +279,6 @@ def test_scope_metrics(self): ) def test_resource_metrics(self): - self.assertEqual( self.resource_metrics_0.to_json(indent=None), self.resource_metrics_0_str, @@ -298,7 +289,6 @@ def test_resource_metrics(self): ) def test_metrics_data(self): - self.assertEqual( self.metrics_data_0.to_json(indent=None), self.metrics_data_0_str ) diff --git a/opentelemetry-sdk/tests/metrics/test_view.py b/opentelemetry-sdk/tests/metrics/test_view.py index 00376a0068b..847872c96cb 100644 --- a/opentelemetry-sdk/tests/metrics/test_view.py +++ b/opentelemetry-sdk/tests/metrics/test_view.py @@ -20,16 +20,13 @@ class TestView(TestCase): def test_required_instrument_criteria(self): - with self.assertRaises(Exception): View() def test_instrument_type(self): - self.assertTrue(View(instrument_type=Mock)._match(Mock())) def test_instrument_name(self): - mock_instrument = Mock() mock_instrument.configure_mock(**{"name": "instrument_name"}) @@ -38,7 +35,6 @@ def test_instrument_name(self): ) def test_instrument_unit(self): - mock_instrument = Mock() mock_instrument.configure_mock(**{"unit": "instrument_unit"}) @@ -47,7 +43,6 @@ def test_instrument_unit(self): ) def test_meter_name(self): - self.assertTrue( View(meter_name="meter_name")._match( Mock(**{"instrumentation_scope.name": "meter_name"}) @@ -55,7 +50,6 @@ def test_meter_name(self): ) def test_meter_version(self): - self.assertTrue( View(meter_version="meter_version")._match( Mock(**{"instrumentation_scope.version": "meter_version"}) @@ -63,7 +57,6 @@ def test_meter_version(self): ) def test_meter_schema_url(self): - self.assertTrue( View(meter_schema_url="meter_schema_url")._match( Mock( @@ -89,7 +82,6 @@ def test_meter_schema_url(self): ) def test_additive_criteria(self): - view = View( meter_name="meter_name", meter_version="meter_version", @@ -120,6 +112,5 @@ def test_additive_criteria(self): ) def test_view_name(self): - with self.assertRaises(Exception): View(name="name", instrument_name="instrument_name*") diff --git a/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py b/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py index c22c2d7a96b..44d9931e183 100644 --- a/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py +++ b/opentelemetry-sdk/tests/metrics/test_view_instrument_match.py @@ -39,7 +39,6 @@ class Test_ViewInstrumentMatch(TestCase): @classmethod def setUpClass(cls): - cls.mock_aggregation_factory = Mock() cls.mock_created_aggregation = ( cls.mock_aggregation_factory._create_aggregation() diff --git a/opentelemetry-sdk/tests/resources/test_resources.py b/opentelemetry-sdk/tests/resources/test_resources.py index da3f9469617..a0c6159010d 100644 --- a/opentelemetry-sdk/tests/resources/test_resources.py +++ b/opentelemetry-sdk/tests/resources/test_resources.py @@ -511,9 +511,9 @@ def test_invalid_key_value_pairs(self): def test_multiple_with_url_decode(self): detector = OTELResourceDetector() - environ[ - OTEL_RESOURCE_ATTRIBUTES - ] = "key=value%20test%0A, key2=value+%202" + environ[OTEL_RESOURCE_ATTRIBUTES] = ( + "key=value%20test%0A, key2=value+%202" + ) self.assertEqual( detector.detect(), Resource({"key": "value test\n", "key2": "value+ 2"}), diff --git a/opentelemetry-sdk/tests/test_configurator.py b/opentelemetry-sdk/tests/test_configurator.py index b825ae931cb..d8279fb527d 100644 --- a/opentelemetry-sdk/tests/test_configurator.py +++ b/opentelemetry-sdk/tests/test_configurator.py @@ -889,7 +889,6 @@ class TestImportConfigComponents(TestCase): def test__import_config_components_missing_entry_point( self, mock_entry_points ): - with raises(RuntimeError) as error: _import_config_components(["a", "b", "c"], "name") self.assertEqual( @@ -903,7 +902,6 @@ def test__import_config_components_missing_entry_point( def test__import_config_components_missing_component( self, mock_entry_points ): - with raises(RuntimeError) as error: _import_config_components(["a", "b", "c"], "name") self.assertEqual( diff --git a/opentelemetry-sdk/tests/trace/export/test_export.py b/opentelemetry-sdk/tests/trace/export/test_export.py index 8175c09f59e..a5a80f16c8b 100644 --- a/opentelemetry-sdk/tests/trace/export/test_export.py +++ b/opentelemetry-sdk/tests/trace/export/test_export.py @@ -179,7 +179,6 @@ class TestBatchSpanProcessor(ConcurrencyTestBase): }, ) def test_args_env_var(self): - batch_span_processor = export.BatchSpanProcessor( MySpanExporter(destination=[]) ) @@ -190,7 +189,6 @@ def test_args_env_var(self): self.assertEqual(batch_span_processor.export_timeout_millis, 4) def test_args_env_var_defaults(self): - batch_span_processor = export.BatchSpanProcessor( MySpanExporter(destination=[]) ) @@ -210,7 +208,6 @@ def test_args_env_var_defaults(self): }, ) def test_args_env_var_value_error(self): - logger.disabled = True batch_span_processor = export.BatchSpanProcessor( MySpanExporter(destination=[]) diff --git a/opentelemetry-sdk/tests/trace/test_sampling.py b/opentelemetry-sdk/tests/trace/test_sampling.py index e976b0f551e..09057ee1c15 100644 --- a/opentelemetry-sdk/tests/trace/test_sampling.py +++ b/opentelemetry-sdk/tests/trace/test_sampling.py @@ -251,7 +251,6 @@ def test_probability_sampler_one(self): ) def test_probability_sampler_limits(self): - # Sample one of every 2^64 (= 5e-20) traces. This is the lowest # possible meaningful sampling rate, only traces with trace ID 0x0 # should get sampled. diff --git a/opentelemetry-sdk/tests/trace/test_trace.py b/opentelemetry-sdk/tests/trace/test_trace.py index 5441bed6dd7..1b7cf927a93 100644 --- a/opentelemetry-sdk/tests/trace/test_trace.py +++ b/opentelemetry-sdk/tests/trace/test_trace.py @@ -889,7 +889,6 @@ def test_links(self): trace_api.Link(other_context2, {"name": "neighbor"}), ) with self.tracer.start_as_current_span("root", links=links) as root: - self.assertEqual(len(root.links), 2) self.assertEqual( root.links[0].context.trace_id, other_context1.trace_id @@ -995,7 +994,6 @@ def test_span_override_start_and_end_time(self): self.assertEqual(end_time, span.end_time) def test_span_set_status(self): - span1 = self.tracer.start_span("span1") span1.set_status(Status(status_code=StatusCode.ERROR)) self.assertEqual(span1.status.status_code, StatusCode.ERROR) diff --git a/opentelemetry-semantic-conventions/tests/test_semconv.py b/opentelemetry-semantic-conventions/tests/test_semconv.py index a7362a8af77..18fe3f045cb 100644 --- a/opentelemetry-semantic-conventions/tests/test_semconv.py +++ b/opentelemetry-semantic-conventions/tests/test_semconv.py @@ -19,6 +19,5 @@ class TestSemanticConventions(TestCase): def test_semantic_conventions(self): - if find_spec("opentelemetry.semconv") is None: self.fail("opentelemetry-semantic-conventions not installed") diff --git a/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py b/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py index a4c51b90c13..6625712e33e 100644 --- a/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py +++ b/propagator/opentelemetry-propagator-b3/tests/test_b3_format.py @@ -29,7 +29,6 @@ def get_child_parent_new_carrier(old_carrier, propagator): - ctx = propagator.extract(old_carrier) parent_span_context = trace_api.get_current_span(ctx).get_span_context() diff --git a/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py b/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py index 201d8bf3d3d..6b6eb8fbf05 100644 --- a/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py +++ b/propagator/opentelemetry-propagator-jaeger/src/opentelemetry/propagators/jaeger/__init__.py @@ -44,7 +44,6 @@ def extract( context: typing.Optional[Context] = None, getter: Getter = default_getter, ) -> Context: - if context is None: context = Context() header = getter.get(carrier, self.TRACE_ID_KEY) diff --git a/propagator/opentelemetry-propagator-jaeger/tests/test_jaeger_propagator.py b/propagator/opentelemetry-propagator-jaeger/tests/test_jaeger_propagator.py index a836cdf4033..d9e31a660ea 100644 --- a/propagator/opentelemetry-propagator-jaeger/tests/test_jaeger_propagator.py +++ b/propagator/opentelemetry-propagator-jaeger/tests/test_jaeger_propagator.py @@ -29,7 +29,6 @@ def get_context_new_carrier(old_carrier, carrier_baggage=None): - ctx = FORMAT.extract(old_carrier) if carrier_baggage: for key, value in carrier_baggage.items(): @@ -64,10 +63,8 @@ def setUpClass(cls): cls.trace_id = generator.generate_trace_id() cls.span_id = generator.generate_span_id() cls.parent_span_id = generator.generate_span_id() - cls.serialized_uber_trace_id = ( - jaeger._format_uber_trace_id( # pylint: disable=protected-access - cls.trace_id, cls.span_id, cls.parent_span_id, 11 - ) + cls.serialized_uber_trace_id = jaeger._format_uber_trace_id( # pylint: disable=protected-access + cls.trace_id, cls.span_id, cls.parent_span_id, 11 ) def test_extract_valid_span(self): @@ -117,10 +114,8 @@ def test_debug_flag_set(self): self.assertEqual(FORMAT.DEBUG_FLAG, debug_flag_value) def test_sample_debug_flags_unset(self): - uber_trace_id = ( - jaeger._format_uber_trace_id( # pylint: disable=protected-access - self.trace_id, self.span_id, self.parent_span_id, 0 - ) + uber_trace_id = jaeger._format_uber_trace_id( # pylint: disable=protected-access + self.trace_id, self.span_id, self.parent_span_id, 0 ) old_carrier = {FORMAT.TRACE_ID_KEY: uber_trace_id} _, new_carrier = get_context_new_carrier(old_carrier) diff --git a/pyproject.toml b/pyproject.toml index 01ae2999afc..21070a180a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,20 +1,53 @@ -[tool.black] -line-length = 79 -exclude = ''' -( - /( # generated files - .tox| - venv| - venv.*| - .venv.*| - target.*| - .*/build/lib/.*| - exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/v2/gen| - opentelemetry-proto/src/opentelemetry/proto/.*/.*| - scripts - )/ -) -''' [tool.pytest.ini_options] addopts = "-rs -v" log_cli = true + +[tool.ruff] +# Minimum supported python version +target-version = "py38" + +line-length = 79 +extend-exclude = [ + # Ignore generated files + "exporter/opentelemetry-exporter-zipkin-proto-http/src/opentelemetry/exporter/zipkin/proto/http/v2/gen", + "*_pb2*.py*", +] + +[tool.ruff.lint] +select = [ + # defaults + "E4", + "E7", + "E9", + "F", + + # pycodestyle + "E", + + # isort + "I", + + # Pylint + "PL", + + # flake8-slf (private-member-access) + # "SLF001", +] + +ignore = [ + "E501", + # pylint too-many-arguments + "PLR0913", + # pylint magic-value-comparison + "PLR2004", +] + +[tool.ruff.lint.isort] +known-third-party = [ + "psutil", + "pytest", + "redis", + "redis_opentracing", + "opencensus", +] +known-first-party = ["opentelemetry", "opentelemetry_example_app"] diff --git a/scripts/check_for_valid_readme.py b/scripts/check_for_valid_readme.py index c65097ea56e..d133ae3d3cb 100644 --- a/scripts/check_for_valid_readme.py +++ b/scripts/check_for_valid_readme.py @@ -1,4 +1,5 @@ """Test script to check given paths for valid README.rst files.""" + import argparse import sys from pathlib import Path @@ -29,7 +30,6 @@ def main(): error = False for path in map(Path, args.paths): - readme = path / "README.rst" try: if not is_valid_rst(readme): diff --git a/scripts/eachdist.py b/scripts/eachdist.py index 51f0f7dd2ae..2917cdd7905 100755 --- a/scripts/eachdist.py +++ b/scripts/eachdist.py @@ -238,7 +238,7 @@ def setup_instparser(instparser): fmtparser = subparsers.add_parser( "format", - help="Formats all source code with black and isort.", + help="Formats all source code with ruff.", ) fmtparser.set_defaults(func=format_args) fmtparser.add_argument( @@ -517,18 +517,18 @@ def lint_args(args): runsubprocess( args.dry_run, - ("black", "--config", "pyproject.toml", ".") + (("--diff", "--check") if args.check_only else ()), - cwd=rootdir, + ("ruff", "check", "--select", "I") + + (() if args.check_only else ("--fix",)), check=True, ) runsubprocess( args.dry_run, - ("isort", "--settings-path", ".isort.cfg", ".") - + (("--diff", "--check-only") if args.check_only else ()), - cwd=rootdir, + ("ruff", "format") + (("--diff",) if args.check_only else ()), check=True, ) - runsubprocess(args.dry_run, ("flake8", "--config", ".flake8", rootdir), check=True) + runsubprocess( + args.dry_run, ("flake8", "--config", ".flake8", rootdir), check=True + ) execute_args( parse_subargs( args, ("exec", "pylint {}", "--all", "--mode", "lintroots") @@ -577,8 +577,8 @@ def update_version_files(targets, version, packages): def update_dependencies(targets, version, packages): print("updating dependencies") # PEP 508 allowed specifier operators - operators = ['==', '!=', '<=', '>=', '<', '>', '===', '~=', '='] - operators_pattern = '|'.join(re.escape(op) for op in operators) + operators = ["==", "!=", "<=", ">=", "<", ">", "===", "~=", "="] + operators_pattern = "|".join(re.escape(op) for op in operators) for pkg in packages: search = rf"({basename(pkg)}[^,]*)({operators_pattern})(.*\.dev)" @@ -654,13 +654,13 @@ def format_args(args): runsubprocess( args.dry_run, - ("black", "--config", f"{root_dir}/pyproject.toml", "."), + ("ruff", "check", "--select", "I", "--fix"), cwd=format_dir, check=True, ) runsubprocess( args.dry_run, - ("isort", "--settings-path", f"{root_dir}/.isort.cfg", "--profile", "black", "."), + ("ruff", "format"), cwd=format_dir, check=True, ) diff --git a/scripts/public_symbols_checker.py b/scripts/public_symbols_checker.py index c8bf7fd22e7..b401f032598 100644 --- a/scripts/public_symbols_checker.py +++ b/scripts/public_symbols_checker.py @@ -29,7 +29,6 @@ def get_symbols(change_type, diff_lines_getter, prefix): - if change_type == "D" or prefix == r"\-": file_path_symbols = removed_symbols else: @@ -40,7 +39,6 @@ def get_symbols(change_type, diff_lines_getter, prefix): .diff(repo.head.commit) .iter_change_type(change_type) ): - if diff_lines.b_blob is None: # This happens if a file has been removed completely. b_file_path = diff_lines.a_blob.path @@ -53,7 +51,8 @@ def get_symbols(change_type, diff_lines_getter, prefix): or "opentelemetry" not in b_file_path or any( # single leading underscore - part[0] == "_" and part[1] != "_" + part[0] == "_" + and part[1] != "_" # tests directories or part == "tests" for part in b_file_path_obj.parts @@ -123,11 +122,10 @@ def remove_common_symbols(): del removed_symbols[file_path] -# If a symbol is added and removed in the same commit, we consider it as not -# added or removed. -remove_common_symbols() - if added_symbols or removed_symbols: + # If a symbol is added and removed in the same commit, we consider it + # as not added or removed. + remove_common_symbols() print("The code in this branch adds the following public symbols:") print() for file_path_, symbols_ in added_symbols.items(): diff --git a/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_span.py b/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_span.py index f3ff804c6f2..2012035247a 100644 --- a/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_span.py +++ b/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_span.py @@ -97,13 +97,13 @@ def add_message_event(self, message_event: MessageEvent): ], } if message_event.uncompressed_size_bytes is not None: - attrs[ - _MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_UNCOMPRESSED - ] = message_event.uncompressed_size_bytes + attrs[_MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_UNCOMPRESSED] = ( + message_event.uncompressed_size_bytes + ) if message_event.compressed_size_bytes is not None: - attrs[ - _MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_COMPRESSED - ] = message_event.compressed_size_bytes + attrs[_MESSAGE_EVENT_ATTRIBUTE_KEY_SIZE_COMPRESSED] = ( + message_event.compressed_size_bytes + ) timestamp = _opencensus_time_to_nanos(message_event.timestamp) self._self_otel_span.add_event( diff --git a/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_tracer.py b/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_tracer.py index a1e30afb500..35386d4f468 100644 --- a/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_tracer.py +++ b/shim/opentelemetry-opencensus-shim/src/opentelemetry/shim/opencensus/_shim_tracer.py @@ -87,7 +87,7 @@ def __init__( wrapped: BaseTracer, *, oc_span_context: SpanContext, - otel_tracer: trace.Tracer + otel_tracer: trace.Tracer, ) -> None: super().__init__(wrapped) self._self_oc_span_context = oc_span_context diff --git a/shim/opentelemetry-opentracing-shim/src/opentelemetry/shim/opentracing_shim/__init__.py b/shim/opentelemetry-opentracing-shim/src/opentelemetry/shim/opentracing_shim/__init__.py index 8fd72da9720..a06d7834722 100644 --- a/shim/opentelemetry-opentracing-shim/src/opentelemetry/shim/opentracing_shim/__init__.py +++ b/shim/opentelemetry-opentracing-shim/src/opentelemetry/shim/opentracing_shim/__init__.py @@ -112,15 +112,17 @@ from opentelemetry.propagate import get_global_textmap from opentelemetry.shim.opentracing_shim import util from opentelemetry.shim.opentracing_shim.version import __version__ -from opentelemetry.trace import INVALID_SPAN_CONTEXT, Link, NonRecordingSpan -from opentelemetry.trace import SpanContext as OtelSpanContext -from opentelemetry.trace import Tracer as OtelTracer from opentelemetry.trace import ( + INVALID_SPAN_CONTEXT, + Link, + NonRecordingSpan, TracerProvider, get_current_span, set_span_in_context, use_span, ) +from opentelemetry.trace import SpanContext as OtelSpanContext +from opentelemetry.trace import Tracer as OtelTracer from opentelemetry.util.types import Attributes ValueT = TypeVar("ValueT", int, float, bool, str) diff --git a/shim/opentelemetry-opentracing-shim/tests/test_shim.py b/shim/opentelemetry-opentracing-shim/tests/test_shim.py index 99394ad2169..85a9f685124 100644 --- a/shim/opentelemetry-opentracing-shim/tests/test_shim.py +++ b/shim/opentelemetry-opentracing-shim/tests/test_shim.py @@ -302,7 +302,7 @@ def test_parent_child_implicit(self): # Verify parent span becomes the active span again. self.assertEqual( self.shim.active_span.context.unwrap(), - parent.span.context.unwrap() + parent.span.context.unwrap(), # TODO: Check equality of the spans themselves rather than # their context once the SpanShim reconstruction problem has # been addressed (see previous TODO). @@ -608,7 +608,6 @@ def test_extract_binary(self): self.shim.extract(opentracing.Format.BINARY, bytearray()) def test_baggage(self): - span_context_shim = SpanContextShim( trace.SpanContext(1234, 5678, is_remote=False) ) @@ -650,13 +649,11 @@ def test_mixed_mode(self): span_shim = self.shim.start_span("TestSpan16") with self.shim.scope_manager.activate(span_shim, finish_on_close=True): - with ( TracerProvider() .get_tracer(__name__) .start_as_current_span("abc") ) as opentelemetry_span: - self.assertIs( span_shim.unwrap().context, opentelemetry_span.parent, @@ -665,9 +662,7 @@ def test_mixed_mode(self): with ( TracerProvider().get_tracer(__name__).start_as_current_span("abc") ) as opentelemetry_span: - with self.shim.start_active_span("TestSpan17") as scope: - self.assertIs( scope.span.unwrap().parent, opentelemetry_span.context, diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_asyncio.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_asyncio.py index 0419ab44a22..7ffad630d23 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_asyncio.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_asyncio.py @@ -54,7 +54,6 @@ def test_main(self): async def task(self, span): # Create a new Span for this task with self.tracer.start_active_span("task"): - with self.tracer.scope_manager.activate(span, True): # Simulate work strictly related to the initial Span pass diff --git a/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_threads.py b/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_threads.py index 4e76c87a03e..fbd0eac308a 100644 --- a/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_threads.py +++ b/shim/opentelemetry-opentracing-shim/tests/testbed/test_active_span_replacement/test_threads.py @@ -50,7 +50,6 @@ def test_main(self): def task(self, span): # Create a new Span for this task with self.tracer.start_active_span("task"): - with self.tracer.scope_manager.activate(span, True): # Simulate work strictly related to the initial Span pass diff --git a/tests/opentelemetry-test-utils/src/opentelemetry/test/__init__.py b/tests/opentelemetry-test-utils/src/opentelemetry/test/__init__.py index 068ed12e86c..84188864bfe 100644 --- a/tests/opentelemetry-test-utils/src/opentelemetry/test/__init__.py +++ b/tests/opentelemetry-test-utils/src/opentelemetry/test/__init__.py @@ -28,7 +28,6 @@ def __enter__(self): def __exit__(self, type_, value, tb): # pylint: disable=invalid-name if value is not None and type_ in self._exception_types: - self._test_case.fail( "Unexpected exception was raised:\n{}".format( "\n".join(format_tb(tb)) @@ -43,13 +42,10 @@ def __call__(self, exception, *exceptions): return self def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) # pylint: disable=invalid-name self.assertNotRaises = self._AssertNotRaises(self) -class TestCase( - _AssertNotRaisesMixin, TestCase -): # pylint: disable=function-redefined +class TestCase(_AssertNotRaisesMixin, TestCase): # pylint: disable=function-redefined pass diff --git a/tests/opentelemetry-test-utils/src/opentelemetry/test/wsgitestutil.py b/tests/opentelemetry-test-utils/src/opentelemetry/test/wsgitestutil.py index 28a4c2698e6..908b1d41847 100644 --- a/tests/opentelemetry-test-utils/src/opentelemetry/test/wsgitestutil.py +++ b/tests/opentelemetry-test-utils/src/opentelemetry/test/wsgitestutil.py @@ -39,9 +39,7 @@ def start_response(self, status, response_headers, exc_info=None): self.exc_info = exc_info return self.write - def assertTraceResponseHeaderMatchesSpan( - self, headers, span - ): # pylint: disable=invalid-name + def assertTraceResponseHeaderMatchesSpan(self, headers, span): # pylint: disable=invalid-name self.assertIn("traceresponse", headers) self.assertEqual( headers["access-control-expose-headers"], diff --git a/tests/opentelemetry-test-utils/tests/test_utils.py b/tests/opentelemetry-test-utils/tests/test_utils.py index ce97951f86d..ccebd94fe95 100644 --- a/tests/opentelemetry-test-utils/tests/test_utils.py +++ b/tests/opentelemetry-test-utils/tests/test_utils.py @@ -17,55 +17,42 @@ class TestAssertNotRaises(TestCase): def test_no_exception(self): - try: - with self.assertNotRaises(Exception): pass except Exception as error: # pylint: disable=broad-except - self.fail( # pylint: disable=no-member f"Unexpected exception {error} was raised" ) def test_no_specified_exception_single(self): - try: - with self.assertNotRaises(KeyError): 1 / 0 # pylint: disable=pointless-statement except Exception as error: # pylint: disable=broad-except - self.fail( # pylint: disable=no-member f"Unexpected exception {error} was raised" ) def test_no_specified_exception_multiple(self): - try: - with self.assertNotRaises(KeyError, IndexError): 1 / 0 # pylint: disable=pointless-statement except Exception as error: # pylint: disable=broad-except - self.fail( # pylint: disable=no-member f"Unexpected exception {error} was raised" ) def test_exception(self): - with self.assertRaises(AssertionError): - with self.assertNotRaises(ZeroDivisionError): 1 / 0 # pylint: disable=pointless-statement def test_missing_exception(self): - with self.assertRaises(AssertionError) as error: - with self.assertNotRaises(ZeroDivisionError): def raise_zero_division_error(): From 629d39a021ca289dfb6f7e4e093b5bd49e23985c Mon Sep 17 00:00:00 2001 From: Aaron Abbott Date: Fri, 29 Mar 2024 20:46:12 +0000 Subject: [PATCH 2/5] fix some awkward formatting and eachdist.py script --- .../opentelemetry/sdk/_configuration/__init__.py | 15 +++------------ scripts/eachdist.py | 2 +- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py index 9038f3675e2..1cbdc1392fa 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_configuration/__init__.py @@ -262,10 +262,7 @@ def _import_exporters( metric_exporters = {} log_exporters = {} - for ( - exporter_name, - exporter_impl, - ) in _import_config_components( + for exporter_name, exporter_impl in _import_config_components( trace_exporter_names, "opentelemetry_traces_exporter" ): if issubclass(exporter_impl, SpanExporter): @@ -273,10 +270,7 @@ def _import_exporters( else: raise RuntimeError(f"{exporter_name} is not a trace exporter") - for ( - exporter_name, - exporter_impl, - ) in _import_config_components( + for exporter_name, exporter_impl in _import_config_components( metric_exporter_names, "opentelemetry_metrics_exporter" ): # The metric exporter components may be push MetricExporter or pull exporters which @@ -286,10 +280,7 @@ def _import_exporters( else: raise RuntimeError(f"{exporter_name} is not a metric exporter") - for ( - exporter_name, - exporter_impl, - ) in _import_config_components( + for exporter_name, exporter_impl in _import_config_components( log_exporter_names, "opentelemetry_logs_exporter" ): if issubclass(exporter_impl, LogExporter): diff --git a/scripts/eachdist.py b/scripts/eachdist.py index 2917cdd7905..d6aa0258c21 100755 --- a/scripts/eachdist.py +++ b/scripts/eachdist.py @@ -648,7 +648,7 @@ def test_args(args): def format_args(args): - root_dir = format_dir = str(find_projectroot()) + format_dir = str(find_projectroot()) if args.path: format_dir = os.path.join(format_dir, args.path) From 268d823cd0337319b1f9d56b00eb11ff2b78a572 Mon Sep 17 00:00:00 2001 From: Aaron Abbott Date: Fri, 29 Mar 2024 20:48:55 +0000 Subject: [PATCH 3/5] minimize ruff lint config until lint PR --- pyproject.toml | 27 ++------------------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 21070a180a0..0a30636ca85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,32 +14,9 @@ extend-exclude = [ ] [tool.ruff.lint] +# Only lint for import sorting for now select = [ - # defaults - "E4", - "E7", - "E9", - "F", - - # pycodestyle - "E", - - # isort - "I", - - # Pylint - "PL", - - # flake8-slf (private-member-access) - # "SLF001", -] - -ignore = [ - "E501", - # pylint too-many-arguments - "PLR0913", - # pylint magic-value-comparison - "PLR2004", + "I", # isort ] [tool.ruff.lint.isort] From 83edd4f649a3e6198e1d7a2560f1b40c2e2e3fd4 Mon Sep 17 00:00:00 2001 From: Aaron Abbott Date: Mon, 1 Apr 2024 15:24:41 +0000 Subject: [PATCH 4/5] Fix autoformatting breaking some "type: ignore" comments --- opentelemetry-api/src/opentelemetry/util/_decorator.py | 4 ++-- opentelemetry-api/tests/trace/test_status.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/opentelemetry-api/src/opentelemetry/util/_decorator.py b/opentelemetry-api/src/opentelemetry/util/_decorator.py index f585078bba6..5bf88552b85 100644 --- a/opentelemetry-api/src/opentelemetry/util/_decorator.py +++ b/opentelemetry-api/src/opentelemetry/util/_decorator.py @@ -30,8 +30,8 @@ class _AgnosticContextManager( - contextlib._GeneratorContextManager, - Generic[R], # type: ignore # FIXME use contextlib._GeneratorContextManager[R] when we drop the python 3.8 support + contextlib._GeneratorContextManager, # type: ignore # FIXME use contextlib._GeneratorContextManager[R] when we drop the python 3.8 support + Generic[R], ): # pylint: disable=protected-access """Context manager that can decorate both async and sync functions. diff --git a/opentelemetry-api/tests/trace/test_status.py b/opentelemetry-api/tests/trace/test_status.py index f670bdb44b7..d7ea944e646 100644 --- a/opentelemetry-api/tests/trace/test_status.py +++ b/opentelemetry-api/tests/trace/test_status.py @@ -31,8 +31,9 @@ def test_constructor(self): def test_invalid_description(self): with self.assertLogs(level=WARNING) as warning: status = Status( - status_code=StatusCode.ERROR, description={"test": "val"} - ) # type: ignore + status_code=StatusCode.ERROR, + description={"test": "val"}, # type: ignore + ) self.assertIs(status.status_code, StatusCode.ERROR) self.assertEqual(status.description, None) self.assertIn( From 122e8a10415ab81380e4d719a21bad57f565acbb Mon Sep 17 00:00:00 2001 From: Aaron Abbott Date: Tue, 2 Apr 2024 16:12:50 +0000 Subject: [PATCH 5/5] Add changelog entry --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 190fbc489a9..e4d33e93557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +- Use ruff instead of black/isort for autoformatting (internal change) + ([#3822](https://github.com/open-telemetry/opentelemetry-python/pull/3822)) + ## Version 1.24.0/0.45b0 (2024-03-28) - Make create_gauge non-abstract method