|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from types import ModuleType |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from linkml_runtime.utils.compile_python import compile_python |
| 8 | + |
| 9 | + |
| 10 | +@pytest.fixture(scope="module") |
| 11 | +def base_module() -> str: |
| 12 | + return """ |
| 13 | +x: int = 2 |
| 14 | +
|
| 15 | +def fun(value: int): |
| 16 | + return f'known value {value}' |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +@pytest.fixture(scope="module") |
| 21 | +def importing_module() -> str: |
| 22 | + return """ |
| 23 | +import MODULE_NAME as m |
| 24 | +
|
| 25 | +def more_fun(message: str): |
| 26 | + return f'got "{message}"' |
| 27 | +""" |
| 28 | + |
| 29 | + |
| 30 | +def check_generated_module(module: ModuleType, module_name: str) -> None: |
| 31 | + assert isinstance(module, ModuleType) |
| 32 | + assert module.__name__ == module_name |
| 33 | + assert module.x == 2 |
| 34 | + assert module.fun(3) == "known value 3" |
| 35 | + |
| 36 | + |
| 37 | +@pytest.mark.parametrize(("name_arg", "module_name"), [(None, "test"), ("", "test"), ("base_module", "base_module")]) |
| 38 | +def test_compile_python_module_name(base_module: str, name_arg: str | None, module_name: str) -> None: |
| 39 | + """Test the compilation of python code to create a module.""" |
| 40 | + m = compile_python(base_module, module_name=name_arg) |
| 41 | + check_generated_module(m, module_name) |
| 42 | + |
| 43 | + |
| 44 | +@pytest.mark.parametrize(("name_arg", "module_name"), [(None, "test"), ("", "test"), ("base_module", "base_module")]) |
| 45 | +def test_compile_python_importing_module_local_module( |
| 46 | + base_module: str, |
| 47 | + importing_module: str, |
| 48 | + name_arg: str | None, |
| 49 | + module_name: str, |
| 50 | +) -> None: |
| 51 | + """Test the compilation of python code to create a local module and then compile a second module that imports the first.""" |
| 52 | + m = compile_python(base_module, module_name=name_arg) |
| 53 | + check_generated_module(m, module_name) |
| 54 | + |
| 55 | + # switch in the appropriate module name |
| 56 | + importing_module_text = importing_module.replace("MODULE_NAME", module_name) |
| 57 | + m2 = compile_python(importing_module_text, package_path=".", module_name="module_2") |
| 58 | + assert isinstance(m2, ModuleType) |
| 59 | + assert m2.__name__ == "module_2" |
| 60 | + assert m2.more_fun("hello") == 'got "hello"' |
| 61 | + |
| 62 | + # check the imported module, m2.m, has the correct type, name, etc. |
| 63 | + check_generated_module(m2.m, module_name) |
0 commit comments