PAYAL / test_api.py
abeerrai01
INTIAL
382ea2d
"""
Test script for Payal Farmer Advisory Chatbot API
Run this script to test all API endpoints
"""
import requests
import json
from datetime import datetime
# Base URL - change if running on different host/port
BASE_URL = "http://localhost:8000"
# Test user ID and session (optional, for testing conversation history)
TEST_UID = "test_user_123"
TEST_SESSION_ID = "" # Will be auto-generated
def print_response(title, response):
"""Pretty print API response"""
print(f"\n{'='*60}")
print(f"{title}")
print(f"{'='*60}")
print(f"Status Code: {response.status_code}")
try:
data = response.json()
print(f"Response:")
print(json.dumps(data, indent=2, ensure_ascii=False))
except:
print(f"Response: {response.text}")
def test_crop_advice_english():
"""Test crop advice endpoint in English"""
url = f"{BASE_URL}/chat/crop"
payload = {
"query": "What crops should I grow in my area?",
"lat": 28.6139, # Delhi coordinates
"lon": 77.2090,
"soil": "Loamy",
"local_info": "Moderate rainfall area",
"uid": TEST_UID,
"language": "en"
}
response = requests.post(url, json=payload)
print_response("🌾 Crop Advice (English)", response)
return response.json().get("session_id")
def test_crop_advice_hindi():
"""Test crop advice endpoint in Hindi"""
url = f"{BASE_URL}/chat/crop"
payload = {
"query": "मेरे क्षेत्र में कौन सी फसलें उगानी चाहिए?",
"lat": 17.3850, # Hyderabad coordinates
"lon": 78.4867,
"soil": "दोमट मिट्टी",
"local_info": "मध्यम वर्षा",
"uid": TEST_UID,
"language": "hi"
}
response = requests.post(url, json=payload)
print_response("🌾 Crop Advice (Hindi)", response)
return response.json().get("session_id")
def test_fertilizer_advice():
"""Test fertilizer advice endpoint"""
url = f"{BASE_URL}/chat/fertilizer"
payload = {
"crop": "Wheat",
"stage": "Vegetative",
"soil_test": "Nitrogen: Low, Phosphorus: Medium",
"uid": TEST_UID,
"language": "en"
}
response = requests.post(url, json=payload)
print_response("🌱 Fertilizer Advice", response)
def test_soil_health():
"""Test soil health advice endpoint"""
url = f"{BASE_URL}/chat/soil"
payload = {
"soil_info": "pH level is 6.5, organic matter is low, clay soil",
"uid": TEST_UID,
"language": "hi"
}
response = requests.post(url, json=payload)
print_response("🏞️ Soil Health Advice", response)
def test_weather_advice():
"""Test weather advice endpoint"""
url = f"{BASE_URL}/chat/weather"
payload = {
"lat": 28.6139,
"lon": 77.2090,
"days": 3,
"uid": TEST_UID,
"language": "en"
}
response = requests.post(url, json=payload)
print_response("🌧️ Weather Advice", response)
def test_mandi_price():
"""Test mandi price endpoint"""
url = f"{BASE_URL}/chat/mandi"
payload = {
"district_name": "Delhi",
"market_name": "Azadpur",
"crop": "Tomato",
"uid": TEST_UID,
"language": "hi"
}
response = requests.post(url, json=payload)
print_response("💰 Mandi Price", response)
def test_pest_detection():
"""Test pest detection endpoint"""
url = f"{BASE_URL}/chat/pest"
params = {
"farmer_id": "farmer_001",
"uid": TEST_UID,
"language": "hi"
}
response = requests.get(url, params=params)
print_response("🐛 Pest Detection", response)
def test_phishing_check():
"""Test phishing URL check endpoint"""
url = f"{BASE_URL}/chat/phishing"
payload = {
"url": "https://www.google.com",
"uid": TEST_UID,
"language": "en"
}
response = requests.post(url, json=payload)
print_response("🔒 Phishing URL Check", response)
def test_sentiment_analysis():
"""Test sentiment analysis endpoint"""
url = f"{BASE_URL}/chat/sentiment"
payload = {
"query": "I am very happy with the crop yield this year!",
"uid": TEST_UID,
"language": "en"
}
response = requests.post(url, json=payload)
print_response("📊 Sentiment Analysis", response)
def test_government_schemes():
"""Test government schemes endpoint"""
url = f"{BASE_URL}/chat/schemes"
payload = {
"text": "I need information about farming subsidies and schemes",
"uid": TEST_UID,
"session_id": "",
"language": "en"
}
response = requests.post(url, json=payload)
print_response("🏛️ Government Schemes", response)
# Test with Hindi
payload_hindi = {
"text": "कृषि ऋण और सब्सिडी योजनाओं के बारे में जानकारी चाहिए",
"uid": TEST_UID,
"session_id": "",
"language": "hi"
}
response = requests.post(url, json=payload_hindi)
print_response("🏛️ Government Schemes (Hindi)", response)
def test_conversation_history(session_id):
"""Test conversation history endpoint"""
url = f"{BASE_URL}/chat/history"
params = {
"uid": TEST_UID,
"session_id": session_id if session_id else ""
}
response = requests.get(url, params=params)
print_response("📜 Conversation History", response)
def test_multilingual():
"""Test multilingual support"""
languages = ["hi", "en", "te", "pa", "ta"]
url = f"{BASE_URL}/chat/crop"
print(f"\n{'='*60}")
print("🌐 Testing Multilingual Support")
print(f"{'='*60}")
for lang in languages:
payload = {
"query": "Best crops to grow" if lang == "en" else "सबसे अच्छी फसलें",
"lat": 28.6139,
"lon": 77.2090,
"uid": TEST_UID,
"language": lang
}
response = requests.post(url, json=payload)
data = response.json()
print(f"\n{lang.upper()}: {data.get('language', 'unknown')}")
print(f"Response: {data.get('response', '')[:100]}...")
def main():
"""Run all tests"""
print("\n" + "="*60)
print("🧪 PAYAL FARMER ADVISORY CHATBOT API - TEST SUITE")
print("="*60)
print(f"\nTesting API at: {BASE_URL}")
print(f"Test User ID: {TEST_UID}")
print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
try:
# Test basic connectivity
response = requests.get(f"{BASE_URL}/docs")
if response.status_code != 200:
print(f"\n❌ ERROR: Cannot connect to {BASE_URL}")
print("Make sure the server is running: uvicorn main:app --reload")
return
except requests.exceptions.ConnectionError:
print(f"\n❌ ERROR: Cannot connect to {BASE_URL}")
print("Make sure the server is running: uvicorn main:app --reload")
return
print("\n✅ Server is running!")
# Run tests
try:
session_id = test_crop_advice_english()
test_crop_advice_hindi()
test_fertilizer_advice()
test_soil_health()
test_weather_advice()
test_mandi_price()
test_pest_detection()
test_phishing_check()
test_sentiment_analysis()
test_government_schemes()
if session_id:
test_conversation_history(session_id)
test_multilingual()
print("\n" + "="*60)
print("✅ ALL TESTS COMPLETED")
print("="*60)
print("\n💡 Tip: Check the Swagger UI at http://localhost:8000/docs")
print(" for interactive API testing and documentation")
except Exception as e:
print(f"\n❌ Error during testing: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()