Skip to content

Commit

Permalink
Add line-specific filter to catch warning
Browse files Browse the repository at this point in the history
Fixes #3163
  • Loading branch information
ocelotl committed Feb 6, 2023
1 parent 209093b commit fc0b621
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import math
import os
from abc import ABC, abstractmethod
from enum import Enum
Expand All @@ -23,7 +24,6 @@
from typing import IO, Callable, Dict, Iterable, Optional

from typing_extensions import final
import math

# This kind of import is needed to avoid Sphinx errors.
import opentelemetry.sdk.metrics._internal
Expand Down
33 changes: 28 additions & 5 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from collections import OrderedDict
from contextlib import contextmanager
from os import environ
from sys import version_info
from time import time_ns
from types import MappingProxyType, TracebackType
from typing import (
Expand All @@ -37,6 +38,7 @@
Type,
Union,
)
from warnings import filterwarnings

from deprecated import deprecated

Expand Down Expand Up @@ -1167,16 +1169,37 @@ def get_tracer(
logger.error("get_tracer called with missing module name.")
if instrumenting_library_version is None:
instrumenting_library_version = ""

kwargs = {
"message": (
"Call to deprecated method __init__. \(You should use "
"InstrumentationScope\) -- Deprecated since version 1.11.1."
),
"category": DeprecationWarning,
"module": "opentelemetry.sdk.trace",
}

# FIXME: Remove when 3.7 is no longer supported.
# For some reason the lineno argument in 3.7 does not seem to work.
# This is still safe enough because we also filter by message and
# module.
if version_info.minor > 7:
kwargs["lineno"]: 1191

filterwarnings("ignore", **kwargs)

instrumentation_info = InstrumentationInfo(
instrumenting_module_name,
instrumenting_library_version,
schema_url,
)

return Tracer(
self.sampler,
self.resource,
self._active_span_processor,
self.id_generator,
InstrumentationInfo(
instrumenting_module_name,
instrumenting_library_version,
schema_url,
),
instrumentation_info,
self._span_limits,
InstrumentationScope(
instrumenting_module_name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import math
from time import sleep, time_ns
from typing import Sequence
from unittest.mock import Mock

from flaky import flaky
import math

from opentelemetry.sdk.metrics import Counter
from opentelemetry.sdk.metrics._internal import _Counter
Expand Down Expand Up @@ -139,7 +139,9 @@ def test_ticker_not_called_on_infinity(self):
collect_mock = Mock()
exporter = FakeMetricsExporter()
exporter.export = Mock()
pmr = PeriodicExportingMetricReader(exporter, export_interval_millis=math.inf)
pmr = PeriodicExportingMetricReader(
exporter, export_interval_millis=math.inf
)
pmr._set_collect_callback(collect_mock)
sleep(0.1)
self.assertTrue(collect_mock.assert_not_called)
Expand All @@ -149,16 +151,20 @@ def test_ticker_value_exception_on_zero(self):
exporter = FakeMetricsExporter()
exporter.export = Mock()
self.assertRaises(
ValueError, PeriodicExportingMetricReader,
exporter, export_interval_millis=0
ValueError,
PeriodicExportingMetricReader,
exporter,
export_interval_millis=0,
)

def test_ticker_value_exception_on_negative(self):
exporter = FakeMetricsExporter()
exporter.export = Mock()
self.assertRaises(
ValueError, PeriodicExportingMetricReader,
exporter, export_interval_millis=-100
ValueError,
PeriodicExportingMetricReader,
exporter,
export_interval_millis=-100,
)

@flaky(max_runs=3, min_passes=1)
Expand Down
33 changes: 31 additions & 2 deletions opentelemetry-sdk/tests/trace/test_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@
from importlib import reload
from logging import ERROR, WARNING
from random import randint
from sys import version_info
from time import time_ns
from typing import Optional
from unittest import mock
from unittest.mock import Mock

from opentelemetry import trace as trace_api
from opentelemetry.context import Context
Expand All @@ -39,7 +41,7 @@
OTEL_TRACES_SAMPLER,
OTEL_TRACES_SAMPLER_ARG,
)
from opentelemetry.sdk.trace import Resource
from opentelemetry.sdk.trace import Resource, TracerProvider
from opentelemetry.sdk.trace.id_generator import RandomIdGenerator
from opentelemetry.sdk.trace.sampling import (
ALWAYS_OFF,
Expand All @@ -48,16 +50,43 @@
ParentBased,
StaticSampler,
)
from opentelemetry.sdk.util import ns_to_iso_str
from opentelemetry.sdk.util import BoundedDict, ns_to_iso_str
from opentelemetry.sdk.util.instrumentation import InstrumentationInfo
from opentelemetry.test.spantestutil import (
get_span_with_dropped_attributes_events_links,
new_tracer,
)
from opentelemetry.trace import Status, StatusCode

message = """
If this test fails it may be because a change was made in
opentelemetry-sdk/src/trace/__init__.py. That file has a call to
warnings.filterwarnings that needs the line number where an of the line where
InstrumentationInfo instance is created to catch the DeprecationWarning that is
raised. Make sure to update the line number in the warnings.filterwarnings call
if necessary.
"""


class TestTracer(unittest.TestCase):
def test_no_deprecated_warning(self):
try:
with self.assertRaises(AssertionError):
with self.assertWarns(DeprecationWarning) as the_warning:
the_warning = the_warning
TracerProvider(Mock(), Mock()).get_tracer(Mock(), Mock())
except AssertionError as assertion_error:
if version_info > 7:
raise AssertionError(f"{assertion_error.args[0]}:{message}")
raise

# This is being added here to make sure the filter on
# InstrumentationInfo does not affect other DeprecationWarnings that
# may be raised.
with self.assertWarns(DeprecationWarning):
BoundedDict(0)

def test_extends_api(self):
tracer = new_tracer()
self.assertIsInstance(tracer, trace.Tracer)
Expand Down

0 comments on commit fc0b621

Please sign in to comment.