conftest.py 9.3 KB

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