test_bash.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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, box_class, run_as_openhands):
  25. runtime = _load_runtime(temp_dir, box_class, 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, box_class, run_as_openhands):
  50. runtime = _load_runtime(temp_dir, box_class, 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.content
  86. finally:
  87. _close_test_runtime(runtime)
  88. def test_bash_pexcept_eof(temp_dir, box_class, run_as_openhands):
  89. runtime = _load_runtime(temp_dir, box_class, 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.content
  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.content
  122. finally:
  123. _close_test_runtime(runtime)
  124. def test_process_resistant_to_one_sigint(temp_dir, box_class, run_as_openhands):
  125. runtime = _load_runtime(temp_dir, box_class, 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.content
  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, box_class, run_as_openhands):
  171. runtime = _load_runtime(temp_dir, box_class, 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.content
  213. assert 'resistant_script.sh' in obs.content
  214. finally:
  215. _close_test_runtime(runtime)
  216. def test_multiline_commands(temp_dir, box_class):
  217. runtime = _load_runtime(temp_dir, box_class)
  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 "\\n\\n\\n"')
  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, box_class, 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, box_class, 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. assert 'hello\r\nworld "\r\n' in obs.content
  273. finally:
  274. _close_test_runtime(runtime)
  275. def test_no_ps2_in_output(temp_dir, box_class, run_as_openhands):
  276. """Test that the PS2 sign is not added to the output of a multiline command."""
  277. runtime = _load_runtime(temp_dir, box_class, run_as_openhands)
  278. try:
  279. obs = _run_cmd_action(runtime, 'echo -e "hello\nworld"')
  280. assert obs.exit_code == 0, 'The exit code should be 0.'
  281. assert 'hello\r\nworld' in obs.content
  282. assert '>' not in obs.content
  283. finally:
  284. _close_test_runtime(runtime)
  285. def test_multiline_command_loop(temp_dir, box_class):
  286. # https://github.com/All-Hands-AI/OpenHands/issues/3143
  287. init_cmd = """
  288. mkdir -p _modules && \
  289. for month in {01..04}; do
  290. for day in {01..05}; do
  291. touch "_modules/2024-${month}-${day}-sample.md"
  292. done
  293. done
  294. echo "created files"
  295. """
  296. follow_up_cmd = """
  297. for file in _modules/*.md; do
  298. 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/')
  299. mv "$file" "$new_date"
  300. done
  301. echo "success"
  302. """
  303. runtime = _load_runtime(temp_dir, box_class)
  304. try:
  305. obs = _run_cmd_action(runtime, init_cmd)
  306. assert obs.exit_code == 0, 'The exit code should be 0.'
  307. assert 'created files' in obs.content
  308. obs = _run_cmd_action(runtime, follow_up_cmd)
  309. assert obs.exit_code == 0, 'The exit code should be 0.'
  310. assert 'success' in obs.content
  311. finally:
  312. _close_test_runtime(runtime)
  313. def test_cmd_run(temp_dir, box_class, run_as_openhands):
  314. runtime = _load_runtime(temp_dir, box_class, run_as_openhands)
  315. try:
  316. obs = _run_cmd_action(runtime, 'ls -l /openhands/workspace')
  317. assert obs.exit_code == 0
  318. obs = _run_cmd_action(runtime, 'ls -l')
  319. assert obs.exit_code == 0
  320. assert 'total 0' in obs.content
  321. obs = _run_cmd_action(runtime, 'mkdir test')
  322. assert obs.exit_code == 0
  323. obs = _run_cmd_action(runtime, 'ls -l')
  324. assert obs.exit_code == 0
  325. if run_as_openhands:
  326. assert 'openhands' in obs.content
  327. else:
  328. assert 'root' in obs.content
  329. assert 'test' in obs.content
  330. obs = _run_cmd_action(runtime, 'touch test/foo.txt')
  331. assert obs.exit_code == 0
  332. obs = _run_cmd_action(runtime, 'ls -l test')
  333. assert obs.exit_code == 0
  334. assert 'foo.txt' in obs.content
  335. # clean up: this is needed, since CI will not be
  336. # run as root, and this test may leave a file
  337. # owned by root
  338. _run_cmd_action(runtime, 'rm -rf test')
  339. assert obs.exit_code == 0
  340. finally:
  341. _close_test_runtime(runtime)
  342. def test_run_as_user_correct_home_dir(temp_dir, box_class, run_as_openhands):
  343. runtime = _load_runtime(temp_dir, box_class, run_as_openhands)
  344. try:
  345. obs = _run_cmd_action(runtime, 'cd ~ && pwd')
  346. assert obs.exit_code == 0
  347. if run_as_openhands:
  348. assert '/home/openhands' in obs.content
  349. else:
  350. assert '/root' in obs.content
  351. finally:
  352. _close_test_runtime(runtime)
  353. def test_multi_cmd_run_in_single_line(temp_dir, box_class):
  354. runtime = _load_runtime(temp_dir, box_class)
  355. try:
  356. obs = _run_cmd_action(runtime, 'pwd && ls -l')
  357. assert obs.exit_code == 0
  358. assert '/workspace' in obs.content
  359. assert 'total 0' in obs.content
  360. finally:
  361. _close_test_runtime(runtime)
  362. def test_stateful_cmd(temp_dir, box_class):
  363. runtime = _load_runtime(temp_dir, box_class)
  364. sandbox_dir = _get_sandbox_folder(runtime)
  365. try:
  366. obs = _run_cmd_action(runtime, 'mkdir -p test')
  367. assert obs.exit_code == 0, 'The exit code should be 0.'
  368. obs = _run_cmd_action(runtime, 'cd test')
  369. assert obs.exit_code == 0, 'The exit code should be 0.'
  370. obs = _run_cmd_action(runtime, 'pwd')
  371. assert obs.exit_code == 0, 'The exit code should be 0.'
  372. assert f'{sandbox_dir}/test' in obs.content
  373. finally:
  374. _close_test_runtime(runtime)
  375. def test_failed_cmd(temp_dir, box_class):
  376. runtime = _load_runtime(temp_dir, box_class)
  377. try:
  378. obs = _run_cmd_action(runtime, 'non_existing_command')
  379. assert obs.exit_code != 0, 'The exit code should not be 0 for a failed command.'
  380. finally:
  381. _close_test_runtime(runtime)
  382. def _create_test_file(host_temp_dir):
  383. # Single file
  384. with open(os.path.join(host_temp_dir, 'test_file.txt'), 'w') as f:
  385. f.write('Hello, World!')
  386. def test_copy_single_file(temp_dir, box_class):
  387. runtime = _load_runtime(temp_dir, box_class)
  388. try:
  389. sandbox_dir = _get_sandbox_folder(runtime)
  390. sandbox_file = os.path.join(sandbox_dir, 'test_file.txt')
  391. _create_test_file(temp_dir)
  392. runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)
  393. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  394. assert obs.exit_code == 0
  395. assert 'test_file.txt' in obs.content
  396. obs = _run_cmd_action(runtime, f'cat {sandbox_file}')
  397. assert obs.exit_code == 0
  398. assert 'Hello, World!' in obs.content
  399. finally:
  400. _close_test_runtime(runtime)
  401. def _create_host_test_dir_with_files(test_dir):
  402. logger.debug(f'creating `{test_dir}`')
  403. if not os.path.isdir(test_dir):
  404. os.makedirs(test_dir, exist_ok=True)
  405. logger.debug('creating test files in `test_dir`')
  406. with open(os.path.join(test_dir, 'file1.txt'), 'w') as f:
  407. f.write('File 1 content')
  408. with open(os.path.join(test_dir, 'file2.txt'), 'w') as f:
  409. f.write('File 2 content')
  410. def test_copy_directory_recursively(temp_dir, box_class):
  411. runtime = _load_runtime(temp_dir, box_class)
  412. sandbox_dir = _get_sandbox_folder(runtime)
  413. try:
  414. temp_dir_copy = os.path.join(temp_dir, 'test_dir')
  415. # We need a separate directory, since temp_dir is mounted to /workspace
  416. _create_host_test_dir_with_files(temp_dir_copy)
  417. runtime.copy_to(temp_dir_copy, sandbox_dir, recursive=True)
  418. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  419. assert obs.exit_code == 0
  420. assert 'test_dir' in obs.content
  421. assert 'file1.txt' not in obs.content
  422. assert 'file2.txt' not in obs.content
  423. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}/test_dir')
  424. assert obs.exit_code == 0
  425. assert 'file1.txt' in obs.content
  426. assert 'file2.txt' in obs.content
  427. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_dir/file1.txt')
  428. assert obs.exit_code == 0
  429. assert 'File 1 content' in obs.content
  430. finally:
  431. _close_test_runtime(runtime)
  432. def test_copy_to_non_existent_directory(temp_dir, box_class):
  433. runtime = _load_runtime(temp_dir, box_class)
  434. try:
  435. sandbox_dir = _get_sandbox_folder(runtime)
  436. _create_test_file(temp_dir)
  437. runtime.copy_to(
  438. os.path.join(temp_dir, 'test_file.txt'), f'{sandbox_dir}/new_dir'
  439. )
  440. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/new_dir/test_file.txt')
  441. assert obs.exit_code == 0
  442. assert 'Hello, World!' in obs.content
  443. finally:
  444. _close_test_runtime(runtime)
  445. def test_overwrite_existing_file(temp_dir, box_class):
  446. runtime = _load_runtime(temp_dir, box_class)
  447. try:
  448. sandbox_dir = _get_sandbox_folder(runtime)
  449. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  450. assert obs.exit_code == 0
  451. obs = _run_cmd_action(runtime, f'touch {sandbox_dir}/test_file.txt')
  452. assert obs.exit_code == 0
  453. obs = _run_cmd_action(runtime, f'ls -alh {sandbox_dir}')
  454. assert obs.exit_code == 0
  455. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_file.txt')
  456. assert obs.exit_code == 0
  457. assert 'Hello, World!' not in obs.content
  458. _create_test_file(temp_dir)
  459. runtime.copy_to(os.path.join(temp_dir, 'test_file.txt'), sandbox_dir)
  460. obs = _run_cmd_action(runtime, f'cat {sandbox_dir}/test_file.txt')
  461. assert obs.exit_code == 0
  462. assert 'Hello, World!' in obs.content
  463. finally:
  464. _close_test_runtime(runtime)
  465. def test_copy_non_existent_file(temp_dir, box_class):
  466. runtime = _load_runtime(temp_dir, box_class)
  467. try:
  468. sandbox_dir = _get_sandbox_folder(runtime)
  469. with pytest.raises(FileNotFoundError):
  470. runtime.copy_to(
  471. os.path.join(sandbox_dir, 'non_existent_file.txt'),
  472. f'{sandbox_dir}/should_not_exist.txt',
  473. )
  474. obs = _run_cmd_action(runtime, f'ls {sandbox_dir}/should_not_exist.txt')
  475. assert obs.exit_code != 0 # File should not exist
  476. finally:
  477. _close_test_runtime(runtime)
  478. def test_copy_from_directory(temp_dir, box_class):
  479. runtime: Runtime = _load_runtime(temp_dir, box_class)
  480. sandbox_dir = _get_sandbox_folder(runtime)
  481. try:
  482. temp_dir_copy = os.path.join(temp_dir, 'test_dir')
  483. # We need a separate directory, since temp_dir is mounted to /workspace
  484. _create_host_test_dir_with_files(temp_dir_copy)
  485. # Initial state
  486. runtime.copy_to(temp_dir_copy, sandbox_dir, recursive=True)
  487. path_to_copy_from = f'{sandbox_dir}/test_dir'
  488. result = runtime.copy_from(path=path_to_copy_from)
  489. # Result is returned in bytes
  490. assert isinstance(result, bytes)
  491. finally:
  492. _close_test_runtime(runtime)
  493. def test_keep_prompt(box_class, temp_dir):
  494. runtime = _load_runtime(
  495. temp_dir,
  496. box_class=box_class,
  497. run_as_openhands=False,
  498. )
  499. try:
  500. sandbox_dir = _get_sandbox_folder(runtime)
  501. obs = _run_cmd_action(runtime, f'touch {sandbox_dir}/test_file.txt')
  502. assert obs.exit_code == 0
  503. assert 'root@' in obs.content
  504. obs = _run_cmd_action(
  505. runtime, f'cat {sandbox_dir}/test_file.txt', keep_prompt=False
  506. )
  507. assert obs.exit_code == 0
  508. assert 'root@' not in obs.content
  509. finally:
  510. _close_test_runtime(runtime)
  511. @pytest.mark.skipif(
  512. TEST_IN_CI != 'True',
  513. reason='This test is not working in WSL (file ownership)',
  514. )
  515. def test_git_operation(box_class):
  516. # do not mount workspace, since workspace mount by tests will be owned by root
  517. # while the user_id we get via os.getuid() is different from root
  518. # which causes permission issues
  519. runtime = _load_runtime(
  520. temp_dir=None,
  521. box_class=box_class,
  522. # Need to use non-root user to expose issues
  523. run_as_openhands=True,
  524. )
  525. # this will happen if permission of runtime is not properly configured
  526. # fatal: detected dubious ownership in repository at '/workspace'
  527. try:
  528. # check the ownership of the current directory
  529. obs = _run_cmd_action(runtime, 'ls -alh .')
  530. assert obs.exit_code == 0
  531. # drwx--S--- 2 openhands root 64 Aug 7 23:32 .
  532. # drwxr-xr-x 1 root root 4.0K Aug 7 23:33 ..
  533. for line in obs.content.split('\r\n'):
  534. if ' ..' in line:
  535. # parent directory should be owned by root
  536. assert 'root' in line
  537. assert 'openhands' not in line
  538. elif ' .' in line:
  539. # current directory should be owned by openhands
  540. # and its group should be root
  541. assert 'openhands' in line
  542. assert 'root' in line
  543. # make sure all git operations are allowed
  544. obs = _run_cmd_action(runtime, 'git init')
  545. assert obs.exit_code == 0
  546. # create a file
  547. obs = _run_cmd_action(runtime, 'echo "hello" > test_file.txt')
  548. assert obs.exit_code == 0
  549. # git add
  550. obs = _run_cmd_action(runtime, 'git add test_file.txt')
  551. assert obs.exit_code == 0
  552. # git diff
  553. obs = _run_cmd_action(runtime, 'git diff')
  554. assert obs.exit_code == 0
  555. # git commit
  556. obs = _run_cmd_action(runtime, 'git commit -m "test commit"')
  557. assert obs.exit_code == 0
  558. finally:
  559. _close_test_runtime(runtime)
  560. def test_python_version(temp_dir, box_class, run_as_openhands):
  561. runtime = _load_runtime(temp_dir, box_class, run_as_openhands)
  562. try:
  563. obs = runtime.run_action(CmdRunAction(command='python --version'))
  564. assert isinstance(
  565. obs, CmdOutputObservation
  566. ), 'The observation should be a CmdOutputObservation.'
  567. assert obs.exit_code == 0, 'The exit code should be 0.'
  568. assert 'Python 3' in obs.content, 'The output should contain "Python 3".'
  569. finally:
  570. _close_test_runtime(runtime)