first commit

This commit is contained in:
nasir@endelospay.com
2025-08-12 02:54:17 +05:00
commit d97cad1736
225 changed files with 137626 additions and 0 deletions

View File

@@ -0,0 +1,380 @@
#!/usr/bin/env python3
"""
Live Test for QuBeCare Login with Enhanced Voice Agent
This script tests the enhanced voice agent's ability to navigate to QuBeCare
and perform login actions using voice commands.
"""
import asyncio
import logging
import sys
import os
from pathlib import Path
# Add current directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from mcp_chrome_client import MCPChromeClient
class QuBeCareLiveTest:
"""Live test class for QuBeCare login automation"""
def __init__(self):
self.logger = logging.getLogger(__name__)
self.mcp_client = None
self.qubecare_url = "https://app.qubecare.ai/provider/login"
async def setup(self):
"""Set up test environment"""
try:
# Initialize MCP client
chrome_config = {
'mcp_server_type': 'http',
'mcp_server_url': 'http://127.0.0.1:12306/mcp',
'mcp_server_command': None,
'mcp_server_args': []
}
self.mcp_client = MCPChromeClient(chrome_config)
await self.mcp_client.connect()
self.logger.info("✅ Test environment set up successfully")
return True
except Exception as e:
self.logger.error(f"❌ Failed to set up test environment: {e}")
return False
async def navigate_to_qubecare(self):
"""Navigate to QuBeCare login page"""
print(f"\n🌐 Navigating to QuBeCare login page...")
print(f"URL: {self.qubecare_url}")
try:
# Test voice command for navigation
nav_command = f"navigate to {self.qubecare_url}"
print(f"🗣️ Voice Command: '{nav_command}'")
result = await self.mcp_client.process_natural_language_command(nav_command)
print(f"✅ Navigation Result: {result}")
# Wait for page to load
await asyncio.sleep(3)
# Verify we're on the right page
page_content = await self.mcp_client._get_page_content_mcp()
if "qubecare" in page_content.lower() or "login" in page_content.lower():
print("✅ Successfully navigated to QuBeCare login page")
return True
else:
print("⚠️ Page loaded but content verification unclear")
return True # Continue anyway
except Exception as e:
print(f"❌ Navigation failed: {e}")
return False
async def analyze_login_page(self):
"""Analyze the QuBeCare login page structure"""
print(f"\n🔍 Analyzing QuBeCare login page structure...")
try:
# Get form fields
print("🗣️ Voice Command: 'show me form fields'")
form_fields = await self.mcp_client.process_natural_language_command("show me form fields")
print(f"📋 Form Fields Found:\n{form_fields}")
# Get interactive elements
print("\n🗣️ Voice Command: 'what can I click'")
interactive_elements = await self.mcp_client.process_natural_language_command("what can I click")
print(f"🖱️ Interactive Elements:\n{interactive_elements}")
# Get page content summary
print("\n🗣️ Voice Command: 'what's on this page'")
page_content = await self.mcp_client.process_natural_language_command("what's on this page")
print(f"📄 Page Content Summary:\n{page_content[:500]}...")
return True
except Exception as e:
print(f"❌ Page analysis failed: {e}")
return False
async def test_username_entry(self, username="test@example.com"):
"""Test entering username using voice commands"""
print(f"\n👤 Testing username entry...")
username_commands = [
f"fill email with {username}",
f"enter {username} in email field",
f"type {username} in username",
f"email {username}",
f"username {username}"
]
for command in username_commands:
print(f"\n🗣️ Voice Command: '{command}'")
try:
result = await self.mcp_client.process_natural_language_command(command)
print(f"✅ Result: {result}")
if "success" in result.lower() or "filled" in result.lower():
print("✅ Username entry successful!")
return True
await asyncio.sleep(1)
except Exception as e:
print(f"❌ Command failed: {e}")
continue
print("⚠️ All username entry attempts completed")
return False
async def test_password_entry(self, password="testpassword123"):
"""Test entering password using voice commands"""
print(f"\n🔒 Testing password entry...")
password_commands = [
f"fill password with {password}",
f"enter {password} in password field",
f"type {password} in password",
f"password {password}",
f"pass {password}"
]
for command in password_commands:
print(f"\n🗣️ Voice Command: '{command}'")
try:
result = await self.mcp_client.process_natural_language_command(command)
print(f"✅ Result: {result}")
if "success" in result.lower() or "filled" in result.lower():
print("✅ Password entry successful!")
return True
await asyncio.sleep(1)
except Exception as e:
print(f"❌ Command failed: {e}")
continue
print("⚠️ All password entry attempts completed")
return False
async def test_login_button_click(self):
"""Test clicking the login button using voice commands"""
print(f"\n🔘 Testing login button click...")
login_commands = [
"click login button",
"press login",
"click sign in",
"press sign in button",
"login",
"sign in",
"click submit",
"press submit button"
]
for command in login_commands:
print(f"\n🗣️ Voice Command: '{command}'")
try:
result = await self.mcp_client.process_natural_language_command(command)
print(f"✅ Result: {result}")
if "success" in result.lower() or "clicked" in result.lower():
print("✅ Login button click successful!")
return True
await asyncio.sleep(1)
except Exception as e:
print(f"❌ Command failed: {e}")
continue
print("⚠️ All login button click attempts completed")
return False
async def run_live_test(self, username="test@example.com", password="testpassword123"):
"""Run the complete live test"""
print("🎤 QUBECARE LIVE LOGIN TEST")
print("=" * 60)
print(f"Testing enhanced voice agent with QuBeCare login")
print(f"URL: {self.qubecare_url}")
print(f"Username: {username}")
print(f"Password: {'*' * len(password)}")
print("=" * 60)
if not await self.setup():
print("❌ Test setup failed")
return False
try:
# Step 1: Navigate to QuBeCare
if not await self.navigate_to_qubecare():
print("❌ Navigation failed, aborting test")
return False
# Step 2: Analyze page structure
await self.analyze_login_page()
# Step 3: Test username entry
username_success = await self.test_username_entry(username)
# Step 4: Test password entry
password_success = await self.test_password_entry(password)
# Step 5: Test login button click
login_click_success = await self.test_login_button_click()
# Summary
print("\n📊 TEST SUMMARY")
print("=" * 40)
print(f"✅ Navigation: Success")
print(f"{'' if username_success else '⚠️ '} Username Entry: {'Success' if username_success else 'Partial'}")
print(f"{'' if password_success else '⚠️ '} Password Entry: {'Success' if password_success else 'Partial'}")
print(f"{'' if login_click_success else '⚠️ '} Login Click: {'Success' if login_click_success else 'Partial'}")
print("=" * 40)
overall_success = username_success and password_success and login_click_success
if overall_success:
print("🎉 LIVE TEST COMPLETED SUCCESSFULLY!")
else:
print("⚠️ LIVE TEST COMPLETED WITH PARTIAL SUCCESS")
return overall_success
except Exception as e:
print(f"❌ Live test failed: {e}")
return False
finally:
if self.mcp_client:
await self.mcp_client.disconnect()
async def interactive_qubecare_test():
"""Run an interactive test where users can try commands on QuBeCare"""
print("\n🎮 INTERACTIVE QUBECARE TEST")
print("=" * 50)
print("This will navigate to QuBeCare and let you test voice commands.")
# Get credentials from user
username = input("Enter test username (or press Enter for test@example.com): ").strip()
if not username:
username = "test@example.com"
password = input("Enter test password (or press Enter for testpassword123): ").strip()
if not password:
password = "testpassword123"
print(f"\nUsing credentials: {username} / {'*' * len(password)}")
print("=" * 50)
# Set up MCP client
chrome_config = {
'mcp_server_type': 'http',
'mcp_server_url': 'http://127.0.0.1:12306/mcp',
'mcp_server_command': None,
'mcp_server_args': []
}
mcp_client = MCPChromeClient(chrome_config)
try:
await mcp_client.connect()
print("✅ Connected to Chrome MCP server")
# Navigate to QuBeCare
print("🌐 Navigating to QuBeCare...")
await mcp_client.process_natural_language_command("navigate to https://app.qubecare.ai/provider/login")
await asyncio.sleep(3)
print("\n🎤 You can now try voice commands!")
print("Suggested commands:")
print(f"- fill email with {username}")
print(f"- fill password with {password}")
print("- click login button")
print("- show me form fields")
print("- what can I click")
print("\nType 'quit' to exit")
while True:
try:
command = input("\n🗣️ Enter voice command: ").strip()
if command.lower() == 'quit':
break
elif not command:
continue
print(f"🔄 Processing: {command}")
result = await mcp_client.process_natural_language_command(command)
print(f"✅ Result: {result}")
except KeyboardInterrupt:
break
except Exception as e:
print(f"❌ Error: {e}")
except Exception as e:
print(f"❌ Failed to connect to MCP server: {e}")
finally:
await mcp_client.disconnect()
print("\n👋 Interactive test ended")
async def main():
"""Main test function"""
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('qubecare_live_test.log')
]
)
print("🎤 QuBeCare Live Login Test")
print("Choose test mode:")
print("1. Automated Test (with default credentials)")
print("2. Automated Test (with custom credentials)")
print("3. Interactive Test")
try:
choice = input("\nEnter choice (1, 2, or 3): ").strip()
if choice == "1":
test = QuBeCareLiveTest()
success = await test.run_live_test()
return 0 if success else 1
elif choice == "2":
username = input("Enter username: ").strip()
password = input("Enter password: ").strip()
test = QuBeCareLiveTest()
success = await test.run_live_test(username, password)
return 0 if success else 1
elif choice == "3":
await interactive_qubecare_test()
return 0
else:
print("Invalid choice. Please enter 1, 2, or 3.")
return 1
except KeyboardInterrupt:
print("\n👋 Test interrupted by user")
return 0
except Exception as e:
print(f"❌ Test failed: {e}")
return 1
if __name__ == "__main__":
exit_code = asyncio.run(main())
sys.exit(exit_code)