wrolpi/wrolpi/test/test_speedtest.py
lrnselfreliance 91f92683ba
Speed Test calculator: ping, download, and upload against the API (#708)
* Speed Test calculator: ping, download, and upload against the API

Users asking whether the hotspot is fast enough, or how many people can
stream video at once, had no objective tool that works offline.  This
adds one under Calculators > Tools & Reference.

Backend (wrolpi/speedtest.py, /api/speedtest):
* ping: tiny no-store JSON the browser times for round trip latency.
* download: streams slices of a pre-built random buffer for a clamped
  number of seconds (0.1-15).  Random so no proxy or compression can
  flatter the result; slices so no bytes are generated per request.
* upload: streaming-body handler that reads and discards the body and
  reports bytes and elapsed time.  Requests over 8 MiB are refused.
* info: the client address Caddy forwarded plus how many tests are in
  flight.  Sanic now trusts one proxy hop (PROXIES_COUNT = 1) so
  request.remote_addr is the browser, not Caddy.  Nothing else read
  that field before.

There is deliberately no one-test-at-a-time lock.  Several people
testing at once is how a user learns how the link shares between
streamers, so the server only counts in-flight tests (a shared_ctx
Value created pre-fork so every worker sees the same number) and the
UI reports how many others ran alongside.

Both Caddyfiles route /api/speedtest/* unbuffered, as the SSE chat
route already is, so throughput is measured live rather than in bursts.

Frontend:
* speedtest.js holds the logic with no React in it (bucketed
  throughput, steady-state average that drops the first second, ping
  stats, stream-capacity tiers, hotspot address check) so Jest drives
  it with fake fetch and streams.
* SpeedTestCalculator runs 20 pings, a 10 s download, and a 10 s upload
  with a live figure and rolling trace, then shows Mbps and MB/s, ping
  verdict, the client address with a hotspot badge, and a table of how
  many 480p..4K streams the download speed supports.  Upload is
  sequential POSTs of one 4 MiB Blob because Safari cannot stream a
  request body.  Nothing is saved.
* Sparkline is a new inline-SVG ui component (no chart dependency),
  added to /theme-sample and checked in all four themes.  A missing
  sample is a gap, not a plunge to zero.

The page states that it measures the network path, not the drive that
actually serves video files.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* speedtest: bound uploads in time, close the Start race, address review

Review on #708 found three bugs and some polish:

* Start could be clicked again while the first fetchInfo() was still
  pending, because the phase only left `idle` after that await.  A
  second click made a second AbortController and a second concurrent
  run, and Cancel only reached the later one.  start() now refuses when
  a controller already exists and enters a `starting` phase
  synchronously, so the button is Cancel before the first await.

* The upload phase could overrun the advertised 10 s by however long
  the in-flight 4 MiB POST took: on a slow hotspot, the very link this
  tool exists for, that is tens of seconds.  runUpload() now aborts the
  in-flight request at the phase deadline (counting only completed
  requests) and uses 1 MiB bodies so a few-Mbps link still completes
  several inside the phase.

* The server upload sink was capped by size only, so a slow or paused
  body could hold a worker until 8 MiB eventually arrived.  It now also
  enforces MAX_UPLOAD_SECONDS (15 s, matching download) and answers
  408 when exceeded.  Both caps together are what "cannot hold a
  worker" actually requires.

Also: a NaN `seconds` now gets a NaN message instead of "must not be
negative"; the module, Sparkline, and gallery docstrings are trimmed
to purpose; and the upload counter is covered for the mid-stream 413,
the 408, and a broken body.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 18:47:18 -06:00

190 lines
7.5 KiB
Python

import time
from http import HTTPStatus
import pytest
from wrolpi import speedtest
from wrolpi.api_utils import api_app
def _active() -> int:
return api_app.shared_ctx.speedtest_active.value
def test_clamp_seconds():
assert speedtest.clamp_seconds(None) == speedtest.DEFAULT_DOWNLOAD_SECONDS
assert speedtest.clamp_seconds('') == speedtest.DEFAULT_DOWNLOAD_SECONDS
assert speedtest.clamp_seconds('2.5') == 2.5
# Too long is clamped to the ceiling, too short to the floor.
assert speedtest.clamp_seconds('999') == speedtest.MAX_DOWNLOAD_SECONDS
assert speedtest.clamp_seconds('0') == speedtest.MIN_DOWNLOAD_SECONDS
with pytest.raises(speedtest.ValidationError):
speedtest.clamp_seconds('abc')
with pytest.raises(speedtest.ValidationError, match='negative'):
speedtest.clamp_seconds('-1')
with pytest.raises(speedtest.ValidationError, match='NaN'):
speedtest.clamp_seconds('nan')
def test_chunks_never_empty():
"""The chunk generator wraps around the random buffer without ever yielding a short chunk."""
chunks = speedtest.iter_chunks()
seen = [next(chunks) for _ in range(len(speedtest._RANDOM) // speedtest.CHUNK_SIZE + 3)]
assert all(len(i) == speedtest.CHUNK_SIZE for i in seen)
# Wrapped around to the start.
assert seen[0] == seen[len(speedtest._RANDOM) // speedtest.CHUNK_SIZE]
@pytest.mark.asyncio
async def test_ping(async_client):
request, response = await async_client.get('/api/speedtest/ping')
assert response.status_code == HTTPStatus.OK
assert isinstance(response.json['now'], (int, float))
assert response.headers['Cache-Control'] == 'no-store'
@pytest.mark.asyncio
async def test_download_streams_for_requested_seconds(async_client):
assert _active() == 0
start = time.monotonic()
request, response = await async_client.get('/api/speedtest/download?seconds=0.3')
elapsed = time.monotonic() - start
assert response.status_code == HTTPStatus.OK
assert response.headers['Content-Type'] == 'application/octet-stream'
assert response.headers['Cache-Control'] == 'no-store'
assert len(response.body) >= speedtest.CHUNK_SIZE
assert len(response.body) % speedtest.CHUNK_SIZE == 0
# Ran for about the requested duration. Loose upper bound for slow CI.
assert 0.25 <= elapsed < 5
# Counter is released when the stream finishes.
assert _active() == 0
@pytest.mark.asyncio
async def test_download_clamps_seconds(async_client):
"""A client cannot hold a worker longer than MAX_DOWNLOAD_SECONDS."""
with pytest.MonkeyPatch.context() as mp:
mp.setattr(speedtest, 'MAX_DOWNLOAD_SECONDS', 0.2)
start = time.monotonic()
request, response = await async_client.get('/api/speedtest/download?seconds=999')
elapsed = time.monotonic() - start
assert response.status_code == HTTPStatus.OK
assert elapsed < 3
assert _active() == 0
@pytest.mark.asyncio
async def test_download_invalid_seconds(async_client):
request, response = await async_client.get('/api/speedtest/download?seconds=abc')
assert response.status_code == HTTPStatus.BAD_REQUEST
request, response = await async_client.get('/api/speedtest/download?seconds=-1')
assert response.status_code == HTTPStatus.BAD_REQUEST
assert _active() == 0
@pytest.mark.asyncio
async def test_download_client_disconnect_releases_counter(async_client):
"""The active-test counter is released even when the stream dies part way through."""
def broken_chunks():
yield speedtest._RANDOM[:speedtest.CHUNK_SIZE]
raise ConnectionResetError('client went away')
with pytest.MonkeyPatch.context() as mp:
mp.setattr(speedtest, 'iter_chunks', broken_chunks)
try:
await async_client.get('/api/speedtest/download?seconds=0.5')
except Exception:
# The test client may surface the broken stream; the counter is what matters.
pass
assert _active() == 0
@pytest.mark.asyncio
async def test_upload_counts_and_discards(async_client):
body = b'x' * (1024 * 1024)
request, response = await async_client.post('/api/speedtest/upload', content=body)
assert response.status_code == HTTPStatus.OK
assert response.json['bytes'] == len(body)
assert response.json['seconds'] >= 0
assert _active() == 0
@pytest.mark.asyncio
async def test_upload_too_large(async_client):
with pytest.MonkeyPatch.context() as mp:
mp.setattr(speedtest, 'MAX_UPLOAD_CHUNK', 1024)
body = b'x' * 2048
request, response = await async_client.post('/api/speedtest/upload', content=body)
assert response.status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE
assert _active() == 0
@pytest.mark.asyncio
async def test_upload_too_large_mid_stream_releases_counter(async_client):
"""A body that only reveals its size while streaming is refused, and the counter is released."""
async def body():
yield b'x' * 1024
yield b'x' * 1024
with pytest.MonkeyPatch.context() as mp:
mp.setattr(speedtest, 'MAX_UPLOAD_CHUNK', 1024)
request, response = await async_client.post('/api/speedtest/upload', content=body())
assert response.status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE
assert _active() == 0
@pytest.mark.asyncio
async def test_upload_too_slow(async_client):
"""A body that trickles in past the time cap is refused, and the counter is released."""
with pytest.MonkeyPatch.context() as mp:
mp.setattr(speedtest, 'MAX_UPLOAD_SECONDS', 0)
request, response = await async_client.post('/api/speedtest/upload', content=b'x' * 2048)
assert response.status_code == HTTPStatus.REQUEST_TIMEOUT
assert _active() == 0
@pytest.mark.asyncio
async def test_upload_broken_stream_releases_counter(async_client):
"""The counter is released when reading the body blows up part way through."""
async def broken(_request):
raise ConnectionResetError('client went away')
with pytest.MonkeyPatch.context() as mp:
mp.setattr(speedtest, 'drain_upload', broken)
try:
await async_client.post('/api/speedtest/upload', content=b'x' * 1024)
except Exception:
pass
assert _active() == 0
@pytest.mark.asyncio
async def test_info(async_client):
request, response = await async_client.get('/api/speedtest/info')
assert response.status_code == HTTPStatus.OK
assert response.json['client_ip']
assert response.json['active_tests'] == 0
assert response.json['max_download_seconds'] == speedtest.MAX_DOWNLOAD_SECONDS
assert response.json['max_upload_chunk'] == speedtest.MAX_UPLOAD_CHUNK
assert response.json['max_upload_seconds'] == speedtest.MAX_UPLOAD_SECONDS
# Caddy forwards the real client address; Sanic is configured to trust one proxy hop.
request, response = await async_client.get('/api/speedtest/info',
headers={'X-Forwarded-For': '10.42.0.7'})
assert response.json['client_ip'] == '10.42.0.7'
def test_speedtest_counter_in_shared_context():
"""The counter must be created pre-fork so all Sanic workers share it."""
from sanic import Sanic
from wrolpi.contexts import attach_shared_contexts, reset_shared_contexts
test_app = Sanic(f'test_context_{id(test_speedtest_counter_in_shared_context)}')
attach_shared_contexts(test_app)
assert test_app.shared_ctx.speedtest_active.value == 0
test_app.shared_ctx.speedtest_active.value = 3
reset_shared_contexts(test_app)
assert test_app.shared_ctx.speedtest_active.value == 0