Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
clean up test folder.
trohitg5c062c22f9f4
diff --git a/tests/android/check_android_errors.py b/tests/android/check_android_errors.pydeleted file mode 100644index fc82b8a3..00000000--- a/tests/android/check_android_errors.py+++ /dev/null@@ -1,62 +0,0 @@-#!/usr/bin/env python3-"""Check Android service responses for errors"""--import requests-import json--API_URL = "http://localhost:3010/api/workflow/execute-node"--SERVICES = [- ("batteryMonitor", "battery", "status"),- ("networkMonitor", "network", "status"),- ("systemInfo", "system_info", "status"),- ("location", "location", "status"),- ("appLauncher", "app_launcher", "launch"),- ("appList", "app_list", "status"),- ("wifiAutomation", "wifi_automation", "status"),- ("bluetoothAutomation", "bluetooth_automation", "status"),- ("audioAutomation", "audio_automation", "status"),- ("deviceStateAutomation", "device_state_automation", "status"),- ("screenControlAutomation", "screen_control_automation", "status"),- ("airplaneModeControl", "airplane_mode_control", "status"),- ("motionDetection", "motion_detection", "status"),- ("environmentalSensors", "environmental_sensors", "status"),- ("cameraControl", "camera_control", "status"),- ("mediaControl", "media_control", "status"),-]--errors_found = []--for node_type, service_id, action in SERVICES:- payload = {- "node_id": f"check-{node_type}",- "node_type": node_type,- "parameters": {- "service_id": service_id,- "action": action- }- }-- response = requests.post(API_URL, json=payload)- result = response.json()-- # Check if there's an error in the data- if result.get('success') and result.get('result'):- data = result['result'].get('data', {})- if 'error' in data:- errors_found.append({- 'node_type': node_type,- 'service_id': service_id,- 'action': action,- 'error': data['error']- })- print(f"ERROR in {node_type} ({service_id}/{action}):")- print(f" {data['error']}")- print()--if errors_found:- print(f"\nFound {len(errors_found)} services with errors:")- for err in errors_found:- print(f" - {err['node_type']}: {err['error']}")-else:- print("\nNo errors found in any service responses!")diff --git a/tests/android/test_android_nodes.py b/tests/android/test_android_nodes.pydeleted file mode 100644index 8ea8b8ac..00000000--- a/tests/android/test_android_nodes.py+++ /dev/null@@ -1,141 +0,0 @@-#!/usr/bin/env python3-"""-Android Service Nodes Integration Test-Tests all 16 individual Android service nodes-"""--import requests-import json-import time-from typing import Dict, Any--API_URL = "http://localhost:3010/api/workflow/execute-node"--# Service definitions: (node_type, service_id, action, category)-SERVICES = [- # System Monitoring (4)- ("batteryMonitor", "battery", "status", "System Monitoring"),- ("networkMonitor", "network", "status", "System Monitoring"),- ("systemInfo", "system_info", "info", "System Monitoring"), # Fixed: info not status- ("location", "location", "current", "System Monitoring"), # Fixed: current not status-- # App Management (2)- ("appLauncher", "app_launcher", "launch", "App Management"),- ("appList", "app_list", "list", "App Management"), # Fixed: list not status-- # Device Automation (6)- ("wifiAutomation", "wifi_automation", "status", "Device Automation"),- ("bluetoothAutomation", "bluetooth_automation", "status", "Device Automation"),- ("audioAutomation", "audio_automation", "get_volume", "Device Automation"), # Fixed: get_volume- ("deviceStateAutomation", "device_state_automation", "status", "Device Automation"),- ("screenControlAutomation", "screen_control_automation", "status", "Device Automation"),- ("airplaneModeControl", "airplane_mode_control", "status", "Device Automation"),-- # Sensors (2)- ("motionDetection", "motion_detection", "current_motion", "Sensors"), # Fixed: current_motion- ("environmentalSensors", "environmental_sensors", "ambient_conditions", "Sensors"), # Fixed: ambient_conditions-- # Media (2)- ("cameraControl", "camera_control", "camera_info", "Media"), # Fixed: camera_info- ("mediaControl", "media_control", "volume_control", "Media"), # Fixed: volume_control-]--def test_service(node_type: str, service_id: str, action: str) -> Dict[str, Any]:- """Test a single Android service node"""- node_id = f"{node_type}-test-{int(time.time()*1000)}"-- payload = {- "node_id": node_id,- "node_type": node_type,- "parameters": {- "service_id": service_id,- "android_host": "localhost",- "android_port": 8888,- "action": action,- "parameters": "{}"- }- }-- try:- response = requests.post(API_URL, json=payload, timeout=10)- result = response.json()-- success = result.get("success", False)- exec_time = result.get("execution_time", 0)-- # Check if it's actually calling Android API (not generic execution)- is_real_call = exec_time > 0.01 # Real Android calls take >10ms-- return {- "passed": success and is_real_call,- "exec_time": exec_time,- "response": result- }- except Exception as e:- return {- "passed": False,- "exec_time": 0,- "error": str(e)- }--def main():- print("=" * 60)- print("Android Service Nodes Integration Test")- print("=" * 60)- print()-- results = []- current_category = None-- for node_type, service_id, action, category in SERVICES:- # Print category header- if category != current_category:- if current_category is not None:- print()- print(f"\n{category} ({sum(1 for _, _, _, c in SERVICES if c == category)} nodes)")- print("-" * 60)- current_category = category-- print(f"Testing {node_type:25s} ({service_id}/{action})... ", end="", flush=True)-- result = test_service(node_type, service_id, action)- results.append((node_type, result))-- if result["passed"]:- exec_time = result["exec_time"]- print(f"PASS ({exec_time:.3f}s)")- else:- exec_time = result.get("exec_time", 0)- error = result.get("error", "Unknown error")- print(f"FAIL ({exec_time:.3f}s) - {error}")-- # Summary- print()- print("=" * 60)- print("Test Summary")- print("=" * 60)-- passed = sum(1 for _, r in results if r["passed"])- failed = len(results) - passed-- print(f"PASSED: {passed}/16")- print(f"FAILED: {failed}/16")- print()-- if failed > 0:- print("Failed services:")- for node_type, result in results:- if not result["passed"]:- error = result.get("error", "Low execution time")- print(f" - {node_type}: {error}")- print()-- if failed == 0:- print("All Android service nodes working correctly!")- return 0- else:- print(f"{failed} service(s) failed. Check Android device connection.")- return 1--if __name__ == "__main__":- exit(main())diff --git a/tests/android/test_android_service_remote.py b/tests/android/test_android_service_remote.pydeleted file mode 100644index 0e44dc29..00000000--- a/tests/android/test_android_service_remote.py+++ /dev/null@@ -1,212 +0,0 @@-#!/usr/bin/env python3-"""-Test Android Service Nodes with Remote WebSocket Connection-Tests that Android service nodes use WebSocket when remote device is configured-"""-import requests-import json-import time-import os--def test_android_device_setup():- """Step 1: Setup remote Android device connection"""- print("=" * 60)- print("Step 1: Android Device Setup (Remote WebSocket)")- print("=" * 60)-- url = "http://localhost:3010/api/nodes/execute"- payload = {- "nodeId": "android_device_001",- "nodeType": "androidDeviceSetup",- "parameters": {- "connection_type": "remote",- "websocket_url": os.getenv('WEBSOCKET_URL', ''),- "port": 8888- },- "inputs": {},- "workflow": {"nodes": [], "edges": []}- }-- try:- response = requests.post(url, json=payload, timeout=10)-- if response.status_code == 200:- result = response.json()- if result.get('success'):- print("\nDevice Setup: SUCCESS")- print(f" Connection Type: {result['result'].get('connection_type')}")- print(f" WebSocket URL: {result['result'].get('websocket_url')}")- print(f" Client ID: {result['result'].get('client_id')}")- print(f" Status: {result['result'].get('status')}")- return True- else:- print(f"\nDevice Setup: FAILED - {result.get('error')}")- return False- else:- print(f"\nDevice Setup: HTTP {response.status_code}")- return False-- except Exception as e:- print(f"\nDevice Setup: ERROR - {e}")- return False---def test_battery_monitor_service():- """Step 2: Test Battery Monitor service via WebSocket"""- print("\n" + "=" * 60)- print("Step 2: Battery Monitor Service (via WebSocket)")- print("=" * 60)-- url = "http://localhost:3010/api/nodes/execute"- payload = {- "nodeId": "battery_node_001",- "nodeType": "batteryMonitor",- "parameters": {- "service_id": "battery",- "action": "status",- "parameters": {}- },- "inputs": {},- "workflow": {"nodes": [], "edges": []}- }-- try:- response = requests.post(url, json=payload, timeout=15)-- if response.status_code == 200:- result = response.json()- print(f"\nResponse:")- print(json.dumps(result, indent=2))-- if result.get('success'):- service_result = result.get('result', {})- data = service_result.get('data', {})-- print("\nBattery Monitor: SUCCESS")- print(f" Connection Type: {service_result.get('connection_type')}")- print(f" Battery Level: {data.get('level')}%")- print(f" Charging: {data.get('charging')}")- print(f" Temperature: {data.get('temperature')}°C")- print(f" Health: {data.get('health')}")-- if service_result.get('connection_type') == 'remote_websocket':- print("\n[OK] Service used WebSocket connection!")- return True- else:- print("\n[ERROR] Service did NOT use WebSocket connection")- return False- else:- print(f"\nBattery Monitor: FAILED - {result.get('error')}")- return False- else:- print(f"\nBattery Monitor: HTTP {response.status_code}")- print(response.text)- return False-- except Exception as e:- print(f"\nBattery Monitor: ERROR - {e}")- import traceback- traceback.print_exc()- return False---def test_location_service():- """Step 3: Test Location service via WebSocket"""- print("\n" + "=" * 60)- print("Step 3: Location Service (via WebSocket)")- print("=" * 60)-- url = "http://localhost:3010/api/nodes/execute"- payload = {- "nodeId": "location_node_001",- "nodeType": "location",- "parameters": {- "service_id": "location",- "action": "current",- "parameters": {}- },- "inputs": {},- "workflow": {"nodes": [], "edges": []}- }-- try:- response = requests.post(url, json=payload, timeout=15)-- if response.status_code == 200:- result = response.json()-- if result.get('success'):- service_result = result.get('result', {})- data = service_result.get('data', {})-- print("\nLocation Service: SUCCESS")- print(f" Connection Type: {service_result.get('connection_type')}")- print(f" Latitude: {data.get('latitude')}")- print(f" Longitude: {data.get('longitude')}")- print(f" Accuracy: {data.get('accuracy')}m")- print(f" Provider: {data.get('provider')}")-- if service_result.get('connection_type') == 'remote_websocket':- print("\n[OK] Service used WebSocket connection!")- return True- else:- print("\n[ERROR] Service did NOT use WebSocket connection")- return False- else:- print(f"\nLocation Service: FAILED - {result.get('error')}")- return False- else:- print(f"\nLocation Service: HTTP {response.status_code}")- return False-- except Exception as e:- print(f"\nLocation Service: ERROR - {e}")- import traceback- traceback.print_exc()- return False---if __name__ == "__main__":- print("\n" + "=" * 60)- print("Android Service Remote WebSocket Test")- print("=" * 60)- print("\nPrerequisite: Android device simulator must be running")- print("Run: python test_android_simulator.py\n")-- time.sleep(2)-- # Test sequence- results = []-- # Step 1: Setup remote connection- results.append(("Device Setup", test_android_device_setup()))-- if results[0][1]:- # Give WebSocket time to stabilize- time.sleep(1)-- # Step 2: Test battery service- results.append(("Battery Monitor", test_battery_monitor_service()))-- # Step 3: Test location service- results.append(("Location Service", test_location_service()))- else:- print("\n[ERROR] Skipping service tests due to setup failure")-- # Summary- print("\n" + "=" * 60)- print("Test Summary")- print("=" * 60)- for test_name, passed in results:- status = "PASSED" if passed else "FAILED"- print(f" {test_name}: {status}")-- all_passed = all(result[1] for result in results)- print("\n" + "=" * 60)- if all_passed:- print("All Tests PASSED!")- else:- print("Some Tests FAILED!")- print("=" * 60)-- exit(0 if all_passed else 1)diff --git a/tests/android/test_android_service_request.py b/tests/android/test_android_service_request.pydeleted file mode 100644index cde32051..00000000--- a/tests/android/test_android_service_request.py+++ /dev/null@@ -1,131 +0,0 @@-#!/usr/bin/env python3-"""-Test Android Service Request-Response Pattern-Demonstrates how Android device only responds to specific service requests--Before running: export WEBSOCKET_API_KEY=your-key-"""-import asyncio-import json-import os-import sys-import aiohttp-from aiohttp import ClientWSTimeout--# Load from environment - NO FALLBACK-WEBSOCKET_API_KEY = os.getenv('WEBSOCKET_API_KEY')-WEBSOCKET_URL = os.getenv('WEBSOCKET_URL', '')--if not WEBSOCKET_API_KEY:- print("ERROR: WEBSOCKET_API_KEY environment variable not set")- print("Usage: WEBSOCKET_API_KEY=your-key python test_android_service_request.py")- sys.exit(1)--async def test_service_request():- """Test requesting specific services from Android device"""-- print("=" * 60)- print("Android Service Request-Response Test")- print("=" * 60)-- # Configuration- url = WEBSOCKET_URL- web_api_key = WEBSOCKET_API_KEY- web_client_id = "test_web_requester"-- # Connect as Web client- print("\n[Web Client] Connecting...")- session = aiohttp.ClientSession()- ws = await session.ws_connect(url, timeout=ClientWSTimeout(ws_close=10.0))-- # Wait for welcome- msg = await asyncio.wait_for(ws.receive(), timeout=5.0)- welcome = json.loads(msg.data)- print(f"[Web Client] {welcome.get('message')}")-- # Register- await ws.send_json({- "type": "register",- "clientType": "web",- "clientId": web_client_id,- "apiKey": web_api_key- })-- msg = await asyncio.wait_for(ws.receive(), timeout=5.0)- register_response = json.loads(msg.data)- print(f"[Web Client] Registered: {register_response.get('type')}")-- # Request battery status from Android device- print("\n[Web Client] Requesting battery status from Android device...")- await ws.send_json({- "type": "data",- "payload": {- "action": "get_battery_status",- "service": "batteryMonitor"- }- })-- # Wait for response from Android- print("[Web Client] Waiting for Android response...")- try:- msg = await asyncio.wait_for(ws.receive(), timeout=10.0)- if msg.type == aiohttp.WSMsgType.TEXT:- response = json.loads(msg.data)- print(f"\n[Web Client] Received response:")- print(json.dumps(response, indent=2))-- if response.get('type') == 'data':- payload = response.get('payload', {})- data = payload.get('data', {})- print(f"\n[Android Response]")- print(f" Service: {payload.get('service')}")- print(f" Battery Level: {data.get('level')}%")- print(f" Charging: {data.get('charging')}")- print(f" Temperature: {data.get('temperature')}°C")- print(f" Health: {data.get('health')}")- except asyncio.TimeoutError:- print("[Web Client] No response from Android device (timeout)")- print("Make sure Android simulator is running")-- # Request location data- print("\n[Web Client] Requesting location from Android device...")- await ws.send_json({- "type": "data",- "payload": {- "action": "get_location",- "service": "location"- }- })-- # Wait for response- print("[Web Client] Waiting for Android response...")- try:- msg = await asyncio.wait_for(ws.receive(), timeout=10.0)- if msg.type == aiohttp.WSMsgType.TEXT:- response = json.loads(msg.data)-- if response.get('type') == 'data':- payload = response.get('payload', {})- data = payload.get('data', {})- print(f"\n[Android Response]")- print(f" Service: {payload.get('service')}")- print(f" Latitude: {data.get('latitude')}")- print(f" Longitude: {data.get('longitude')}")- print(f" Accuracy: {data.get('accuracy')}m")- print(f" Provider: {data.get('provider')}")- except asyncio.TimeoutError:- print("[Web Client] No response from Android device (timeout)")-- # Disconnect- await ws.close()- await session.close()-- print("\n" + "=" * 60)- print("Test Complete")- print("=" * 60)--if __name__ == "__main__":- try:- asyncio.run(test_service_request())- except KeyboardInterrupt:- print("\n\nTest stopped by user")diff --git a/tests/android/test_android_simulator.py b/tests/android/test_android_simulator.pydeleted file mode 100644index 69910cde..00000000--- a/tests/android/test_android_simulator.py+++ /dev/null@@ -1,524 +0,0 @@-#!/usr/bin/env python3-"""-Simulated Android Device - Sends dummy data through WebSocket-Simulates battery, location, and other sensor data--Required environment variables:- WEBSOCKET_URL - WebSocket server URL (required)- ANDROID_API_KEY - API key for WebSocket authentication-"""-import asyncio-import json-import os-import aiohttp-from aiohttp import ClientWSTimeout-from datetime import datetime-import random--class AndroidDeviceSimulator:- """Simulates an Android device sending sensor data"""-- def __init__(self, url: str, api_key: str, device_id: str):- self.url = url- self.api_key = api_key- self.device_id = device_id- self.ws = None- self.session = None- self.running = False-- async def connect(self):- """Connect to WebSocket and register"""- print(f"[ANDROID DEVICE] Connecting to {self.url}")-- self.session = aiohttp.ClientSession()- self.ws = await self.session.ws_connect(- self.url,- timeout=ClientWSTimeout(ws_close=10.0)- )-- # Wait for welcome- msg = await asyncio.wait_for(self.ws.receive(), timeout=5.0)- welcome = json.loads(msg.data)- print(f"[ANDROID DEVICE] {welcome.get('message')}")-- # Register as Android device- register_msg = {- "type": "register",- "clientType": "android",- "clientId": self.device_id,- "apiKey": self.api_key- }- await self.ws.send_json(register_msg)- print(f"[ANDROID DEVICE] Sent registration")-- # Wait for registration response- msg = await asyncio.wait_for(self.ws.receive(), timeout=5.0)- reg_response = json.loads(msg.data)-- if reg_response.get('type') == 'registered':- print(f"[ANDROID DEVICE] Registered as: {reg_response.get('clientId')}")- self.running = True- return True- else:- print(f"[ANDROID DEVICE] Registration failed: {reg_response}")- return False-- async def send_battery_status(self):- """Send battery status data"""- battery_level = random.randint(20, 100)- charging = random.choice([True, False])- temperature = round(random.uniform(25.0, 45.0), 1)-- data = {- "type": "data",- "payload": {- "service": "battery",- "action": "status",- "data": {- "level": battery_level,- "charging": charging,- "temperature": temperature,- "voltage": round(random.uniform(3.7, 4.2), 2),- "health": "good",- "technology": "Li-ion"- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent battery status: {battery_level}% {'(charging)' if charging else ''} {temperature}°C")-- async def send_location_data(self):- """Send GPS location data"""- # Simulate location in San Francisco area- lat = round(37.7749 + random.uniform(-0.1, 0.1), 6)- lng = round(-122.4194 + random.uniform(-0.1, 0.1), 6)- accuracy = round(random.uniform(5.0, 20.0), 1)-- data = {- "type": "data",- "payload": {- "service": "location",- "action": "get_location",- "data": {- "latitude": lat,- "longitude": lng,- "accuracy": accuracy,- "altitude": round(random.uniform(0, 100), 1),- "provider": "gps",- "speed": round(random.uniform(0, 5), 1)- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent location: {lat}, {lng} (±{accuracy}m)")-- async def send_system_info(self):- """Send system information"""- data = {- "type": "data",- "payload": {- "service": "system_info",- "action": "get_info",- "data": {- "android_version": "14",- "api_level": 34,- "device_model": "Pixel 8",- "manufacturer": "Google",- "total_memory": 8192,- "available_memory": random.randint(2000, 5000),- "storage_total": 128000,- "storage_available": random.randint(40000, 80000)- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent system info: Pixel 8, Android 14")-- async def send_network_status(self):- """Send network status"""- network_type = random.choice(["WIFI", "MOBILE"])- data = {- "type": "data",- "payload": {- "service": "network",- "action": "get_status",- "data": {- "connected": True,- "type": network_type,- "internet_available": True,- "wifi_ssid": "Home-WiFi" if network_type == "WIFI" else None,- "signal_strength": random.randint(1, 5)- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent network status: {network_type}")-- async def send_app_list(self):- """Send list of installed applications"""- apps = [- {"package": "com.google.android.gms", "name": "Google Play Services", "version": "23.45.12"},- {"package": "com.android.chrome", "name": "Chrome", "version": "120.0.6099"},- {"package": "com.whatsapp", "name": "WhatsApp", "version": "2.23.24.9"},- {"package": "com.spotify.music", "name": "Spotify", "version": "8.8.94.527"},- {"package": "com.instagram.android", "name": "Instagram", "version": "308.0.0.38.112"}- ]-- data = {- "type": "data",- "payload": {- "service": "app_list",- "action": "get_apps",- "data": {- "apps": apps,- "total_count": len(apps)- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent app list: {len(apps)} apps")-- async def send_wifi_status(self):- """Send WiFi automation status"""- enabled = random.choice([True, False])- data = {- "type": "data",- "payload": {- "service": "wifi_automation",- "action": "get_status",- "data": {- "enabled": enabled,- "connected": enabled,- "ssid": "Home-WiFi" if enabled else None,- "ip_address": f"192.168.1.{random.randint(100, 200)}" if enabled else None,- "signal_strength": random.randint(-70, -30) if enabled else None- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent WiFi status: {'enabled' if enabled else 'disabled'}")-- async def send_bluetooth_status(self):- """Send Bluetooth automation status"""- enabled = random.choice([True, False])- paired_devices = [- {"name": "AirPods Pro", "address": "00:1A:7D:DA:71:13", "connected": True},- {"name": "Car Bluetooth", "address": "F8:16:54:A6:01:28", "connected": False}- ] if enabled else []-- data = {- "type": "data",- "payload": {- "service": "bluetooth_automation",- "action": "get_status",- "data": {- "enabled": enabled,- "paired_devices": paired_devices,- "connected_devices": [d for d in paired_devices if d.get("connected")]- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent Bluetooth status: {'enabled' if enabled else 'disabled'}")-- async def send_audio_status(self):- """Send audio automation status"""- data = {- "type": "data",- "payload": {- "service": "audio_automation",- "action": "get_volume",- "data": {- "music_volume": random.randint(0, 15),- "ring_volume": random.randint(0, 7),- "alarm_volume": random.randint(0, 7),- "notification_volume": random.randint(0, 7),- "muted": random.choice([True, False])- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent audio status")-- async def send_device_state(self):- """Send device state automation status"""- data = {- "type": "data",- "payload": {- "service": "device_state_automation",- "action": "get_state",- "data": {- "airplane_mode": random.choice([True, False]),- "screen_on": random.choice([True, False]),- "power_save_mode": random.choice([True, False]),- "brightness": random.randint(0, 255),- "auto_brightness": random.choice([True, False])- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent device state")-- async def send_screen_control(self):- """Send screen control status"""- data = {- "type": "data",- "payload": {- "service": "screen_control_automation",- "action": "get_brightness",- "data": {- "brightness": random.randint(0, 255),- "auto_brightness": random.choice([True, False]),- "screen_timeout": random.choice([15000, 30000, 60000, 300000]),- "screen_on": random.choice([True, False])- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent screen control status")-- async def send_motion_data(self):- """Send motion detection sensor data"""- data = {- "type": "data",- "payload": {- "service": "motion_detection",- "action": "get_sensors",- "data": {- "accelerometer": {- "x": round(random.uniform(-10, 10), 3),- "y": round(random.uniform(-10, 10), 3),- "z": round(random.uniform(-10, 10), 3)- },- "gyroscope": {- "x": round(random.uniform(-2, 2), 3),- "y": round(random.uniform(-2, 2), 3),- "z": round(random.uniform(-2, 2), 3)- },- "orientation": random.choice(["portrait", "landscape"]),- "motion_detected": random.choice([True, False])- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent motion sensor data")-- async def send_environmental_sensors(self):- """Send environmental sensor data"""- data = {- "type": "data",- "payload": {- "service": "environmental_sensors",- "action": "get_sensors",- "data": {- "temperature": round(random.uniform(20.0, 30.0), 1),- "humidity": round(random.uniform(30.0, 70.0), 1),- "pressure": round(random.uniform(990.0, 1020.0), 1),- "light_level": random.randint(0, 50000)- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent environmental sensor data")-- async def send_camera_info(self):- """Send camera control info"""- data = {- "type": "data",- "payload": {- "service": "camera_control",- "action": "get_info",- "data": {- "camera_count": 3,- "cameras": [- {"id": 0, "facing": "back", "megapixels": 50},- {"id": 1, "facing": "front", "megapixels": 12},- {"id": 2, "facing": "back", "megapixels": 12, "type": "ultrawide"}- ],- "flash_available": True- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent camera info")-- async def send_media_control_status(self):- """Send media control status"""- data = {- "type": "data",- "payload": {- "service": "media_control",- "action": "get_status",- "data": {- "playing": random.choice([True, False]),- "track": "Shape of You - Ed Sheeran",- "duration": 233000,- "position": random.randint(0, 233000),- "volume": random.randint(0, 100)- },- "timestamp": datetime.now().isoformat()- }- }-- await self.ws.send_json(data)- print(f"[ANDROID DEVICE] Sent media control status")-- async def listen_for_commands(self):- """Listen for commands from Web clients"""- while self.running:- try:- msg = await asyncio.wait_for(self.ws.receive(), timeout=2.0)-- if msg.type == aiohttp.WSMsgType.TEXT:- data = json.loads(msg.data)-- if data.get('type') == 'data':- payload = data.get('payload', {})- action = payload.get('action')- service = payload.get('service')-- print(f"\n[ANDROID DEVICE] Received command: {service}/{action}")-- # Respond based on service and action- # Official service IDs from androidServiceNodes.ts- if service == 'battery':- await self.send_battery_status()- elif service == 'location':- await self.send_location_data()- elif service == 'system_info':- await self.send_system_info()- elif service == 'network':- await self.send_network_status()- elif service == 'app_list':- await self.send_app_list()- elif service == 'app_launcher':- await self.send_app_list()- elif service == 'wifi_automation':- await self.send_wifi_status()- elif service == 'bluetooth_automation':- await self.send_bluetooth_status()- elif service == 'audio_automation':- await self.send_audio_status()- elif service == 'device_state_automation':- await self.send_device_state()- elif service == 'screen_control_automation':- await self.send_screen_control()- elif service == 'airplane_mode_control':- await self.send_device_state()- elif service == 'motion_detection':- await self.send_motion_data()- elif service == 'environmental_sensors':- await self.send_environmental_sensors()- elif service == 'camera_control':- await self.send_camera_info()- elif service == 'media_control':- await self.send_media_control_status()- else:- print(f"[ANDROID DEVICE] Unknown service/action: {service}/{action}")-- elif msg.type == aiohttp.WSMsgType.CLOSED:- print("[ANDROID DEVICE] Connection closed")- self.running = False- break-- except asyncio.TimeoutError:- # No message, continue listening- continue- except Exception as e:- print(f"[ANDROID DEVICE] Error: {e}")- break-- async def run_service(self):- """Run as background service - only responds to requests"""- print("\n[ANDROID DEVICE] Service started")- print("[ANDROID DEVICE] Simulating all 17 Android service nodes")- print("[ANDROID DEVICE] Listening for commands - will only send data when requested")- print("[ANDROID DEVICE] Press Ctrl+C to stop\n")-- try:- # Run command listener indefinitely- await self.listen_for_commands()-- except KeyboardInterrupt:- print("\n[ANDROID DEVICE] Service stopped by user")- self.running = False-- async def disconnect(self):- """Disconnect from WebSocket"""- if self.ws:- await self.ws.close()- print("[ANDROID DEVICE] Disconnected")- if self.session:- await self.session.close()---async def main():- print("=" * 60)- print("Android Device Simulator - Background Service")- print("Responds to Android service requests via WebSocket")- print("=" * 60)-- # Configuration from environment variables- url = os.getenv("WEBSOCKET_URL")- android_api_key = os.getenv("ANDROID_API_KEY")-- if not url:- print("[ERROR] WEBSOCKET_URL environment variable is required")- print("[ERROR] Set it with: export WEBSOCKET_URL=ws://your-server/ws")- return-- if not android_api_key:- print("[ERROR] ANDROID_API_KEY environment variable is required")- print("[ERROR] Set it with: export ANDROID_API_KEY=your-api-key")- return- device_id = f"android_pixel8_{int(datetime.now().timestamp())}"-- # Create simulator- simulator = AndroidDeviceSimulator(url, android_api_key, device_id)-- # Connect- if await simulator.connect():- # Run as background service (runs indefinitely until Ctrl+C)- await simulator.run_service()- else:- print("[ANDROID DEVICE] Failed to connect")-- # Disconnect- await simulator.disconnect()-- print("\n" + "=" * 60)- print("Service Stopped")- print("=" * 60)---if __name__ == "__main__":- try:- asyncio.run(main())- except KeyboardInterrupt:- print("\n\nService stopped by user")diff --git a/tests/fixtures/test_battery.json b/tests/fixtures/test_battery.jsondeleted file mode 100644index 60df73c7..00000000--- a/tests/fixtures/test_battery.json+++ /dev/null@@ -1,10 +0,0 @@-{- "node_id": "battery_1",- "node_type": "batteryMonitor",- "parameters": {- "service_id": "battery",- "action": "status",- "parameters": {}- },- "connected_nodes": {}-}diff --git a/tests/fixtures/test_config.json b/tests/fixtures/test_config.jsondeleted file mode 100644index 23db2df8..00000000--- a/tests/fixtures/test_config.json+++ /dev/null@@ -1,10 +0,0 @@-{- "node_id": "test_setup",- "node_type": "androidDeviceSetup",- "parameters": {- "connection_type": "remote",- "websocket_url": "",- "port": 8888- },- "connected_nodes": {}-}diff --git a/tests/fixtures/test_setup.json b/tests/fixtures/test_setup.jsondeleted file mode 100644index 829a3fd9..00000000--- a/tests/fixtures/test_setup.json+++ /dev/null@@ -1,10 +0,0 @@-{- "node_id": "setup_1",- "node_type": "androidDeviceSetup",- "parameters": {- "connection_type": "remote",- "websocket_url": "",- "port": 8888- },- "connected_nodes": {}-}diff --git a/tests/websocket/test_websocket.py b/tests/websocket/test_websocket.pydeleted file mode 100644index 3b753a54..00000000--- a/tests/websocket/test_websocket.py+++ /dev/null@@ -1,348 +0,0 @@-#!/usr/bin/env python3-"""-Test WebSocket connection for remote Android devices--Before running, set environment variables:- export WEBSOCKET_API_KEY=your-web-api-key- export ANDROID_API_KEY=your-android-api-key (optional, for bidirectional test)- export WEBSOCKET_URL=ws://your-relay-server.com/ws-"""-import asyncio-import json-import os-import sys-import aiohttp--# Load from environment - NO FALLBACK-WEBSOCKET_API_KEY = os.getenv('WEBSOCKET_API_KEY')-ANDROID_API_KEY = os.getenv('ANDROID_API_KEY')-WEBSOCKET_URL = os.getenv('WEBSOCKET_URL', '')--if not WEBSOCKET_API_KEY:- print("ERROR: WEBSOCKET_API_KEY environment variable not set")- print("Usage: WEBSOCKET_API_KEY=your-key python test_websocket.py")- sys.exit(1)--async def test_health_endpoint():- """Test the WebSocket health endpoint"""- base = WEBSOCKET_URL.replace('ws://', 'http://').replace('wss://', 'https://').rstrip('/ws')- url = f"{base}/ws-health"- print(f"\nTesting health endpoint: {url}")-- try:- async with aiohttp.ClientSession() as session:- async with session.get(url, timeout=10) as response:- print(f"Status: {response.status}")- content = await response.text()- print(f"Response: {content}")-- if response.status == 200:- print("Health check: PASSED")- return True- else:- print("Health check: FAILED")- return False- except Exception as e:- print(f"Health check error: {e}")- return False--async def test_stats_endpoint():- """Test the WebSocket stats endpoint"""- base = WEBSOCKET_URL.replace('ws://', 'http://').replace('wss://', 'https://').rstrip('/ws')- url = f"{base}/ws-stats"- print(f"\nTesting stats endpoint: {url}")-- try:- async with aiohttp.ClientSession() as session:- async with session.get(url, timeout=10) as response:- print(f"Status: {response.status}")- content = await response.text()- print(f"Response: {content}")-- if response.status == 200:- print("Stats check: PASSED")- return True- else:- print("Stats check: FAILED")- return False- except Exception as e:- print(f"Stats check error: {e}")- return False--async def test_websocket_connection():- """Test WebSocket connection with API key authentication"""- url = WEBSOCKET_URL- web_api_key = WEBSOCKET_API_KEY-- print(f"\nTesting WebSocket connection: {url}")- print(f"Using Web API Key: {web_api_key[:20]}...")-- try:- async with aiohttp.ClientSession() as session:- async with session.ws_connect(url, timeout=10) as ws:- print("WebSocket connection: ESTABLISHED")-- # Wait for initial "connected" message- try:- msg = await asyncio.wait_for(ws.receive(), timeout=5.0)- if msg.type == aiohttp.WSMsgType.TEXT:- data = json.loads(msg.data)- print(f"Received welcome: {data}")-- if data.get('type') != 'connected':- print("Unexpected welcome message")- return False- except asyncio.TimeoutError:- print("No welcome message received")- return False-- # Now send registration with API key- register_message = {- "type": "register",- "clientType": "web",- "clientId": "test_client_001",- "apiKey": web_api_key- }- await ws.send_json(register_message)- print(f"Sent registration: {register_message}")-- # Wait for registration response- try:- msg = await asyncio.wait_for(ws.receive(), timeout=5.0)- print(f"Received: {msg.data}")-- if msg.type == aiohttp.WSMsgType.TEXT:- data = json.loads(msg.data)- print(f"Parsed response: {data}")-- if data.get('type') == 'registered':- print("Registration: SUCCESS")- print(f"Client ID: {data.get('clientId')}")-- # Test sending data message- data_message = {- "type": "data",- "payload": {- "action": "test",- "timestamp": asyncio.get_event_loop().time()- }- }- await ws.send_json(data_message)- print(f"Sent data message: {data_message}")-- # Wait for any response (timeout is expected if no Android client)- try:- msg2 = await asyncio.wait_for(ws.receive(), timeout=3.0)- if msg2.type == aiohttp.WSMsgType.TEXT:- response = json.loads(msg2.data)- print(f"Response to data: {response}")- except asyncio.TimeoutError:- print("No response to data message (expected - no Android clients)")-- # Test ping/pong- ping_message = {"type": "ping"}- await ws.send_json(ping_message)- print(f"Sent ping: {ping_message}")-- try:- msg3 = await asyncio.wait_for(ws.receive(), timeout=3.0)- if msg3.type == aiohttp.WSMsgType.TEXT:- pong = json.loads(msg3.data)- print(f"Received pong: {pong}")- if pong.get('type') == 'pong':- print("Ping/Pong: SUCCESS")- except asyncio.TimeoutError:- print("No pong response")-- print("WebSocket test: PASSED")- return True- elif data.get('type') == 'error':- print(f"Registration FAILED: {data.get('message')}")- print("WebSocket test: FAILED")- return False-- except asyncio.TimeoutError:- print("No registration response received (timeout)")- print("WebSocket test: FAILED")- return False-- except aiohttp.ClientConnectorError as e:- print(f"Connection error: {e}")- return False- except Exception as e:- print(f"WebSocket error: {e}")- import traceback- traceback.print_exc()- return False--async def test_android_to_web_flow():- """Test Android -> WebSocket -> Web bidirectional data flow"""- url = WEBSOCKET_URL- web_api_key = WEBSOCKET_API_KEY- android_api_key = ANDROID_API_KEY-- if not android_api_key:- print(f"\nSkipping Android -> WebSocket -> Web bidirectional flow test")- print("ANDROID_API_KEY not set in environment")- return True # Don't fail, just skip-- print(f"\nTesting Android -> WebSocket -> Web bidirectional flow")- print("=" * 60)-- try:- async with aiohttp.ClientSession() as session:- # Step 1: Connect Web client- print("\n[WEB] Connecting...")- web_ws = await session.ws_connect(url, timeout=10)- msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)- print(f"[WEB] {json.loads(msg.data).get('message')}")-- # Register Web client- await web_ws.send_json({- "type": "register",- "clientType": "web",- "clientId": "test_web_001",- "apiKey": web_api_key- })-- msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)- web_reg = json.loads(msg.data)- if web_reg.get('type') != 'registered':- print(f"[WEB] Registration FAILED: {web_reg}")- return False- print(f"[WEB] Registered as: {web_reg.get('clientId')}")-- # Step 2: Connect Android client- print("\n[ANDROID] Connecting...")- android_ws = await session.ws_connect(url, timeout=10)- msg = await asyncio.wait_for(android_ws.receive(), timeout=5.0)- print(f"[ANDROID] {json.loads(msg.data).get('message')}")-- # Register Android client- await android_ws.send_json({- "type": "register",- "clientType": "android",- "clientId": "test_android_001",- "apiKey": android_api_key- })-- msg = await asyncio.wait_for(android_ws.receive(), timeout=5.0)- android_reg = json.loads(msg.data)- if android_reg.get('type') != 'registered':- print(f"[ANDROID] Registration FAILED: {android_reg}")- return False- print(f"[ANDROID] Registered as: {android_reg.get('clientId')}")-- # Web should receive join notification- try:- msg = await asyncio.wait_for(web_ws.receive(), timeout=3.0)- notif = json.loads(msg.data)- if notif.get('type') == 'client_joined':- print(f"[WEB] Notification: Android client {notif.get('clientId')} joined")- except asyncio.TimeoutError:- pass-- # Step 3: Android sends battery data broadcast- print("\n[ANDROID] Broadcasting battery status...")- await android_ws.send_json({- "type": "data",- "payload": {- "service": "battery",- "level": 85,- "charging": True- }- })-- msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)- data = json.loads(msg.data)- if data.get('type') == 'data' and data.get('fromType') == 'android':- print(f"[WEB] Received from Android: {data.get('payload')}")- else:- print(f"[WEB] Unexpected message: {data}")- return False-- # Step 4: Web sends targeted command to Android- print("\n[WEB] Sending targeted command to Android...")- await web_ws.send_json({- "type": "data",- "targetId": "test_android_001",- "payload": {"action": "get_location"}- })-- msg = await asyncio.wait_for(android_ws.receive(), timeout=5.0)- cmd = json.loads(msg.data)- if cmd.get('type') == 'data' and cmd.get('fromType') == 'web':- print(f"[ANDROID] Received command: {cmd.get('payload')}")- else:- print(f"[ANDROID] Unexpected message: {cmd}")- return False-- # Step 5: Android responds with location- print("\n[ANDROID] Sending location response...")- await android_ws.send_json({- "type": "data",- "targetId": "test_web_001",- "payload": {- "service": "location",- "lat": 37.7749,- "lng": -122.4194- }- })-- msg = await asyncio.wait_for(web_ws.receive(), timeout=5.0)- loc = json.loads(msg.data)- if loc.get('type') == 'data' and loc.get('fromType') == 'android':- payload = loc.get('payload')- print(f"[WEB] Received location: {payload.get('lat')}, {payload.get('lng')}")- print("\nBidirectional flow test: PASSED")- await web_ws.close()- await android_ws.close()- return True-- await web_ws.close()- await android_ws.close()- return False-- except Exception as e:- print(f"Flow test error: {e}")- import traceback- traceback.print_exc()- return False---async def main():- print("=" * 60)- print("WebSocket Connection Test for Remote Android Devices")- print("=" * 60)-- results = {- "health": await test_health_endpoint(),- "stats": await test_stats_endpoint(),- "websocket": await test_websocket_connection(),- "android_web_flow": await test_android_to_web_flow()- }-- print("\n" + "=" * 60)- print("Test Results Summary")- print("=" * 60)- for test_name, result in results.items():- status = "PASS" if result else "FAIL"- print(f"{test_name.upper()}: {status}")-- all_passed = all(results.values())- print("\n" + "=" * 60)- if all_passed:- print("Overall: ALL TESTS PASSED")- else:- print("Overall: SOME TESTS FAILED")- print("=" * 60)-- return all_passed--if __name__ == "__main__":- try:- result = asyncio.run(main())- exit(0 if result else 1)- except KeyboardInterrupt:- print("\nTest interrupted by user")- exit(1)diff --git a/tests/websocket/test_workflow_websocket.py b/tests/websocket/test_workflow_websocket.pydeleted file mode 100644index e5d0812c..00000000--- a/tests/websocket/test_workflow_websocket.py+++ /dev/null@@ -1,90 +0,0 @@-#!/usr/bin/env python3-"""-Test WebSocket connection from React Flow workflow node-Simulates executing the androidDeviceSetup node with remote connection-"""-import requests-import json-import os--def test_android_device_setup_remote():- """Test Android Device Setup node with remote WebSocket connection"""-- print("Testing Android Device Setup Node - Remote WebSocket")- print("=" * 60)-- # Workflow execution endpoint- url = "http://localhost:3010/api/nodes/execute"-- # Simulate androidDeviceSetup node execution with remote connection- payload = {- "nodeId": "test_node_001",- "nodeType": "androidDeviceSetup",- "parameters": {- "connection_type": "remote",- "websocket_url": os.getenv('WEBSOCKET_URL', ''),- "port": 8888- },- "inputs": {},- "workflow": {- "nodes": [],- "edges": []- }- }-- print(f"\nSending request to: {url}")- print(f"Payload: {json.dumps(payload, indent=2)}")-- try:- response = requests.post(url, json=payload, timeout=30)-- print(f"\nResponse Status: {response.status_code}")- print(f"Response Body:")- print(json.dumps(response.json(), indent=2))-- if response.status_code == 200:- result = response.json()-- if result.get('success'):- connection_info = result.get('result', {})- print("\nWebSocket Connection: SUCCESS")- print(f" Client ID: {connection_info.get('client_id')}")- print(f" Status: {connection_info.get('status')}")- print(f" Registered: {connection_info.get('registered')}")- print(f" WebSocket URL: {connection_info.get('websocket_url')}")- print(f" Message: {connection_info.get('message')}")- return True- else:- print(f"\nWebSocket Connection: FAILED")- print(f" Error: {result.get('error')}")- return False- else:- print(f"\nHTTP Request FAILED: {response.status_code}")- return False-- except requests.exceptions.ConnectionError:- print("\nERROR: Cannot connect to backend server")- print("Make sure the Python backend is running on http://localhost:3010")- return False- except Exception as e:- print(f"\nERROR: {e}")- import traceback- traceback.print_exc()- return False---if __name__ == "__main__":- print("\n" + "=" * 60)- print("React Flow Node WebSocket Test")- print("=" * 60)-- result = test_android_device_setup_remote()-- print("\n" + "=" * 60)- if result:- print("Test Result: PASSED")- else:- print("Test Result: FAILED")- print("=" * 60)-- exit(0 if result else 1)