test_ipython.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import pathlib
  2. import tempfile
  3. from unittest.mock import MagicMock, call, patch
  4. import pytest
  5. from opendevin.core.config import SandboxConfig
  6. from opendevin.events.action import IPythonRunCellAction
  7. from opendevin.events.observation import IPythonRunCellObservation
  8. from opendevin.runtime.server.runtime import ServerRuntime
  9. @pytest.fixture
  10. def temp_dir(monkeypatch):
  11. # get a temporary directory
  12. with tempfile.TemporaryDirectory() as temp_dir:
  13. pathlib.Path().mkdir(parents=True, exist_ok=True)
  14. yield temp_dir
  15. @pytest.mark.asyncio
  16. async def test_run_python_backticks():
  17. # Create a mock event_stream
  18. mock_event_stream = MagicMock()
  19. test_code = "print('Hello, `World`!\n')"
  20. # Mock the asynchronous sandbox execute method
  21. mock_sandbox_execute = MagicMock()
  22. mock_sandbox_execute.side_effect = [
  23. (0, ''), # Initial call during DockerSSHBox initialization
  24. (0, ''), # Initial call during DockerSSHBox initialization
  25. (0, ''), # Initial call during DockerSSHBox initialization
  26. (0, ''), # Write command
  27. (0, test_code), # Execute command
  28. ]
  29. # Set up the patches for the runtime and sandbox
  30. with patch(
  31. 'opendevin.runtime.docker.ssh_box.DockerSSHBox.execute',
  32. new=mock_sandbox_execute,
  33. ):
  34. # Initialize the runtime with the mock event_stream
  35. runtime = ServerRuntime(
  36. sandbox_config=SandboxConfig(box_type='ssh', persist_sandbox=False),
  37. event_stream=mock_event_stream,
  38. )
  39. # Define the test action with a simple IPython command
  40. action = IPythonRunCellAction(code=test_code)
  41. # Call the run_ipython method with the test action
  42. result = await runtime.run_action(action)
  43. # Assert that the result is an instance of IPythonRunCellObservation
  44. assert isinstance(result, IPythonRunCellObservation)
  45. # Assert that the execute method was called with the correct commands
  46. expected_write_command = (
  47. "cat > /tmp/opendevin_jupyter_temp.py <<'EOL'\n" f'{test_code}\n' 'EOL'
  48. )
  49. expected_execute_command = 'cat /tmp/opendevin_jupyter_temp.py | execute_cli'
  50. mock_sandbox_execute.assert_has_calls(
  51. [
  52. call('mkdir -p /tmp'),
  53. call('git config --global user.name "OpenDevin"'),
  54. call('git config --global user.email "opendevin@all-hands.dev"'),
  55. call(expected_write_command),
  56. call(expected_execute_command),
  57. ]
  58. )
  59. assert (
  60. test_code == result.content
  61. ), f'The output should contain the expected print output, got: {result.content}'