Release xiaohuicat MOTD plugin with 24-hour player history

This commit is contained in:
itxiaohui committed 2026-10-05 12:22:51 +08:00
commit 2144e218ec
23 files changed
+1904

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
import asyncio
import json
from types import SimpleNamespace
import httpx
from services.mc_api import MinecraftServerAPI
async def test_real_java_status_protocol_on_local_server():
api = MinecraftServerAPI({"ping_timeout": 2})
async def extra(*args, **kwargs):
return {
"online": True,
"software": "Paper",
"plugins": {"names": ["Demo"]},
"players_online": 999,
"latency_ms": 999,
}
api._query_api = extra
async def handle(reader, writer):
try:
length = await api._read_varint(reader)
handshake = await reader.readexactly(length)
assert handshake[0] == 0
assert await reader.readexactly(2) == b"\x01\x00"
payload = json.dumps(
{
"version": {"name": "1.21.1", "protocol": 767},
"players": {
"online": 2,
"max": 50,
"sample": [{"name": "Alex", "id": "00000000-0000-0000-0000-000000000000"}],
},
"description": {"text": "Hello server"},
}
).encode()
packet = b"\x00" + api._encode_varint(len(payload)) + payload
writer.write(api._encode_varint(len(packet)) + packet)
await writer.drain()
size = await api._read_varint(reader)
ping = await reader.readexactly(size)
writer.write(api._encode_varint(len(ping)) + ping)
await writer.drain()
finally:
writer.close()
await writer.wait_closed()
server = await asyncio.start_server(handle, "127.0.0.1", 0)
try:
port = server.sockets[0].getsockname()[1]
result = await api.query(f"127.0.0.1:{port}")
assert result["source"] == "direct"
assert result["software"] == "Paper" and result["plugins"]["names"] == ["Demo"]
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
# 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
finally:
server.close()
await server.wait_closed()
async def test_api_fallback_and_player_normalization(monkeypatch):
async def unavailable(*args, **kwargs):
raise OSError("direct unavailable")
monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", unavailable)
real_client = httpx.AsyncClient
seen = []
def response(request):
seen.append(str(request.url))
return httpx.Response(
200,
json={
"online": True,
"version": "Paper 1.21",
"port": 25565,
"motd": {"clean": ["First", "Second"]},
"players": {
"online": 5,
"max": 20,
"list": ["Steve", {"name": "Alex"}, {"username": "Third"}],
},
"plugins": {"names": ["Example"]},
"software": "Paper",
},
)
monkeypatch.setattr(
"services.mc_api.httpx.AsyncClient",
lambda **kwargs: real_client(transport=httpx.MockTransport(response), **kwargs),
)
api = MinecraftServerAPI({})
data = await api.query("mc.example.com")
assert data["source"] == "api" and data["motd"] == "First | Second"
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)
assert "Steve" in text and "插件: 1 个" in text and "缓存" in text
async def test_api_offline_different_from_transport_error(monkeypatch):
async def unavailable(*args, **kwargs):
raise OSError("down")
monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", unavailable)
real_client = httpx.AsyncClient
status = [200]
monkeypatch.setattr(
"services.mc_api.httpx.AsyncClient",
lambda **kwargs: real_client(
transport=httpx.MockTransport(
lambda req: httpx.Response(status[0], json={"online": False})
),
**kwargs,
),
)
api = MinecraftServerAPI({})
assert (await api.query("a.test"))["online"] is False
status[0] = 503
assert await api.query("a.test") is None
async def test_srv_lookup_input_is_not_changed(monkeypatch):
seen = []
async def status(**kwargs):
return SimpleNamespace(
raw={},
version=SimpleNamespace(name="1.21"),
motd=SimpleNamespace(to_plain=lambda: "Hi"),
players=SimpleNamespace(online=0, max=20),
latency=5,
)
async def lookup(address, **kwargs):
seen.append(address)
return SimpleNamespace(
address=SimpleNamespace(host="srv-target.test", port=25570), async_status=status
)
monkeypatch.setattr("services.mc_api.JavaServer.async_lookup", lookup)
api = MinecraftServerAPI({})
async def no_extra(*args, **kwargs):
return None
api._query_api = no_extra
data = await api.query("mc.example.com")
assert seen == ["mc.example.com"] and data["port"] == 25570
+148
View File
@@ -0,0 +1,148 @@
"""Framework-free adapter contract tests; the actual QQ account needs deployment verification."""
import importlib.util
import logging
import sys
import types
from pathlib import Path
import pytest
class Event:
def __init__(self, platform="qq-main", group="group-openid", admin=False, image_error=False):
self.platform, self.group, self.admin = platform, group, admin
self.image_error = image_error
self.unified_msg_origin = f"{platform}:private:user"
self.messages = []
self.stopped = False
def get_group_id(self):
return self.group
def get_platform_id(self):
return self.platform
def get_sender_id(self):
return "user-openid"
def is_admin(self):
return self.admin
def plain_result(self, text):
return ("text", text)
def image_result(self, path):
return ("image", path)
def stop_event(self):
self.stopped = True
async def send(self, result):
if result[0] == "image":
assert Path(result[1]).is_file()
if self.image_error:
raise RuntimeError("QQ upload failed")
self.messages.append(result)
@pytest.fixture
def plugin_class(monkeypatch, tmp_path):
class Star:
def __init__(self, context):
self.context = context
def command(name, alias):
def decorate(func):
func.registered_aliases = alias
return func
return decorate
modules = {
"astrbot": types.ModuleType("astrbot"),
"astrbot.api": types.ModuleType("astrbot.api"),
"astrbot.api.event": types.ModuleType("astrbot.api.event"),
"astrbot.api.star": types.ModuleType("astrbot.api.star"),
}
modules["astrbot.api"].AstrBotConfig = dict
modules["astrbot.api"].logger = logging.getLogger("test")
modules["astrbot.api.event"].AstrMessageEvent = Event
modules["astrbot.api.event"].filter = types.SimpleNamespace(command=command)
modules["astrbot.api.star"].Star = Star
modules["astrbot.api.star"].Context = object
modules["astrbot.api.star"].StarTools = types.SimpleNamespace(
get_data_dir=lambda name: tmp_path
)
for name, module in modules.items():
monkeypatch.setitem(sys.modules, name, module)
root = Path(__file__).resolve().parents[1]
package = types.ModuleType("plugin_under_test")
package.__path__ = [str(root)]
monkeypatch.setitem(sys.modules, "plugin_under_test", package)
spec = importlib.util.spec_from_file_location("plugin_under_test.main", root / "main.py")
module = importlib.util.module_from_spec(spec)
monkeypatch.setitem(sys.modules, spec.name, module)
spec.loader.exec_module(module)
return module.MotdPlugin
async def test_permission_binding_scope_aliases_and_clear(plugin_class):
plugin = plugin_class(object(), {"history_enabled": False})
async def no_send(*args):
pass
plugin._query_and_send = no_send
ordinary = Event()
await plugin.motd(ordinary, "set", "mc.example.com")
assert "管理员" in ordinary.messages[-1][1]
assert await plugin.store.get_binding(plugin._scope(ordinary)) is None
admin = Event(admin=True)
await plugin.motd(admin, "设置", "MC.Example.COM")
assert await plugin.store.get_binding(plugin._scope(admin)) == "mc.example.com"
assert await plugin.store.get_binding(plugin._scope(Event(platform="second-bot"))) is None
await plugin.motd(admin, "清除")
assert await plugin.store.get_binding(plugin._scope(admin)) is None
assert admin.stopped and plugin.motd.registered_aliases == {"mc", "mcstatus"}
await plugin.terminate()
async def test_query_image_fallback_and_file_cleanup(plugin_class, tmp_path):
plugin = plugin_class(object(), {"history_enabled": False})
async def query(address):
return {
"online": True,
"address": address,
"players_online": 5,
"players_max": 20,
"player_list": ["Alex"],
"source": "direct",
}
plugin.api.query = query
event = Event(image_error=True)
await plugin.motd(event, "mc.example.com")
assert "Alex" in event.messages[-1][1] and "人数最低 5" in event.messages[-1][1]
assert not list(tmp_path.glob("card-*.png"))
success = Event()
await plugin.motd(success, "history", "mc.example.com")
assert success.messages[-1][0] == "image"
assert not list(tmp_path.glob("card-*.png"))
await plugin.terminate()
async def test_missing_default_invalid_and_private_setting(plugin_class):
plugin = plugin_class(object(), {"history_enabled": False})
event = Event()
await plugin.motd(event)
assert "还没有设置" in event.messages[-1][1]
await plugin.motd(event, "https://bad")
assert "格式不正确" in event.messages[-1][1]
private = Event(group="", admin=True)
await plugin.motd(private, "set", "a.test")
assert "请在群内" in private.messages[-1][1]
await plugin.motd(event, "help")
assert "/mcstatus" in event.messages[-1][1]
await plugin.terminate()
+79
View File
@@ -0,0 +1,79 @@
import io
import pytest
from PIL import Image
from services.address import normalize_address
from services.motd_card import history_segments, render_motd_card
@pytest.mark.parametrize(
"address", ["mc.example.com", "127.0.0.1:25565", "localhost", "[::1]:25565", "[2001:db8::1]"]
)
def test_valid_address(address):
assert normalize_address(" " + address.upper() + " ") == address
@pytest.mark.parametrize(
"address",
[
"",
"https://a.test",
"a.test:0",
"a.test:65536",
"a.test:",
"../a",
"-a.test",
"a..test",
"[broken]:1",
"a.test:1",
"a.test;command",
],
)
def test_invalid_address(address):
with pytest.raises(ValueError):
normalize_address(address)
def test_history_does_not_bridge_offline_errors_or_shutdown():
points = [
{"timestamp": stamp, "online": online, "players": players}
for stamp, online, players in [
(100000, 1, 0),
(100300, 1, 2),
(100600, 0, None),
(100900, 1, 5),
(101200, None, None),
(101500, 1, 7),
(110000, 1, 10),
]
]
segments = history_segments(points, 110000, 300)
assert [[p["players"] for p in segment] for segment in segments] == [[0, 2], [5], [7], [10]]
@pytest.mark.parametrize(
"online,failed,history",
[
(True, False, []),
(False, False, []),
(False, True, []),
(True, False, [{"timestamp": 100000, "online": 1, "players": 0}]),
],
)
def test_card_handles_empty_history_offline_failure_and_zero(online, failed, history):
raw = render_motd_card(
{
"online": online,
"query_failed": failed,
"address": "mc.example.com",
"icon": "invalid-base64",
"motd": "中文标语 " * 100,
"players_online": 0,
"players_max": 0,
},
history=history,
now=100000,
)
image = Image.open(io.BytesIO(raw))
assert image.format == "PNG" and image.size == (1200, 1080)
+101
View File
@@ -0,0 +1,101 @@
import asyncio
from services.monitor import PlayerMonitor
from services.storage import MotdStore
async def test_binding_isolation_persistence_and_history_window(tmp_path):
path = tmp_path / "motd.db"
store = MotdStore(path)
await store.initialize()
await store.set_binding("bot-a:group-1", "one.test", "admin")
await store.set_binding("bot-b:group-1", "two.test", "admin")
await store.record(
"one.test", {"online": True, "players_online": 0, "source": "direct"}, 100000
)
await store.record("one.test", {"online": False}, 100300)
await store.record("one.test", None, 100600)
await store.record("one.test", {"online": True, "players_online": 9}, 1)
reloaded = MotdStore(path)
await reloaded.initialize()
assert await reloaded.get_binding("bot-a:group-1") == "one.test"
assert await reloaded.get_binding("bot-b:group-1") == "two.test"
assert [(p["online"], p["players"]) for p in await reloaded.history("one.test", 101000)] == [
(1, 0),
(0, None),
(None, None),
]
await reloaded.clear_binding("bot-a:group-1")
assert await reloaded.get_binding("bot-a:group-1") is None
assert await reloaded.get_binding("bot-b:group-1") == "two.test"
async def test_tracking_expiry_bindings_and_prune(tmp_path, monkeypatch):
monkeypatch.setattr("services.storage.time.time", lambda: 200000)
store = MotdStore(tmp_path / "motd.db")
await store.initialize()
await store.track("temporary.test")
await store.set_binding("a", "permanent.test", "admin")
assert set(await store.monitored_addresses(200001)) == {"temporary.test", "permanent.test"}
assert await store.monitored_addresses(286401) == ["permanent.test"]
await store.record("temporary.test", {"online": True, "players_online": 4}, 1)
await store.record("temporary.test", {"online": True, "players_online": 5}, 199999)
await store.prune(48)
assert len(await store.history("temporary.test", 200000)) == 1
async def test_concurrent_queries_and_background_sampling(tmp_path):
class API:
calls = 0
async def query(self, address):
self.calls += 1
await asyncio.sleep(0.02)
return {"online": True, "players_online": 3, "source": "direct"}
store = MotdStore(tmp_path / "motd.db")
await store.initialize()
await store.set_binding("group-a", "same.test", "a")
await store.set_binding("group-b", "same.test", "a")
api = API()
monitor = PlayerMonitor(api, store, addresses=["extra.test"])
result = await asyncio.gather(*(monitor.query("same.test") for _ in range(5)))
assert api.calls == 1 and all(p["players_online"] == 3 for p in result)
await monitor.sample_once()
assert api.calls == 2 # same.test cached, extra.test polled
assert len(await store.history("extra.test")) == 1
monitor.start()
task = monitor._task
await monitor.close()
assert task.done() and not monitor._pending
async def test_api_exception_records_unknown_not_zero(tmp_path):
class API:
async def query(self, address):
raise OSError("network down")
store = MotdStore(tmp_path / "motd.db")
await store.initialize()
monitor = PlayerMonitor(API(), store)
assert await monitor.query("a.test") is None
point = (await store.history("a.test"))[0]
assert point["players"] is None and point["online"] is None
async def test_cancellation_joins_inflight_queries(tmp_path):
started = asyncio.Event()
class API:
async def query(self, address):
started.set()
await asyncio.Event().wait()
store = MotdStore(tmp_path / "motd.db")
await store.initialize()
monitor = PlayerMonitor(API(), store)
request = asyncio.create_task(monitor.query("a.test"))
await started.wait()
await monitor.close()
results = await asyncio.gather(request, return_exceptions=True)
assert isinstance(results[0], asyncio.CancelledError)