diff --git a/src/bootstraparse/modules/preparser.py b/src/bootstraparse/modules/preparser.py index 586e99c..d8283cb 100644 --- a/src/bootstraparse/modules/preparser.py +++ b/src/bootstraparse/modules/preparser.py @@ -228,6 +228,38 @@ class PreParser: self.replacements_done = True return self.file_with_all_replacements + def get_element_from_config(self, *list_keys): + """ + Fetches an element from the config + """ + sub_dict = self.__env.config.loaded_conf + validated_elements = [] + for key in list_keys: + try: + sub_dict = sub_dict[key] + validated_elements.append(f'[{key}]') + except KeyError: + error_mngr.log_exception( + KeyError(f"Could not find key {key} in dict config{''.join(validated_elements)} in configs {'; '.join(self.__env.config.config_folders)}"), + level='CRITICAL' + ) + return sub_dict + + @staticmethod + def make_replacements(message, *var_list, **var_dict): + """ + Tries to format the message or give an error message and return the original message + """ + try: + return message.format(*var_list, **var_dict) + except (KeyError, IndexError) as e: + error_mngr.log_message( + 'Could not find appropriate replacement values in options provided' + f'"{message}" : {var_list}, {var_dict}' + f"{str(e)}", level='WARNING' + ) + return message + def get_alias_from_config(self, shortcut, optionals): """ Fetches shortcut paths from aliases.yaml @@ -235,22 +267,10 @@ class PreParser: :param shortcut: id of the shortcut to fetch :param optionals: optional parameters along with alias """ - try: - output = self.__env.config.loaded_conf['aliases']['shortcuts'][shortcut] - except KeyError: - error_mngr.log_exception( - KeyError( - f'Shortcut "{shortcut}" could not be found in {"; ".join(self.__env.config.config_folders)}.' - ), level='CRITICAL' - ) + output = self.get_element_from_config('aliases', 'shortcuts', shortcut) _, _, var_list, var_dict = export.split_optionals(optionals) - try: - output = output.format(*var_list, **var_dict) # noqa - except KeyError: - error_mngr.log_message( - 'Could not find appropriate replacement values in options provided', level='WARNING' - ) - return output + + return self.make_replacements(output, *var_list, **var_dict) def get_image_from_config(self, shortcut, optionals): """ @@ -259,9 +279,13 @@ class PreParser: :param shortcut: the id of the picture to fetch :param optionals: optional parameters along with image """ + shortcut_s = self.get_element_from_config('aliases', 'images', shortcut) + + _, _, var_list, var_dict = export.split_optionals(optionals) request = export.ExportRequest('inline_elements', 'image', export.format_optionals(optionals)) output = self.__env.export_mngr(request) - return output.start + shortcut + output.end + + return output.start + self.make_replacements(shortcut_s, *var_list, **var_dict) + output.end def __repr__(self): """ diff --git a/tests/modules/test_preparser.py b/tests/modules/test_preparser.py index e25ef6c..3cc7868 100644 --- a/tests/modules/test_preparser.py +++ b/tests/modules/test_preparser.py @@ -8,7 +8,7 @@ from itertools import zip_longest import pytest import rich -from bootstraparse.modules import preparser +from bootstraparse.modules import preparser, config, pathresolver from bootstraparse.modules import environment from bootstraparse.modules import export @@ -17,6 +17,8 @@ from bootstraparse.modules import export env = environment.Environment() env.export_mngr = export.ExportManager('', '') +env.config = config.ConfigLoader(pathresolver.b_path("../../example_userfiles/config/")) +env.export_mngr = export.ExportManager('', '') _BASE_PATH_PREPARSER = "../../" _TEMP_DIRECTORY = tempfile.TemporaryDirectory() @@ -105,14 +107,19 @@ website_tree = { "pages/subpages/spage6.bpr": content_sub_page6, } -get_from_config = '''@{whatever_picture} {whatever_picture} ["whateverpicture", i=42] -@{picture}{class="shortcut", type=2, name="shortcut"}[type=33, name="shortcut"]{{classinsert}} -@[shortcut]{class="picture", type=2, name="picture"}[type=33, name="picture"]{{hello}} +get_from_config = '''@{do_not_remove_p} {whatever_picture} ["whateverpicture", i=42] +@{do_not_remove_p}{class="shortcut", type=2, name="shortcut"}[type=33, name="shortcut"]{{classinsert}} +@[do_not_remove_s]{class="picture", type=2, name="picture"}[type=33, name="picture"]{{hello}} +@[do_not_remove_f]{class="picture", type=2, name="picture"}[12,1222, a=33, b="picture"]{{hello}} +@{do_not_remove_f}[a=33, b="picture", 42, 4242]{{hello}} ''' -final_from_config = """ - -

shortcut

+final_from_config = """ + +This is a test +This is a test 12.0 1222.0 33.0 picture + """ +# TODO: Fix images @pytest.fixture(autouse=True) @@ -355,16 +362,17 @@ def test_rich_tree(): pp.rich_tree(force=False) -@pytest.mark.xfail(reason="Not implemented") +# @pytest.mark.xfail(reason="Not implemented") def test_get_shortcut_from_config(): from_config = temp_name("get_from_config.bpr") make_new_file(from_config, get_from_config) + assert os.path.exists(from_config) pp = preparser.PreParser(from_config, env) pp.do_imports() pp.parse_shortcuts_and_images() - assert pp.get_image_from_config("any_picture", "") == '''''' - assert pp.get_alias_from_config("any_shortcut", None) == "

any_shortcut

" + assert pp.get_image_from_config("do_not_remove_p", "") == '''''' + assert pp.get_alias_from_config("do_not_remove_s", None) == "This is a test" assert assert_readlines_equals(pp.do_replacements().readlines(), final_from_config.split("\n")[:-1]) @@ -386,3 +394,26 @@ def test_early_tree(base_architecture): pp = preparser.PreParser(tree_file, env) rich.print(pp.rich_tree()) + + +def test_get_errors(): + from_config = temp_name("test_get_errors.bpr") + pp = preparser.PreParser(from_config, env) + assert pp.get_element_from_config("aliases", "shortcuts", "do_not_remove_s") == "This is a test" + assert pp.get_element_from_config("aliases", "images", "do_not_remove_p") == 'This is a test' + with pytest.raises(SystemExit): + pp.get_element_from_config("aliases", "not_existing", "do_not_remove_s") + with pytest.raises(SystemExit): + pp.get_element_from_config("images", "not_existing", "do_not_remove_p") + + +def test_make_replacement_errors(): + from_config = temp_name("test_get_errors.bpr") + pp = preparser.PreParser(from_config, env) + assert pp.make_replacements("This is a test") == "This is a test" + assert pp.make_replacements("This is a test", "not_existing") == "This is a test" + assert pp.make_replacements("This is a test {}", "shortcuts") == "This is a test shortcuts" + assert pp.make_replacements("This is a test {}", "images") == "This is a test images" + assert pp.make_replacements("This is a test {} {} {image} {b}", 1, 2, image="images", b="b") == "This is a test 1 2 images b" + assert pp.make_replacements("This is a test {} {} {image} {b}", karm=3) == "This is a test {} {} {image} {b}" +