conftest.py 8.5 KB

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