You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
swarms/api/tests.py

328 lines
9.8 KiB

2 weeks ago
import asyncio
import json
2 weeks ago
import os
2 weeks ago
import sys
2 weeks ago
from typing import Any, Dict
import aiohttp
2 weeks ago
from loguru import logger
# Configure loguru
LOG_PATH = "api_tests.log"
1 week ago
logger.add(
LOG_PATH,
2 weeks ago
format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}",
rotation="1 day",
retention="7 days",
1 week ago
level="DEBUG",
)
BASE_URL = (
"https://api.swarms.ai/v1" # Change this to match your server URL
2 weeks ago
)
1 week ago
async def log_request_details(
method: str, url: str, headers: dict, data: Any = None
):
2 weeks ago
"""Log request details before sending."""
logger.debug(f"\n{'='*50}")
logger.debug(f"REQUEST: {method} {url}")
logger.debug(f"HEADERS: {json.dumps(headers, indent=2)}")
if data:
logger.debug(f"PAYLOAD: {json.dumps(data, indent=2)}")
1 week ago
async def log_response_details(
response: aiohttp.ClientResponse, data: Any = None
):
2 weeks ago
"""Log response details after receiving."""
logger.debug(f"\nRESPONSE Status: {response.status}")
1 week ago
logger.debug(
f"RESPONSE Headers: {json.dumps(dict(response.headers), indent=2)}"
)
2 weeks ago
if data:
logger.debug(f"RESPONSE Body: {json.dumps(data, indent=2)}")
logger.debug(f"{'='*50}\n")
1 week ago
async def test_create_user(
session: aiohttp.ClientSession,
) -> Dict[str, str]:
2 weeks ago
"""Test user creation endpoint."""
url = f"{BASE_URL}/users"
payload = {"username": "test_user"}
1 week ago
2 weeks ago
logger.info("Testing user creation...")
await log_request_details("POST", url, {}, payload)
1 week ago
2 weeks ago
try:
async with session.post(url, json=payload) as response:
data = await response.json()
await log_response_details(response, data)
1 week ago
2 weeks ago
if response.status != 200:
1 week ago
logger.error(
f"Failed to create user. Status: {response.status}, Response: {data}"
)
2 weeks ago
sys.exit(1)
1 week ago
2 weeks ago
logger.success("✓ Created user successfully")
1 week ago
return {
"user_id": data["user_id"],
"api_key": data["api_key"],
}
2 weeks ago
except Exception as e:
logger.exception(f"Exception in user creation: {str(e)}")
sys.exit(1)
1 week ago
async def test_create_agent(
session: aiohttp.ClientSession, api_key: str
) -> str:
2 weeks ago
"""Test agent creation endpoint."""
url = f"{BASE_URL}/agent"
config = {
"agent_name": "test_agent",
"system_prompt": "You are a helpful test agent",
"model_name": "gpt-4",
"description": "Test agent for API validation",
"max_loops": 1,
"temperature": 0.5,
"tags": ["test"],
"streaming_on": False,
"user_name": "test_user", # Added required field
1 week ago
"output_type": "string", # Added required field
2 weeks ago
}
1 week ago
2 weeks ago
headers = {"api-key": api_key}
logger.info("Testing agent creation...")
await log_request_details("POST", url, headers, config)
1 week ago
2 weeks ago
try:
1 week ago
async with session.post(
url, headers=headers, json=config
) as response:
2 weeks ago
data = await response.json()
await log_response_details(response, data)
1 week ago
2 weeks ago
if response.status != 200:
1 week ago
logger.error(
f"Failed to create agent. Status: {response.status}, Response: {data}"
)
2 weeks ago
return None
1 week ago
2 weeks ago
logger.success("✓ Created agent successfully")
return data["agent_id"]
except Exception as e:
logger.exception(f"Exception in agent creation: {str(e)}")
return None
1 week ago
async def test_agent_update(
session: aiohttp.ClientSession, agent_id: str, api_key: str
):
2 weeks ago
"""Test agent update endpoint."""
url = f"{BASE_URL}/agent/{agent_id}"
update_data = {
"description": "Updated test agent",
"system_prompt": "Updated system prompt",
"temperature": 0.7,
1 week ago
"tags": ["test", "updated"],
2 weeks ago
}
1 week ago
2 weeks ago
headers = {"api-key": api_key}
logger.info(f"Testing agent update for agent {agent_id}...")
await log_request_details("PATCH", url, headers, update_data)
1 week ago
2 weeks ago
try:
1 week ago
async with session.patch(
url, headers=headers, json=update_data
) as response:
2 weeks ago
data = await response.json()
await log_response_details(response, data)
1 week ago
2 weeks ago
if response.status != 200:
1 week ago
logger.error(
f"Failed to update agent. Status: {response.status}, Response: {data}"
)
2 weeks ago
return False
1 week ago
2 weeks ago
logger.success("✓ Updated agent successfully")
return True
except Exception as e:
logger.exception(f"Exception in agent update: {str(e)}")
return False
1 week ago
async def test_completion(
session: aiohttp.ClientSession, agent_id: str, api_key: str
):
2 weeks ago
"""Test completion endpoint."""
url = f"{BASE_URL}/agent/completions"
completion_request = {
"prompt": "Hello, how are you?",
"agent_id": agent_id,
"max_tokens": 100,
1 week ago
"stream": False,
2 weeks ago
}
1 week ago
2 weeks ago
headers = {"api-key": api_key}
logger.info(f"Testing completion for agent {agent_id}...")
1 week ago
await log_request_details(
"POST", url, headers, completion_request
)
2 weeks ago
try:
1 week ago
async with session.post(
url, headers=headers, json=completion_request
) as response:
2 weeks ago
data = await response.json()
await log_response_details(response, data)
1 week ago
2 weeks ago
if response.status != 200:
1 week ago
logger.error(
f"Failed to process completion. Status: {response.status}, Response: {data}"
)
2 weeks ago
return False
1 week ago
2 weeks ago
logger.success("✓ Processed completion successfully")
return True
except Exception as e:
1 week ago
logger.exception(
f"Exception in completion processing: {str(e)}"
)
2 weeks ago
return False
1 week ago
async def test_get_metrics(
session: aiohttp.ClientSession, agent_id: str, api_key: str
):
2 weeks ago
"""Test metrics endpoint."""
url = f"{BASE_URL}/agent/{agent_id}/metrics"
headers = {"api-key": api_key}
1 week ago
2 weeks ago
logger.info(f"Testing metrics retrieval for agent {agent_id}...")
await log_request_details("GET", url, headers)
1 week ago
2 weeks ago
try:
async with session.get(url, headers=headers) as response:
data = await response.json()
await log_response_details(response, data)
1 week ago
2 weeks ago
if response.status != 200:
1 week ago
logger.error(
f"Failed to get metrics. Status: {response.status}, Response: {data}"
)
2 weeks ago
return False
1 week ago
2 weeks ago
logger.success("✓ Retrieved metrics successfully")
return True
except Exception as e:
logger.exception(f"Exception in metrics retrieval: {str(e)}")
return False
1 week ago
2 weeks ago
async def run_tests():
"""Run all API tests."""
logger.info("Starting API test suite...")
logger.info(f"Using base URL: {BASE_URL}")
1 week ago
2 weeks ago
timeout = aiohttp.ClientTimeout(total=30) # 30 second timeout
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
# Create test user
user_data = await test_create_user(session)
if not user_data:
logger.error("User creation failed, stopping tests.")
return
1 week ago
logger.info(
"User created successfully, proceeding with agent tests..."
)
user_data["user_id"]
2 weeks ago
api_key = user_data["api_key"]
1 week ago
2 weeks ago
# Create test agent
agent_id = await test_create_agent(session, api_key)
if not agent_id:
logger.error("Agent creation failed, stopping tests.")
return
1 week ago
logger.info(
"Agent created successfully, proceeding with other tests..."
)
2 weeks ago
# Run remaining tests
test_results = []
1 week ago
2 weeks ago
# Test metrics retrieval
logger.info("Testing metrics retrieval...")
1 week ago
metrics_result = await test_get_metrics(
session, agent_id, api_key
)
2 weeks ago
test_results.append(("Metrics", metrics_result))
1 week ago
2 weeks ago
# Test agent update
logger.info("Testing agent update...")
1 week ago
update_result = await test_agent_update(
session, agent_id, api_key
)
2 weeks ago
test_results.append(("Agent Update", update_result))
1 week ago
2 weeks ago
# Test completion
logger.info("Testing completion...")
1 week ago
completion_result = await test_completion(
session, agent_id, api_key
)
2 weeks ago
test_results.append(("Completion", completion_result))
1 week ago
2 weeks ago
# Log final results
logger.info("\nTest Results Summary:")
all_passed = True
for test_name, result in test_results:
status = "PASSED" if result else "FAILED"
logger.info(f"{test_name}: {status}")
if not result:
all_passed = False
1 week ago
2 weeks ago
if all_passed:
1 week ago
logger.success(
"\n🎉 All tests completed successfully!"
)
2 weeks ago
else:
1 week ago
logger.error(
"\n❌ Some tests failed. Check the logs for details."
)
logger.info(
f"\nDetailed logs available at: {os.path.abspath(LOG_PATH)}"
)
2 weeks ago
except Exception as e:
1 week ago
logger.exception(
f"Unexpected error during test execution: {str(e)}"
)
2 weeks ago
raise
finally:
logger.info("Test suite execution completed.")
1 week ago
2 weeks ago
def main():
1 week ago
logger.info("=" * 50)
2 weeks ago
logger.info("API TEST SUITE EXECUTION")
1 week ago
logger.info("=" * 50)
2 weeks ago
try:
asyncio.run(run_tests())
except KeyboardInterrupt:
logger.warning("Test execution interrupted by user.")
2 weeks ago
except Exception:
2 weeks ago
logger.exception("Fatal error in test execution:")
finally:
logger.info("Test suite shutdown complete.")
1 week ago
2 weeks ago
if __name__ == "__main__":
1 week ago
main()