test_bash.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. """Bash-related tests for the EventStreamRuntime, which connects to the ActionExecutor running in the sandbox."""
  2. import os
  3. import pytest
  4. from conftest import (
  5. TEST_IN_CI,
  6. _close_test_runtime,
  7. _get_sandbox_folder,
  8. _load_runtime,
  9. )
  10. from openhands.core.logger import openhands_logger as logger
  11. from openhands.events.action import CmdRunAction
  12. from openhands.events.observation import CmdOutputObservation
  13. from openhands.runtime.base import Runtime
  14. # ============================================================================================================================
  15. # Bash-specific tests
  16. # ============================================================================================================================
  17. def _run_cmd_action(runtime, custom_command: str, keep_prompt=True):
  18. action = CmdRunAction(command=custom_command, keep_prompt=keep_prompt)
  19. logger.info(action, extra={'msg_type': 'ACTION'})
  20. obs = runtime.run_action(action)
  21. assert isinstance(obs, CmdOutputObservation)
  22. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  23. return obs
  24. def test_bash_command_pexcept(temp_dir, runtime_cls, run_as_openhands):
  25. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  26. try:
  27. # We set env var PS1="\u@\h:\w $"
  28. # and construct the PEXCEPT prompt base on it.
  29. # When run `env`, bad implementation of CmdRunAction will be pexcepted by this
  30. # and failed to pexcept the right content, causing it fail to get error code.
  31. obs = runtime.run_action(CmdRunAction(command='env'))
  32. # For example:
  33. # 02:16:13 - openhands:DEBUG: client.py:78 - Executing command: env
  34. # 02:16:13 - openhands:DEBUG: client.py:82 - Command output: PYTHONUNBUFFERED=1
  35. # CONDA_EXE=/openhands/miniforge3/bin/conda
  36. # [...]
  37. # LC_CTYPE=C.UTF-8
  38. # PS1=\u@\h:\w $
  39. # 02:16:13 - openhands:DEBUG: client.py:89 - Executing command for exit code: env
  40. # 02:16:13 - openhands:DEBUG: client.py:92 - Exit code Output:
  41. # CONDA_DEFAULT_ENV=base
  42. # As long as the exit code is 0, the test will pass.
  43. assert isinstance(
  44. obs, CmdOutputObservation
  45. ), 'The observation should be a CmdOutputObservation.'
  46. assert obs.exit_code == 0, 'The exit code should be 0.'
  47. finally:
  48. _close_test_runtime(runtime)
  49. def test_bash_timeout_and_keyboard_interrupt(temp_dir, runtime_cls, run_as_openhands):
  50. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  51. try:
  52. action = CmdRunAction(command='python -c "import time; time.sleep(10)"')
  53. action.timeout = 1
  54. obs = runtime.run_action(action)
  55. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  56. assert isinstance(obs, CmdOutputObservation)
  57. assert (
  58. '[Command timed out after 1 seconds. SIGINT was sent to interrupt the command.]'
  59. in obs.content
  60. )
  61. assert 'KeyboardInterrupt' in obs.content
  62. # follow up command should not be affected
  63. action = CmdRunAction(command='ls')
  64. action.timeout = 1
  65. obs = runtime.run_action(action)
  66. assert isinstance(obs, CmdOutputObservation)
  67. assert obs.exit_code == 0
  68. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  69. # run it again!
  70. action = CmdRunAction(command='python -c "import time; time.sleep(10)"')
  71. action.timeout = 1
  72. obs = runtime.run_action(action)
  73. assert isinstance(obs, CmdOutputObservation)
  74. assert (
  75. '[Command timed out after 1 seconds. SIGINT was sent to interrupt the command.]'
  76. in obs.content
  77. )
  78. assert 'KeyboardInterrupt' in obs.content
  79. # things should still work
  80. action = CmdRunAction(command='ls')
  81. action.timeout = 1
  82. obs = runtime.run_action(action)
  83. assert isinstance(obs, CmdOutputObservation)
  84. assert obs.exit_code == 0
  85. assert '/workspace' in obs.interpreter_details
  86. finally:
  87. _close_test_runtime(runtime)
  88. def test_bash_pexcept_eof(temp_dir, runtime_cls, run_as_openhands):
  89. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  90. try:
  91. action = CmdRunAction(command='python3 -m http.server 8080')
  92. action.timeout = 1
  93. obs = runtime.run_action(action)
  94. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  95. assert isinstance(obs, CmdOutputObservation)
  96. assert obs.exit_code == 130 # script was killed by SIGINT
  97. assert 'Serving HTTP on 0.0.0.0 port 8080' in obs.content
  98. assert 'Keyboard interrupt received, exiting.' in obs.content
  99. action = CmdRunAction(command='ls')
  100. action.timeout = 1
  101. obs = runtime.run_action(action)
  102. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  103. assert isinstance(obs, CmdOutputObservation)
  104. assert obs.exit_code == 0
  105. assert '/workspace' in obs.interpreter_details
  106. # run it again!
  107. action = CmdRunAction(command='python3 -m http.server 8080')
  108. action.timeout = 1
  109. obs = runtime.run_action(action)
  110. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  111. assert isinstance(obs, CmdOutputObservation)
  112. assert obs.exit_code == 130 # script was killed by SIGINT
  113. assert 'Serving HTTP on 0.0.0.0 port 8080' in obs.content
  114. assert 'Keyboard interrupt received, exiting.' in obs.content
  115. # things should still work
  116. action = CmdRunAction(command='ls')
  117. action.timeout = 1
  118. obs = runtime.run_action(action)
  119. assert isinstance(obs, CmdOutputObservation)
  120. assert obs.exit_code == 0
  121. assert '/workspace' in obs.interpreter_details
  122. finally:
  123. _close_test_runtime(runtime)
  124. def test_process_resistant_to_one_sigint(temp_dir, runtime_cls, run_as_openhands):
  125. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  126. try:
  127. # Create a bash script that ignores SIGINT up to 1 times
  128. script_content = """
  129. #!/bin/bash
  130. trap_count=0
  131. trap 'echo "Caught SIGINT ($((++trap_count))/1), ignoring..."; [ $trap_count -ge 1 ] && trap - INT && exit' INT
  132. while true; do
  133. echo "Still running..."
  134. sleep 1
  135. done
  136. """.strip()
  137. with open(f'{temp_dir}/resistant_script.sh', 'w') as f:
  138. f.write(script_content)
  139. os.chmod(f'{temp_dir}/resistant_script.sh', 0o777)
  140. runtime.copy_to(
  141. os.path.join(temp_dir, 'resistant_script.sh'),
  142. runtime.config.workspace_mount_path_in_sandbox,
  143. )
  144. # Run the resistant script
  145. action = CmdRunAction(command='sudo bash ./resistant_script.sh')
  146. action.timeout = 5
  147. action.blocking = True
  148. logger.info(action, extra={'msg_type': 'ACTION'})
  149. obs = runtime.run_action(action)
  150. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  151. assert isinstance(obs, CmdOutputObservation)
  152. assert obs.exit_code == 130 # script was killed by SIGINT
  153. assert 'Still running...' in obs.content
  154. assert 'Caught SIGINT (1/1), ignoring...' in obs.content
  155. assert 'Stopped' not in obs.content
  156. assert (
  157. '[Command timed out after 5 seconds. SIGINT was sent to interrupt the command.]'
  158. in obs.content
  159. )
  160. # Normal command should still work
  161. action = CmdRunAction(command='ls')
  162. action.timeout = 10
  163. obs = runtime.run_action(action)
  164. assert isinstance(obs, CmdOutputObservation)
  165. assert obs.exit_code == 0
  166. assert '/workspace' in obs.interpreter_details
  167. assert 'resistant_script.sh' in obs.content
  168. finally:
  169. _close_test_runtime(runtime)
  170. def test_process_resistant_to_multiple_sigint(temp_dir, runtime_cls, run_as_openhands):
  171. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  172. try:
  173. # Create a bash script that ignores SIGINT up to 2 times
  174. script_content = """
  175. #!/bin/bash
  176. trap_count=0
  177. trap 'echo "Caught SIGINT ($((++trap_count))/3), ignoring..."; [ $trap_count -ge 3 ] && trap - INT && exit' INT
  178. while true; do
  179. echo "Still running..."
  180. sleep 1
  181. done
  182. """.strip()
  183. with open(f'{temp_dir}/resistant_script.sh', 'w') as f:
  184. f.write(script_content)
  185. os.chmod(f'{temp_dir}/resistant_script.sh', 0o777)
  186. runtime.copy_to(
  187. os.path.join(temp_dir, 'resistant_script.sh'),
  188. runtime.config.workspace_mount_path_in_sandbox,
  189. )
  190. # Run the resistant script
  191. action = CmdRunAction(command='sudo bash ./resistant_script.sh')
  192. action.timeout = 2
  193. action.blocking = True
  194. logger.info(action, extra={'msg_type': 'ACTION'})
  195. obs = runtime.run_action(action)
  196. logger.info(obs, extra={'msg_type': 'OBSERVATION'})
  197. assert isinstance(obs, CmdOutputObservation)
  198. assert obs.exit_code == 0
  199. assert 'Still running...' in obs.content
  200. assert 'Caught SIGINT (1/3), ignoring...' in obs.content
  201. assert '[1]+' and 'Stopped' in obs.content
  202. assert (
  203. '[Command timed out after 2 seconds. SIGINT was sent to interrupt the command, but failed. The command was killed.]'
  204. in obs.content
  205. )
  206. # Normal command should still work
  207. action = CmdRunAction(command='ls')
  208. action.timeout = 10
  209. obs = runtime.run_action(action)
  210. assert isinstance(obs, CmdOutputObservation)
  211. assert obs.exit_code == 0
  212. assert '/workspace' in obs.interpreter_details
  213. assert 'resistant_script.sh' in obs.content
  214. finally:
  215. _close_test_runtime(runtime)
  216. def test_multiline_commands(temp_dir, runtime_cls):
  217. runtime = _load_runtime(temp_dir, runtime_cls)
  218. try:
  219. # single multiline command
  220. obs = _run_cmd_action(runtime, 'echo \\\n -e "foo"')
  221. assert obs.exit_code == 0, 'The exit code should be 0.'
  222. assert 'foo' in obs.content
  223. # test multiline echo
  224. obs = _run_cmd_action(runtime, 'echo -e "hello\nworld"')
  225. assert obs.exit_code == 0, 'The exit code should be 0.'
  226. assert 'hello\r\nworld' in obs.content
  227. # test whitespace
  228. obs = _run_cmd_action(runtime, 'echo -e "a\\n\\n\\nz"')
  229. assert obs.exit_code == 0, 'The exit code should be 0.'
  230. assert '\r\n\r\n\r\n' in obs.content
  231. finally:
  232. _close_test_runtime(runtime)
  233. def test_multiple_multiline_commands(temp_dir, runtime_cls, run_as_openhands):
  234. cmds = [
  235. 'ls -l',
  236. 'echo -e "hello\nworld"',
  237. """
  238. echo -e "hello it\\'s me"
  239. """.strip(),
  240. """
  241. echo \\
  242. -e 'hello' \\
  243. -v
  244. """.strip(),
  245. """
  246. echo -e 'hello\\nworld\\nare\\nyou\\nthere?'
  247. """.strip(),
  248. """
  249. echo -e 'hello
  250. world
  251. are
  252. you\\n
  253. there?'
  254. """.strip(),
  255. """
  256. echo -e 'hello
  257. world "
  258. '
  259. """.strip(),
  260. ]
  261. joined_cmds = '\n'.join(cmds)
  262. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  263. try:
  264. obs = _run_cmd_action(runtime, joined_cmds)
  265. assert obs.exit_code == 0, 'The exit code should be 0.'
  266. assert 'total 0' in obs.content
  267. assert 'hello\r\nworld' in obs.content
  268. assert "hello it\\'s me" in obs.content
  269. assert 'hello -v' in obs.content
  270. assert 'hello\r\nworld\r\nare\r\nyou\r\nthere?' in obs.content
  271. assert 'hello\r\nworld\r\nare\r\nyou\r\n\r\nthere?' in obs.content
  272. finally:
  273. _close_test_runtime(runtime)
  274. def test_no_ps2_in_output(temp_dir, runtime_cls, run_as_openhands):
  275. """Test that the PS2 sign is not added to the output of a multiline command."""
  276. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  277. try:
  278. obs = _run_cmd_action(runtime, 'echo -e "hello\nworld"')
  279. assert obs.exit_code == 0, 'The exit code should be 0.'
  280. assert 'hello\r\nworld' in obs.content
  281. assert '>' not in obs.content
  282. finally:
  283. _close_test_runtime(runtime)
  284. def test_multiline_command_loop(temp_dir, runtime_cls):
  285. # https://github.com/All-Hands-AI/OpenHands/issues/3143
  286. init_cmd = """
  287. mkdir -p _modules && \
  288. for month in {01..04}; do
  289. for day in {01..05}; do
  290. touch "_modules/2024-${month}-${day}-sample.md"
  291. done
  292. done
  293. echo "created files"
  294. """
  295. follow_up_cmd = """
  296. for file in _modules/*.md; do
  297. new_date=$(echo $file | sed -E 's/2024-(01|02|03|04)-/2024-/;s/2024-01/2024-08/;s/2024-02/2024-09/;s/2024-03/2024-10/;s/2024-04/2024-11/')
  298. mv "$file" "$new_date"
  299. done
  300. echo "success"
  301. """
  302. runtime = _load_runtime(temp_dir, runtime_cls)
  303. try:
  304. obs = _run_cmd_action(runtime, init_cmd)
  305. assert obs.exit_code == 0, 'The exit code should be 0.'
  306. assert 'created files' in obs.content
  307. obs = _run_cmd_action(runtime, follow_up_cmd)
  308. assert obs.exit_code == 0, 'The exit code should be 0.'
  309. assert 'success' in obs.content
  310. finally:
  311. _close_test_runtime(runtime)
  312. def test_cmd_run(temp_dir, runtime_cls, run_as_openhands):
  313. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  314. try:
  315. obs = _run_cmd_action(runtime, 'ls -l /openhands/workspace')
  316. assert obs.exit_code == 0
  317. obs = _run_cmd_action(runtime, 'ls -l')
  318. assert obs.exit_code == 0
  319. assert 'total 0' in obs.content
  320. obs = _run_cmd_action(runtime, 'mkdir test')
  321. assert obs.exit_code == 0
  322. obs = _run_cmd_action(runtime, 'ls -l')
  323. assert obs.exit_code == 0
  324. if run_as_openhands:
  325. assert 'openhands' in obs.content
  326. else:
  327. assert 'root' in obs.content
  328. assert 'test' in obs.content
  329. obs = _run_cmd_action(runtime, 'touch test/foo.txt')
  330. assert obs.exit_code == 0
  331. obs = _run_cmd_action(runtime, 'ls -l test')
  332. assert obs.exit_code == 0
  333. assert 'foo.txt' in obs.content
  334. # clean up: this is needed, since CI will not be
  335. # run as root, and this test may leave a file
  336. # owned by root
  337. _run_cmd_action(runtime, 'rm -rf test')
  338. assert obs.exit_code == 0
  339. finally:
  340. _close_test_runtime(runtime)
  341. def test_run_as_user_correct_home_dir(temp_dir, runtime_cls, run_as_openhands):
  342. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  343. try:
  344. obs = _run_cmd_action(runtime, 'cd ~ && pwd')
  345. assert obs.exit_code == 0
  346. if run_as_openhands:
  347. assert '/home/openhands' in obs.content
  348. else:
  349. assert '/root' in obs.content
  350. finally:
  351. _close_test_runtime(runtime)
  352. def test_multi_cmd_run_in_single_line(temp_dir, runtime_cls):
  353. runtime = _load_runtime(temp_dir, runtime_cls)
  354. try:
  355. obs = _run_cmd_action(runtime, 'pwd && ls -l')
  356. assert obs.exit_code == 0
  357. assert '/workspace' in obs.content
  358. assert 'total 0' in obs.content
  359. finally:
  360. _close_test_runtime(runtime)
  361. def test_stateful_cmd(temp_dir, runtime_cls):
  362. runtime = _load_runtime(temp_dir, runtime_cls)
  363. sandbox_dir = _get_sandbox_folder(runtime)
  364. try:
  365. obs = _run_cmd_action(runtime, 'mkdir -p test')
  366. assert obs.exit_code == 0, 'The exit code should be 0.'
  367. obs = _run_cmd_action(runtime, 'cd test')
  368. assert obs.exit_code == 0, 'The exit code should be 0.'
  369. obs = _run_cmd_action(runtime, 'pwd')
  370. assert obs.exit_code == 0, 'The exit code should be 0.'
  371. assert f'{sandbox_dir}/test' in obs.content
  372. finally:
  373. _close_test_runtime(runtime)
  374. def test_failed_cmd(temp_dir, runtime_cls):
  375. runtime = _load_runtime(temp_dir, runtime_cls)
  376. try:
  377. obs = _run_cmd_action(runtime, 'non_existing_command')
  378. assert obs.exit_code != 0, 'The exit code should not be 0 for a failed command.'
  379. finally:
  380. _close_test_runtime(runtime)
  381. def _create_test_file(host_temp_dir):
  382. # Single file
  383. with open(os.path.join(host_temp_dir, 'test_file.txt'), 'w') as f:
  384. f.write('Hello, World!')
  385. def test_copy_single_file(temp_dir, runtime_cls):
  386. runtime = _load_runtime(temp_dir, runtime_cls)
  387. try:
  388. sandbox_dir = _get_sandbox_folder(runtime)
  389. sandbox_file = os.path.join(sandbox_dir, 'test_file.txt')
  390. _create_test_file(temp_dir)
  391. runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)
  392. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  393. assert obs.exit_code == 0
  394. assert 'test_file.txt' in obs.content
  395. obs = _run_cmd_action(runtime, f'cat {sandbox_file}')
  396. assert obs.exit_code == 0
  397. assert 'Hello, World!' in obs.content
  398. finally:
  399. _close_test_runtime(runtime)
  400. def _create_host_test_dir_with_files(test_dir):
  401. logger.debug(f'creating `{test_dir}`')
  402. if not os.path.isdir(test_dir):
  403. os.makedirs(test_dir, exist_ok=True)
  404. logger.debug('creating test files in `test_dir`')
  405. with open(os.path.join(test_dir, 'file1.txt'), 'w') as f:
  406. f.write('File 1 content')
  407. with open(os.path.join(test_dir, 'file2.txt'), 'w') as f:
  408. f.write('File 2 content')
  409. def test_copy_directory_recursively(temp_dir, runtime_cls):
  410. runtime = _load_runtime(temp_dir, runtime_cls)
  411. sandbox_dir = _get_sandbox_folder(runtime)
  412. try:
  413. temp_dir_copy = os.path.join(temp_dir, 'test_dir')
  414. # We need a separate directory, since temp_dir is mounted to /workspace
  415. _create_host_test_dir_with_files(temp_dir_copy)
  416. runtime.copy_to(temp_dir_copy, sandbox_dir, recursive=True)
  417. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  418. assert obs.exit_code == 0
  419. assert 'test_dir' in obs.content
  420. assert 'file1.txt' not in obs.content
  421. assert 'file2.txt' not in obs.content
  422. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}/test_dir')
  423. assert obs.exit_code == 0
  424. assert 'file1.txt' in obs.content
  425. assert 'file2.txt' in obs.content
  426. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_dir/file1.txt')
  427. assert obs.exit_code == 0
  428. assert 'File 1 content' in obs.content
  429. finally:
  430. _close_test_runtime(runtime)
  431. def test_copy_to_non_existent_directory(temp_dir, runtime_cls):
  432. runtime = _load_runtime(temp_dir, runtime_cls)
  433. try:
  434. sandbox_dir = _get_sandbox_folder(runtime)
  435. _create_test_file(temp_dir)
  436. runtime.copy_to(
  437. os.path.join(temp_dir, 'test_file.txt'), f'{sandbox_dir}/new_dir'
  438. )
  439. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/new_dir/test_file.txt')
  440. assert obs.exit_code == 0
  441. assert 'Hello, World!' in obs.content
  442. finally:
  443. _close_test_runtime(runtime)
  444. def test_overwrite_existing_file(temp_dir, runtime_cls):
  445. runtime = _load_runtime(temp_dir, runtime_cls)
  446. try:
  447. sandbox_dir = _get_sandbox_folder(runtime)
  448. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  449. assert obs.exit_code == 0
  450. obs = _run_cmd_action(runtime, f'touch {sandbox_dir}/test_file.txt')
  451. assert obs.exit_code == 0
  452. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  453. assert obs.exit_code == 0
  454. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_file.txt')
  455. assert obs.exit_code == 0
  456. assert 'Hello, World!' not in obs.content
  457. _create_test_file(temp_dir)
  458. runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)
  459. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_file.txt')
  460. assert obs.exit_code == 0
  461. assert 'Hello, World!' in obs.content
  462. finally:
  463. _close_test_runtime(runtime)
  464. def test_copy_non_existent_file(temp_dir, runtime_cls):
  465. runtime = _load_runtime(temp_dir, runtime_cls)
  466. try:
  467. sandbox_dir = _get_sandbox_folder(runtime)
  468. with pytest.raises(FileNotFoundError):
  469. runtime.copy_to(
  470. os.path.join(sandbox_dir, 'non_existent_file.txt'),
  471. f'{sandbox_dir}/should_not_exist.txt',
  472. )
  473. obs = _run_cmd_action(runtime, f'ls {sandbox_dir}/should_not_exist.txt')
  474. assert obs.exit_code != 0 # File should not exist
  475. finally:
  476. _close_test_runtime(runtime)
  477. def test_copy_from_directory(temp_dir, runtime_cls):
  478. runtime: Runtime = _load_runtime(temp_dir, runtime_cls)
  479. sandbox_dir = _get_sandbox_folder(runtime)
  480. try:
  481. temp_dir_copy = os.path.join(temp_dir, 'test_dir')
  482. # We need a separate directory, since temp_dir is mounted to /workspace
  483. _create_host_test_dir_with_files(temp_dir_copy)
  484. # Initial state
  485. runtime.copy_to(temp_dir_copy, sandbox_dir, recursive=True)
  486. path_to_copy_from = f'{sandbox_dir}/test_dir'
  487. result = runtime.copy_from(path=path_to_copy_from)
  488. # Result is returned in bytes
  489. assert isinstance(result, bytes)
  490. finally:
  491. _close_test_runtime(runtime)
  492. def test_keep_prompt(runtime_cls, temp_dir):
  493. runtime = _load_runtime(
  494. temp_dir,
  495. runtime_cls=runtime_cls,
  496. run_as_openhands=False,
  497. )
  498. try:
  499. sandbox_dir = _get_sandbox_folder(runtime)
  500. obs = _run_cmd_action(runtime, f'touch {sandbox_dir}/test_file.txt')
  501. assert obs.exit_code == 0
  502. assert 'root@' in obs.interpreter_details
  503. obs = _run_cmd_action(
  504. runtime, f'cat {sandbox_dir}/test_file.txt', keep_prompt=False
  505. )
  506. assert obs.exit_code == 0
  507. assert 'root@' not in obs.interpreter_details
  508. finally:
  509. _close_test_runtime(runtime)
  510. @pytest.mark.skipif(
  511. TEST_IN_CI != 'True',
  512. reason='This test is not working in WSL (file ownership)',
  513. )
  514. def test_git_operation(runtime_cls):
  515. # do not mount workspace, since workspace mount by tests will be owned by root
  516. # while the user_id we get via os.getuid() is different from root
  517. # which causes permission issues
  518. runtime = _load_runtime(
  519. temp_dir=None,
  520. runtime_cls=runtime_cls,
  521. # Need to use non-root user to expose issues
  522. run_as_openhands=True,
  523. )
  524. # this will happen if permission of runtime is not properly configured
  525. # fatal: detected dubious ownership in repository at '/workspace'
  526. try:
  527. # check the ownership of the current directory
  528. obs = _run_cmd_action(runtime, 'ls -alh .')
  529. assert obs.exit_code == 0
  530. # drwx--S--- 2 openhands root 64 Aug 7 23:32 .
  531. # drwxr-xr-x 1 root root 4.0K Aug 7 23:33 ..
  532. for line in obs.content.split('\r\n'):
  533. if ' ..' in line:
  534. # parent directory should be owned by root
  535. assert 'root' in line
  536. assert 'openhands' not in line
  537. elif ' .' in line:
  538. # current directory should be owned by openhands
  539. # and its group should be root
  540. assert 'openhands' in line
  541. assert 'root' in line
  542. # make sure all git operations are allowed
  543. obs = _run_cmd_action(runtime, 'git init')
  544. assert obs.exit_code == 0
  545. # create a file
  546. obs = _run_cmd_action(runtime, 'echo "hello" > test_file.txt')
  547. assert obs.exit_code == 0
  548. # git add
  549. obs = _run_cmd_action(runtime, 'git add test_file.txt')
  550. assert obs.exit_code == 0
  551. # git diff
  552. obs = _run_cmd_action(runtime, 'git diff')
  553. assert obs.exit_code == 0
  554. # git commit
  555. obs = _run_cmd_action(runtime, 'git commit -m "test commit"')
  556. assert obs.exit_code == 0
  557. finally:
  558. _close_test_runtime(runtime)
  559. def test_python_version(temp_dir, runtime_cls, run_as_openhands):
  560. runtime = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
  561. try:
  562. obs = runtime.run_action(CmdRunAction(command='python --version'))
  563. assert isinstance(
  564. obs, CmdOutputObservation
  565. ), 'The observation should be a CmdOutputObservation.'
  566. assert obs.exit_code == 0, 'The exit code should be 0.'
  567. assert 'Python 3' in obs.content, 'The output should contain "Python 3".'
  568. finally:
  569. _close_test_runtime(runtime)