Files
DronePlanning/tools/test_api.py
2025-09-21 01:16:33 +08:00

76 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
# --- Configuration ---
# The base URL of your running FastAPI service
BASE_URL = "http://127.0.0.1:8000"
# The endpoint we want to test
ENDPOINT = "/generate_plan"
# The user prompt we will send for the test
TEST_PROMPT = "已知目标检测红色气球危险性高于蓝色气球高于绿色气球飞往搜索区搜索并锁定危险性最高的气球对其跟踪30秒后进行打击操作"
def test_generate_plan():
"""
Sends a request to the /generate_plan endpoint and validates the response.
"""
url = BASE_URL + ENDPOINT
payload = {"user_prompt": TEST_PROMPT}
headers = {"Content-Type": "application/json"}
print("--- API Test: Generate Plan ---")
print(f"✅ URL: {url}")
print(f"✅ Sending Prompt: \"{TEST_PROMPT}\"")
try:
# Send the POST request
response = requests.post(url, data=json.dumps(payload), headers=headers)
# Check for HTTP errors (e.g., 404, 500)
response.raise_for_status()
# Parse the JSON response
data = response.json()
print("✅ Received Response:")
print(json.dumps(data, indent=2, ensure_ascii=False))
# --- Validation ---
print("\n--- Validation Checks ---")
# 1. Check if the response is a dictionary
if isinstance(data, dict):
print("PASS: Response is a valid JSON object.")
else:
print("FAIL: Response is not a valid JSON object.")
return
# 2. Check for the existence of the 'root' key
if "root" in data and isinstance(data['root'], dict):
print("PASS: Response contains a valid 'root' key.")
else:
print("FAIL: Response does not contain a valid 'root' key.")
# 3. Check for the existence and format of the 'visualization_url' key
if "visualization_url" in data and data["visualization_url"].endswith(".png"):
print(f"PASS: Response contains a valid 'visualization_url': {data['visualization_url']}")
else:
print("FAIL: Response does not contain a valid 'visualization_url'.")
except requests.exceptions.RequestException as e:
print(f"\n❌ TEST FAILED: Could not connect to the server.")
print(" Please make sure the backend service is running.")
print(f" Error details: {e}")
except json.JSONDecodeError:
print(f"\n❌ TEST FAILED: The server response was not valid JSON.")
print(f" Response text: {response.text}")
except Exception as e:
print(f"\n❌ TEST FAILED: An unexpected error occurred: {e}")
if __name__ == "__main__":
test_generate_plan()