From 8ea351705752fb701cdbfd966ff72482872c6385 Mon Sep 17 00:00:00 2001 From: Stuart Maxwell Date: Wed, 13 Nov 2024 19:35:07 +1300 Subject: [PATCH] Fix missing coverage --- src/djpress/__init__.py | 20 +++++++++++------ tests/test_init.py | 49 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 7 deletions(-) create mode 100644 tests/test_init.py diff --git a/src/djpress/__init__.py b/src/djpress/__init__.py index c5ba5a1..2732d32 100644 --- a/src/djpress/__init__.py +++ b/src/djpress/__init__.py @@ -5,12 +5,18 @@ try: import tomllib except ImportError: - import tomli as tomllib + import tomli as tomllib # Alias tomli as tomllib for compatibility with Python versions < 3.11 -# Define the path to pyproject.toml -pyproject_path = Path(__file__).parent.parent.parent / "pyproject.toml" -# Read the version from pyproject.toml -with pyproject_path.open("rb") as f: - pyproject_data = tomllib.load(f) - __version__ = pyproject_data["project"]["version"] +def load_version() -> str: + """Load the version from pyproject.toml.""" + # Define the path to pyproject.toml + pyproject_path = Path(__file__).parent.parent.parent / "pyproject.toml" + + # Read the version from pyproject.toml + with pyproject_path.open("rb") as f: + pyproject_data = tomllib.load(f) + return pyproject_data["project"]["version"] + + +__version__ = load_version() diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..83199fa --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,49 @@ +import importlib +from unittest.mock import mock_open, patch + +import pytest + + +def test_version_loading(): + mock_toml_content = """ + [project] + version = "1.0.0" + """ + + with patch("pathlib.Path.open", mock_open(read_data=mock_toml_content)): + with patch("tomllib.load") as mock_load: + mock_load.return_value = {"project": {"version": "1.0.0"}} + + import djpress + + importlib.reload(djpress) # Reload the module to apply the mock + + assert djpress.__version__ == "1.0.0" + + +def test_version_loading_error(): + with patch("pathlib.Path.open", mock_open()) as mock_file: + mock_file.side_effect = FileNotFoundError() + + with pytest.raises(FileNotFoundError): + import djpress + + importlib.reload(djpress) # Reload the module to apply the mock + + +def test_tomllib_import_error(): + mock_toml_content = """ + [project] + version = "1.0.0" + """ + + with patch.dict("sys.modules", {"tomllib": None}): + with patch("pathlib.Path.open", mock_open(read_data=mock_toml_content)): + with patch("tomli.load") as mock_load: + mock_load.return_value = {"project": {"version": "1.0.0"}} + + import djpress + + importlib.reload(djpress) # Reload the module to apply the mock + + assert djpress.__version__ == "1.0.0"