From 62e6e0b886ff427cda343bba0ca803a86d2a9f18 Mon Sep 17 00:00:00 2001 From: clavedeluna Date: Mon, 9 Oct 2023 09:22:20 -0300 Subject: [PATCH] add code validation to int tests --- integration_tests/base_test.py | 3 ++- tests/validations.py | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 tests/validations.py diff --git a/integration_tests/base_test.py b/integration_tests/base_test.py index 3732ec918..1e0a6b219 100644 --- a/integration_tests/base_test.py +++ b/integration_tests/base_test.py @@ -7,7 +7,7 @@ from codemodder import __VERSION__ from codemodder import registry - +from tests.validations import validate_code SAMPLES_DIR = "tests/samples" @@ -121,6 +121,7 @@ def check_code_after(self): with open(self.code_path, "r", encoding="utf-8") as f: new_code = f.read() assert new_code == self.expected_new_code + validate_code(path=self.code_path) def test_file_rewritten(self): """ diff --git a/tests/validations.py b/tests/validations.py new file mode 100644 index 000000000..a56324a20 --- /dev/null +++ b/tests/validations.py @@ -0,0 +1,20 @@ +import importlib.util +import tempfile + +def validate_code(*, path=None, code=None): + """ + Ensure that code written in `path` or in `code` str is importable. + """ + assert (path is None) != (code is None), "Must pass either path to code or code as a str." + + if path: + _try_code_import(path) + return + with tempfile.NamedTemporaryFile(suffix=".py", mode='w+t') as temp: + temp.write(code) + _try_code_import(temp.name) + +def _try_code_import(path): + spec = importlib.util.spec_from_file_location("output_code", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module)