test_server.py•5.59 kB
"""Simple test script to validate Trade Me MCP server functionality."""
import asyncio
import os
import sys
from dotenv import load_dotenv
from src.trademe_mcp.client import TradeMeClient
from src.trademe_mcp.tools import catalogue, search, listings
# Force UTF-8 output on Windows
if sys.platform == 'win32':
sys.stdout.reconfigure(encoding='utf-8')
# Load environment
load_dotenv()
async def test_catalogue_tools():
"""Test catalogue tools (no auth required)."""
print("\n=== Testing Catalogue Tools ===")
client = TradeMeClient()
try:
# Test 1: Get categories
print("\n1. Testing get_categories...")
result = await catalogue.get_categories(client, depth=2)
print(f"✓ Got {len(result.get('Subcategories', []))} top-level categories")
# Test 2: Get localities
print("\n2. Testing get_localities...")
result = await catalogue.get_localities(client)
print(f"✓ Got locality data")
print("\n✅ Catalogue tools working!")
except Exception as e:
print(f"❌ Error: {e}")
finally:
client.close()
async def test_search_tools():
"""Test search tools (no auth required)."""
print("\n=== Testing Search Tools ===")
client = TradeMeClient()
try:
# Test 1: General search
print("\n1. Testing search_general...")
result = await search.search_general(client, search_string="laptop", rows=5)
total = result.get('TotalCount', 0)
listings = len(result.get('List', []))
print(f"✓ Found {total} total results, showing {listings} listings")
# Test 2: Property search
print("\n2. Testing search_property_residential...")
result = await search.search_property_residential(client, rows=5)
total = result.get('TotalCount', 0)
print(f"✓ Found {total} residential properties")
# Test 3: Motors search
print("\n3. Testing search_motors...")
result = await search.search_motors(client, make="Toyota", rows=5)
total = result.get('TotalCount', 0)
print(f"✓ Found {total} Toyota vehicles")
print("\n✅ Search tools working!")
except Exception as e:
print(f"❌ Error: {e}")
finally:
client.close()
async def test_listing_tools():
"""Test listing retrieval tools (no auth required)."""
print("\n=== Testing Listing Tools ===")
client = TradeMeClient()
try:
# First, get a listing ID from search
print("\n1. Getting a test listing ID from search...")
search_result = await search.search_general(client, rows=1)
if search_result.get('List') and len(search_result['List']) > 0:
listing_id = search_result['List'][0]['ListingId']
print(f"✓ Using listing ID: {listing_id}")
# Test 2: Get listing details
print("\n2. Testing get_listing_details...")
result = await listings.get_listing_details(client, listing_id)
print(f"✓ Got listing: {result.get('Title', 'N/A')}")
print(f" Price: ${result.get('BuyNowPrice', result.get('StartPrice', 'N/A'))}")
# Test 3: Get listing photos
print("\n3. Testing get_listing_photos...")
result = await listings.get_listing_photos(client, listing_id)
photo_count = len(result.get('Photos', []) if isinstance(result, dict) else result)
print(f"✓ Found {photo_count} photos")
print("\n✅ Listing tools working!")
else:
print("⚠️ No listings found in search to test with")
except Exception as e:
print(f"❌ Error: {e}")
finally:
client.close()
async def test_authenticated_tools():
"""Test authenticated tools (requires access tokens)."""
print("\n=== Testing Authenticated Tools ===")
if not os.getenv('TRADEME_ACCESS_TOKEN'):
print("⚠️ Skipping - No access tokens configured")
print(" Set TRADEME_ACCESS_TOKEN and TRADEME_ACCESS_TOKEN_SECRET to test")
return
client = TradeMeClient()
try:
print("\n1. Testing get_watchlist...")
result = await listings.get_watchlist(client, rows=5)
count = len(result.get('List', []))
print(f"✓ Got watchlist with {count} items")
print("\n✅ Authenticated tools working!")
except Exception as e:
print(f"❌ Error: {e}")
finally:
client.close()
async def main():
"""Run all tests."""
print("=" * 60)
print("Trade Me MCP Server - Test Suite")
print("=" * 60)
# Check environment
env = os.getenv('TRADEME_ENVIRONMENT', 'sandbox')
has_consumer_keys = bool(os.getenv('TRADEME_CONSUMER_KEY'))
has_access_tokens = bool(os.getenv('TRADEME_ACCESS_TOKEN'))
print(f"\nEnvironment: {env}")
print(f"Consumer Keys: {'✓ Configured' if has_consumer_keys else '❌ Missing'}")
print(f"Access Tokens: {'✓ Configured' if has_access_tokens else '⚠️ Not configured (optional)'}")
if not has_consumer_keys:
print("\n❌ ERROR: Please set TRADEME_CONSUMER_KEY and TRADEME_CONSUMER_SECRET in .env")
print("Get credentials from: https://www.trademe.co.nz/MyTradeMe/Api/DeveloperOptions.aspx")
return
# Run tests
await test_catalogue_tools()
await test_search_tools()
await test_listing_tools()
await test_authenticated_tools()
print("\n" + "=" * 60)
print("✅ Testing complete!")
print("=" * 60)
if __name__ == "__main__":
asyncio.run(main())