|
| 1 | +# Copyright 2010 New Relic, Inc. |
| 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 | + |
| 15 | +import sys |
| 16 | + |
| 17 | +import pytest |
| 18 | +from testing_support.validators.validate_function_called import validate_function_called |
| 19 | + |
| 20 | +from newrelic.common.package_version_utils import ( |
| 21 | + NULL_VERSIONS, |
| 22 | + VERSION_ATTRS, |
| 23 | + get_package_version, |
| 24 | +) |
| 25 | + |
| 26 | +IS_PY38_PLUS = sys.version_info[:2] >= (3, 8) |
| 27 | +SKIP_IF_NOT_IMPORTLIB_METADATA = pytest.mark.skipif(not IS_PY38_PLUS, reason="importlib.metadata is not supported.") |
| 28 | +SKIP_IF_IMPORTLIB_METADATA = pytest.mark.skipif( |
| 29 | + IS_PY38_PLUS, reason="importlib.metadata is preferred over pkg_resources." |
| 30 | +) |
| 31 | + |
| 32 | + |
| 33 | +@pytest.fixture(scope="function", autouse=True) |
| 34 | +def patched_pytest_module(monkeypatch): |
| 35 | + for attr in VERSION_ATTRS: |
| 36 | + if hasattr(pytest, attr): |
| 37 | + monkeypatch.delattr(pytest, attr) |
| 38 | + |
| 39 | + yield pytest |
| 40 | + |
| 41 | + |
| 42 | +@pytest.mark.parametrize( |
| 43 | + "attr,value,expected_value", |
| 44 | + ( |
| 45 | + ("version", "1.2.3.4", "1.2.3.4"), |
| 46 | + ("__version__", "1.3.5rc2", "1.3.5rc2"), |
| 47 | + ("__version_tuple__", (3, 5, 8), "3.5.8"), |
| 48 | + ("version_tuple", [3, 1, "0b2"], "3.1.0b2"), |
| 49 | + ), |
| 50 | +) |
| 51 | +def test_get_package_version(attr, value, expected_value): |
| 52 | + # There is no file/module here, so we monkeypatch |
| 53 | + # pytest instead for our purposes |
| 54 | + setattr(pytest, attr, value) |
| 55 | + version = get_package_version("pytest") |
| 56 | + assert version == expected_value |
| 57 | + delattr(pytest, attr) |
| 58 | + |
| 59 | + |
| 60 | +@SKIP_IF_NOT_IMPORTLIB_METADATA |
| 61 | +@validate_function_called("importlib.metadata", "version") |
| 62 | +def test_importlib_metadata(): |
| 63 | + version = get_package_version("pytest") |
| 64 | + assert version not in NULL_VERSIONS, version |
| 65 | + |
| 66 | + |
| 67 | +@SKIP_IF_IMPORTLIB_METADATA |
| 68 | +@validate_function_called("pkg_resources", "get_distribution") |
| 69 | +def test_pkg_resources_metadata(): |
| 70 | + version = get_package_version("pytest") |
| 71 | + assert version not in NULL_VERSIONS, version |
0 commit comments