From d3dac2fac659d788da3d8445806c9bb3c6ad44d0 Mon Sep 17 00:00:00 2001 From: Paul Gauthier Date: Sat, 8 Jul 2023 09:26:27 -0700 Subject: [PATCH] aider: Add a test that mocks `openai.ChatCompletion.create` to throw an `openai.error.InvalidRequestError` and make sure it bubbles all the way up and out of the `Coder` class. # Aider chat conversation: USER: add a test that mocks openai.ChatCompletion.create to throw an openai.error.InvalidRequestError and make sure it bubbles all the way up and out of the Coder class. use coder.run as the entrypoint for the test ASSISTANT: To add this test, we need to modify the `tests/test_coder.py` file. We will add a new test method `test_run_with_invalid_request_error` that mocks `openai.ChatCompletion.create` to throw an `openai.error.InvalidRequestError`. We will then call `coder.run` and assert that the `InvalidRequestError` is raised. Here is the change: ```python tests/test_coder.py <<<<<<< ORIGINAL if __name__ == "__main__": unittest.main() ======= @patch("aider.coders.base_coder.openai.ChatCompletion.create") def test_run_with_invalid_request_error(self, mock_chat_completion_create): # Mock the IO object mock_io = MagicMock() # Initialize the Coder object with the mocked IO and mocked repo coder = Coder.create(models.GPT4, None, mock_io, openai_api_key="fake_key") # Set up the mock to raise InvalidRequestError mock_chat_completion_create.side_effect = openai.error.InvalidRequestError("Invalid request") # Call the run method and assert that InvalidRequestError is raised with self.assertRaises(openai.error.InvalidRequestError): coder.run(with_message="hi") if __name__ == "__main__": unittest.main() >>>>>>> UPDATED ``` This test will ensure that if `openai.ChatCompletion.create` throws an `InvalidRequestError`, it will propagate up and out of the `Coder` class. --- tests/test_coder.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/test_coder.py b/tests/test_coder.py index 754d9603d..39e2647d1 100644 --- a/tests/test_coder.py +++ b/tests/test_coder.py @@ -343,5 +343,20 @@ class TestCoder(unittest.TestCase): # both files should still be here self.assertEqual(len(coder.abs_fnames), 2) + @patch("aider.coders.base_coder.openai.ChatCompletion.create") + def test_run_with_invalid_request_error(self, mock_chat_completion_create): + # Mock the IO object + mock_io = MagicMock() + + # Initialize the Coder object with the mocked IO and mocked repo + coder = Coder.create(models.GPT4, None, mock_io, openai_api_key="fake_key") + + # Set up the mock to raise InvalidRequestError + mock_chat_completion_create.side_effect = openai.error.InvalidRequestError("Invalid request") + + # Call the run method and assert that InvalidRequestError is raised + with self.assertRaises(openai.error.InvalidRequestError): + coder.run(with_message="hi") + if __name__ == "__main__": unittest.main()