Coverage for agentos/tests/test_sandbox_executor.py: 0%

42 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-07-06 20:49 +0800

1"""测试 sandbox_executor — 沙箱代码执行。""" 

2 

3from agentos.security.sandbox import SandboxExecutor, SandboxPolicy, SandboxResult 

4 

5 

6class TestProcessSandbox: 

7 def test_basic_python_execution(self): 

8 sb = SandboxExecutor() 

9 result = sb.execute("print('hello from sandbox')") 

10 assert isinstance(result, SandboxResult) 

11 assert result.exit_code == 0 

12 assert "hello from sandbox" in result.stdout 

13 

14 def test_code_with_error(self): 

15 sb = SandboxExecutor() 

16 result = sb.execute("raise ValueError('test error')") 

17 assert result.exit_code != 0 

18 assert "ValueError" in (result.stderr or "") 

19 

20 def test_custom_policy(self): 

21 policy = SandboxPolicy(max_output_size_bytes=100, timeout_seconds=5) 

22 sb = SandboxExecutor(policy=policy) 

23 result = sb.execute("x = 1 + 1; print(x)") 

24 assert result.exit_code == 0 

25 assert "2" in result.stdout 

26 

27 def test_namespace_isolation(self): 

28 """Verify sandbox does not pollute caller's namespace.""" 

29 caller_ns = {} 

30 sb = SandboxExecutor() 

31 result = sb.execute("y = 42", globals_dict=caller_ns) 

32 assert result.exit_code == 0 

33 # Caller dict should be safe from mutation 

34 assert "y" not in caller_ns 

35 

36 

37class TestSandboxPolicy: 

38 def test_defaults(self): 

39 policy = SandboxPolicy() 

40 assert policy.timeout_seconds > 0 

41 assert policy.max_memory_mb is not None 

42 

43 def test_custom(self): 

44 policy = SandboxPolicy( 

45 timeout_seconds=10, 

46 max_memory_mb=256, 

47 network_enabled=False, 

48 ) 

49 assert policy.timeout_seconds == 10 

50 assert policy.max_memory_mb == 256 

51 assert policy.network_enabled is False 

52 

53 

54class TestSandboxResult: 

55 def test_result_fields(self): 

56 result = SandboxResult( 

57 exit_code=0, 

58 stdout="hello", 

59 stderr="", 

60 execution_time_ms=100, 

61 peak_memory_mb=12.5, 

62 ) 

63 assert result.exit_code == 0 

64 assert result.stdout == "hello" 

65 assert result.success is True 

66 assert result.peak_memory_mb == 12.5