diff --git a/b_asic/utils.py b/b_asic/utils.py index 24ee5f62e6d68950d641a07a1194c0a04472feb2..42242fd31297462c1d763e37a372acfbe9b73d2f 100644 --- a/b_asic/utils.py +++ b/b_asic/utils.py @@ -54,3 +54,14 @@ def load_structure(_path: str) -> AbstractOperation: print("Unexpected error occured while loading structure: ", e) return None + +def load_recipe(module: str) -> None: + """Given the module name or the path to a module, import the module and let it evaluate it's content. + Returns None as the content from the module will be added to the namespace. + + This runs .py scripts inline by importing them, it currently does no checks for security measure. + + Arguments: + module: The path or name of the module to import from. + """ + pass diff --git a/test/test_load_save_structure.py b/test/test_load_save_structure.py index 9e4190a9d4b1cf2e79c79db12b7374d24658157b..4881e2374a5261c61b411eccda69d58158ce8331 100644 --- a/test/test_load_save_structure.py +++ b/test/test_load_save_structure.py @@ -8,7 +8,7 @@ from string import ascii_lowercase import pytest -from b_asic import SFG, Output, load_structure, save_structure +from b_asic import SFG, Output, load_structure, save_structure, load_recipe class TestSaveStructures: @@ -50,4 +50,38 @@ class TestSaveStructures: _path = load_structure(_path=_invalid_path) assert _path is None - \ No newline at end of file + + def test_load_recipe_file(self): + # Create a file that doesn't exist + _file = "".join(choice(ascii_lowercase) for _ in range(4)) + ".py" + while path.exists(path.join(getcwd(), _file)): + _file = "".join(choice(ascii_lowercase) for _ in range(4)) + ".py" + + try: + with open(_file, "w+") as handle: + # The string is indented that way so the file is properly indented, .strip() did not work idk why + handle.write( +""" +from b_asic import SFG, Output, Addition, Constant +sfg = SFG(outputs=[Output(Addition(Addition(Constant(2), Constant(3)), Addition(Constant(4), Constant(5))))]) +""" + ) + except Exception as e: + assert False, f"Could not create file: {e}" + + # Not defined yet + with pytest.raises(NameError): + sfg.evaluate() == 14 + + load_recipe(_file) + assert sfg.evaluate() == 14 + + def test_load_invalid_recipe_file(self): + _file = "".join(choice(ascii_lowercase) for _ in range(4)) + ".py" + while path.exists(path.join(getcwd(), _file)): + _file = "".join(choice(ascii_lowercase) for _ in range(4)) + ".py" + + load_recipe(_file) + with pytest.raises(NameError): + assert sfg.evaluate() == 14 + \ No newline at end of file