import unittest
import json
from unittest.mock import patch
from rp.core.api import call_api, list_models
class TestApi(unittest.TestCase):
@patch("rp.core.http_client.http_client.post")
@patch("rp.core.api.auto_slim_messages")
def test_call_api_success(self, mock_slim, mock_post):
mock_slim.return_value = [{"role": "user", "content": "test"}]
mock_post.return_value = {
"status": 200,
"text": '{"choices": [{"message": {"content": "response"}}], "usage": {"tokens": 10}}',
"json": lambda: json.loads(
'{"choices": [{"message": {"content": "response"}}], "usage": {"tokens": 10}}'
),
}
result = call_api([], "model", "http://url", "key", True, [{"name": "tool"}])
self.assertIn("choices", result)
mock_post.assert_called_once()
@patch("rp.core.http_client.http_client.post")
@patch("rp.core.api.auto_slim_messages")
def test_call_api_http_error(self, mock_slim, mock_post):
mock_slim.return_value = [{"role": "user", "content": "test"}]
mock_post.return_value = {"error": True, "status": 500, "text": "error"}
result = call_api([], "model", "http://url", "key", False, [])
self.assertIn("error", result)
@patch("rp.core.http_client.http_client.post")
@patch("rp.core.api.auto_slim_messages")
def test_call_api_general_error(self, mock_slim, mock_post):
mock_slim.return_value = [{"role": "user", "content": "test"}]
mock_post.return_value = {"error": True, "exception": "test error"}
result = call_api([], "model", "http://url", "key", False, [])
self.assertIn("error", result)
@patch("rp.core.http_client.http_client.get")
def test_list_models_success(self, mock_get):
mock_get.return_value = {
"status": 200,
"text": '{"data": [{"id": "model1"}]}',
"json": lambda: json.loads('{"data": [{"id": "model1"}]}'),
}
result = list_models("http://url", "key")
self.assertEqual(result, [{"id": "model1"}])
@patch("rp.core.http_client.http_client.get")
def test_list_models_error(self, mock_get):
mock_get.return_value = {"error": True, "exception": "error"}
result = list_models("http://url", "key")
self.assertIn("error", result)
if __name__ == "__main__":
unittest.main()