From 7247fb875418ce093bcc1b58dd61e6165f7c6c74 Mon Sep 17 00:00:00 2001 From: ScarPC Date: Tue, 8 Sep 2026 21:25:16 +0300 Subject: [PATCH] Verify saved translations through client resource pack reloads --- README.md | 5 + build.gradle.kts | 2 + .../editor/verification/IconVerification.java | 6 +- .../verification/TranslationVerification.java | 225 ++++++++++++++++++ 4 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 src/verification/java/online/astradev/plus/editor/verification/TranslationVerification.java diff --git a/README.md b/README.md index 468167f..0c3dfc7 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,11 @@ `-PiconVerificationPort=...`) и загруженный ресурспак. Проверяются серверные стеки каталога, ограничение больших данных, отсутствие модели, совместимость со старым ответом, открытие определения нажатием иконки, формы переводов, сохранение неизвестных полей и размеры GUI. +Затем проверяется полный цикл переводов: сохранение настоящей кнопкой редактора и чтение +с сервера, определения предмета/блока/моба, сборка ZIP, выдача образцов и яйца, призыв моба, +перезагрузка ресурспака в `en_us` и `ru_ru`, реальные названия и строки описания с наследованием. +Путь к ZIP по умолчанию `build/icon-server/astraplus/output/AstraPlus.zip`; другой тестовый +файл задаётся `-PtranslationPack=...`. Копия загружается только в изолированном клиенте. Снимки настоящего интерфейса сохраняются рядом с остальными PNG проверки. Для сетевых проверок нужен отдельно запущенный **изолированный** сервер AstraPlus на diff --git a/build.gradle.kts b/build.gradle.kts index 89c9a81..40e50b1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -50,6 +50,8 @@ neoForge { systemProperty("astrapluseditor.mobTransportVerification", providers.gradleProperty("mobTransportVerification").orElse("false").get()) systemProperty("astrapluseditor.iconVerification", providers.gradleProperty("iconVerification").orElse("false").get()) systemProperty("astrapluseditor.iconVerificationPort", providers.gradleProperty("iconVerificationPort").orElse("26702").get()) + systemProperty("astrapluseditor.translationPack", providers.gradleProperty("translationPack") + .orElse(layout.buildDirectory.file("icon-server/astraplus/output/AstraPlus.zip").map { it.asFile.absolutePath }).get()) programArgument("--width"); programArgument("1280") programArgument("--height"); programArgument("720") programArgument("--username"); programArgument("AstraEditVerify") diff --git a/src/verification/java/online/astradev/plus/editor/verification/IconVerification.java b/src/verification/java/online/astradev/plus/editor/verification/IconVerification.java index d187eb3..ff3d179 100644 --- a/src/verification/java/online/astradev/plus/editor/verification/IconVerification.java +++ b/src/verification/java/online/astradev/plus/editor/verification/IconVerification.java @@ -34,9 +34,11 @@ final class IconVerification { private volatile int screenshots; private ContentDraft translationDraft; private online.astradev.plus.editor.screen.TranslationsScreen translations; + private TranslationVerification translated; void tick() { if (finished) return; + if (translated != null) { translated.tick(); return; } var minecraft = Minecraft.getInstance(); try { if (System.nanoTime() - started > 180_000_000_000L) throw new IllegalStateException("Timed out in stage " + stage); @@ -169,7 +171,9 @@ final class IconVerification { } case 12 -> { if (screenshots != 5) throw new IllegalStateException("Screenshots were not completed"); - finish("PASS: " + count + " catalog stacks; " + available + " resource-pack icons; bounded heavy stack; missing/legacy/malformed fallback; icon click opens definition; translation name/lore controls preserve unknown fields; 5 native GUI screenshots on NeoForge .75."); + translated = new TranslationVerification(connection, translationDraft, + () -> finish("PASS: " + count + " catalog stacks; " + available + " resource-pack icons; bounded heavy stack; missing/legacy/malformed fallback; icon click opens definition; translation controls; item GUI save and reload; block/mob translations saved; resource ZIP build and reload in en_us/ru_ru; item/block/egg/entity names and lore; 7 native GUI screenshots on NeoForge .75."), + message -> finish("FAIL translation lifecycle: " + message)); } default -> {} } diff --git a/src/verification/java/online/astradev/plus/editor/verification/TranslationVerification.java b/src/verification/java/online/astradev/plus/editor/verification/TranslationVerification.java new file mode 100644 index 0000000..f4fbe81 --- /dev/null +++ b/src/verification/java/online/astradev/plus/editor/verification/TranslationVerification.java @@ -0,0 +1,225 @@ +package online.astradev.plus.editor.verification; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.zip.ZipFile; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.minecraft.client.Minecraft; +import net.minecraft.client.Screenshot; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.CustomData; +import online.astradev.plus.editor.client.EditorCatalog; +import online.astradev.plus.editor.form.ContentDraft; +import online.astradev.plus.editor.network.EditorConnection; +import online.astradev.plus.editor.screen.ContentBrowserScreen; +import online.astradev.plus.editor.screen.ContentEditorScreen; +import online.astradev.plus.editor.screen.EditorScreen; +import org.lwjgl.glfw.GLFW; + +/** Tests saved translations through resource-pack building and the vanilla client's language reload. */ +final class TranslationVerification { + private final EditorConnection connection; + private final Runnable complete; + private final Consumer failure; + private final String id = "verification:translated_" + UUID.randomUUID().toString().replace("-", ""); + private final long started = System.nanoTime(); + private final ContentDraft item; + private int stage, tick, next; + private boolean waiting; + private volatile int screenshots; + private JsonObject block, mob; + + TranslationVerification(EditorConnection connection, ContentDraft edited, Runnable complete, Consumer failure) { + this.connection = connection; this.complete = complete; this.failure = failure; + item = new ContentDraft(edited.document(), "new"); + item.string(id, "id"); item.string("Fallback item", "name"); + item.string("minecraft:amethyst_shard", "material"); item.string("minecraft:item/amethyst_shard", "texture"); + item.set(null, "translations", "en_us", "future"); + item.string("Русский предмет 100%", "translations", "ru_ru", "name"); + item.set(JsonParser.parseString("[\"Русское описание\"]"), "translations", "ru_ru", "lore"); + item.component(JsonParser.parseString(""" + [{"text":"Base first line","color":"gray","italic":false}, + {"text":"Base second line","color":"gray","italic":false}] + """), "minecraft:lore"); + } + + void tick() { + var minecraft = Minecraft.getInstance(); + try { + if (System.nanoTime() - started > 180_000_000_000L) throw new IllegalStateException("Timed out in stage " + stage); + tick++; + minecraft.gui.toastManager().clear(); + if (waiting || tick < next || minecraft.gui.overlay() != null) return; + switch (stage) { + case 0 -> { + minecraft.options.guiScale().set(2); minecraft.resizeGui(); + minecraft.gui.setScreen(new ContentEditorScreen(new ContentBrowserScreen(connection), connection, new EditorCatalog(), item)); + click("Сохранить"); stage++; next = tick + 10; + } + case 1 -> { if (!item.dirty()) stage++; } + case 2 -> request("get", id(id), response -> { + if (!response.getAsJsonObject("document").get("translations").equals(item.get("translations"))) + throw new IllegalStateException("GUI save did not persist item translations"); + }); + case 3 -> { + var draft = ContentDraft.create(true); + draft.string(id + "_block", "id"); draft.string("Fallback block", "name"); + draft.string("Русский блок", "translations", "ru_ru", "name"); + draft.string("English block", "translations", "en_us", "name"); + block = draft.document(); request("save", save(block), response -> {}); + } + case 4 -> request("get", id(id + "_block"), response -> { + if (!response.getAsJsonObject("document").get("translations").equals(block.get("translations"))) + throw new IllegalStateException("Block translations did not reload"); + }); + case 5 -> { + mob = JsonParser.parseString(""" + {"name":"Fallback mob","entity":"minecraft:pig","health":20,"skills":[], + "translations":{"en_us":{"name":"English mob"},"ru_ru":{"name":"Русский моб"}}} + """).getAsJsonObject(); + mob.addProperty("id", id + "_mob"); request("mob_save", save(mob), response -> {}); + } + case 6 -> request("mob_get", id(id + "_mob"), response -> { + if (!response.getAsJsonObject("document").get("translations").equals(mob.get("translations"))) + throw new IllegalStateException("Mob translations did not reload"); + }); + case 7 -> request("build", new JsonObject(), response -> {}); + case 8 -> { + Path source = Path.of(System.getProperty("astrapluseditor.translationPack")); + if (!packReady(source)) { next = tick + 10; return; } + String filename = "AstraPlus-translations-" + id.substring(id.indexOf(':') + 1) + ".zip"; + Files.copy(source, minecraft.getResourcePackDirectory().resolve(filename)); + var repository = minecraft.getResourcePackRepository(); repository.reload(); + if (!repository.addPack("file/" + filename)) throw new IllegalStateException("Generated resource pack was not discovered"); + language("en_us"); + } + case 9 -> request("give", id(id), response -> {}); + case 10 -> request("give", id(id + "_block"), response -> {}); + case 11 -> request("mob_egg", id(id + "_mob"), response -> {}); + case 12 -> request("mob_spawn", id(id + "_mob"), response -> { next = tick + 20; }); + case 13 -> { + check(false); + minecraft.gui.setScreen(new ResultScreen(false)); + stage++; next = tick + 10; + } + case 14 -> { capture("27-english-content.png"); stage++; next = tick + 5; } + case 15 -> language("ru_ru"); + case 16 -> { + check(true); + minecraft.gui.setScreen(new ResultScreen(true)); + stage++; next = tick + 10; + } + case 17 -> { capture("28-russian-content.png"); stage++; next = tick + 5; } + case 18 -> { + if (screenshots != 2) throw new IllegalStateException("Translated screenshots are incomplete"); + complete.run(); + } + default -> throw new IllegalStateException("Unknown stage " + stage); + } + } catch (Exception error) { failure.accept("Stage " + stage + ": " + error); } + } + + private void check(boolean russian) { + String expectedItem = russian ? "Русский предмет 100%" : "English item name"; + if (!stack(id, false).getHoverName().getString().equals(expectedItem)) throw new IllegalStateException("Item name: " + stack(id, false).getHoverName().getString()); + var lore = stack(id, false).get(DataComponents.LORE).lines(); + if (lore.size() != 2 || !lore.get(0).getString().equals(russian ? "Русское описание" : "English description") + || !lore.get(1).getString().equals(russian ? "Base second line" : "Second line")) + throw new IllegalStateException("Translated lore or line fallback differs: " + lore); + if (!Boolean.FALSE.equals(lore.get(1).getStyle().isItalic())) throw new IllegalStateException("Fallback lore style was lost"); + if (!stack(id + "_block", false).getHoverName().getString().equals(russian ? "Русский блок" : "English block")) + throw new IllegalStateException("Block name differs"); + String expectedMob = russian ? "Русский моб" : "English mob"; + if (!stack(id + "_mob", true).getHoverName().getString().equals((russian ? "Яйцо призыва: " : "Spawn Egg: ") + expectedMob)) + throw new IllegalStateException("Mob egg name differs: " + stack(id + "_mob", true).getHoverName().getString()); + boolean found = false; + for (var entity : Minecraft.getInstance().level.entitiesForRendering()) + if (entity.getCustomName() != null + && entity.getCustomName().getContents() instanceof net.minecraft.network.chat.contents.TranslatableContents translated + && translated.getKey().equals("entity." + id.replace(':', '.') + "_mob") + && entity.getCustomName().getString().equals(expectedMob)) found = true; + if (!found) throw new IllegalStateException("Spawned mob name was not translated"); + } + + private ItemStack stack(String value, boolean egg) { + var inventory = Minecraft.getInstance().player.getInventory(); + for (int slot = 0; slot < inventory.getContainerSize(); slot++) { + var stack = inventory.getItem(slot); + if (stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag() + .getString(egg ? "astraplus:mob_egg" : "astraplus:id").orElse("").equals(value)) return stack; + } + throw new IllegalStateException("No synchronized sample: " + value); + } + + private boolean packReady(Path source) throws Exception { + if (!Files.isRegularFile(source)) return false; + try (var zip = new ZipFile(source.toFile())) { + var language = zip.getEntry("assets/verification/lang/en_us.json"); + if (language == null) return false; + try (var input = zip.getInputStream(language)) { + var json = JsonParser.parseString(new String(input.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(); + return json.has("item." + id.replace(':', '.')) && json.has("block." + id.replace(':', '.') + "_block") + && json.has("entity." + id.replace(':', '.') + "_mob"); + } + } + } + + private void language(String locale) { + var minecraft = Minecraft.getInstance(); + minecraft.getLanguageManager().setSelected(locale); minecraft.options.languageCode = locale; + waiting = true; + minecraft.reloadResourcePacks().whenCompleteAsync((ignored, error) -> { + if (error != null) failure.accept("Language reload: " + error); + else { waiting = false; stage++; next = tick + 10; } + }, minecraft); + } + + private void request(String action, JsonObject request, Consumer callback) { + waiting = true; + connection.request(action, request, response -> { + try { + if (!EditorConnection.success(response)) throw new IllegalStateException(EditorConnection.message(response)); + callback.accept(response); stage++; next = Math.max(next, tick + 6); waiting = false; + } catch (Exception error) { failure.accept("Stage " + stage + ": " + error); } + }); + } + + private JsonObject save(JsonObject document) { + var request = id(document.get("id").getAsString()); request.addProperty("revision", "new"); request.add("document", document); return request; + } + private JsonObject id(String value) { var request = new JsonObject(); request.addProperty("id", value); return request; } + private void click(String label) { + for (var child : Minecraft.getInstance().gui.screen().children()) + if (child instanceof Button button && button.getMessage().getString().equals(label)) { button.onPress(new KeyEvent(GLFW.GLFW_KEY_ENTER, 0, 0)); return; } + throw new IllegalStateException("Missing button: " + label); + } + private void capture(String file) { + var minecraft = Minecraft.getInstance(); + Screenshot.grab(minecraft.gameDirectory, file, minecraft.gameRenderer.mainRenderTarget(), 1, ignored -> screenshots++); + } + + private final class ResultScreen extends EditorScreen { + private ResultScreen(boolean russian) { super(russian ? "Переведённый контент: ru_ru" : "Translated content: en_us"); } + @Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { + super.extractRenderState(graphics, mouseX, mouseY, a); + int y = 60; + for (var entry : java.util.List.of(stack(id, false), stack(id + "_block", false), stack(id + "_mob", true))) { + graphics.item(entry, 20, y); + graphics.text(font, entry.getHoverName(), 50, y, 0xFFE4F2EF); + if (entry.has(DataComponents.LORE)) for (Component line : entry.get(DataComponents.LORE).lines()) { + y += 14; graphics.text(font, line, 50, y, 0xFF94B3BD); + } + y += 45; + } + } + } +}