diff --git a/.github/workflows/generate_workflows.py b/.github/workflows/generate_workflows.py index fa60ada6225..2b456d29423 100644 --- a/.github/workflows/generate_workflows.py +++ b/.github/workflows/generate_workflows.py @@ -1,10 +1,10 @@ from pathlib import Path from generate_workflows_lib import ( - generate_test_workflow, - generate_lint_workflow, generate_contrib_workflow, - generate_misc_workflow + generate_lint_workflow, + generate_misc_workflow, + generate_test_workflow, ) tox_ini_path = Path(__file__).parent.parent.parent.joinpath("tox.ini") diff --git a/docs/conf.py b/docs/conf.py index 2224eedde5c..965a806d06a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -204,9 +204,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 e5d7e6239a8..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 @@ -144,7 +144,6 @@ def translate_to_collector(spans: Sequence[ReadableSpan]): if span.events: for event in span.events: - collector_annotation = trace_pb2.Span.TimeEvent.Annotation( description=trace_pb2.TruncatableString(value=event.name) ) 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 65f94771407..4e75a6bcbe5 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 47ff0cf3e0f..b1f116135e5 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 b3c7b98f1db..9f2b27d5a55 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,53 +12,51 @@ # See the License for the specific language governing permissions and # limitations under the License. import logging - -from opentelemetry.sdk.metrics.export import ( - MetricExporter, -) -from opentelemetry.sdk.metrics.view import Aggregation from os import environ -from opentelemetry.sdk.metrics import ( - Counter, - Histogram, - ObservableCounter, - ObservableGauge, - ObservableUpDownCounter, - UpDownCounter, -) +from typing import Dict + from opentelemetry.exporter.otlp.proto.common._internal import ( _encode_attributes, _encode_span_id, _encode_trace_id, ) -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, - Sum, - ExponentialHistogram as ExponentialHistogramType, -) -from typing import Dict 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 import ( + Counter, + Histogram, + ObservableCounter, + ObservableGauge, + ObservableUpDownCounter, + UpDownCounter, +) +from opentelemetry.sdk.metrics.export import ( + AggregationTemporality, + Gauge, + MetricExporter, + MetricsData, + Sum, +) +from opentelemetry.sdk.metrics.export import ( + ExponentialHistogram as ExponentialHistogramType, +) +from opentelemetry.sdk.metrics.export import ( + Histogram as HistogramType, ) from opentelemetry.sdk.metrics.view import ( - ExponentialBucketHistogramAggregation, + Aggregation, ExplicitBucketHistogramAggregation, + ExponentialBucketHistogramAggregation, ) _logger = logging.getLogger(__name__) @@ -70,7 +68,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), @@ -80,7 +77,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, @@ -137,7 +133,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", @@ -146,17 +141,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 " @@ -306,7 +298,6 @@ def _encode_metric(metric, pb2_metric): 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, 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 ef0ae98b501..44092bdc18a 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 @@ -33,19 +33,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 d8f2ba2efb6..8f629899d77 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_CLIENT_CERTIFICATE, @@ -48,7 +47,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 b07d24e0d0e..582d083e86f 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, ) @@ -61,9 +60,9 @@ ) from opentelemetry.proto.resource.v1.resource_pb2 import Resource # noqa: F401 from opentelemetry.sdk.environment_variables import ( + OTEL_EXPORTER_OTLP_CERTIFICATE, OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE, OTEL_EXPORTER_OTLP_CLIENT_KEY, - OTEL_EXPORTER_OTLP_CERTIFICATE, OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS, @@ -306,7 +305,6 @@ def _export( return self._result.SUCCESS except RpcError as error: - if error.code() in [ StatusCode.CANCELLED, StatusCode.DEADLINE_EXCEEDED, @@ -316,7 +314,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 645885b6f28..c4701908e75 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 ( @@ -50,24 +50,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__) @@ -104,7 +104,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 ce8dcaabdf7..c78c1b81bb6 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,15 +38,17 @@ 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_CLIENT_CERTIFICATE, OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY, - OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_HEADERS, @@ -96,7 +94,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 5840b7360f2..a31679fb0d5 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 @@ -43,11 +43,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 ( @@ -395,7 +394,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": [0.01]}) add_LogsServiceServicer_to_server( @@ -411,7 +409,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( @@ -476,7 +473,6 @@ def test_exported_log_without_span_id(self): self.fail("No log records found") 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 d1b7ce9df59..1d2bae2486d 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 @@ -148,7 +148,6 @@ class TestOTLPMetricExporter(TestCase): # pylint: disable=too-many-public-methods def setUp(self): - self.exporter = OTLPMetricExporter() self.server = server(ThreadPoolExecutor(max_workers=10)) @@ -487,7 +486,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": [0.01]}) add_MetricsServiceServicer_to_server( @@ -504,7 +502,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( @@ -522,7 +519,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( @@ -892,7 +888,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "CUMULATIVE"}, ): - otlp_metric_exporter = OTLPMetricExporter() for ( @@ -905,7 +900,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() @@ -920,7 +914,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "DELTA"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -954,7 +947,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "LOWMEMORY"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -985,7 +977,6 @@ def test_aggregation_temporality(self): ) def test_exponential_explicit_bucket_histogram(self): - self.assertIsInstance( # pylint: disable=protected-access OTLPMetricExporter()._preferred_aggregation[Histogram], @@ -1036,7 +1027,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 7facce1f70f..fe0b94ac787 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 @@ -46,17 +46,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, @@ -528,7 +534,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": [0.01]}) add_TraceServiceServicer_to_server( @@ -543,7 +548,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( @@ -571,7 +575,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 597b012a49a..21b877380c8 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,6 +26,15 @@ _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_CLIENT_CERTIFICATE, @@ -33,27 +42,17 @@ 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_CLIENT_CERTIFICATE, OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY, + 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__) @@ -64,7 +63,6 @@ class OTLPLogExporter(LogExporter): - _MAX_RETRY_TIMEOUT = 64 def __init__( @@ -163,7 +161,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 16ac042dd89..d08014c22e7 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,56 +41,52 @@ 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 +from opentelemetry.proto.common.v1.common_pb2 import ( # noqa: F401 # 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_CLIENT_CERTIFICATE, OTEL_EXPORTER_OTLP_CLIENT_KEY, - 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_CLIENT_CERTIFICATE, OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY, + 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__) @@ -93,7 +97,6 @@ class OTLPMetricExporter(MetricExporter, OTLPMetricExporterMixin): - _MAX_RETRY_TIMEOUT = 64 def __init__( @@ -196,7 +199,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 ac69b6acde3..7bcf4b4ced1 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,30 +28,29 @@ 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_CLIENT_CERTIFICATE, - OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY, - 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_CLIENT_CERTIFICATE, OTEL_EXPORTER_OTLP_CLIENT_KEY, + 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_CLIENT_CERTIFICATE, + OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY, + 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__) @@ -62,7 +61,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..aec46da1a24 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 ( + Event, # noqa: F401 + Resource, # noqa: F401 +) +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 ( + Link, # noqa: F401 + SpanKind, # noqa: F401 +) 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 ac039d4ff81..dc0b1d985f1 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 @@ -86,7 +86,6 @@ # pylint: disable=protected-access class TestOTLPMetricExporter(TestCase): def setUp(self): - self.metrics = { "sum_int": MetricsData( resource_metrics=[ @@ -113,7 +112,6 @@ def setUp(self): } def test_constructor_default(self): - exporter = OTLPMetricExporter() self.assertEqual( @@ -218,7 +216,6 @@ def test_exporter_constructor_take_priority(self): }, ) def test_exporter_env(self): - exporter = OTLPMetricExporter() self.assertEqual(exporter._certificate_file, OS_ENV_CERTIFICATE) @@ -237,7 +234,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( @@ -250,7 +246,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( @@ -265,7 +260,6 @@ def test_exporter_env_endpoint_with_slash(self): }, ) def test_headers_parse_from_env(self): - with self.assertLogs(level="WARNING") as cm: _ = OTLPMetricExporter() @@ -307,7 +301,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 @@ -350,7 +343,6 @@ def test_exponential_backoff(self, mock_sleep): ) def test_aggregation_temporality(self): - otlp_metric_exporter = OTLPMetricExporter() for ( @@ -362,7 +354,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "CUMULATIVE"}, ): - otlp_metric_exporter = OTLPMetricExporter() for ( @@ -375,7 +366,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() @@ -390,7 +380,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "DELTA"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -424,7 +413,6 @@ def test_aggregation_temporality(self): environ, {OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "LOWMEMORY"}, ): - otlp_metric_exporter = OTLPMetricExporter() self.assertEqual( @@ -455,7 +443,6 @@ def test_aggregation_temporality(self): ) def test_exponential_explicit_bucket_histogram(self): - self.assertIsInstance( OTLPMetricExporter()._preferred_aggregation[Histogram], ExplicitBucketHistogramAggregation, @@ -513,7 +500,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 f5606794620..66b0f890d76 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 @@ -68,7 +68,6 @@ class TestOTLPHTTPLogExporter(unittest.TestCase): def test_constructor_default(self): - exporter = OTLPLogExporter() self.assertEqual( @@ -181,7 +180,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 9d57c62bae8..8d8ff6037aa 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 @@ -57,7 +57,6 @@ # pylint: disable=protected-access class TestOTLPSpanExporter(unittest.TestCase): def test_constructor_default(self): - exporter = OTLPSpanExporter() self.assertEqual( @@ -171,7 +170,6 @@ def test_exporter_constructor_take_priority(self): }, ) def test_exporter_env(self): - exporter = OTLPSpanExporter() self.assertEqual(exporter._certificate_file, OS_ENV_CERTIFICATE) @@ -190,7 +188,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( @@ -203,7 +200,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( @@ -218,7 +214,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 09ca1f901e5..801d70c7b60 100644 --- a/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py +++ b/exporter/opentelemetry-exporter-prometheus/src/opentelemetry/exporter/prometheus/__init__.py @@ -89,14 +89,14 @@ OTEL_EXPORTER_PROMETHEUS_PORT, OTEL_PYTHON_EXPERIMENTAL_DISABLE_PROMETHEUS_UNIT_NORMALIZATION, ) -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, @@ -302,7 +302,6 @@ 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__] ) @@ -323,7 +322,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__] ) @@ -344,7 +342,6 @@ def _translate_to_prometheus( 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__] ) diff --git a/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py b/exporter/opentelemetry-exporter-prometheus/tests/test_prometheus_exporter.py index ed11bb9ab7b..52a18963715 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/_events/__init__.py b/opentelemetry-api/src/opentelemetry/_events/__init__.py index 8284f0830db..a291055ec71 100644 --- a/opentelemetry-api/src/opentelemetry/_events/__init__.py +++ b/opentelemetry-api/src/opentelemetry/_events/__init__.py @@ -31,7 +31,6 @@ class Event(LogRecord): - def __init__( self, name: str, @@ -58,7 +57,6 @@ def __init__( class EventLogger(ABC): - def __init__( self, name: str, @@ -77,7 +75,6 @@ def emit(self, event: "Event") -> None: class NoOpEventLogger(EventLogger): - def emit(self, event: Event) -> None: pass @@ -119,7 +116,6 @@ def emit(self, event: Event) -> None: class EventLoggerProvider(ABC): - @abstractmethod def get_event_logger( self, @@ -132,7 +128,6 @@ def get_event_logger( class NoOpEventLoggerProvider(EventLoggerProvider): - def get_event_logger( self, name: str, @@ -146,7 +141,6 @@ def get_event_logger( class ProxyEventLoggerProvider(EventLoggerProvider): - def get_event_logger( self, name: str, @@ -175,7 +169,6 @@ def get_event_logger( def get_event_logger_provider() -> EventLoggerProvider: - global _EVENT_LOGGER_PROVIDER # pylint: disable=global-variable-not-assigned if _EVENT_LOGGER_PROVIDER is None: if _OTEL_PYTHON_EVENT_LOGGER_PROVIDER not in environ: @@ -208,7 +201,6 @@ def set_elp() -> None: def set_event_logger_provider( event_logger_provider: EventLoggerProvider, ) -> None: - _set_event_logger_provider(event_logger_provider, log=True) diff --git a/opentelemetry-api/src/opentelemetry/context/__init__.py b/opentelemetry-api/src/opentelemetry/context/__init__.py index a932c644a0e..b9a5a17b2f1 100644 --- a/opentelemetry-api/src/opentelemetry/context/__init__.py +++ b/opentelemetry-api/src/opentelemetry/context/__init__.py @@ -37,9 +37,7 @@ def _load_runtime_context() -> _RuntimeContext: # environment variables default_context = "contextvars_context" - configured_context = environ.get( - OTEL_PYTHON_CONTEXT, default_context - ) # type: str + configured_context = environ.get(OTEL_PYTHON_CONTEXT, default_context) # type: str try: return next( # 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 972ff2707c6..8ee3c1e6b99 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 622b8fff6fd..afe406fb593 100644 --- a/opentelemetry-api/src/opentelemetry/propagate/__init__.py +++ b/opentelemetry-api/src/opentelemetry/propagate/__init__.py @@ -134,7 +134,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 27400c996f1..d38a7bc8df4 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 4afc4d520a2..325bb9064a8 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..5bf88552b85 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, # 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/src/opentelemetry/util/_providers.py b/opentelemetry-api/src/opentelemetry/util/_providers.py index 0a1f70f7fa7..b748eadfe0a 100644 --- a/opentelemetry-api/src/opentelemetry/util/_providers.py +++ b/opentelemetry-api/src/opentelemetry/util/_providers.py @@ -30,9 +30,7 @@ def _load_provider( provider_environment_variable: str, provider: str ) -> Provider: # type: ignore[type-var] - try: - provider_name = cast( str, environ.get(provider_environment_variable, f"default_{provider}"), diff --git a/opentelemetry-api/tests/events/test_event_logger_provider.py b/opentelemetry-api/tests/events/test_event_logger_provider.py index 35a8ea0c44e..4c8bb54c8de 100644 --- a/opentelemetry-api/tests/events/test_event_logger_provider.py +++ b/opentelemetry-api/tests/events/test_event_logger_provider.py @@ -35,7 +35,6 @@ def test_get_event_logger_provider(self): "OTEL_PYTHON_EVENT_LOGGER_PROVIDER": "test_event_logger_provider" }, ): - with patch("opentelemetry._events._load_provider", Mock()): with patch( "opentelemetry._events.cast", diff --git a/opentelemetry-api/tests/logs/test_logger_provider.py b/opentelemetry-api/tests/logs/test_logger_provider.py index 71f403c695f..2bd4041b66a 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 840fbf6e132..982cb6b6112 100644 --- a/opentelemetry-api/tests/metrics/test_instruments.py +++ b/opentelemetry-api/tests/metrics/test_instruments.py @@ -677,7 +677,6 @@ def test_name_check(self): ) def test_unit_check(self): - instrument = ChildInstrument("name") self.assertEqual( @@ -711,7 +710,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 984690bdbbf..4fb9e047b60 100644 --- a/opentelemetry-api/tests/metrics/test_meter.py +++ b/opentelemetry-api/tests/metrics/test_meter.py @@ -63,7 +63,6 @@ def create_observable_up_down_counter( class TestMeter(TestCase): # pylint: disable=no-member 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 8caec848f65..a570d47624f 100644 --- a/opentelemetry-api/tests/metrics/test_meter_provider.py +++ b/opentelemetry-api/tests/metrics/test_meter_provider.py @@ -98,7 +98,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 2200fc6f384..46db45f4d34 100644 --- a/opentelemetry-api/tests/propagators/test_w3cbaggagepropagator.py +++ b/opentelemetry-api/tests/propagators/test_w3cbaggagepropagator.py @@ -130,7 +130,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( @@ -227,7 +226,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) @@ -250,7 +248,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 9db07add257..4ad9e89069d 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 6860f98e9e4..f5475cb8eba 100644 --- a/opentelemetry-api/tests/trace/test_globals.py +++ b/opentelemetry-api/tests/trace/test_globals.py @@ -111,7 +111,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 = SpanTest(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..d7ea944e646 100644 --- a/opentelemetry-api/tests/trace/test_status.py +++ b/opentelemetry-api/tests/trace/test_status.py @@ -30,7 +30,10 @@ 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 dce949c47d8..78551536fe7 100644 --- a/opentelemetry-api/tests/util/test__importlib_metadata.py +++ b/opentelemetry-api/tests/util/test__importlib_metadata.py @@ -15,16 +15,18 @@ from unittest import TestCase from opentelemetry.metrics import MeterProvider -from opentelemetry.util._importlib_metadata import EntryPoint, EntryPoints +from opentelemetry.util._importlib_metadata import ( + EntryPoint, + EntryPoints, + version, +) from opentelemetry.util._importlib_metadata import ( entry_points as importlib_metadata_entry_points, ) -from opentelemetry.util._importlib_metadata import version 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 940303f1375..8b2e46b7ec5 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): # pylint: disable=invalid-name ) @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 97de4fb1001..8cc15d3bf49 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, "")) @@ -424,7 +421,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 b7e56eda388..048ab319593 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py @@ -107,7 +107,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 40b4969b9bd..e5669580c4b 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 728c773fa48..3e0e778f1ae 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-exception-caught 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 b89c08da042..b022f1294f0 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py @@ -25,15 +25,15 @@ SimpleFixedSizeExemplarReservoir, TraceBasedExemplarFilter, ) -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__ = [ "AlignedHistogramBucketExemplarReservoir", diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py index f9ed0280325..7740ba1b5fd 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/__init__.py @@ -87,7 +87,6 @@ def __init__( self._instrument_id_instrument_lock = Lock() def create_counter(self, name, unit="", description="") -> APICounter: - ( is_instrument_registered, instrument_id, @@ -123,7 +122,6 @@ def create_counter(self, name, unit="", description="") -> APICounter: def create_up_down_counter( self, name, unit="", description="" ) -> APIUpDownCounter: - ( is_instrument_registered, instrument_id, @@ -161,7 +159,6 @@ def create_up_down_counter( def create_observable_counter( self, name, callbacks=None, unit="", description="" ) -> APIObservableCounter: - ( is_instrument_registered, instrument_id, @@ -200,7 +197,6 @@ def create_observable_counter( return instrument def create_histogram(self, name, unit="", description="") -> APIHistogram: - ( is_instrument_registered, instrument_id, @@ -233,7 +229,6 @@ def create_histogram(self, name, unit="", description="") -> APIHistogram: return instrument def create_gauge(self, name, unit="", description="") -> APIGauge: - ( is_instrument_registered, instrument_id, @@ -269,7 +264,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, @@ -310,7 +304,6 @@ def create_observable_gauge( def create_observable_up_down_counter( self, name, callbacks=None, unit="", description="" ) -> APIObservableUpDownCounter: - ( is_instrument_registered, instrument_id, @@ -435,7 +428,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: # pylint: disable=broad-exception-raised @@ -468,11 +460,9 @@ def force_flush(self, timeout_millis: float = 10_000) -> bool: # pylint: disable=broad-exception-caught 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)}" @@ -516,7 +506,6 @@ def _shutdown(): # pylint: disable=broad-exception-caught except Exception as error: - metric_reader_error[metric_reader] = error if self._atexit_handler is not None: @@ -524,7 +513,6 @@ def _shutdown(): self._atexit_handler = None if metric_reader_error: - metric_reader_error_string = "\n".join( [ f"{metric_reader.__class__.__name__}: {repr(error)}" @@ -548,7 +536,6 @@ def get_meter( schema_url: Optional[str] = None, attributes: Optional[Attributes] = 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 5431d1fa02d..be81d70e5cd 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 @@ -91,9 +91,7 @@ def conflicts(self, other: "_ViewInstrumentMatch") -> bool: def consume_measurement( self, measurement: Measurement, should_sample_exemplar: bool = True ) -> None: - if self._view._attribute_keys is not None: - attributes = {} for key, value in (measurement.attributes or {}).items(): @@ -140,7 +138,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 39c967e4c86..a579e3072e9 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/aggregation.py @@ -55,16 +55,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) @@ -328,7 +326,6 @@ def collect( collection_aggregation_temporality is AggregationTemporality.DELTA ): - previous_collection_start_nano = ( self._previous_collection_start_nano ) @@ -498,7 +495,6 @@ def _get_empty_bucket_counts(self) -> List[int]: def aggregate( self, measurement: Measurement, should_sample_exemplar: bool = True ) -> None: - with self._lock: if self._value is None: self._value = self._get_empty_bucket_counts() @@ -545,7 +541,6 @@ def collect( collection_aggregation_temporality is AggregationTemporality.DELTA ): - previous_collection_start_nano = ( self._previous_collection_start_nano ) @@ -765,7 +760,6 @@ def aggregate( high = index if is_rescaling_needed: - scale_change = self._get_scale_change(low, high) self._downscale( scale_change, @@ -851,7 +845,6 @@ def collect( collection_aggregation_temporality is AggregationTemporality.DELTA ): - previous_collection_start_nano = ( self._previous_collection_start_nano ) @@ -1062,7 +1055,6 @@ def _get_low_high_previous_current( current_scale, min_scale, ): - (previous_point_low, previous_point_high) = self._get_low_high( previous_point_buckets, self._previous_scale, min_scale ) @@ -1100,7 +1092,6 @@ def _new_mapping(scale: int) -> Mapping: return LogarithmMapping(scale) def _get_scale_change(self, low, high): - change = 0 while high - low >= self._max_size: @@ -1113,7 +1104,6 @@ def _get_scale_change(self, low, high): @staticmethod def _downscale(change: int, positive, negative): - if change == 0: return @@ -1132,13 +1122,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 @@ -1235,7 +1223,6 @@ def _create_aggregation( ], start_time_unix_nano: int, ) -> _Aggregation: - # pylint: disable=too-many-return-statements if isinstance(instrument, Counter): return _SumAggregation( @@ -1326,7 +1313,6 @@ def _create_aggregation( ], start_time_unix_nano: int, ) -> _Aggregation: - instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED if isinstance(instrument, Synchronous): instrument_aggregation_temporality = AggregationTemporality.DELTA @@ -1392,7 +1378,6 @@ def _create_aggregation( ], start_time_unix_nano: int, ) -> _Aggregation: - instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED if isinstance(instrument, Synchronous): instrument_aggregation_temporality = AggregationTemporality.DELTA @@ -1426,7 +1411,6 @@ def _create_aggregation( ], 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 8877985c234..e8a93326088 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. @@ -78,7 +77,6 @@ def get_offset_counts(self): return self._counts[-bias:] + self._counts[:-bias] 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 @@ -160,7 +158,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 5c9bd2d2a9a..387b1d1444f 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 4acf1cc81dd..cd9aafaa190 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" @@ -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, @@ -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 \ @@ -533,7 +529,6 @@ def _receive_metrics( timeout_millis: float = 10_000, **kwargs, ) -> None: - token = attach(set_value(_SUPPRESS_INSTRUMENTATION_KEY, True)) # pylint: disable=broad-exception-caught,invalid-name try: diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py index ea373ccc6fb..c93f83a4e62 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/instrument.py @@ -110,11 +110,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 b516d6abb05..2acbe1734c0 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement_consumer.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/measurement_consumer.py @@ -103,7 +103,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 @@ -113,11 +112,9 @@ def collect( default_timeout_ns = 10000 * 1e6 for async_instrument in self._async_instruments: - remaining_time = deadline_ns - time_ns() if remaining_time < default_timeout_ns: - callback_options = CallbackOptions( timeout_millis=remaining_time / 1e6 ) 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 1c94733a3d3..f5121811ebc 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 @@ -139,7 +139,6 @@ def collect(self) -> Optional[MetricsData]: collection_start_nanos = time_ns() with self._lock: - instrumentation_scope_scope_metrics: Dict[ InstrumentationScope, ScopeMetrics ] = {} @@ -155,7 +154,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 ) @@ -219,7 +217,6 @@ def collect(self) -> Optional[MetricsData]: ) if metrics: - if instrument.instrumentation_scope not in ( instrumentation_scope_scope_metrics ): @@ -236,7 +233,6 @@ def collect(self) -> Optional[MetricsData]: ].metrics.extend(metrics) if instrumentation_scope_scope_metrics: - return MetricsData( resource_metrics=[ ResourceMetrics( @@ -281,7 +277,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 5dd11be1f94..b3fa029d6c7 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/view.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/metrics/_internal/view.py @@ -165,7 +165,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 0ebd42349c4..0123fe9c08e 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 @@ -320,7 +320,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 58cbf01e08b..b144e071a8a 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py @@ -619,7 +619,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, @@ -726,12 +725,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, ) @@ -890,7 +887,6 @@ def add_link( context: SpanContext, attributes: types.Attributes = None, ) -> None: - if not _is_valid_link(context, attributes): return @@ -1118,7 +1114,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 98f82f08b74..bdfc348611e 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 c0b460f8c29..fb6990a0075 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/sampling.py @@ -131,6 +131,7 @@ def get_sampler(sampler_argument): 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 b09cb9858a9..e949ad4ebc3 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: ... # pylint: disable=no-self-use @@ -52,9 +52,7 @@ class BoundedList(Sequence[_T]): def append(self, item: _T): ... def extend(self, seq: Sequence[_T]): ... @classmethod - def from_seq( - cls, maxlen: int, seq: Iterable[_T] - ) -> BoundedList[_T]: ... # pylint: disable=undefined-variable + def from_seq(cls, maxlen: int, seq: Iterable[_T]) -> BoundedList[_T]: ... # pylint: disable=undefined-variable class BoundedDict(MutableMapping[_KT, _VT]): """An ordered dict with a fixed max capacity. diff --git a/opentelemetry-sdk/tests/error_handler/test_error_handler.py b/opentelemetry-sdk/tests/error_handler/test_error_handler.py index 9dc1b67256c..b753c1c5970 100644 --- a/opentelemetry-sdk/tests/error_handler/test_error_handler.py +++ b/opentelemetry-sdk/tests/error_handler/test_error_handler.py @@ -26,7 +26,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(): # pylint: disable=broad-exception-raised @@ -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/metrics/exponential_histogram/test_exponent_mapping.py b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py index e3fd6ae4448..5a7a43aa954 100644 --- a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py +++ b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_exponent_mapping.py @@ -49,7 +49,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)) @@ -63,19 +62,16 @@ def test_singleton(self): "exponent_mapping.ExponentMapping._init" ) def test_init_called_once(self, mock_init): # pylint: disable=no-self-use - 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 @@ -135,7 +131,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) @@ -309,7 +304,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_logarithm_mapping.py b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py index 43820d677b0..d8f9c4ae327 100644 --- a/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py +++ b/opentelemetry-sdk/tests/metrics/exponential_histogram/test_logarithm_mapping.py @@ -34,7 +34,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 @@ -70,7 +69,6 @@ def assertInEpsilon(self, first, second, epsilon): "logarithm_mapping.LogarithmMapping._init" ) def test_init_called_once(self, mock_init): # pylint: disable=no-self-use - LogarithmMapping(3) LogarithmMapping(3) @@ -81,7 +79,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 @@ -133,12 +130,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 @@ -159,7 +154,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 7e77a878d87..ca934b14ccf 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_console_exporter.py @@ -38,7 +38,6 @@ def tearDown(self): reset_metrics_globals() def test_console_exporter(self): - output = StringIO() exporter = ConsoleMetricExporter(out=output) reader = PeriodicExportingMetricReader( @@ -79,7 +78,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_explicit_bucket_histogram_aggregation.py b/opentelemetry-sdk/tests/metrics/integration_test/test_explicit_bucket_histogram_aggregation.py index fee13525a32..05ccd1469c9 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 @@ -27,7 +27,6 @@ class TestExplicitBucketHistogramAggregation(TestCase): - test_values = [1, 6, 11, 26, 51, 76, 101, 251, 501, 751] @mark.skipif( @@ -39,7 +38,6 @@ class TestExplicitBucketHistogramAggregation(TestCase): ), ) def test_synchronous_delta_temporality(self): - aggregation = ExplicitBucketHistogramAggregation() reader = InMemoryMetricReader( @@ -55,7 +53,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -122,7 +119,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -171,7 +167,6 @@ def test_synchronous_delta_temporality(self): ), ) def test_synchronous_cumulative_temporality(self): - aggregation = ExplicitBucketHistogramAggregation() reader = InMemoryMetricReader( @@ -189,7 +184,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -198,7 +192,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()) @@ -212,7 +205,6 @@ def test_synchronous_cumulative_temporality(self): ) for index, metrics_data in enumerate(results): - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -246,7 +238,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) provider.shutdown() @@ -261,7 +252,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_exponential_bucket_histogram.py b/opentelemetry-sdk/tests/metrics/integration_test/test_exponential_bucket_histogram.py index a6750eecf54..fa44cc6ce50 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_exponential_bucket_histogram.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_exponential_bucket_histogram.py @@ -29,7 +29,6 @@ class TestExponentialBucketHistogramAggregation(TestCase): - test_values = [2, 4, 1, 1, 8, 0.5, 0.1, 0.045] @mark.skipif( @@ -67,7 +66,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -132,7 +130,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -184,7 +181,6 @@ def test_synchronous_delta_temporality(self): ), ) def test_synchronous_cumulative_temporality(self): - aggregation = ExponentialBucketHistogramAggregation() reader = InMemoryMetricReader( 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 6095781cb21..303ad187f91 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_histogram_export.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_histogram_export.py @@ -25,7 +25,6 @@ class TestHistogramExport(TestCase): def test_histogram_counter_collection(self): - in_memory_metric_reader = InMemoryMetricReader() provider = MeterProvider( @@ -94,7 +93,6 @@ def test_histogram_counter_collection(self): ) def test_histogram_with_exemplars(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 0d56ca92bc5..b876ac99064 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_sum_aggregation.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_sum_aggregation.py @@ -41,7 +41,6 @@ class TestSumAggregation(TestCase): ), ) def test_asynchronous_delta_temporality(self): - eight_multiple_generator = count(start=8, step=8) counter = 0 @@ -127,7 +126,6 @@ def observable_counter_callback(callback_options): ) for metrics_data in results[1:]: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -166,7 +164,6 @@ def observable_counter_callback(callback_options): ), ) def test_asynchronous_cumulative_temporality(self): - eight_multiple_generator = count(start=8, step=8) counter = 0 @@ -228,7 +225,6 @@ def observable_counter_callback(callback_options): ) for index, metrics_data in enumerate(results): - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -263,7 +259,6 @@ def observable_counter_callback(callback_options): ), ) def test_synchronous_delta_temporality(self): - aggregation = SumAggregation() reader = InMemoryMetricReader( @@ -279,7 +274,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -325,7 +319,6 @@ def test_synchronous_delta_temporality(self): ) for metrics_data in results[1:]: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -345,7 +338,6 @@ def test_synchronous_delta_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -394,7 +386,6 @@ def test_synchronous_delta_temporality(self): ), ) def test_synchronous_cumulative_temporality(self): - aggregation = SumAggregation() reader = InMemoryMetricReader( @@ -410,7 +401,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) for metrics_data in results: @@ -419,7 +409,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - counter.add(8) results.append(reader.get_metrics_data()) @@ -433,7 +422,6 @@ def test_synchronous_cumulative_temporality(self): ) for index, metrics_data in enumerate(results): - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -449,7 +437,6 @@ def test_synchronous_cumulative_temporality(self): results = [] for _ in range(10): - results.append(reader.get_metrics_data()) provider.shutdown() @@ -464,7 +451,6 @@ def test_synchronous_cumulative_temporality(self): ) for metrics_data in results: - metric_data = ( metrics_data.resource_metrics[0] .scope_metrics[0] @@ -478,7 +464,6 @@ def test_synchronous_cumulative_temporality(self): self.assertEqual(metric_data.value, 80) def test_sum_aggregation_with_exemplars(self): - in_memory_metric_reader = InMemoryMetricReader() provider = MeterProvider( diff --git a/opentelemetry-sdk/tests/metrics/integration_test/test_time_align.py b/opentelemetry-sdk/tests/metrics/integration_test/test_time_align.py index 32f439af85f..b04056f4a1a 100644 --- a/opentelemetry-sdk/tests/metrics/integration_test/test_time_align.py +++ b/opentelemetry-sdk/tests/metrics/integration_test/test_time_align.py @@ -26,7 +26,6 @@ class TestTimeAlign(TestCase): - # This delay is needed for these tests to pass when they are run in # Windows. delay = 0.001 diff --git a/opentelemetry-sdk/tests/metrics/test_aggregation.py b/opentelemetry-sdk/tests/metrics/test_aggregation.py index 3eeb63e26c3..4a625908afb 100644 --- a/opentelemetry-sdk/tests/metrics/test_aggregation.py +++ b/opentelemetry-sdk/tests/metrics/test_aggregation.py @@ -657,7 +657,6 @@ def test_observable_gauge(self): class TestExemplarsFromAggregations(TestCase): - def test_collection_simple_fixed_size_reservoir(self): synchronous_sum_aggregation = _SumAggregation( Mock(), @@ -683,7 +682,6 @@ def test_collection_simple_fixed_size_reservoir(self): def test_collection_simple_fixed_size_reservoir_with_default_reservoir( self, ): - synchronous_sum_aggregation = _SumAggregation( Mock(), True, diff --git a/opentelemetry-sdk/tests/metrics/test_exemplarreservoir.py b/opentelemetry-sdk/tests/metrics/test_exemplarreservoir.py index 2c205a6ee0c..bdc25d1f6e7 100644 --- a/opentelemetry-sdk/tests/metrics/test_exemplarreservoir.py +++ b/opentelemetry-sdk/tests/metrics/test_exemplarreservoir.py @@ -17,7 +17,6 @@ class TestSimpleFixedSizeExemplarReservoir(TestCase): - TRACE_ID = int("d4cda95b652f4a1592b449d5929fda1b", 16) SPAN_ID = int("6e0c63257de34c92", 16) @@ -83,7 +82,6 @@ def test_reset_after_collection(self): class TestAlignedHistogramBucketExemplarReservoir(TestCase): - TRACE_ID = int("d4cda95b652f4a1592b449d5929fda1b", 16) SPAN_ID = int("6e0c63257de34c92", 16) 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 40a0f3a3042..bd70d18d201 100644 --- a/opentelemetry-sdk/tests/metrics/test_in_memory_metric_reader.py +++ b/opentelemetry-sdk/tests/metrics/test_in_memory_metric_reader.py @@ -111,7 +111,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 bedffaaeff0..fe58ec4acac 100644 --- a/opentelemetry-sdk/tests/metrics/test_measurement_consumer.py +++ b/opentelemetry-sdk/tests/metrics/test_measurement_consumer.py @@ -33,7 +33,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 5a09112bd0e..2f7aad25c6e 100644 --- a/opentelemetry-sdk/tests/metrics/test_metric_reader.py +++ b/opentelemetry-sdk/tests/metrics/test_metric_reader.py @@ -76,7 +76,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, @@ -150,7 +149,6 @@ def test_configure_aggregation(self): # pylint: disable=no-self-use 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 1785c8ec24f..7c9484b9177 100644 --- a/opentelemetry-sdk/tests/metrics/test_metric_reader_storage.py +++ b/opentelemetry-sdk/tests/metrics/test_metric_reader_storage.py @@ -322,7 +322,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( @@ -349,7 +348,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()) @@ -393,7 +391,6 @@ def test_same_collection_start(self): ) def test_conflicting_view_configuration(self): - observable_counter = _ObservableCounter( "observable_counter", Mock(), @@ -554,9 +551,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 f899b30808a..400087774c5 100644 --- a/opentelemetry-sdk/tests/metrics/test_metrics.py +++ b/opentelemetry-sdk/tests/metrics/test_metrics.py @@ -66,7 +66,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") @@ -247,7 +246,6 @@ def test_get_meter_comparison_with_attributes(self): ) def test_shutdown(self): - mock_metric_reader_0 = MagicMock( **{ "shutdown.side_effect": ZeroDivisionError(), @@ -355,7 +353,6 @@ def test_creates_sync_measurement_consumer( def test_register_asynchronous_instrument( self, mock_sync_measurement_consumer ): - meter_provider = MeterProvider() # pylint: disable=no-member @@ -564,7 +561,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 962b4fdd643..3cbc3c9fe60 100644 --- a/opentelemetry-sdk/tests/metrics/test_periodic_exporting_metric_reader.py +++ b/opentelemetry-sdk/tests/metrics/test_periodic_exporting_metric_reader.py @@ -137,7 +137,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 e773f3187f5..c5a4def85de 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, @@ -237,34 +234,28 @@ def test_histogram_data_point(self): ) def test_exp_histogram_data_point(self): - self.assertEqual( self.exp_histogram_data_point_0.to_json(indent=None), self.exp_histogram_data_point_0_str, ) def test_sum(self): - self.assertEqual(self.sum_0.to_json(indent=None), self.sum_0_str) def test_gauge(self): - 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 ) def test_exp_histogram(self): - self.assertEqual( self.exp_histogram_0.to_json(indent=None), self.exp_histogram_0_str ) 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) @@ -272,7 +263,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 ) @@ -281,7 +271,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, @@ -292,7 +281,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 96d433677cf..ee5df52a7b9 100644 --- a/opentelemetry-sdk/tests/metrics/test_view.py +++ b/opentelemetry-sdk/tests/metrics/test_view.py @@ -22,16 +22,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"}) @@ -40,7 +37,6 @@ def test_instrument_name(self): ) def test_instrument_unit(self): - mock_instrument = Mock() mock_instrument.configure_mock(**{"unit": "instrument_unit"}) @@ -49,7 +45,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"}) @@ -57,7 +52,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"}) @@ -65,7 +59,6 @@ def test_meter_version(self): ) def test_meter_schema_url(self): - self.assertTrue( View(meter_schema_url="meter_schema_url")._match( Mock( @@ -91,7 +84,6 @@ def test_meter_schema_url(self): ) def test_additive_criteria(self): - view = View( meter_name="meter_name", meter_version="meter_version", @@ -122,6 +114,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/test_configurator.py b/opentelemetry-sdk/tests/test_configurator.py index 403b1eff005..5b04a6f3b98 100644 --- a/opentelemetry-sdk/tests/test_configurator.py +++ b/opentelemetry-sdk/tests/test_configurator.py @@ -985,7 +985,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( @@ -999,7 +998,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 7a29ef3c42d..aa94a514cad 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 779093f736f..790d7fd2a07 100644 --- a/opentelemetry-sdk/tests/trace/test_trace.py +++ b/opentelemetry-sdk/tests/trace/test_trace.py @@ -940,7 +940,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 @@ -1092,7 +1091,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/src/opentelemetry/semconv/_incubating/attributes/container_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/container_attributes.py index 128769194e7..9c5be2b6869 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/container_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/container_attributes.py @@ -100,7 +100,9 @@ """ -@deprecated(reason="The attribute container.cpu.state is deprecated - Replaced by `cpu.mode`") # type: ignore +@deprecated( + reason="The attribute container.cpu.state is deprecated - Replaced by `cpu.mode`" +) # type: ignore class ContainerCpuStateValues(Enum): USER = "user" """When tasks of the cgroup are in user mode (Linux). When all container processes are in user mode (Windows).""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/db_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/db_attributes.py index 14974bbd4ff..2f3b5bae7e8 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/db_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/db_attributes.py @@ -286,7 +286,9 @@ class DbClientConnectionStateValues(Enum): """used.""" -@deprecated(reason="The attribute db.client.connections.state is deprecated - Replaced by `db.client.connection.state`") # type: ignore +@deprecated( + reason="The attribute db.client.connections.state is deprecated - Replaced by `db.client.connection.state`" +) # type: ignore class DbClientConnectionsStateValues(Enum): IDLE = "idle" """idle.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/error_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/error_attributes.py index d3d33ff395c..a86592be983 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/error_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/error_attributes.py @@ -23,7 +23,9 @@ """ -@deprecated(reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.error_attributes.ErrorTypeValues`.") # type: ignore +@deprecated( + reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.error_attributes.ErrorTypeValues`." +) # type: ignore class ErrorTypeValues(Enum): OTHER = "_OTHER" """Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.error_attributes.ErrorTypeValues.OTHER`.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/http_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/http_attributes.py index 3631c890c65..f2e1ccb7408 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/http_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/http_attributes.py @@ -159,7 +159,9 @@ class HttpConnectionStateValues(Enum): """idle state.""" -@deprecated(reason="The attribute http.flavor is deprecated - Replaced by `network.protocol.name`") # type: ignore +@deprecated( + reason="The attribute http.flavor is deprecated - Replaced by `network.protocol.name`" +) # type: ignore class HttpFlavorValues(Enum): HTTP_1_0 = "1.0" """HTTP/1.0.""" @@ -175,7 +177,9 @@ class HttpFlavorValues(Enum): """QUIC protocol.""" -@deprecated(reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.http_attributes.HttpRequestMethodValues`.") # type: ignore +@deprecated( + reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.http_attributes.HttpRequestMethodValues`." +) # type: ignore class HttpRequestMethodValues(Enum): CONNECT = "CONNECT" """Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.http_attributes.HttpRequestMethodValues.CONNECT`.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/message_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/message_attributes.py index 770b01592be..8728d81b46e 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/message_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/message_attributes.py @@ -38,7 +38,9 @@ """ -@deprecated(reason="The attribute message.type is deprecated - Replaced by `rpc.message.type`") # type: ignore +@deprecated( + reason="The attribute message.type is deprecated - Replaced by `rpc.message.type`" +) # type: ignore class MessageTypeValues(Enum): SENT = "SENT" """sent.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/net_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/net_attributes.py index a22bf1e0098..a1789a06fcb 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/net_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/net_attributes.py @@ -93,7 +93,9 @@ """ -@deprecated(reason="The attribute net.sock.family is deprecated - Split to `network.transport` and `network.type`") # type: ignore +@deprecated( + reason="The attribute net.sock.family is deprecated - Split to `network.transport` and `network.type`" +) # type: ignore class NetSockFamilyValues(Enum): INET = "inet" """IPv4 address.""" @@ -103,7 +105,9 @@ class NetSockFamilyValues(Enum): """Unix domain socket path.""" -@deprecated(reason="The attribute net.transport is deprecated - Replaced by `network.transport`") # type: ignore +@deprecated( + reason="The attribute net.transport is deprecated - Replaced by `network.transport`" +) # type: ignore class NetTransportValues(Enum): IP_TCP = "ip_tcp" """ip_tcp.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/network_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/network_attributes.py index 354356d6225..0742e6e6a5f 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/network_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/network_attributes.py @@ -158,7 +158,9 @@ class NetworkIoDirectionValues(Enum): """receive.""" -@deprecated(reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.network_attributes.NetworkTransportValues`.") # type: ignore +@deprecated( + reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.network_attributes.NetworkTransportValues`." +) # type: ignore class NetworkTransportValues(Enum): TCP = "tcp" """Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.network_attributes.NetworkTransportValues.TCP`.""" @@ -172,7 +174,9 @@ class NetworkTransportValues(Enum): """QUIC.""" -@deprecated(reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.network_attributes.NetworkTypeValues`.") # type: ignore +@deprecated( + reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.network_attributes.NetworkTypeValues`." +) # type: ignore class NetworkTypeValues(Enum): IPV4 = "ipv4" """Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.network_attributes.NetworkTypeValues.IPV4`.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/otel_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/otel_attributes.py index 968e0609443..c58c750f06e 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/otel_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/otel_attributes.py @@ -48,7 +48,9 @@ """ -@deprecated(reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.otel_attributes.OtelStatusCodeValues`.") # type: ignore +@deprecated( + reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.otel_attributes.OtelStatusCodeValues`." +) # type: ignore class OtelStatusCodeValues(Enum): OK = "OK" """Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.otel_attributes.OtelStatusCodeValues.OK`.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/other_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/other_attributes.py index 510d7926082..2f4ae932f61 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/other_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/other_attributes.py @@ -23,7 +23,9 @@ """ -@deprecated(reason="The attribute state is deprecated - Replaced by `db.client.connection.state`") # type: ignore +@deprecated( + reason="The attribute state is deprecated - Replaced by `db.client.connection.state`" +) # type: ignore class StateValues(Enum): IDLE = "idle" """idle.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/process_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/process_attributes.py index e5d7dc69d34..ca6c8b399b7 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/process_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/process_attributes.py @@ -195,7 +195,9 @@ class ProcessContextSwitchTypeValues(Enum): """involuntary.""" -@deprecated(reason="The attribute process.cpu.state is deprecated - Replaced by `cpu.mode`") # type: ignore +@deprecated( + reason="The attribute process.cpu.state is deprecated - Replaced by `cpu.mode`" +) # type: ignore class ProcessCpuStateValues(Enum): SYSTEM = "system" """system.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/system_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/system_attributes.py index b4cae158090..b224863e93b 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/system_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/system_attributes.py @@ -88,7 +88,9 @@ """ -@deprecated(reason="The attribute system.cpu.state is deprecated - Replaced by `cpu.mode`") # type: ignore +@deprecated( + reason="The attribute system.cpu.state is deprecated - Replaced by `cpu.mode`" +) # type: ignore class SystemCpuStateValues(Enum): USER = "user" """user.""" @@ -202,7 +204,9 @@ class SystemProcessStatusValues(Enum): """defunct.""" -@deprecated(reason="The attribute system.processes.status is deprecated - Replaced by `system.process.status`") # type: ignore +@deprecated( + reason="The attribute system.processes.status is deprecated - Replaced by `system.process.status`" +) # type: ignore class SystemProcessesStatusValues(Enum): RUNNING = "running" """running.""" diff --git a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/telemetry_attributes.py b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/telemetry_attributes.py index f871f19cfd0..3ba6d9f7c8a 100644 --- a/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/telemetry_attributes.py +++ b/opentelemetry-semantic-conventions/src/opentelemetry/semconv/_incubating/attributes/telemetry_attributes.py @@ -45,7 +45,9 @@ """ -@deprecated(reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.telemetry_attributes.TelemetrySdkLanguageValues`.") # type: ignore +@deprecated( + reason="Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.telemetry_attributes.TelemetrySdkLanguageValues`." +) # type: ignore class TelemetrySdkLanguageValues(Enum): CPP = "cpp" """Deprecated in favor of stable :py:const:`opentelemetry.semconv.attributes.telemetry_attributes.TelemetrySdkLanguageValues.CPP`.""" 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/scripts/add_required_checks.py b/scripts/add_required_checks.py index bc58883b2d3..ee7d38dbc6c 100644 --- a/scripts/add_required_checks.py +++ b/scripts/add_required_checks.py @@ -1,18 +1,23 @@ # This script is to be used by maintainers by running it locally. -from requests import put +from json import dumps from os import environ + +from requests import put from yaml import safe_load -from json import dumps job_names = ["EasyCLA"] # Check that the files below are all the workflow YAML files that should be # considered. for yml_file_name in [ - "test_0", "test_1", "misc_0", "lint_0", "contrib_0", "check-links" + "test_0", + "test_1", + "misc_0", + "lint_0", + "contrib_0", + "check-links", ]: - with open(f"../.github/workflows/{yml_file_name}.yml") as yml_file: job_names.extend( [job["name"] for job in safe_load(yml_file)["jobs"].values()] @@ -35,9 +40,9 @@ # and read and write permissions must be granted for administration # permissions and read permissions must be granted for metadata # permissions. - "Authorization": f"token {environ.get('REQUIRED_CHECKS_TOKEN')}" + "Authorization": f"token {environ.get('REQUIRED_CHECKS_TOKEN')}", }, - data=dumps({"contexts": job_names}) + data=dumps({"contexts": job_names}), ) if response.status_code == 200: 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 5a2b7603899..71349363047 100755 --- a/scripts/eachdist.py +++ b/scripts/eachdist.py @@ -7,13 +7,14 @@ import shutil import subprocess import sys -from toml import load from configparser import ConfigParser from inspect import cleandoc from itertools import chain from os.path import basename from pathlib import Path, PurePath +from toml import load + DEFAULT_ALLSEP = " " DEFAULT_ALLFMT = "{rel}" @@ -508,7 +509,8 @@ def lint_args(args): runsubprocess( args.dry_run, - ("black", "--config", "pyproject.toml", ".") + (("--diff", "--check") if args.check_only else ()), + ("black", "--config", "pyproject.toml", ".") + + (("--diff", "--check") if args.check_only else ()), cwd=rootdir, check=True, ) @@ -519,7 +521,9 @@ def lint_args(args): cwd=rootdir, 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") @@ -561,10 +565,10 @@ def update_version_files(targets, version, packages): replace = f'__version__ = "{version}"' for target in filter_packages(targets, packages): - version_file_path = target.joinpath( - load(target.joinpath("pyproject.toml")) - ["tool"]["hatch"]["version"]["path"] + load(target.joinpath("pyproject.toml"))["tool"]["hatch"][ + "version" + ]["path"] ) with open(version_file_path) as file: @@ -581,8 +585,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)" @@ -664,7 +668,14 @@ def format_args(args): ) runsubprocess( args.dry_run, - ("isort", "--settings-path", f"{root_dir}/.isort.cfg", "--profile", "black", "."), + ( + "isort", + "--settings-path", + f"{root_dir}/.isort.cfg", + "--profile", + "black", + ".", + ), cwd=format_dir, check=True, ) diff --git a/scripts/public_symbols_checker.py b/scripts/public_symbols_checker.py index 7dd9b5d309d..31f4dc1bb62 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 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 ac5fbeea4e6..796a4e064b1 100644 --- a/shim/opentelemetry-opentracing-shim/tests/test_shim.py +++ b/shim/opentelemetry-opentracing-shim/tests/test_shim.py @@ -609,7 +609,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) ) @@ -651,13 +650,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, @@ -666,9 +663,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/globals_test.py b/tests/opentelemetry-test-utils/src/opentelemetry/test/globals_test.py index fb85840634f..c373658222b 100644 --- a/tests/opentelemetry-test-utils/src/opentelemetry/test/globals_test.py +++ b/tests/opentelemetry-test-utils/src/opentelemetry/test/globals_test.py @@ -51,7 +51,9 @@ def reset_event_globals() -> None: """WARNING: only use this for tests.""" events_api._EVENT_LOGGER_PROVIDER_SET_ONCE = Once() # type: ignore[attr-defined] events_api._EVENT_LOGGER_PROVIDER = None # type: ignore[attr-defined] - events_api._PROXY_EVENT_LOGGER_PROVIDER = events_api.ProxyEventLoggerProvider() # type: ignore[attr-defined] + events_api._PROXY_EVENT_LOGGER_PROVIDER = ( + events_api.ProxyEventLoggerProvider() + ) # type: ignore[attr-defined] class TraceGlobalsTest(unittest.TestCase): 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 180fe55e6fa..dbf06880eca 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-exception-caught - 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-exception-caught - 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-exception-caught - 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():