test_env_vars.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Env vars related tests for the EventStreamRuntime, which connects to the RuntimeClient running in the sandbox."""
  2. import os
  3. import time
  4. from unittest.mock import patch
  5. from conftest import _load_runtime
  6. from openhands.events.action import CmdRunAction
  7. from openhands.events.observation import CmdOutputObservation
  8. # ============================================================================================================================
  9. # Environment variables tests
  10. # ============================================================================================================================
  11. def test_env_vars_os_environ(temp_dir, box_class, run_as_openhands):
  12. with patch.dict(os.environ, {'SANDBOX_ENV_FOOBAR': 'BAZ'}):
  13. runtime = _load_runtime(temp_dir, box_class, run_as_openhands)
  14. obs: CmdOutputObservation = runtime.run_action(CmdRunAction(command='env'))
  15. print(obs)
  16. obs: CmdOutputObservation = runtime.run_action(
  17. CmdRunAction(command='echo $FOOBAR')
  18. )
  19. print(obs)
  20. assert obs.exit_code == 0, 'The exit code should be 0.'
  21. assert (
  22. obs.content.strip().split('\n\r')[0].strip() == 'BAZ'
  23. ), f'Output: [{obs.content}] for {box_class}'
  24. runtime.close(rm_all_containers=False)
  25. time.sleep(1)
  26. def test_env_vars_runtime_operations(temp_dir, box_class):
  27. runtime = _load_runtime(temp_dir, box_class)
  28. # Test adding single env var
  29. runtime.add_env_vars({'QUUX': 'abc"def'})
  30. obs = runtime.run_action(CmdRunAction(command='echo $QUUX'))
  31. assert (
  32. obs.exit_code == 0 and obs.content.strip().split('\r\n')[0].strip() == 'abc"def'
  33. )
  34. # Test adding multiple env vars
  35. runtime.add_env_vars({'FOOBAR': 'xyz'})
  36. obs = runtime.run_action(CmdRunAction(command='echo $QUUX $FOOBAR'))
  37. assert (
  38. obs.exit_code == 0
  39. and obs.content.strip().split('\r\n')[0].strip() == 'abc"def xyz'
  40. )
  41. # Test adding empty dict
  42. prev_env = runtime.run_action(CmdRunAction(command='env')).content
  43. runtime.add_env_vars({})
  44. current_env = runtime.run_action(CmdRunAction(command='env')).content
  45. assert prev_env == current_env
  46. # Test overwriting env vars
  47. runtime.add_env_vars({'QUUX': 'new_value'})
  48. obs = runtime.run_action(CmdRunAction(command='echo $QUUX'))
  49. assert (
  50. obs.exit_code == 0
  51. and obs.content.strip().split('\r\n')[0].strip() == 'new_value'
  52. )
  53. runtime.close(rm_all_containers=False)
  54. time.sleep(1)