conftest.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import io
  2. import os
  3. import re
  4. import shutil
  5. import subprocess
  6. import tempfile
  7. import time
  8. from functools import partial
  9. from http.server import HTTPServer, SimpleHTTPRequestHandler
  10. from threading import Thread
  11. import pytest
  12. from litellm import completion
  13. from openhands.llm.llm import message_separator
  14. script_dir = os.environ.get('SCRIPT_DIR')
  15. project_root = os.environ.get('PROJECT_ROOT')
  16. workspace_path = os.environ.get('WORKSPACE_BASE')
  17. test_runtime = os.environ.get('TEST_RUNTIME')
  18. MOCK_ROOT_DIR = os.path.join(
  19. script_dir,
  20. 'mock',
  21. f'{test_runtime}_runtime',
  22. os.environ.get('DEFAULT_AGENT'),
  23. )
  24. assert script_dir is not None, 'SCRIPT_DIR environment variable is not set'
  25. assert project_root is not None, 'PROJECT_ROOT environment variable is not set'
  26. assert workspace_path is not None, 'WORKSPACE_BASE environment variable is not set'
  27. assert test_runtime is not None, 'TEST_RUNTIME environment variable is not set'
  28. class SecretExit(Exception):
  29. pass
  30. @pytest.hookimpl(tryfirst=True)
  31. def pytest_exception_interact(node, call, report):
  32. if isinstance(call.excinfo.value, SecretExit):
  33. report.outcome = 'failed'
  34. report.longrepr = (
  35. 'SecretExit: Exiting due to an error without revealing secrets.'
  36. )
  37. call.excinfo = None
  38. def filter_out_symbols(input):
  39. # remove shell hostname patterns (e.g., will change between each run)
  40. # openhands@379c7fce40b4:/workspace $
  41. input = re.sub(r'(openhands|root)@.*(:/.*)', r'\1[DUMMY_HOSTNAME]\2', input)
  42. # mask the specific part in a poetry path
  43. input = re.sub(
  44. r'(/open[a-z]{5}/poetry/open[a-z]{5}-)[a-zA-Z0-9-]+(-py3\.\d+/bin/python)',
  45. r'\1[DUMMY_STRING]\2',
  46. input,
  47. )
  48. # handle size param
  49. input = re.sub(r' size=\d+ ', ' size=[DUMMY_SIZE] ', input)
  50. # handle sha256 hashes
  51. # sha256=4ecf8be428f55981e2a188f510ba5f9022bed88f5fb404d7d949f44382201e3d
  52. input = re.sub(r'sha256=[a-z0-9]+', 'sha256=[DUMMY_HASH]', input)
  53. # remove newlines and whitespace
  54. input = re.sub(r'\\n|\\r\\n|\\r|\s+', '', input)
  55. # remove all non-alphanumeric characters
  56. input = re.sub(r'[^a-zA-Z0-9]', '', input)
  57. return input
  58. def get_log_id(prompt_log_name):
  59. match = re.search(r'prompt_(\d+).log', prompt_log_name)
  60. if match:
  61. return match.group(1)
  62. def apply_prompt_and_get_mock_response(test_name: str, messages: str, id: int) -> str:
  63. """Apply the mock prompt, and find mock response based on id.
  64. If there is no matching response file, return None.
  65. Note: this function blindly replaces existing prompt file with the given
  66. input without checking the contents.
  67. """
  68. mock_dir = os.path.join(MOCK_ROOT_DIR, test_name)
  69. prompt_file_path = os.path.join(mock_dir, f'prompt_{"{0:03}".format(id)}.log')
  70. resp_file_path = os.path.join(mock_dir, f'response_{"{0:03}".format(id)}.log')
  71. try:
  72. # load response
  73. with open(resp_file_path, 'r') as resp_file:
  74. response = resp_file.read()
  75. # apply prompt
  76. with open(prompt_file_path, 'w') as prompt_file:
  77. prompt_file.write(messages)
  78. prompt_file.write('\n')
  79. return response
  80. except FileNotFoundError:
  81. return None
  82. def get_mock_response(test_name: str, messages: str, id: int) -> str:
  83. """Find mock response based on prompt. Prompts are stored under nested
  84. folders under mock folder. If prompt_{id}.log matches,
  85. then the mock response we're looking for is at response_{id}.log.
  86. Note: we filter out all non-alphanumerical characters, otherwise we would
  87. see surprising mismatches caused by linters and minor discrepancies between
  88. different platforms.
  89. We could have done a slightly more efficient string match with the same time
  90. complexity (early-out upon first character mismatch), but it is unnecessary
  91. for tests. Empirically, different prompts of the same task usually only
  92. differ near the end of file, so the comparison would be more efficient if
  93. we start from the end of the file, but again, that is unnecessary and only
  94. makes test code harder to understand.
  95. """
  96. mock_dir = os.path.join(MOCK_ROOT_DIR, test_name)
  97. prompt = filter_out_symbols(messages)
  98. prompt_file_path = os.path.join(mock_dir, f'prompt_{"{0:03}".format(id)}.log')
  99. resp_file_path = os.path.join(mock_dir, f'response_{"{0:03}".format(id)}.log')
  100. # Open the prompt file and compare its contents
  101. with open(prompt_file_path, 'r') as f:
  102. file_content = filter_out_symbols(f.read())
  103. if file_content.strip() == prompt.strip():
  104. # Read the response file and return its content
  105. with open(resp_file_path, 'r') as resp_file:
  106. return resp_file.read()
  107. else:
  108. # print the mismatched lines
  109. print('Mismatched Prompt File path', prompt_file_path)
  110. print('---' * 10)
  111. # Create a temporary file to store messages
  112. with tempfile.NamedTemporaryFile(
  113. delete=False, mode='w', encoding='utf-8'
  114. ) as tmp_file:
  115. tmp_file_path = tmp_file.name
  116. tmp_file.write(messages)
  117. try:
  118. # Use diff command to compare files and capture the output
  119. result = subprocess.run(
  120. ['diff', '-u', prompt_file_path, tmp_file_path],
  121. capture_output=True,
  122. text=True,
  123. )
  124. if result.returncode != 0:
  125. print('Diff:')
  126. print(result.stdout)
  127. else:
  128. print('No differences found.')
  129. finally:
  130. # Clean up the temporary file
  131. os.remove(tmp_file_path)
  132. print('---' * 10)
  133. def mock_user_response(*args, test_name, **kwargs):
  134. """The agent will ask for user input using `input()` when calling `asyncio.run(main(task))`.
  135. This function mocks the user input by providing the response from the mock response file.
  136. It will read the `user_responses.log` file in the test directory and set as
  137. STDIN input for the agent to read.
  138. """
  139. user_response_file = os.path.join(
  140. script_dir,
  141. 'mock',
  142. os.environ.get('DEFAULT_AGENT'),
  143. test_name,
  144. 'user_responses.log',
  145. )
  146. if not os.path.exists(user_response_file):
  147. return ''
  148. with open(user_response_file, 'r') as f:
  149. ret = f.read().rstrip()
  150. ret += '\n'
  151. return ret
  152. def mock_completion(*args, test_name, **kwargs):
  153. global cur_id
  154. messages = kwargs['messages']
  155. message_str = ''
  156. for message in messages:
  157. for m in message['content']:
  158. if m['type'] == 'text':
  159. message_str += message_separator + m['text']
  160. # this assumes all response_(*).log filenames are in numerical order, starting from one
  161. cur_id += 1
  162. if os.environ.get('FORCE_APPLY_PROMPTS') == 'true':
  163. mock_response = apply_prompt_and_get_mock_response(
  164. test_name, message_str, cur_id
  165. )
  166. else:
  167. mock_response = get_mock_response(test_name, message_str, cur_id)
  168. if mock_response is None:
  169. raise SecretExit('Mock response for prompt is not found')
  170. response = completion(**kwargs, mock_response=mock_response)
  171. return response
  172. @pytest.fixture
  173. def current_test_name(request):
  174. return request.node.name
  175. @pytest.fixture(autouse=True)
  176. def patch_completion(monkeypatch, request):
  177. test_name = request.node.name
  178. # Mock LLM completion
  179. monkeypatch.setattr(
  180. 'openhands.llm.llm.litellm_completion',
  181. partial(mock_completion, test_name=test_name),
  182. )
  183. # Mock LLM completion cost (1 USD per conversation)
  184. monkeypatch.setattr(
  185. 'openhands.llm.llm.litellm_completion_cost',
  186. lambda completion_response, **extra_kwargs: 1,
  187. )
  188. # Mock user input (only for tests that have user_responses.log)
  189. user_responses_str = mock_user_response(test_name=test_name)
  190. if user_responses_str:
  191. user_responses = io.StringIO(user_responses_str)
  192. monkeypatch.setattr('sys.stdin', user_responses)
  193. @pytest.fixture
  194. def http_server():
  195. web_dir = os.path.join(os.path.dirname(__file__), 'static')
  196. os.chdir(web_dir)
  197. handler = SimpleHTTPRequestHandler
  198. # Start the server
  199. server = HTTPServer(('localhost', 8000), handler)
  200. thread = Thread(target=server.serve_forever)
  201. thread.setDaemon(True)
  202. thread.start()
  203. time.sleep(1)
  204. print('HTTP server started...')
  205. yield server
  206. # Stop the server
  207. server.shutdown()
  208. thread.join()
  209. def set_up():
  210. global cur_id
  211. cur_id = 0
  212. assert workspace_path is not None, 'workspace_path is not set'
  213. # Remove and recreate the workspace_path
  214. if os.path.exists(workspace_path):
  215. shutil.rmtree(workspace_path)
  216. os.makedirs(workspace_path)
  217. @pytest.fixture(autouse=True)
  218. def resource_setup():
  219. try:
  220. original_cwd = os.getcwd()
  221. except FileNotFoundError:
  222. print(
  223. '[DEBUG] Original working directory does not exist. Using /tmp as fallback.'
  224. )
  225. original_cwd = '/tmp'
  226. os.chdir('/tmp')
  227. try:
  228. set_up()
  229. yield
  230. finally:
  231. try:
  232. print(f'[DEBUG] Final working directory: {os.getcwd()}')
  233. except FileNotFoundError:
  234. print('[DEBUG] Final working directory does not exist')
  235. if os.path.exists(workspace_path):
  236. shutil.rmtree(workspace_path)
  237. os.makedirs(workspace_path, exist_ok=True)
  238. # Try to change back to the original directory
  239. try:
  240. os.chdir(original_cwd)
  241. print(f'[DEBUG] Changed back to original directory: {original_cwd}')
  242. except Exception:
  243. os.chdir('/tmp')