File size: 2,171 Bytes
58bdb55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74ca799
58bdb55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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("(вывод обрезан)")