From b61eb5f8973d9de35784611817c3594702f934cb Mon Sep 17 00:00:00 2001 From: Sina Atalay Date: Sun, 17 Mar 2024 20:46:37 +0100 Subject: [PATCH] data_models: handle SyntaxError and ImportError for custom themes --- rendercv/data_models.py | 10 ++++++++-- tests/test_data_models.py | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/rendercv/data_models.py b/rendercv/data_models.py index 19e61d1..33f2328 100644 --- a/rendercv/data_models.py +++ b/rendercv/data_models.py @@ -1014,7 +1014,7 @@ class RenderCVDataModel(RenderCVBaseModel): if path_to_init_file.exists(): spec = importlib.util.spec_from_file_location( - "", # this is somehow not required + "theme", path_to_init_file, ) if spec is None: @@ -1024,7 +1024,13 @@ class RenderCVDataModel(RenderCVBaseModel): ) theme_module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(theme_module) # type: ignore + try: + spec.loader.exec_module(theme_module) # type: ignore + except SyntaxError or ImportError: + raise ValueError( + f"The custom theme {theme_name}'s __init__.py file is not" + " valid. Please check the file and try again.", + ) ThemeDataModel = getattr( theme_module, f"{theme_name.title()}ThemeOptions" # type: ignore diff --git a/tests/test_data_models.py b/tests/test_data_models.py index c8d86ea..70c0071 100644 --- a/tests/test_data_models.py +++ b/tests/test_data_models.py @@ -514,3 +514,28 @@ def test_custom_theme_without_init_file(tmp_path, testdata_directory_path): ) assert data_model.design.theme == "dummytheme" + + +def test_custom_theme_with_broken_init_file(tmp_path, testdata_directory_path): + reference_custom_theme_path = ( + testdata_directory_path + / "test_copy_theme_files_to_output_directory_custom_theme" + / "dummytheme" + ) + + # copy the directory to tmp_path: + custom_theme_path = tmp_path / "dummytheme" + shutil.copytree(reference_custom_theme_path, custom_theme_path, dirs_exist_ok=True) + + # remove the __init__.py file: + init_file = custom_theme_path / "__init__.py" + init_file.write_text("invalid python code", encoding="utf-8") + + os.chdir(tmp_path) + with pytest.raises(pydantic.ValidationError): + dm.RenderCVDataModel( + **{ # type: ignore + "cv": {"name": "John Doe"}, + "design": {"theme": "dummytheme"}, + } + )