This code runs poorly with: pytest file.py --cov
(2-10 sec) vs pytest file.py
(0.15-0.45sec)
from contextlib import contextmanager
from logging import getLogger
from time import perf_counter_ns
from fastapi import FastAPI
from fastapi import WebSocket
from fastapi import WebSocketDisconnect
from fastapi.testclient import TestClient
app = FastAPI()
log = getLogger(__name__)
@contextmanager
def log_time(pref):
start = perf_counter_ns()
yield
log.error('%s: %s', pref, perf_counter_ns() - start)
@app.websocket('/ws')
async def ws(websocket: WebSocket):
await websocket.accept()
while True:
try:
with log_time('server receive'):
data = await websocket.receive_json()
except WebSocketDisconnect:
break
with log_time('server send'):
await websocket.send_json({
'type': 'pingback',
'data': data
})
await websocket.close()
def test_ws():
client = TestClient(app)
with client.websocket_connect('/ws') as wsclient:
with log_time('client send'):
wsclient.send_json({'test': 'aoe'})
with log_time('client receive'):
resp = wsclient.receive_json()
assert resp['type'] == 'pingback'
assert False
After changing starlette/testclient.py:353
0
to 0.1
12345
async def _asgi_receive(self) -> Message:
while self._receive_queue.empty():
await anyio.sleep(0) # 0.1 here
return self._receive_queue.get()
Code runs acceptable but with logs its obvious that there is delay 0.1 sec for server/client receive
I also tried 0.01, 0.001 and etc. The problem appears on value 0.000001.
Conclusion:
0.00001 - runs equally fast with pytest file.py
and pytest file.py --cov
Could it be the problem with my hardware?
PS: CPU: AMD Ryzen 9 5900X (24) @ 3.700GHz
PSS: I don’t know is this relevant but i’m using Archlinux with all kernel modules that supported for this cpu