Improve smooth player chart, colored MOTD and complete paged player names

This commit is contained in:
itxiaohui committed 2026-10-06 14:46:30 +08:00
1 parent 1bbecbfaa1
commit bd1cf2ff4c
14 files changed
+775 -122

No files matched your search

+56 -2
View File
@@ -3,6 +3,7 @@ import json
from types import SimpleNamespace
import httpx
import pytest
from services.mc_api import MinecraftServerAPI
@@ -35,7 +36,7 @@ async def test_real_java_status_protocol_on_local_server():
"max": 50,
"sample": [{"name": "Alex", "id": "00000000-0000-0000-0000-000000000000"}],
},
"description": {"text": "Hello server"},
"description": {"text": "Hello server", "color": "gold"},
}
).encode()
packet = b"\x00" + api._encode_varint(len(payload)) + payload
@@ -58,6 +59,7 @@ async def test_real_java_status_protocol_on_local_server():
assert result["players_online"] == 2 and result["players_max"] == 50
assert result["player_list"] == ["Alex"] and result["version"] == "1.21.1"
assert result["motd"] == "Hello server" and result["latency_ms"] >= 0
assert result["motd_raw"] == {"text": "Hello server", "color": "gold"}
# Exercise the migrated fallback ping/pong path too.
latency = await api._measure_minecraft_latency("127.0.0.1", port, "127.0.0.1", 767)
assert latency is not None and latency >= 0
@@ -82,7 +84,7 @@ async def test_api_fallback_and_player_normalization(monkeypatch):
"online": True,
"version": "Paper 1.21",
"port": 25565,
"motd": {"clean": ["First", "Second"]},
"motd": {"clean": ["First", "Second"], "raw": ["§cFirst", "§bSecond"]},
"players": {
"online": 5,
"max": 20,
@@ -100,6 +102,7 @@ async def test_api_fallback_and_player_normalization(monkeypatch):
api = MinecraftServerAPI({})
data = await api.query("mc.example.com")
assert data["source"] == "api" and data["motd"] == "First | Second"
assert data["motd_raw"] == "§cFirst\n§bSecond"
assert data["player_list"] == ["Steve", "Alex", "Third"]
assert seen == ["https://api.mcsrvstat.us/2/mc.example.com"] # no forced :25565
text = api.format_server_info(data)
@@ -155,3 +158,54 @@ async def test_srv_lookup_input_is_not_changed(monkeypatch):
api._query_api = no_extra
data = await api.query("mc.example.com")
assert seen == ["mc.example.com"] and data["port"] == 25570
@pytest.mark.parametrize("mode", ["query", "error", "disabled", "complete"])
async def test_query_full_names_and_cache_never_replace_realtime_list(monkeypatch, mode):
calls = []
direct_names = ["Alex", "Steve", "Third"] if mode == "complete" else ["Alex"]
async def status(**kwargs):
return SimpleNamespace(
raw={"players": {"sample": [{"name": name} for name in direct_names]}},
version=SimpleNamespace(name="1.21"),
motd=SimpleNamespace(to_plain=lambda: "Hello"),
players=SimpleNamespace(online=3, max=20),
latency=5,
)
async def query(**kwargs):
calls.append("query")
if mode == "error":
raise OSError("UDP disabled")
return SimpleNamespace(players=SimpleNamespace(names=["Alex", "Steve", "Third"]))
async def lookup(*args, **kwargs):
return SimpleNamespace(
address=SimpleNamespace(host="test.example", port=25565),
async_status=status,
async_query=query,
)
monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", lookup)
api = MinecraftServerAPI({"query_players": mode != "disabled"})
async def cached(*args, **kwargs):
return {
"online": True,
"player_list": ["Old1", "Old2", "Old3", "Old4"],
"players_online": 99,
"latency_ms": 999,
}
api._query_api = cached
data = await api.query("test.example")
assert data["players_online"] == 3 and data["latency_ms"] == 5
assert data["source"] == "direct"
assert calls == (["query"] if mode in ("query", "error") else [])
if mode in ("query", "complete"):
assert data["player_list"] == ["Alex", "Steve", "Third"]
assert not data.get("player_list_cached")
else:
assert data["player_list"] == ["Old1", "Old2", "Old3", "Old4"]
assert data["player_list_cached"]
+126
View File
@@ -0,0 +1,126 @@
import io
import pytest
from PIL import Image, ImageDraw
from services.chart import smooth_points
from services.minecraft_text import TextStyle, motd_runs
from services.motd_card import (
_layout_motd,
player_pages,
player_rows,
render_motd_card,
render_motd_cards,
)
def test_legacy_colors_hex_and_reset():
runs = motd_runs("§cRed §lBold §rPlain §x§1§2§3§4§5§6Hex §#ABCDEFMore")
assert "".join(run.text for run in runs) == "Red Bold Plain Hex More"
assert runs[0].style.color == "#FF5555"
assert runs[1].style.bold and runs[1].style.color == "#FF5555"
assert runs[2].style == TextStyle()
assert runs[3].style.color == "#123456"
assert runs[4].style.color == "#ABCDEF"
def test_json_component_inheritance_and_explicit_reset():
runs = motd_runs(
{
"text": "A",
"color": "gold",
"bold": True,
"extra": [
{"text": "B"},
{"text": "C", "bold": False, "color": "#123456"},
{"text": "D", "color": "reset"},
],
}
)
assert "".join(run.text for run in runs) == "ABCD"
assert runs[1].style.bold and runs[1].style.color == "#FFAA00"
assert not runs[2].style.bold and runs[2].style.color == "#123456"
assert runs[3].style == TextStyle()
def test_wrapping_preserves_long_motd_and_line_styles():
draw = ImageDraw.Draw(Image.new("RGB", (1, 1)))
text = "完整中文标语" * 100
lines = _layout_motd(draw, motd_runs("§c" + text), 940, "")
assert len(lines) > 2
assert "".join(run.text for line in lines for run in line) == text
assert all(run.style.color == "#FF5555" for line in lines for run in line)
def test_card_contains_real_colored_glyph_pixels():
image = Image.open(
io.BytesIO(
render_motd_card(
{
"address": "example.test",
"online": True,
"motd_raw": "§c████ §b████ §x§1§2§3§4§5§6████",
},
now=100000,
)
)
)
colors = image.crop((100, 495, 800, 540)).getcolors(800 * 100)
colors = {color: count for count, color in colors}
for color in [(255, 85, 85), (85, 255, 255), (18, 52, 86)]:
assert colors.get(color, 0) > 20
def test_player_wrap_preserves_long_names_and_pages_all_players():
names = [f"Player_{i:03d}_LongName" for i in range(100)] + ["超长中文名字" * 20]
rows = player_rows(names)
chips = [chip for row in rows for chip in row["chips"]]
assert ["".join(chip["lines"]) for chip in chips] == names
assert all(sum(chip["width"] + 10 for chip in row["chips"]) - 10 <= 944 for row in rows)
pages = player_pages(names)
assert len(pages) > 1 and [name for page in pages for name in page] == names
def test_multiple_cards_actually_draw_every_player(monkeypatch):
names = [f"Player_{i:03d}_LongName" for i in range(100)]
drawn = []
original = ImageDraw.ImageDraw.text
def track(self, position, text, *args, **kwargs):
drawn.append(text)
return original(self, position, text, *args, **kwargs)
monkeypatch.setattr(ImageDraw.ImageDraw, "text", track)
cards = render_motd_cards(
{"online": True, "address": "example.test", "player_list": names, "players_online": 100},
now=100000,
)
assert len(cards) > 1
assert all(drawn.count(name) == 1 for name in names)
assert all(Image.open(io.BytesIO(card)).height < 1800 for card in cards)
@pytest.mark.parametrize(
"points",
[
[(0, 0), (10, 100), (20, 0)],
[(0, 8), (1, 8), (20, 2), (30, 2)],
[(0, 0), (0.3, 2), (50, 4)],
[(0, 10), (8, 0), (15, 20), (30, 1)],
],
)
def test_curve_passes_samples_and_does_not_invent_extrema(points):
curve = smooth_points(points, 0.25)
assert curve[0] == points[0] and curve[-1] == pytest.approx(points[-1])
for x, y in points:
assert next(point[1] for point in curve if abs(point[0] - x) < 1e-8) == pytest.approx(y)
for start, end in zip(points, points[1:]):
for x, y in curve:
if start[0] <= x <= end[0]:
assert min(start[1], end[1]) - 1e-8 <= y <= max(start[1], end[1]) + 1e-8
def test_single_sample_duplicate_timestamp_and_zero_series():
assert smooth_points([(5, 0)]) == [(5, 0)]
assert smooth_points([(1, 0), (1, 2)]) == [(1, 2)]
assert all(y == 0 for x, y in smooth_points([(0, 0), (10, 0), (20, 0)]))
+28
View File
@@ -222,3 +222,31 @@ async def test_group_grant_is_limited_to_one_group_and_adapter(plugin_class):
assert "qq-main|group-openid|user-openid" in event.messages[-1][1]
assert not plugin._is_admin(event)
await plugin.terminate()
async def test_paged_images_uploaded_before_replacing_file_and_cleaned(
plugin_class, monkeypatch, tmp_path
):
plugin = plugin_class(object(), {"history_enabled": False})
pages = [b"page-one", b"page-two", b"page-three"]
monkeypatch.setattr(
sys.modules[plugin_class.__module__], "render_motd_cards", lambda *args: pages
)
async def query(address):
return {"online": True, "address": address, "players_online": 100, "players_max": 200}
plugin.api.query = query
uploaded = []
class UploadEvent(Event):
async def send(self, result):
if result[0] == "image":
uploaded.append(Path(result[1]).read_bytes())
await super().send(result)
event = UploadEvent()
await plugin.motd(event, "mc.example.com")
assert uploaded == pages
assert not list(tmp_path.glob("card-*.png"))
await plugin.terminate()
+1 -1
View File
@@ -76,4 +76,4 @@ def test_card_handles_empty_history_offline_failure_and_zero(online, failed, his
now=100000,
)
image = Image.open(io.BytesIO(raw))
assert image.format == "PNG" and image.size == (1200, 1080)
assert image.format == "PNG" and image.width == 1200 and image.height > 1500