11import pytest
22from fastmcp import Client
33from src .news_mcp_server .mcp_server import mcp
4-
4+ import os , time , asyncio
55
66@pytest .mark .asyncio
77async def test_mcp_client ():
@@ -11,4 +11,44 @@ async def test_mcp_client():
1111 print (f"Available tools: { tools } " )
1212 assert len (tools ) > 0 , "No tools found"
1313 result = await client .call_tool ("search_news" , {"query" : "实验" })
14- print (f"Result: { result } " )
14+ print (f"Result: { result } " )
15+
16+
17+ @pytest .mark .asyncio
18+ @pytest .mark .parametrize ("concurrency" , [10 , 50 , 100 , 500 , 1000 , 5000 ])
19+ async def test_mcp_concurrency (concurrency ):
20+ """
21+ On my Macbook Pro M2 Pro, the result is as follows:
22+ PASSED [ 16%]并发: 10, 成功: 10, 失败: 0, 平均耗时: 0.207s, P95: 0.234s
23+ PASSED [ 33%]并发: 50, 成功: 50, 失败: 0, 平均耗时: 0.404s, P95: 0.461s
24+ PASSED [ 50%]并发: 100, 成功: 100, 失败: 0, 平均耗时: 0.899s, P95: 1.148s
25+ PASSED [ 66%]并发: 500, 成功: 500, 失败: 0, 平均耗时: 7.679s, P95: 11.930s
26+ PASSED [ 83%]并发: 1000, 成功: 1000, 失败: 0, 平均耗时: 21.783s, P95: 36.699s
27+ """
28+ url = os .getenv ("MCP_URL" , "http://127.0.0.1:28000/mcp-server/es-news-mcp" )
29+ async with Client (url ) as client :
30+ # 并发任务函数
31+ async def worker (idx ):
32+ start = time .perf_counter ()
33+ try :
34+ await client .call_tool ("search_news" , {"query" : "测试" })
35+ status = "ok"
36+ except Exception as e :
37+ status = "error"
38+ latency = time .perf_counter () - start
39+ return status , latency
40+
41+ # 三阶段:灌入期、稳态期、退载期
42+ # 简化版:一次性发起 concurrency 个请求
43+ tasks = [asyncio .create_task (worker (i )) for i in range (concurrency )]
44+ results = await asyncio .gather (* tasks , return_exceptions = True )
45+
46+ # 统计
47+ ok = sum (1 for r in results if isinstance (r , tuple ) and r [0 ]== "ok" )
48+ err = sum (1 for r in results if r [0 ]== "error" or isinstance (r , Exception ))
49+ latencies = [r [1 ] for r in results if isinstance (r , tuple )]
50+ avg_latency = sum (latencies ) / len (latencies )
51+ p95 = sorted (latencies )[int (len (latencies )* 0.95 )]
52+
53+ print (f"并发: { concurrency } , 成功: { ok } , 失败: { err } , 平均耗时: { avg_latency :.3f} s, P95: { p95 :.3f} s" )
54+ assert err == 0 , f"有 { err } 请求失败"
0 commit comments