conftest.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import io
  2. import os
  3. import re
  4. import shutil
  5. import socket
  6. import subprocess
  7. import tempfile
  8. from functools import partial
  9. from http.server import HTTPServer, SimpleHTTPRequestHandler
  10. import pytest
  11. from litellm import completion
  12. from openhands.core.message import format_messages
  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(
  63. test_name: str, messages: str, id: int
  64. ) -> str | None:
  65. """Apply the mock prompt, and find mock response based on id.
  66. If there is no matching response file, return None.
  67. Note: this function blindly replaces existing prompt file with the given
  68. input without checking the contents.
  69. """
  70. mock_dir = os.path.join(MOCK_ROOT_DIR, test_name)
  71. prompt_file_path = os.path.join(mock_dir, f'prompt_{"{0:03}".format(id)}.log')
  72. resp_file_path = os.path.join(mock_dir, f'response_{"{0:03}".format(id)}.log')
  73. try:
  74. # load response
  75. with open(resp_file_path, 'r') as resp_file:
  76. response = resp_file.read()
  77. # apply prompt
  78. with open(prompt_file_path, 'w') as prompt_file:
  79. prompt_file.write(messages)
  80. prompt_file.write('\n')
  81. return response
  82. except FileNotFoundError:
  83. return None
  84. def get_mock_response(test_name: str, messages: str, id: int) -> str:
  85. """Find mock response based on prompt. Prompts are stored under nested
  86. folders under mock folder. If prompt_{id}.log matches,
  87. then the mock response we're looking for is at response_{id}.log.
  88. Note: we filter out all non-alphanumerical characters, otherwise we would
  89. see surprising mismatches caused by linters and minor discrepancies between
  90. different platforms.
  91. We could have done a slightly more efficient string match with the same time
  92. complexity (early-out upon first character mismatch), but it is unnecessary
  93. for tests. Empirically, different prompts of the same task usually only
  94. differ near the end of file, so the comparison would be more efficient if
  95. we start from the end of the file, but again, that is unnecessary and only
  96. makes test code harder to understand.
  97. """
  98. mock_dir = os.path.join(MOCK_ROOT_DIR, test_name)
  99. prompt = filter_out_symbols(messages)
  100. prompt_file_path = os.path.join(mock_dir, f'prompt_{"{0:03}".format(id)}.log')
  101. resp_file_path = os.path.join(mock_dir, f'response_{"{0:03}".format(id)}.log')
  102. # Open the prompt file and compare its contents
  103. with open(prompt_file_path, 'r') as f:
  104. file_content = filter_out_symbols(f.read())
  105. if file_content.strip() == prompt.strip():
  106. # Read the response file and return its content
  107. with open(resp_file_path, 'r') as resp_file:
  108. return resp_file.read()
  109. else:
  110. # print the mismatched lines
  111. print('Mismatched Prompt File path', prompt_file_path)
  112. print('---' * 10)
  113. # Create a temporary file to store messages
  114. with tempfile.NamedTemporaryFile(
  115. delete=False, mode='w', encoding='utf-8'
  116. ) as tmp_file:
  117. tmp_file_path = tmp_file.name
  118. tmp_file.write(messages)
  119. try:
  120. # Use diff command to compare files and capture the output
  121. result = subprocess.run(
  122. ['diff', '-u', prompt_file_path, tmp_file_path],
  123. capture_output=True,
  124. text=True,
  125. )
  126. if result.returncode != 0:
  127. print('Diff:')
  128. print(result.stdout)
  129. else:
  130. print('No differences found.')
  131. finally:
  132. # Clean up the temporary file
  133. os.remove(tmp_file_path)
  134. print('---' * 10)
  135. def mock_user_response(*args, test_name, **kwargs):
  136. """The agent will ask for user input using `input()` when calling `asyncio.run(main(task))`.
  137. This function mocks the user input by providing the response from the mock response file.
  138. It will read the `user_responses.log` file in the test directory and set as
  139. STDIN input for the agent to read.
  140. """
  141. user_response_file = os.path.join(
  142. script_dir,
  143. 'mock',
  144. os.environ.get('DEFAULT_AGENT'),
  145. test_name,
  146. 'user_responses.log',
  147. )
  148. if not os.path.exists(user_response_file):
  149. return ''
  150. with open(user_response_file, 'r') as f:
  151. ret = f.read().rstrip()
  152. ret += '\n'
  153. return ret
  154. def mock_completion(*args, test_name, **kwargs):
  155. global cur_id
  156. messages = kwargs['messages']
  157. plain_messages = format_messages(
  158. messages, with_images=False, with_prompt_caching=False
  159. )
  160. message_str = message_separator.join(msg['content'] for msg in plain_messages)
  161. # this assumes all response_(*).log filenames are in numerical order, starting from one
  162. cur_id += 1
  163. if os.environ.get('FORCE_APPLY_PROMPTS') == 'true':
  164. mock_response = apply_prompt_and_get_mock_response(
  165. test_name, message_str, cur_id
  166. )
  167. else:
  168. mock_response = get_mock_response(test_name, message_str, cur_id)
  169. if mock_response is None:
  170. raise SecretExit('\n\n***** Mock response for prompt is not found *****\n')
  171. response = completion(**kwargs, mock_response=mock_response)
  172. return response
  173. @pytest.fixture
  174. def current_test_name(request):
  175. return request.node.name
  176. @pytest.fixture(autouse=True)
  177. def patch_completion(monkeypatch, request):
  178. test_name = request.node.name
  179. # Mock LLM completion
  180. monkeypatch.setattr(
  181. 'openhands.llm.llm.litellm_completion',
  182. partial(mock_completion, test_name=test_name),
  183. )
  184. # Mock LLM completion cost (1 USD per conversation)
  185. monkeypatch.setattr(
  186. 'openhands.llm.llm.litellm_completion_cost',
  187. lambda completion_response, **extra_kwargs: 1,
  188. )
  189. # Mock LLMConfig to disable vision support
  190. monkeypatch.setattr(
  191. 'openhands.llm.llm.LLM.vision_is_active',
  192. lambda self: False,
  193. )
  194. # Mock user input (only for tests that have user_responses.log)
  195. user_responses_str = mock_user_response(test_name=test_name)
  196. if user_responses_str:
  197. user_responses = io.StringIO(user_responses_str)
  198. monkeypatch.setattr('sys.stdin', user_responses)
  199. class MultiAddressServer(HTTPServer):
  200. def server_bind(self):
  201. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  202. self.socket.bind(self.server_address)
  203. class LoggingHTTPRequestHandler(SimpleHTTPRequestHandler):
  204. def log_message(self, format, *args):
  205. print(
  206. f'Request received: {self.address_string()} - {self.log_date_time_string()} - {format % args}'
  207. )
  208. def set_up():
  209. global cur_id
  210. cur_id = 0
  211. assert workspace_path is not None, 'workspace_path is not set'
  212. # Remove and recreate the workspace_path
  213. if os.path.exists(workspace_path):
  214. shutil.rmtree(workspace_path)
  215. os.makedirs(workspace_path)
  216. @pytest.fixture(autouse=True)
  217. def resource_setup():
  218. try:
  219. original_cwd = os.getcwd()
  220. except FileNotFoundError:
  221. print(
  222. '[DEBUG] Original working directory does not exist. Using /tmp as fallback.'
  223. )
  224. original_cwd = '/tmp'
  225. os.chdir('/tmp')
  226. try:
  227. set_up()
  228. yield
  229. finally:
  230. try:
  231. print(f'[DEBUG] Final working directory: {os.getcwd()}')
  232. except FileNotFoundError:
  233. print('[DEBUG] Final working directory does not exist')
  234. if os.path.exists(workspace_path):
  235. shutil.rmtree(workspace_path)
  236. os.makedirs(workspace_path, exist_ok=True)
  237. # Try to change back to the original directory
  238. try:
  239. os.chdir(original_cwd)
  240. print(f'[DEBUG] Changed back to original directory: {original_cwd}')
  241. except Exception:
  242. os.chdir('/tmp')