""" Unit tests for custom script sandbox executor (Task 3). Verifies AST static safety inspection, allowlisted execution, entrypoints, and error handling. """ import sys import unittest from pathlib import Path # Add backend directory to sys.path backend_dir = Path(__file__).resolve().parent.parent if str(backend_dir) not in sys.path: sys.path.insert(0, str(backend_dir)) from language_core.executor.custom_script_executor import ( WorkflowExecutionError, execute_custom_script_node, ) class TestCustomScriptExecutor(unittest.TestCase): def test_basic_expression_execution(self): res = execute_custom_script_node( node_inputs={"x": 21}, params={"code": "result = x * 2"}, node_id="node_custom_1", label="Multiplier", ) self.assertEqual(res["result"], 42) self.assertEqual(res["out"], 42) def test_entrypoint_function_execution(self): code = """ def run(a, b): return {"sum": a + b, "diff": a - b} """ res = execute_custom_script_node( node_inputs={"a": 10, "b": 3}, params={"code": code}, node_id="node_custom_2", label="Adder", ) self.assertEqual(res["sum"], 13) self.assertEqual(res["diff"], 7) def test_blocks_os_import(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "import os\nos.system('ls')"}, node_id="node_bad_1", ) self.assertIn("[ERR-SECURITY-UNSAFE-IMPORT]", str(ctx.exception)) def test_blocks_eval_call(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "result = eval('1 + 1')"}, node_id="node_bad_2", ) self.assertIn("[ERR-SECURITY-DANGEROUS-CALL]", str(ctx.exception)) def test_blocks_dunder_inspection(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "x = ().__class__.__bases__"}, node_id="node_bad_3", ) self.assertIn("[ERR-SECURITY-FORBIDDEN-ATTR]", str(ctx.exception)) def test_syntax_error_reported(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "def broken(:"}, node_id="node_bad_4", ) self.assertIn("[ERR-SYNTAX]", str(ctx.exception)) def test_timeout_enforcement(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "while True: pass", "timeout_seconds": 0.1}, node_id="node_timeout", ) self.assertIn("[ERR-TIMEOUT]", str(ctx.exception)) if __name__ == "__main__": unittest.main()