Spaces:
Sleeping
Sleeping
File size: 5,573 Bytes
1bb4678 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | # Path: QAgents-workflos/tests/test_mcp_client.py
# Relations: Tests client/mcp_client.py
# Description: Comprehensive tests for MCP client with Gradio and fallback implementations
"""
Test suite for MCP client functionality.
Tests both Gradio-based endpoints and local fallback implementations.
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from client.mcp_client import get_client, MCPClient, QASMLocalAnalyzer
# Sample QASM for testing
BELL_STATE_QASM = '''OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0], q[1];
measure q -> c;'''
def test_health_check():
"""Test server health check."""
client = get_client()
result = client.health_check()
print(f"Health Check: {'OK' if result else 'FAILED'}")
return result
def test_create_circuit():
"""Test circuit creation from template (uses Gradio)."""
client = get_client()
result = client.create_circuit_from_template('bell_state', 2)
print(f"Create Circuit:")
print(f" Success: {result.success}")
print(f" Endpoint: {result.endpoint}")
print(f" Time: {result.execution_time_ms:.2f}ms")
if result.success and result.data:
print(f" Data preview: {str(result.data)[:80]}...")
return result.success
def test_analyze_circuit():
"""Test circuit analysis (uses fallback)."""
client = get_client()
result = client.analyze_circuit(BELL_STATE_QASM)
print(f"Analyze Circuit:")
print(f" Success: {result.success}")
print(f" Is Fallback: {result.is_fallback}")
if result.success:
print(f" Depth: {result.data.get('depth')}")
print(f" Gate Count: {result.data.get('gate_count')}")
print(f" Two-qubit Gates: {result.data.get('two_qubit_gates')}")
return result.success
def test_validate_syntax():
"""Test syntax validation (uses Gradio)."""
client = get_client()
result = client.validate_syntax(BELL_STATE_QASM)
print(f"Validate Syntax:")
print(f" Success: {result.success}")
print(f" Endpoint: {result.endpoint}")
print(f" Time: {result.execution_time_ms:.2f}ms")
return result.success
def test_simulate_circuit():
"""Test circuit simulation (uses Gradio)."""
client = get_client()
result = client.simulate_circuit(BELL_STATE_QASM, shots=100)
print(f"Simulate Circuit:")
print(f" Success: {result.success}")
print(f" Endpoint: {result.endpoint}")
print(f" Time: {result.execution_time_ms:.2f}ms")
if result.success and result.data:
print(f" Data preview: {str(result.data)[:80]}...")
return result.success
def test_complexity_score():
"""Test complexity scoring (uses Gradio or fallback)."""
client = get_client()
result = client.calculate_complexity_score(BELL_STATE_QASM)
print(f"Complexity Score:")
print(f" Success: {result.success}")
print(f" Is Fallback: {result.is_fallback}")
if result.success and result.data:
if isinstance(result.data, dict):
print(f" Score: {result.data.get('complexity_score', 'N/A')}")
return result.success
def test_estimate_noise():
"""Test noise estimation (uses fallback)."""
client = get_client()
result = client.estimate_noise(BELL_STATE_QASM, hardware='ibm_brisbane')
print(f"Estimate Noise:")
print(f" Success: {result.success}")
print(f" Is Fallback: {result.is_fallback}")
if result.success:
print(f" Fidelity: {result.data.get('estimated_fidelity')}")
print(f" Total Error: {result.data.get('total_error_probability')}")
return result.success
def test_local_analyzer():
"""Test QASMLocalAnalyzer directly."""
analyzer = QASMLocalAnalyzer()
# Parse
parsed = analyzer.parse_qasm(BELL_STATE_QASM)
print(f"Local Parser:")
print(f" Qubits: {parsed['num_qubits']}")
print(f" Gates: {len(parsed['gates'])}")
# Analyze
analysis = analyzer.analyze_circuit(BELL_STATE_QASM)
print(f"Local Analyzer:")
print(f" Depth: {analysis['depth']}")
print(f" Gate breakdown: {analysis['gate_breakdown']}")
# Complexity
complexity = analyzer.calculate_complexity(BELL_STATE_QASM)
print(f"Local Complexity:")
print(f" Score: {complexity['complexity_score']}")
return True
def run_all_tests():
"""Run all MCP client tests."""
print("=" * 50)
print("MCP Client Test Suite")
print("=" * 50)
tests = [
("Health Check", test_health_check),
("Create Circuit", test_create_circuit),
("Analyze Circuit", test_analyze_circuit),
("Validate Syntax", test_validate_syntax),
("Simulate Circuit", test_simulate_circuit),
("Complexity Score", test_complexity_score),
("Estimate Noise", test_estimate_noise),
("Local Analyzer", test_local_analyzer),
]
results = []
for name, test_func in tests:
print(f"\n--- {name} ---")
try:
passed = test_func()
results.append((name, passed))
except Exception as e:
print(f"ERROR: {e}")
results.append((name, False))
print("\n" + "=" * 50)
print("Summary")
print("=" * 50)
passed = sum(1 for _, p in results if p)
print(f"Passed: {passed}/{len(results)}")
for name, p in results:
status = "✓" if p else "✗"
print(f" {status} {name}")
return all(p for _, p in results)
if __name__ == "__main__":
run_all_tests()
|