Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make default meter a DefaultMeter #7

Merged
merged 1 commit into from
Feb 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion opentelemetry-api/src/opentelemetry/metrics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,12 @@ def meter() -> Meter:

if _METER is None:
# pylint:disable=protected-access
_METER = loader._load_impl(Meter, _METER_FACTORY)
try:
_METER = loader._load_impl(Meter, _METER_FACTORY)
except TypeError:
# if we raised an exception trying to instantiate an
# abstract class, default to no-op tracer impl
_METER = DefaultMeter()
del _METER_FACTORY

return _METER
Expand Down
32 changes: 32 additions & 0 deletions opentelemetry-api/tests/metrics/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# limitations under the License.

import unittest
from contextlib import contextmanager
from unittest import mock

from opentelemetry import metrics

Expand Down Expand Up @@ -90,3 +92,33 @@ def test_gauge_handle(self):
def test_measure_handle(self):
handle = metrics.MeasureHandle()
handle.record(1)


@contextmanager
def patch_metrics_globals(meter=None, meter_factory=None):
"""Mock metrics._METER and metrics._METER_FACTORY.

This prevents previous changes to these values from affecting the code in
this scope, and prevents changes in this scope from leaking out and
affecting other tests.
"""
with mock.patch("opentelemetry.metrics._METER", meter):
with mock.patch("opentelemetry.metrics._METER_FACTORY", meter_factory):
yield


class TestGlobals(unittest.TestCase):
def test_meter_default_factory(self):
"""Check that the default meter is a DefaultMeter."""
with patch_metrics_globals():
meter = metrics.meter()
self.assertIsInstance(meter, metrics.DefaultMeter)
# Check that we don't create a new instance on each call
self.assertIs(meter, metrics.meter())

def test_meter_custom_factory(self):
"""Check that we use the provided factory for custom global meters."""
mock_meter = mock.Mock(metrics.Meter)
with patch_metrics_globals(meter_factory=lambda _: mock_meter):
meter = metrics.meter()
self.assertIs(meter, mock_meter)