Add searchable wiki catalogue and biology material navigation

This commit is contained in:
shen
2026-10-15 00:48:50 -07:00
parent 6472d17306
commit 9d9993b007
21 changed files with 7926 additions and 3 deletions
+66 -3
View File
@@ -130,7 +130,19 @@ static int count_syserr(const char* needle)
static bool py(const std::string& source)
{
std::string error;
if (PythonBoot::RunLine(source.c_str(), &error))
std::string code = source;
if (std::getenv("MT_TEST_WIKI")) {
code = "# -*- coding: utf-8 -*-\ntry:\n";
size_t start=0;
while (start<source.size()) {
size_t end=source.find('\n',start);
if (end==std::string::npos) end=source.size();
code += " "+source.substr(start,end-start)+"\n";
start=end+1;
}
code += "except BaseException as _wiki_error:\n import sys\n sys.stderr.write('wiki integration error: '+repr(_wiki_error)+'\\n')\n raise\n";
}
if (PythonBoot::RunLine(code.c_str(), &error))
return true;
std::fprintf(stderr, "python: %s\n%s\n", source.c_str(), error.c_str());
return false;
@@ -381,7 +393,7 @@ int main(int argc, char** argv)
// CPythonSkill read skilldesc.txt and skilltable.txt (RegisterSkillDesc/RegisterSkillTable); skill 1's
// cool time is skilltable's constant "12".
CHECK(py("import skill\n"
"assert skill.GetSkillName(1, 0) and (__import__('os').getenv('MT_LIVE_BIOLOG') or skill.GetSkillName(1, 0) == 'Three-Way Cut'), skill.GetSkillName(1, 0)\n"
"assert skill.GetSkillName(1, 0) and (__import__('os').getenv('MT_LIVE_BIOLOG') or __import__('os').getenv('MT_TEST_WIKI') or skill.GetSkillName(1, 0) == 'Three-Way Cut'), skill.GetSkillName(1, 0)\n"
"assert skill.GetSkillType(1) == skill.SKILL_TYPE_ACTIVE, skill.GetSkillType(1)\n"
"assert skill.GetSkillCoolTime(1, 1.0) == 12, skill.GetSkillCoolTime(1, 1.0)"));
}
@@ -544,6 +556,57 @@ int main(int argc, char** argv)
CHECK(pump_until(3, [] { return py_true("_bio.count==4"); }));
CHECK(py_true("not _bio.CanAct() and _bio.Remaining()>0"));
CHECK(py("assert _bio.SetData('9 11 0'.split())\nassert _bio.Phase()=='gift'\nassert sum(button.IsShow() for button in _bio.choices)==3\nassert _bio.SetData('13 36 0'.split())\nassert sum(button.IsShow() for button in _bio.choices)==2\nplayer.SetStatus(player.LEVEL,_old_level)\n_bio.Hide()"));
}
if (!live && std::getenv("MT_TEST_WIKI")) {
CHECK(py("import mt_wiki, mt_wiki_data, mt_biolog, player\n"
"assert mt_wiki.g_window and mt_wiki.g_entry\n"
"assert not mt_wiki.CAPABILITIES['live_drops']\n"
"mt_wiki.g_entry.OnUpdate()"));
std::string xy;
CHECK(PythonBoot::Evaluate("'%d %d' % mt_wiki.g_entry.GetGlobalPosition()", &xy, nullptr));
int x=0,y=0;
CHECK(std::sscanf(xy.c_str(), "'%d %d'", &x,&y)==2 || std::sscanf(xy.c_str(), "%d %d", &x,&y)==2);
PythonBoot::UIMouseMove(x+30,y+24);
CHECK(py_true("__import__('wndMgr').IsPickedWindow(mt_wiki.g_entry.hWnd)"));
PythonBoot::UIMouseButton(1,true,x+30,y+24);
PythonBoot::UIMouseButton(1,false,x+30,y+24);
CHECK(py("_wiki=mt_wiki.g_window\nassert _wiki.IsShow() and _wiki.catalogue, _wiki.error\n"
"assert _wiki.catalogue.FindItem(300004)['name']==u'\\u6989\\u6728\\u6811\\u679d', repr(_wiki.catalogue.FindItem(300004)['name'])\n"
"_wiki.search.SetText(player.AutoHuntLocalize('榉木'))\n_wiki.search.eventReturn()\n"
"assert len(_wiki.results)==1 and _wiki.results[0]['id']==300004\n"
"_wiki.SelectResult(0)\nassert _wiki.selected==('items',300004)\n"
"import item\nitem.SelectItem(19)\n_selected_name=item.GetItemName()\n"
"assert item.FeatureGetIconPath(300004)\nassert not item.FeatureGetIconPath(4294967295)\n"
"assert item.GetItemName()==_selected_name\n"
"_wiki.Open(10)\nassert any(link==11 for text,link in _wiki.links)\n"
"_wiki.Follow(next(i for i,p in enumerate(_wiki.links) if p[1]==11))\n"
"assert _wiki.selected==('items',11)\n_wiki.Back()\nassert _wiki.selected==('items',10)\n"
"_wiki.search.SetText('')\n_wiki.SetMode('mobs')\nassert _wiki.results\n"
"_wiki.NextCategory()\n_wiki.NextCategory()\nassert all(r['kind']=='STONE' for r in _wiki.results)\n"
"_wiki.Page(999999)\nassert len(_wiki.results)<=_wiki.rowCount\n"
"_wiki.Hide()\nassert not _wiki.IsShow()\n"
"_bio.Toggle()\n_bio.SetData('5 0 0'.split())\n_bio.Refresh()\n"
"assert _bio.iconVnum==300004\n"));
CHECK(PythonBoot::Evaluate("'%d %d' % _bio.materialLink.GetGlobalPosition()", &xy, nullptr));
CHECK(std::sscanf(xy.c_str(), "'%d %d'", &x,&y)==2 || std::sscanf(xy.c_str(), "%d %d", &x,&y)==2);
PythonBoot::UIMouseMove(x+24,y+24);
PythonBoot::UIMouseButton(1,true,x+24,y+24);
PythonBoot::UIMouseButton(1,false,x+24,y+24);
CHECK(py("assert _wiki.IsShow() and _wiki.selected==('items',300004)\n_wiki.Hide()\n_bio.Hide()"));
PythonBoot::SetUISize(640,360);
CHECK(py("_wiki.Open(10)\n_wiki.OnUpdate()\n"
"assert _wiki.GetWidth()<=624 and _wiki.GetHeight()<=344\n"
"assert _wiki.rowCount==2\n"
"assert _wiki.categoryButton.GetLocalPosition()[0]+_wiki.categoryButton.GetWidth()<_wiki.split\n"
"assert _wiki.listButtons[1].GetLocalPosition()[1]+44<=_wiki.prev.GetLocalPosition()[1]\n"
"_wiki.Hide()\n"
"import json\nassert json.loads('{\"schema\":1}')['schema']==1\n"
"_missing=mt_wiki.WikiWindow()\n_saved_path=mt_wiki.PATH\nmt_wiki.PATH='wiki/not-installed.txt'\n"
"_missing.Open()\nassert _missing.error and not _missing.catalogue\n"
"_missing.Destroy()\nmt_wiki.PATH=_saved_path"));
PythonBoot::SetUISize(800,600);
CHECK(count_syserr("mt_wiki: install failed")==0);
CHECK(count_syserr("mt_wiki_data: install failed")==0);
}
CHECK(count_syserr("Unknown packet header") == 0);
CHECK(count_syserr(kUnhandledPacket) == 0);
@@ -711,7 +774,7 @@ int main(int argc, char** argv)
// item module (PythonItemModule.cpp) over the loaded item_proto: SelectItem + the selected item's fields.
CHECK(py("import item\n"
"item.SelectItem(19)\n"
"assert item.GetItemName() == 'Sword+9', item.GetItemName()\n"
"assert item.GetItemName() and (__import__('os').getenv('MT_TEST_WIKI') or item.GetItemName() == 'Sword+9'), item.GetItemName()\n"
"assert item.GetItemType() == item.ITEM_TYPE_WEAPON and item.GetItemSubType() == item.WEAPON_SWORD\n"
"assert item.GetValue(3) > 0, 'min attack'"));
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Contract tests execute the exact parser embedded in CPython 2, under Python 3 too."""
import hashlib
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / 'src/platform/ScriptLib/WikiDataScript.inc'
ns = {}
exec(SOURCE.read_text().split('R"PY(', 1)[1].rsplit(')PY";', 1)[0], ns)
Catalogue = ns['Catalogue']
RAW = (ROOT / 'data/wiki/catalogue.txt').read_bytes()
class CatalogueTests(unittest.TestCase):
def setUp(self):
self.catalogue = Catalogue(RAW)
def test_real_catalogue_manifest_and_unique_ranges(self):
report = json.loads((ROOT / 'data/wiki/manifest.json').read_text())
self.assertEqual(hashlib.sha256(RAW.split(b'\n', 1)[1]).hexdigest(), report['catalogue_sha256'])
self.assertEqual(self.catalogue.version, report['catalogue_sha256'])
self.assertEqual(len(self.catalogue.items), report['items'])
self.assertEqual(len(self.catalogue.mobs), report['monsters'])
self.assertEqual(len(self.catalogue.recipes), report['refine_recipes'])
def test_research_materials_and_chinese_search(self):
for row in json.loads((ROOT / 'tools/server/biolog/catalog.json').read_text()):
for field in ('material', 'stone', 'enhancer', 'skip'):
self.assertIsNotNone(self.catalogue.FindItem(row[field]))
row = self.catalogue.FindItem(300004)
self.assertEqual(row['name'], '榉木树枝')
results, count, page, pages = self.catalogue.Search('items', '榉木')
self.assertIn(300004, [r['id'] for r in results])
self.assertGreater(count, 0)
def test_template_ranges_resolve_without_expansion(self):
row = self.catalogue.FindItem(110050)
self.assertEqual((row['id'], row['end']), (110000, 110099))
results, count, _, _ = self.catalogue.Search('items', '110050')
self.assertIn(110000, [r['id'] for r in results])
self.assertIsNone(self.catalogue.FindItem(4294967295))
self.assertIsNone(self.catalogue.FindItem(0))
def test_pagination_filters_and_unicode_no_results(self):
results, count, page, pages = self.catalogue.Search('mobs', category='STONE', page=999999, page_size=2)
self.assertEqual(page, pages-1)
self.assertTrue(all(r['kind']=='STONE' for r in results))
results, count, page, pages = self.catalogue.Search('items', '不存在的测试物品')
self.assertEqual((results,count,page,pages),([],0,0,1))
results, count, page, pages = self.catalogue.Search('items', page=-20)
self.assertEqual(page,0)
self.assertLessEqual(len(results),6)
for kwargs in ({'mode':'unknown'},{'mode':'items','page_size':99},{'mode':'items','query':'x'*81}):
with self.assertRaises(ValueError):self.catalogue.Search(**kwargs)
def test_refine_links_and_materials_are_integer_data(self):
sword = self.catalogue.FindItem(10)
self.assertEqual(sword['refined'],11)
recipe = self.catalogue.recipes[sword['recipe']]
self.assertEqual((recipe['cost'],recipe['probability']),(600,90))
self.assertEqual(self.catalogue.mobs[101]['hp'],126)
self.assertEqual((self.catalogue.mobs[101]['attack_min'],self.catalogue.mobs[101]['attack_max']),(20,24))
def test_reject_bad_version_truncation_duplicate_and_markup(self):
cases = [RAW.replace(b'MTWIKI\t1',b'MTWIKI\t9',1), RAW+b'I\tbroken\n',
RAW+RAW.splitlines()[1]+b'\n', b'X'*2097153,
RAW.replace(b'ITEM_WEAPON',b'ITEM_|Hlink',1), RAW.replace(b'\t600\t90\t',b'\t600\t101\t',1)]
for raw in cases:
with self.assertRaises((ValueError,UnicodeError)):Catalogue(raw)
def test_generator_deterministic_when_local_snapshot_exists(self):
snapshot=ROOT/'build/wiki-source'
if not (snapshot/'refine.tsv').is_file():self.skipTest('private source snapshot not installed')
spec=importlib.util.spec_from_file_location('build_wiki',ROOT/'tools/wiki/build_catalogue.py')
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
with tempfile.TemporaryDirectory() as folder:
output=Path(folder)
report=module.build(snapshot,output,ROOT/'data/zh_40250')
self.assertEqual((output/'catalogue.txt').read_bytes(),RAW)
self.assertEqual(report['catalogue_sha256'],self.catalogue.version)
if __name__=='__main__':unittest.main()