hybrid-solver / tests /test_code_executor.py
LeonidNN
Three independent solving methods with answer agreement, figures, new UI and benchmark
74ca799
Raw History Blame Contribute Delete
2.17 kB
import os
import sys
import pytest
import config
from app.code_executor import execute_code
def test_prints_result():
assert execute_code("print(2 + 2)") == "4"
def test_markdown_wrapper_is_stripped():
assert execute_code("```python\nprint('ok')\n```") == "ok"
def test_numpy_and_scipy_available():
code = "from scipy.integrate import quad\nprint(round(quad(lambda x: x**2, 0, 3)[0], 6))"
assert execute_code(code) == "9.0"
def test_error_is_reported():
assert execute_code("1 / 0").startswith("Error during execution")
def test_timeout(monkeypatch):
monkeypatch.setattr(config, "CODE_EXECUTION_TIMEOUT", 3)
assert "Превышено время" in execute_code("while True: pass")
def test_environment_has_no_secrets(monkeypatch):
monkeypatch.setenv("POLZA_API_KEY", "secret-value")
output = execute_code("import os\nprint(dict(os.environ))")
assert "secret-value" not in output
def test_reading_project_files_is_blocked():
path = os.path.abspath("config.py")
output = execute_code(f"print(open({path!r}).read())")
assert "запрещён" in output
def test_writing_files_is_blocked():
assert "запрещена" in execute_code("open('x.txt', 'w').write('1')")
@pytest.mark.parametrize("code", [
"import subprocess\nsubprocess.run(['echo', 'hi'])",
"import os\nos.system('echo hi')",
"import socket\nsocket.create_connection(('example.com', 80))",
"import ctypes\nctypes.CDLL(None)",
"import ctypes\nctypes.string_at(id(1), 8)",
])
def test_dangerous_operations_are_blocked(code):
assert execute_code(code).startswith("Error during execution")
@pytest.mark.skipif(
sys.version_info >= (3, 13),
reason="в 3.13+ создание субинтерпретатора не вызывает audit event",
)
def test_subinterpreters_are_blocked():
output = execute_code("import _xxsubinterpreters as m\nm.create()")
assert output.startswith("Error during execution")
def test_output_is_truncated(monkeypatch):
monkeypatch.setattr(config, "MAX_OUTPUT_CHARS", 100)
assert execute_code("print('a' * 1000)").endswith("(вывод обрезан)")