|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# type: ignore |
| 15 | + |
| 16 | +from os import environ |
| 17 | +from os.path import abspath, dirname, pathsep |
| 18 | +from unittest import TestCase |
| 19 | +from unittest.mock import patch |
| 20 | + |
| 21 | +from opentelemetry.instrumentation import auto_instrumentation |
| 22 | + |
| 23 | +# TODO: convert to assertNoLogs instead of mocking logger when 3.10 is baseline |
| 24 | + |
| 25 | + |
| 26 | +class TestInitialize(TestCase): |
| 27 | + auto_instrumentation_path = dirname(abspath(auto_instrumentation.__file__)) |
| 28 | + |
| 29 | + @patch.dict("os.environ", {}, clear=True) |
| 30 | + @patch("opentelemetry.instrumentation.auto_instrumentation._logger") |
| 31 | + def test_handles_pythonpath_not_set(self, logger_mock): |
| 32 | + auto_instrumentation.initialize() |
| 33 | + self.assertNotIn("PYTHONPATH", environ) |
| 34 | + logger_mock.exception.assert_not_called() |
| 35 | + |
| 36 | + @patch.dict("os.environ", {"PYTHONPATH": "."}) |
| 37 | + @patch("opentelemetry.instrumentation.auto_instrumentation._logger") |
| 38 | + def test_handles_pythonpath_set(self, logger_mock): |
| 39 | + auto_instrumentation.initialize() |
| 40 | + self.assertEqual(environ["PYTHONPATH"], ".") |
| 41 | + logger_mock.exception.assert_not_called() |
| 42 | + |
| 43 | + @patch.dict( |
| 44 | + "os.environ", |
| 45 | + {"PYTHONPATH": auto_instrumentation_path + pathsep + "foo"}, |
| 46 | + ) |
| 47 | + @patch("opentelemetry.instrumentation.auto_instrumentation._logger") |
| 48 | + def test_clears_auto_instrumentation_path(self, logger_mock): |
| 49 | + auto_instrumentation.initialize() |
| 50 | + self.assertEqual(environ["PYTHONPATH"], "foo") |
| 51 | + logger_mock.exception.assert_not_called() |
| 52 | + |
| 53 | + @patch("opentelemetry.instrumentation.auto_instrumentation._logger") |
| 54 | + @patch("opentelemetry.instrumentation.auto_instrumentation._load_distro") |
| 55 | + def test_handles_exceptions(self, load_distro_mock, logger_mock): |
| 56 | + # pylint:disable=no-self-use |
| 57 | + load_distro_mock.side_effect = ValueError |
| 58 | + auto_instrumentation.initialize() |
| 59 | + logger_mock.exception.assert_called_once_with( |
| 60 | + "Failed to auto initialize OpenTelemetry" |
| 61 | + ) |
0 commit comments