Certainly! Below is a comprehensive Python unit test using the unittest framework and the requests library to replicate and fully test all the parameters from your curl request. This test ensures that each parameter is correctly sent to the API and handles the response appropriately.
Prerequisites
-
Python 3.x installed on your machine.
-
requests library: You can install it using pip if you haven't already:
pip install requests
-
Mock Server (Optional): If you want to avoid making actual HTTP requests during testing, you can use the responses library to mock HTTP responses.
pip install responses
Unit Test Implementation
Here's the complete unit test code:
import unittest
import requests
import json
# Optional: Uncomment if you choose to mock HTTP responses
# import responses
class TestChatCompletionsAPI(unittest.TestCase):
def setUp(self):
self.url = "http://127.0.0.1:8000/v1/chat/completions"
self.headers = {
"Content-Type": "application/json",
"Authorization": "Bearer sk-fakeapikey"
}
self.payload = {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Do you love me?"}
],
"model": "model",
"store": False,
"metadata": {"foo": "bar"},
"frequency_penalty": 0,
"logit_bias": None,
"logprobs": True,
"top_logprobs": 1,
"max_tokens": 512,
"max_completion_tokens": 256,
"n": 1,
"modalities": ["text"],
"presence_penalty": 0,
"response_format": None,
"seed": 1,
"service_tier": "auto",
"stop": None,
"stream": True,
"stream_options": {"include_usage": True},
"temperature": 1,
"top_p": 0.95,
"tools": None,
"tool_choice": None,
"parallel_tool_calls": True,
"user": None
}
# Optional: Use this decorator if mocking is desired
# @responses.activate
def test_chat_completions(self):
# If mocking, set up the mock response here
# responses.add(
# responses.POST,
# self.url,
# json={"success": True, "data": "Mock response"},
# status=200
# )
try:
response = requests.post(
self.url,
headers=self.headers,
data=json.dumps(self.payload),
timeout=10 # Optional: Set a timeout for the request
)
except requests.exceptions.RequestException as e:
self.fail(f"Request failed: {e}")
# Check if the response status code is as expected (e.g., 200 OK)
self.assertEqual(response.status_code, 200, f"Expected status code 200, got {response.status_code}")
# Parse the JSON response
try:
response_json = response.json()
except json.JSONDecodeError:
self.fail("Response is not valid JSON")
# Example assertions based on expected response structure
# Adjust these based on your actual API's response
# Check for specific keys in the response
expected_keys = ["id", "object", "created", "model", "choices"]
for key in expected_keys:
self.assertIn(key, response_json, f"Response JSON does not contain key: {key}")
# Further assertions can be added here to validate the contents
# For example, checking the 'choices' array
self.assertIsInstance(response_json.get("choices"), list, "'choices' should be a list")
self.assertGreater(len(response_json["choices"]), 0, "'choices' list should not be empty")
# Validate each parameter was processed correctly (Example)
# This depends on how your API echoes or processes the input parameters
# For demonstration, let's assume the API echoes back some of the parameters
# Example: Check if 'model' is echoed back correctly
self.assertEqual(response_json.get("model"), self.payload["model"], "Model parameter mismatch")
# Add more detailed checks as per your API's response
# Optional: Additional tests for individual parameters can be added here
if __name__ == "__main__":
unittest.main()
Explanation of the Test Code
-
Imports:
unittest: Python’s built-in testing framework.
requests: To make HTTP requests.
json: To handle JSON data.
responses (optional): To mock HTTP responses without making actual API calls.
-
Test Class: TestChatCompletionsAPI inherits from unittest.TestCase.
-
setUp Method:
- Initializes the URL, headers, and payload that replicate your
curl request.
- This method runs before each test method.
-
test_chat_completions Method:
-
Making the Request:
- Sends a
POST request to the specified URL with headers and the JSON payload.
- Converts the payload dictionary to a JSON string using
json.dumps.
- Includes a timeout to prevent hanging indefinitely.
-
Response Validation:
- Status Code: Asserts that the response status code is
200 OK.
- JSON Parsing: Ensures the response is valid JSON.
- Content Validation: Checks for expected keys and validates their types and contents.
- Custom Assertions: Depending on your API's behavior, you can add more assertions to verify that each parameter is handled correctly.
-
Running the Test:
- The
unittest.main() call allows the test to be run when the script is executed directly.
Optional: Mocking HTTP Responses
If you prefer not to make actual HTTP requests (e.g., during continuous integration or when the API server isn't available), you can mock the HTTP responses using the responses library. Here's how to modify the test:
-
Uncomment the Import and Decorator:
import responses
@responses.activate
def test_chat_completions(self):
...
-
Set Up Mock Response:
responses.add(
responses.POST,
self.url,
json={"id": "test-id", "object": "chat.completion", "created": 1234567890, "model": "model", "choices": []},
status=200
)
-
Adjust Assertions:
Ensure that the assertions match the mocked response structure.
Running the Test
Save the test code to a file, for example, test_chat_completions.py, and run it using the following command:
python test_chat_completions.py
You should see output similar to:
.
----------------------------------------------------------------------
Ran 1 test in 0.123s
OK
This indicates that the test passed successfully. If there are any issues, the test will provide detailed error messages to help you debug.
Extending the Test
To fully ensure that all parameters are handled correctly, consider the following extensions:
-
Parameter-Specific Tests: Create separate test methods for different parameter combinations, especially edge cases (e.g., maximum and minimum values).
-
Error Handling: Test how the API responds to invalid parameters or missing required fields.
-
Response Content: Validate that the response content accurately reflects the input parameters where applicable.
-
Performance: Measure response times if performance is a concern.
-
Security: Test authentication mechanisms by providing invalid or missing API keys.
Example: Testing an Invalid Parameter
Here's an example of how you might test the API's response to an invalid parameter value:
def test_invalid_max_tokens(self):
invalid_payload = self.payload.copy()
invalid_payload["max_tokens"] = -10 # Invalid value
response = requests.post(
self.url,
headers=self.headers,
data=json.dumps(invalid_payload)
)
self.assertNotEqual(response.status_code, 200, "API should not accept negative max_tokens")
self.assertIn("error", response.json(), "Response should contain an error message")
Conclusion
This unit test provides a solid foundation for testing your /v1/chat/completions API endpoint. By verifying that all parameters are correctly sent and handled, you can ensure the reliability and correctness of your API interactions. Feel free to customize and expand the tests based on the specific behaviors and requirements of your API.