test_runtime.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. """Test the EventStreamRuntime, which connects to the RuntimeClient running in the sandbox."""
  2. import os
  3. import pathlib
  4. import tempfile
  5. from unittest.mock import patch
  6. import pytest
  7. from opendevin.core.config import SandboxConfig
  8. from opendevin.core.logger import opendevin_logger as logger
  9. from opendevin.events import EventStream
  10. from opendevin.events.action import (
  11. CmdRunAction,
  12. )
  13. from opendevin.events.observation import (
  14. CmdOutputObservation,
  15. )
  16. from opendevin.runtime.client.runtime import EventStreamRuntime
  17. from opendevin.runtime.plugins import AgentSkillsRequirement, JupyterRequirement
  18. from opendevin.runtime.server.runtime import ServerRuntime
  19. @pytest.fixture
  20. def temp_dir(monkeypatch):
  21. # get a temporary directory
  22. with tempfile.TemporaryDirectory() as temp_dir:
  23. pathlib.Path().mkdir(parents=True, exist_ok=True)
  24. yield temp_dir
  25. async def _load_runtime(box_class, event_stream, plugins, sid):
  26. sandbox_config = SandboxConfig(
  27. use_host_network=False,
  28. )
  29. container_image = sandbox_config.container_image
  30. # NOTE: we will use the default container image specified in the config.sandbox
  31. # if it is an official od_runtime image.
  32. if 'od_runtime' not in container_image:
  33. container_image = 'ubuntu:22.04'
  34. logger.warning(
  35. f'`sandbox_config.container_image` is not an od_runtime image. Will use `{container_image}` as the container image for testing.'
  36. )
  37. if box_class == EventStreamRuntime:
  38. runtime = EventStreamRuntime(
  39. sandbox_config=sandbox_config,
  40. event_stream=event_stream,
  41. sid=sid,
  42. # NOTE: we probably don't have a default container image `/sandbox` for the event stream runtime
  43. # Instead, we will pre-build a suite of container images with OD-runtime-cli installed.
  44. container_image=container_image,
  45. plugins=plugins,
  46. )
  47. await runtime.ainit()
  48. elif box_class == ServerRuntime:
  49. runtime = ServerRuntime(
  50. sandbox_config=sandbox_config, event_stream=event_stream, sid=sid
  51. )
  52. await runtime.ainit()
  53. runtime.init_sandbox_plugins(plugins)
  54. runtime.init_runtime_tools(
  55. [],
  56. is_async=False,
  57. runtime_tools_config={},
  58. )
  59. else:
  60. raise ValueError(f'Invalid box class: {box_class}')
  61. return runtime
  62. RUNTIME_TO_TEST = [EventStreamRuntime, ServerRuntime]
  63. @pytest.mark.asyncio
  64. async def test_env_vars_os_environ():
  65. with patch.dict(os.environ, {'SANDBOX_ENV_FOOBAR': 'BAZ'}):
  66. plugins = [JupyterRequirement(), AgentSkillsRequirement()]
  67. sid = 'test'
  68. cli_session = 'main_test'
  69. for box_class in RUNTIME_TO_TEST:
  70. event_stream = EventStream(cli_session)
  71. runtime = await _load_runtime(box_class, event_stream, plugins, sid)
  72. obs: CmdOutputObservation = await runtime.run_action(
  73. CmdRunAction(command='env')
  74. )
  75. print(obs)
  76. obs: CmdOutputObservation = await runtime.run_action(
  77. CmdRunAction(command='echo $FOOBAR')
  78. )
  79. print(obs)
  80. assert obs.exit_code == 0, 'The exit code should be 0.'
  81. assert (
  82. obs.content.strip().split('\n\r')[0].strip() == 'BAZ'
  83. ), f'Output: [{obs.content}] for {box_class}'
  84. await runtime.close()
  85. @pytest.mark.asyncio
  86. async def test_env_vars_runtime_add_env_vars():
  87. plugins = [JupyterRequirement(), AgentSkillsRequirement()]
  88. sid = 'test'
  89. cli_session = 'main_test'
  90. for box_class in RUNTIME_TO_TEST:
  91. event_stream = EventStream(cli_session)
  92. runtime = await _load_runtime(box_class, event_stream, plugins, sid)
  93. await runtime.add_env_vars({'QUUX': 'abc"def'})
  94. obs: CmdOutputObservation = await runtime.run_action(
  95. CmdRunAction(command='echo $QUUX')
  96. )
  97. print(obs)
  98. assert obs.exit_code == 0, 'The exit code should be 0.'
  99. assert (
  100. obs.content.strip().split('\r\n')[0].strip() == 'abc"def'
  101. ), f'Output: [{obs.content}] for {box_class}'
  102. await runtime.close()
  103. @pytest.mark.asyncio
  104. async def test_env_vars_runtime_add_empty_dict():
  105. plugins = [JupyterRequirement(), AgentSkillsRequirement()]
  106. sid = 'test'
  107. cli_session = 'main_test'
  108. for box_class in RUNTIME_TO_TEST:
  109. event_stream = EventStream(cli_session)
  110. runtime = await _load_runtime(box_class, event_stream, plugins, sid)
  111. prev_obs = await runtime.run_action(CmdRunAction(command='env'))
  112. assert prev_obs.exit_code == 0, 'The exit code should be 0.'
  113. print(prev_obs)
  114. await runtime.add_env_vars({})
  115. obs = await runtime.run_action(CmdRunAction(command='env'))
  116. assert obs.exit_code == 0, 'The exit code should be 0.'
  117. print(obs)
  118. assert (
  119. obs.content == prev_obs.content
  120. ), 'The env var content should be the same after adding an empty dict.'
  121. await runtime.close()
  122. @pytest.mark.asyncio
  123. async def test_env_vars_runtime_add_multiple_env_vars():
  124. plugins = [JupyterRequirement(), AgentSkillsRequirement()]
  125. sid = 'test'
  126. cli_session = 'main_test'
  127. for box_class in RUNTIME_TO_TEST:
  128. event_stream = EventStream(cli_session)
  129. runtime = await _load_runtime(box_class, event_stream, plugins, sid)
  130. await runtime.add_env_vars({'QUUX': 'abc"def', 'FOOBAR': 'xyz'})
  131. obs: CmdOutputObservation = await runtime.run_action(
  132. CmdRunAction(command='echo $QUUX $FOOBAR')
  133. )
  134. print(obs)
  135. assert obs.exit_code == 0, 'The exit code should be 0.'
  136. assert (
  137. obs.content.strip().split('\r\n')[0].strip() == 'abc"def xyz'
  138. ), f'Output: [{obs.content}] for {box_class}'
  139. await runtime.close()
  140. @pytest.mark.asyncio
  141. async def test_env_vars_runtime_add_env_vars_overwrite():
  142. plugins = [JupyterRequirement(), AgentSkillsRequirement()]
  143. sid = 'test'
  144. cli_session = 'main_test'
  145. for box_class in RUNTIME_TO_TEST:
  146. with patch.dict(os.environ, {'SANDBOX_ENV_FOOBAR': 'BAZ'}):
  147. event_stream = EventStream(cli_session)
  148. runtime = await _load_runtime(box_class, event_stream, plugins, sid)
  149. await runtime.add_env_vars({'FOOBAR': 'xyz'})
  150. obs: CmdOutputObservation = await runtime.run_action(
  151. CmdRunAction(command='echo $FOOBAR')
  152. )
  153. print(obs)
  154. assert obs.exit_code == 0, 'The exit code should be 0.'
  155. assert (
  156. obs.content.strip().split('\r\n')[0].strip() == 'xyz'
  157. ), f'Output: [{obs.content}] for {box_class}'
  158. await runtime.close()
  159. @pytest.mark.asyncio
  160. async def test_bash_command_pexcept(temp_dir):
  161. plugins = [JupyterRequirement(), AgentSkillsRequirement()]
  162. sid = 'test'
  163. cli_session = 'main_test'
  164. box_class = EventStreamRuntime
  165. event_stream = EventStream(cli_session)
  166. runtime = await _load_runtime(box_class, event_stream, plugins, sid)
  167. # We set env var PS1="\u@\h:\w $"
  168. # and construct the PEXCEPT prompt base on it.
  169. # When run `env`, bad implementation of CmdRunAction will be pexcepted by this
  170. # and failed to pexcept the right content, causing it fail to get error code.
  171. obs = await runtime.run_action(CmdRunAction(command='env'))
  172. # For example:
  173. # 02:16:13 - opendevin:DEBUG: client.py:78 - Executing command: env
  174. # 02:16:13 - opendevin:DEBUG: client.py:82 - Command output: PYTHONUNBUFFERED=1
  175. # CONDA_EXE=/opendevin/miniforge3/bin/conda
  176. # [...]
  177. # LC_CTYPE=C.UTF-8
  178. # PS1=\u@\h:\w $
  179. # 02:16:13 - opendevin:DEBUG: client.py:89 - Executing command for exit code: env
  180. # 02:16:13 - opendevin:DEBUG: client.py:92 - Exit code Output:
  181. # CONDA_DEFAULT_ENV=base
  182. # As long as the exit code is 0, the test will pass.
  183. assert isinstance(
  184. obs, CmdOutputObservation
  185. ), 'The observation should be a CmdOutputObservation.'
  186. assert obs.exit_code == 0, 'The exit code should be 0.'