Add modular class loaders, enhanced mod verification, and new test cases for mod loading and validation.

This commit is contained in:
Overlord committed 2026-10-02 11:20:31 +02:00
1 parent df4d58a279
commit 3b21fc3aa6
27 files changed
+1871 -105

No files matched your search

@@ -1,24 +1,29 @@
package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModVersion;
import dev.overlord.zomboidforge.core.mods.TestMods;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import testmods.ContextMod;
import testmods.Recorder;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -26,46 +31,55 @@ class ForgeTest
{
private static final GameVersion GAME = GameVersion.parse("42.21.0");
/** Mods that call {@link Recorder} use the fake game jar, so they declare {@code game}. */
private static final String USES_GAME = "game = [\"42\"]\n";
@TempDir
Path directory;
private Path mods;
/** Entry point on the test class path; records what its context returns in the constructor. */
public static final class ContextMod extends Mod
{
public static ContextMod instance;
public final String idInConstructor = this.id();
public final GameVersion gameInConstructor = this.gameVersion();
public final Path directoryInConstructor = this.directory();
public ContextMod() { ContextMod.instance = this; }
}
private Path gameJar;
@BeforeEach
void setUp() throws IOException
{
this.mods = Files.createDirectories(this.directory.resolve("mods"));
TestMods.Recorder.EVENTS.clear();
this.mods = Files.createDirectories(this.directory.resolve("mods"));
this.gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
Recorder.EVENTS.clear();
}
private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); }
private Forge load() throws ModLoadException
{
Forge forge = this.forge();
forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader());
return forge;
}
/** {@link ContextMod} and its settings record, packaged as the mod {@code context}. */
private void contextMod(String extra, @Nullable String defaultConfig) throws IOException
{
TestMods.folder(this.mods, "context", TestMods.toml("context", ContextMod.class.getName(), extra), defaultConfig, Map.of(
"testmods/ContextMod", TestMods.classFile(ContextMod.class),
"testmods/ContextMod$Settings", TestMods.classFile(ContextMod.Settings.class)
));
}
@Test
void loadsStartsAndStopsModsInDependencyOrder() throws Exception
{
TestMods.folder(this.mods, "shop", TestMods.toml("shop", "shop.ShopMod", "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
TestMods.folder(this.mods, "shop", TestMods.toml("shop", "shop.ShopMod", ForgeTest.USES_GAME + "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
"shop/ShopMod", TestMods.modClass("shop/ShopMod", "shop", "economy/Accounts", false)
));
TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ""), Map.of(
TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ForgeTest.USES_GAME), Map.of(
"economy/EconomyMod", TestMods.modClass("economy/EconomyMod", "economy", null, false),
"economy/Accounts", TestMods.pingClass("economy/Accounts")
));
Forge forge = this.forge();
forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader());
Forge forge = this.load();
assertEquals(Lifecycle.Phase.LOADED, forge.phase());
assertEquals(List.of("economy", "shop"), forge.mods().stream().map(mod -> mod.descriptor().id()).toList());
@@ -80,23 +94,68 @@ class ForgeTest
"economy:onServerStarted", "shop:onServerStarted",
"shop:onStopping", "economy:onStopping"
),
TestMods.Recorder.EVENTS
Recorder.EVENTS
);
}
@Test
void modsSeeTheirContextInTheConstructor() throws Exception
void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception
{
TestMods.folder(this.mods, "context", TestMods.toml("context", ContextMod.class.getName(), ""), Map.of());
this.contextMod("", """
greeting = "default"
limit = 5
Forge forge = this.forge();
forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader());
[prices]
apple = 3
""");
Files.writeString(this.mods.resolve("context").resolve("config.toml"), "greeting = \"hi\"\n");
ContextMod mod = ContextMod.instance;
assertSame(mod, forge.mods().getFirst().mod());
assertEquals("context", mod.idInConstructor);
assertEquals(ForgeTest.GAME, mod.gameInConstructor);
assertEquals(this.mods.resolve("context"), mod.directoryInConstructor);
Object mod = this.load().mods().getFirst().mod();
assertNotSame(ContextMod.class, mod.getClass(), "the mod class comes from the mod's jar");
assertEquals("context", ForgeTest.field(mod, "idInConstructor"));
assertEquals(ForgeTest.GAME, ForgeTest.field(mod, "gameInConstructor"));
assertEquals(this.mods.resolve("context"), ForgeTest.field(mod, "directoryInConstructor"));
assertEquals("Settings[greeting=hi, limit=5, extra=Optional.empty, prices={apple=3}]", ForgeTest.field(mod, "settings").toString());
}
@Test
void writesTheDefaultSettingsWhenTheFolderHasNone() throws Exception
{
String defaults = "greeting = \"default\"\nlimit = 5\n[prices]\n";
this.contextMod("", defaults);
this.load();
assertEquals(defaults, Files.readString(this.mods.resolve("context").resolve("config.toml")));
}
@Test
void failsWhenTheSettingsDoNotMatchTheRecord() throws IOException
{
this.contextMod("", "greeting = 7\n");
ModLoadException e = assertThrows(ModLoadException.class, this::load);
assertEquals(
List.of("'context': the constructor of 'testmods.ContextMod' threw java.lang.IllegalStateException: config.toml does not match 'Settings': 'greeting' must be a string, found 7. 'limit' is missing. 'prices' is missing."),
e.problems()
);
}
@Test
void skipsDisabledModsAndFailsTheirDependents() throws Exception
{
this.contextMod("", null);
Files.writeString(this.mods.resolve("context").resolve("config.toml"), "[forge]\nenabled = false\n");
Forge forge = this.load();
assertTrue(forge.mods().isEmpty());
TestMods.folder(this.mods, "needs", TestMods.toml("needs", "needs.Mod", "[dependencies]\ncontext = \"1.0\"\n"), Map.of());
ModLoadException e = assertThrows(ModLoadException.class, this::load);
assertEquals(List.of("'needs': requires 'context', which is disabled in its config.toml."), e.problems());
}
@Test
@@ -112,8 +171,7 @@ class ForgeTest
{
Files.delete(this.mods);
Forge forge = this.forge();
forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader());
Forge forge = this.load();
assertTrue(forge.mods().isEmpty());
assertEquals(Lifecycle.Phase.LOADED, forge.phase());
@@ -122,12 +180,12 @@ class ForgeTest
@Test
void failsWhenOnLoadThrows() throws IOException
{
TestMods.folder(this.mods, "broken", TestMods.toml("broken", "broken.BrokenMod", ""), Map.of(
TestMods.folder(this.mods, "broken", TestMods.toml("broken", "broken.BrokenMod", ForgeTest.USES_GAME), Map.of(
"broken/BrokenMod", TestMods.modClass("broken/BrokenMod", "broken", null, true)
));
Forge forge = this.forge();
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader()));
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader()));
assertEquals(List.of("'broken': onLoad() threw java.lang.IllegalStateException: broken."), e.problems());
assertEquals(Lifecycle.Phase.BOOTING, forge.phase());
@@ -136,17 +194,30 @@ class ForgeTest
@Test
void failsWhenTheEntryPointIsNoMod() throws IOException
{
TestMods.folder(this.mods, "plain", TestMods.toml("plain", "plain.Accounts", ""), Map.of(
TestMods.folder(this.mods, "plain", TestMods.toml("plain", "plain.Accounts", ForgeTest.USES_GAME), Map.of(
"plain/Accounts", TestMods.pingClass("plain/Accounts")
));
TestMods.folder(this.mods, "missing", TestMods.toml("missing", "missing.Gone", ""), Map.of());
ModLoadException missing = assertThrows(ModLoadException.class, () -> this.forge().load(ForgeTest.GAME, ForgeTest.class.getClassLoader()));
assertEquals(List.of("'missing': entry point 'missing.Gone' cannot be loaded: java.lang.ClassNotFoundException: missing.Gone."), missing.problems());
ModLoadException missing = assertThrows(ModLoadException.class, this::load);
assertEquals(List.of("'missing': entry point 'missing.Gone' cannot be loaded: java.lang.ClassNotFoundException: missing.Gone (not visible to mod 'missing')."), missing.problems());
Files.walk(this.mods.resolve("missing")).sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
try (Stream<Path> paths = Files.walk(this.mods.resolve("missing"))) { paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete()); }
ModLoadException plain = assertThrows(ModLoadException.class, () -> this.forge().load(ForgeTest.GAME, ForgeTest.class.getClassLoader()));
ModLoadException plain = assertThrows(ModLoadException.class, this::load);
assertEquals(List.of("'plain': entry point 'plain.Accounts' does not extend 'dev.overlord.zomboidforge.api.Mod'."), plain.problems());
}
@Test
void settingsOfOptionalValues() throws Exception
{
this.contextMod("", "greeting = \"a\"\nlimit = 1\nextra = \"b\"\n[prices]\n");
Object mod = this.load().mods().getFirst().mod();
Object settings = ForgeTest.field(mod, "settings");
assertEquals(Optional.of("b"), settings.getClass().getMethod("extra").invoke(settings));
}
private static Object field(Object mod, String name) throws ReflectiveOperationException { return mod.getClass().getField(name).get(mod); }
}
@@ -0,0 +1,136 @@
package dev.overlord.zomboidforge.core.config;
import dev.overlord.zomboidforge.core.ConsoleLogger;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class TomlModConfigTest
{
private enum Mode { EASY, HARD }
private record Limits(int perDay, double factor) {}
private record Settings(
String greeting,
boolean enabled,
long maxBalance,
float ratio,
Mode mode,
List<String> admins,
Map<String, Long> prices,
Limits limits,
Optional<String> motd,
Optional<Integer> httpPort
) {}
private static TomlModConfig config(String defaults, String settings)
{
return new TomlModConfig(TomlTree.merge(TomlTree.parse(defaults), TomlTree.parse(settings)), new ConsoleLogger("test"));
}
@Test
void bindsEverySupportedTypeOverDefaults()
{
TomlModConfig config = TomlModConfigTest.config("""
greeting = "default"
enabled = true
max_balance = 100
ratio = 0.5
mode = "easy"
admins = ["a"]
[prices]
apple = 3
[limits]
per_day = 10
factor = 1.5
""", """
greeting = "hi"
mode = "HARD"
http_port = 8080
unused = 1
[limits]
per_day = 20
""");
assertEquals(
new Settings("hi", true, 100, 0.5F, Mode.HARD, List.of("a"), Map.of("apple", 3L), new Limits(20, 1.5), Optional.empty(), Optional.of(8080)),
config.bind(Settings.class)
);
}
@Test
void reportsEveryProblem()
{
TomlModConfig config = TomlModConfigTest.config("", """
greeting = 1
enabled = "yes"
mode = "medium"
admins = ["a", 2]
prices = 5
http_port = 99999999999
[limits]
per_day = 1.5
""");
IllegalStateException e = assertThrows(IllegalStateException.class, () -> config.bind(Settings.class));
assertEquals(
"config.toml does not match 'Settings': "
+ "'greeting' must be a string, found 1. "
+ "'enabled' must be true or false, found \"yes\". "
+ "'max_balance' is missing. "
+ "'ratio' is missing. "
+ "'mode' must be one of \"easy\", \"hard\", found \"medium\". "
+ "'admins[1]' must be a string, found 2. "
+ "'prices' must be a table, found 5. "
+ "'limits.per_day' must be an integer, found 1.5. "
+ "'limits.factor' is missing. "
+ "'http_port' must be between -2147483648 and 2147483647, found 99999999999.",
e.getMessage()
);
}
@Test
void readsSingleValuesByPath()
{
TomlModConfig config = TomlModConfigTest.config("[limits]\nper_day = 10\n", "");
assertEquals(Optional.of(10L), config.get("limits.per_day", Long.class));
assertEquals(Optional.of(10), config.get("limits.per_day", Integer.class));
assertEquals(Optional.empty(), config.get("limits.other", Long.class));
assertEquals(Optional.empty(), config.get("missing.per_day", Long.class));
assertThrows(IllegalStateException.class, () -> config.get("limits.per_day", String.class));
}
@Test
void convertsComponentNamesToKeys()
{
assertEquals("max_balance", RecordBinder.key("maxBalance"));
assertEquals("http_port", RecordBinder.key("httpPort"));
assertEquals("http_port", RecordBinder.key("HTTPPort"));
assertEquals("api_key2", RecordBinder.key("apiKey2"));
assertEquals("name", RecordBinder.key("name"));
}
@Test
void mergesTablesKeyByKey()
{
Map<String, Object> merged = TomlTree.merge(
TomlTree.parse("a = 1\n[t]\nx = 1\ny = 2\n"),
TomlTree.parse("b = 2.5\n[t]\ny = 3\n")
);
assertEquals(Map.of("a", 1L, "b", 2.5, "t", Map.of("x", 1L, "y", 3L)), merged);
}
}
@@ -0,0 +1,104 @@
package dev.overlord.zomboidforge.core.mods;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ModClassLoaderTest
{
@TempDir
Path directory;
private GameClasses game;
private URLClassLoader parent;
@BeforeEach
void setUp() throws IOException
{
Path gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
this.game = GameClasses.open(gameJar);
this.parent = new URLClassLoader(new URL[]{gameJar.toUri().toURL()}, ModClassLoaderTest.class.getClassLoader());
}
@AfterEach
void tearDown() throws IOException
{
this.game.close();
this.parent.close();
}
private ModClassLoader loader(String id, Map<String, byte[]> own, Map<String, byte[]> library, List<ModClassLoader> dependencies, @Nullable GameClasses game) throws IOException
{
Path jar = this.directory.resolve(id + ".jar");
Path lib = this.directory.resolve(id + "-lib.jar");
TestMods.jar(jar, null, own);
TestMods.jar(lib, null, library);
return new ModClassLoader(id, jar, List.of(lib), this.parent, dependencies, game);
}
@Test
void seesTheJdkAndTheApiButNotZomboidForgeInternals() throws Exception
{
try (ModClassLoader loader = this.loader("plain", Map.of(), Map.of(), List.of(), null))
{
assertSame(String.class, loader.loadClass("java.lang.String"));
assertSame(java.sql.Connection.class, loader.loadClass("java.sql.Connection"));
assertSame(dev.overlord.zomboidforge.api.Mod.class, loader.loadClass("dev.overlord.zomboidforge.api.Mod"));
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("dev.overlord.zomboidforge.api.internal.ModBinding"));
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("dev.overlord.zomboidforge.core.Forge"));
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("org.junit.jupiter.api.Test"));
}
}
@Test
void seesGameClassesOnlyWithDeclaredGameVersions() throws Exception
{
try (ModClassLoader without = this.loader("without", Map.of(), Map.of(), List.of(), null);
ModClassLoader with = this.loader("with", Map.of(), Map.of(), List.of(), this.game))
{
ClassNotFoundException e = assertThrows(ClassNotFoundException.class, () -> without.loadClass("zombie.core.Core"));
assertEquals("zombie.core.Core (not visible to mod 'without')", e.getMessage());
assertSame(this.parent.loadClass("zombie.core.Core"), with.loadClass("zombie.core.Core"));
}
}
@Test
void ownLibrariesTakePrecedenceOverGameLibraries() throws Exception
{
Map<String, byte[]> shared = Map.of("com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null));
try (ModClassLoader loader = this.loader("bundled", Map.of(), shared, List.of(), this.game))
{
assertSame(loader, loader.loadClass("com.example.Shared").getClassLoader());
}
}
@Test
void dependenciesShareTheirOwnJarButNotTheirLibraries() throws Exception
{
try (ModClassLoader economy = this.loader("economy", Map.of("economy/Accounts", TestMods.pingClass("economy/Accounts")), Map.of("economy/lib/Util", TestMods.type("economy/lib/Util", "java/lang/Object", null)), List.of(), null);
ModClassLoader shop = this.loader("shop", Map.of(), Map.of(), List.of(economy), null))
{
assertSame(economy.loadClass("economy.Accounts"), shop.loadClass("economy.Accounts"));
assertThrows(ClassNotFoundException.class, () -> shop.loadClass("economy.lib.Util"));
}
}
}
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.core.ConsoleLogger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -14,6 +16,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
class ModDiscoveryTest
{
private static final System.Logger LOGGER = new ConsoleLogger("test");
@TempDir
Path mods;
@@ -30,7 +34,7 @@ class ModDiscoveryTest
Files.writeString(economy.resolve("config.toml"), "");
Files.writeString(this.mods.resolve(".hidden"), "");
List<ModDiscovery.Candidate> candidates = ModDiscovery.discover(this.mods);
List<ModDiscovery.Candidate> candidates = ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER);
assertEquals(List.of("economy", "shop"), candidates.stream().map(ModDiscovery.Candidate::id).toList());
assertEquals(economy.resolve("economy.jar"), candidates.getFirst().jar());
@@ -51,7 +55,7 @@ class ModDiscoveryTest
TestMods.folder(this.mods, "plain", null, Map.of());
TestMods.folder(this.mods, "typo", TestMods.toml("typo", "a.Typo", "colour = \"red\"\n"), Map.of());
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods));
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER));
assertEquals(
List.of(
@@ -65,4 +69,33 @@ class ModDiscoveryTest
e.problems()
);
}
@Test
void readsTheForgeTableAndReportsBadSettings() throws Exception
{
Path off = TestMods.folder(this.mods, "off", TestMods.toml("off", "a.Off", ""), Map.of());
Files.writeString(off.resolve("config.toml"), "[forge]\nenabled = false\n");
Path typo = TestMods.folder(this.mods, "typo", TestMods.toml("typo", "a.Typo", ""), Map.of());
Files.writeString(typo.resolve("config.toml"), "[forge]\nenable = false\nenabled = \"no\"\n");
Path broken = TestMods.folder(this.mods, "broken", TestMods.toml("broken", "a.Broken", ""), Map.of());
Files.writeString(broken.resolve("config.toml"), "limit = \n");
TestMods.folder(this.mods, "author", TestMods.toml("author", "a.Author", ""), "[forge\n", Map.of());
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER));
assertEquals(List.of("author", "broken", "typo", "typo"), e.problems().stream().map(problem -> problem.substring(1, problem.indexOf("'", 1))).toList());
assertEquals("'typo': 'config.toml': unknown key 'forge.enable'; [forge] only has 'enabled'.", e.problems().get(2));
assertEquals("'typo': 'config.toml': 'forge.enabled' must be true or false.", e.problems().get(3));
Files.delete(typo.resolve("config.toml"));
Files.writeString(broken.resolve("config.toml"), "");
TestMods.folder(this.mods, "author", TestMods.toml("author", "a.Author", ""), "[forge]\nenabled = false\n", Map.of());
List<ModDiscovery.Candidate> candidates = ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER);
assertEquals(List.of("author", "broken", "off", "typo"), candidates.stream().map(ModDiscovery.Candidate::id).toList());
assertEquals(List.of(false, true, false, true), candidates.stream().map(ModDiscovery.Candidate::enabled).toList());
}
}
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -19,7 +20,7 @@ class ModResolverTest
private static ModDiscovery.Candidate mod(String id, String extra) throws ModLoadException
{
Path directory = Path.of("mods", id);
return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)));
return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)), true, Map.of());
}
/** A mod built against API 0.4. */
@@ -28,7 +29,7 @@ class ModResolverTest
Path directory = Path.of("mods", id);
String toml = TestMods.toml(id, "a.Mod", "").replace("api = \"0.3\"", "api = \"0.4\"");
return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(toml));
return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(toml), true, Map.of());
}
private static List<String> order(ModDiscovery.Candidate... candidates) throws ModLoadException
@@ -0,0 +1,147 @@
package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.GameVersion;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ModVerifierTest
{
private static final GameVersion GAME = GameVersion.parse("42.21.0");
private static final String CORE = "zombie/core/Core";
@TempDir
Path directory;
private GameClasses game;
@BeforeEach
void setUp() throws IOException { this.game = GameClasses.open(TestMods.gameJar(this.directory.resolve("projectzomboid.jar"))); }
@AfterEach
void tearDown() throws IOException { this.game.close(); }
private ModDiscovery.Candidate mod(String id, String extra, Map<String, byte[]> classes, Map<String, byte[]> library) throws Exception
{
Path folder = TestMods.folder(this.directory.resolve("mods"), id, TestMods.toml(id, "a.Mod", extra), classes);
List<Path> libraries = List.of();
if (!library.isEmpty()) {
Path jar = Files.createDirectories(folder.resolve("lib")).resolve("library.jar");
TestMods.jar(jar, null, library);
libraries = List.of(jar);
}
return new ModDiscovery.Candidate(folder, folder.resolve(id + ".jar"), libraries, ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)), true, Map.of());
}
private List<String> problems(ModDiscovery.Candidate... candidates)
{
ModLoadException e = assertThrows(ModLoadException.class, () -> ModVerifier.verify(List.of(candidates), this.game, ModVerifierTest.GAME));
return e.problems();
}
@Test
void acceptsGameUseWithDeclaredVersionsThatLinks() throws Exception
{
ModDiscovery.Candidate mod = this.mod("linked", "game = [\"42\"]\n", Map.of("a/Use", TestMods.user("a/Use",
TestMods.Use.staticCall(ModVerifierTest.CORE, "version", "()I"),
TestMods.Use.virtualCall(ModVerifierTest.CORE, "inherited", "()V"),
TestMods.Use.virtualCall(ModVerifierTest.CORE, "toString", "()Ljava/lang/String;"),
TestMods.Use.field(ModVerifierTest.CORE, "counter", "I"),
TestMods.Use.type("java/util/List")
)), Map.of());
assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
}
@Test
void reportsMissingGameClassesAndMembers() throws Exception
{
ModDiscovery.Candidate mod = this.mod("linked", "game = [\"42\"]\n", Map.of("a/Use", TestMods.user("a/Use",
TestMods.Use.staticCall(ModVerifierTest.CORE, "gone", "()V"),
TestMods.Use.field(ModVerifierTest.CORE, "missing", "I"),
TestMods.Use.type("zombie/core/Removed")
)), Map.of());
assertEquals(
List.of("'linked': uses 'zombie.core.Removed', 'zombie.core.Core.gone()V', 'zombie.core.Core.missing:I', which do not exist in Project Zomboid 42.21.0."),
this.problems(mod)
);
}
@Test
void requiresGameVersionsForGameClassesIncludingBundledLibraries() throws Exception
{
ModDiscovery.Candidate mod = this.mod("plain", "", Map.of("a/Use", TestMods.user("a/Use",
TestMods.Use.staticCall(ModVerifierTest.CORE, "version", "()I"),
TestMods.Use.type("com/example/Shared")
)), Map.of());
assertEquals(
List.of("'plain': uses classes of the Project Zomboid jar ('com.example.Shared', 'zombie.core.Core') but declares no 'game' versions in mod.toml."),
this.problems(mod)
);
}
@Test
void ownLibrariesAndAnnotationsDoNotCountAsGameUse() throws Exception
{
ModDiscovery.Candidate mod = this.mod("bundled", "", Map.of(
"a/Use", TestMods.user("a/Use", TestMods.Use.type("com/example/Shared")),
"a/Annotated", TestMods.type("a/Annotated", "java/lang/Object", "Lorg/jetbrains/annotations/Nullable;")
), Map.of(
"com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null)
));
assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
}
@Test
void reportsInternalClassesAndForbiddenPackages() throws Exception
{
ModDiscovery.Candidate mod = this.mod("sneaky", "game = [\"42\"]\n", Map.of(
"a/Use", TestMods.user("a/Use",
TestMods.Use.type("dev/overlord/zomboidforge/core/Forge"),
TestMods.Use.type("dev/overlord/zomboidforge/api/internal/ModBinding"),
TestMods.Use.type("dev/overlord/zomboidforge/api/Mod")
),
ModVerifierTest.CORE, TestMods.type(ModVerifierTest.CORE, "java/lang/Object", null),
"dev/overlord/zomboidforge/api/Fake", TestMods.type("dev/overlord/zomboidforge/api/Fake", "java/lang/Object", null)
), Map.of());
assertEquals(
List.of(
"'sneaky': contains 'dev.overlord.zomboidforge.api.Fake', which is in a ZomboidForge package.",
"'sneaky': contains 'zombie.core.Core', which is a class of Project Zomboid.",
"'sneaky': uses 'dev.overlord.zomboidforge.api.internal.ModBinding', which is internal to ZomboidForge.",
"'sneaky': uses 'dev.overlord.zomboidforge.core.Forge', which is internal to ZomboidForge."
),
this.problems(mod)
);
}
@Test
void dependenciesProvideTheirOwnClasses() throws Exception
{
// Accounts.ping() calls Recorder, which is in the fake game jar.
ModDiscovery.Candidate economy = this.mod("economy", "game = [\"42\"]\n", Map.of("economy/Accounts", TestMods.pingClass("economy/Accounts")), Map.of());
ModDiscovery.Candidate shop = this.mod("shop", "[dependencies]\neconomy = \"1.0\"\n", Map.of("a/Use", TestMods.user("a/Use",
TestMods.Use.staticCall("economy/Accounts", "ping", "()V")
)), Map.of());
assertDoesNotThrow(() -> ModVerifier.verify(List.of(economy, shop), this.game, ModVerifierTest.GAME));
}
}
@@ -1,17 +1,18 @@
package dev.overlord.zomboidforge.core.mods;
import testmods.Recorder;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@@ -20,11 +21,21 @@ import java.util.jar.JarOutputStream;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ATHROW;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.DCONST_0;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.FCONST_0;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.LCONST_0;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
@@ -33,20 +44,119 @@ import static org.objectweb.asm.Opcodes.V25;
public final class TestMods
{
private static final String MOD = "dev/overlord/zomboidforge/api/Mod";
private static final String RECORDER = Type.getInternalName(TestMods.Recorder.class);
private static final String RECORDER = Type.getInternalName(Recorder.class);
/** Events recorded by generated classes, e.g. {@code "shop:onLoad"}. */
public static final class Recorder
/**
* One instruction of {@link #user}: {@code NEW}/{@code CHECKCAST} use only {@code owner};
* {@code GETSTATIC}/{@code GETFIELD} and the {@code INVOKE...} opcodes use all parts.
*/
public record Use(int opcode, String owner, String name, String desc)
{
public static final List<String> EVENTS = Collections.synchronizedList(new ArrayList<>());
private Recorder() {}
public static void record(String event) { Recorder.EVENTS.add(event); }
public static Use type(String owner) { return new Use(CHECKCAST, owner, "", ""); }
public static Use field(String owner, String name, String desc) { return new Use(GETSTATIC, owner, name, desc); }
public static Use staticCall(String owner, String name, String desc) { return new Use(INVOKESTATIC, owner, name, desc); }
public static Use virtualCall(String owner, String name, String desc) { return new Use(INVOKEVIRTUAL, owner, name, desc); }
}
private TestMods() {}
/** A public class extending {@code superName}, optionally carrying a class annotation (not loaded at runtime). */
public static byte[] type(String name, String superName, @Nullable String annotationDescriptor, String... methods)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
writer.visit(V25, ACC_PUBLIC, name, null, superName, null);
if (annotationDescriptor != null) writer.visitAnnotation(annotationDescriptor, false).visitEnd();
MethodVisitor init = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, superName, "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
// "name:desc" declares a public static method returning a default value; "name" with a field descriptor declares a field.
for (String member : methods)
{
String[] parts = member.split(":");
if (parts[1].startsWith("(")) {
MethodVisitor method = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, parts[0], parts[1], null, null);
Type returnType = Type.getReturnType(parts[1]);
switch (returnType.getSort())
{
case Type.VOID -> {}
case Type.LONG -> method.visitInsn(LCONST_0);
case Type.FLOAT -> method.visitInsn(FCONST_0);
case Type.DOUBLE -> method.visitInsn(DCONST_0);
case Type.OBJECT, Type.ARRAY -> method.visitInsn(ACONST_NULL);
default -> method.visitInsn(ICONST_0);
}
method.visitInsn(returnType.getOpcode(IRETURN));
method.visitMaxs(0, 0);
}
else writer.visitField(ACC_PUBLIC | ACC_STATIC, parts[0], parts[1], null, null).visitEnd();
}
writer.visitEnd();
return writer.toByteArray();
}
/** A class whose static {@code run()} performs {@code uses}; meant to be scanned, not run. */
public static byte[] user(String name, Use... uses)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
writer.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor run = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "()V", null, null);
for (Use use : uses)
{
switch (use.opcode())
{
case NEW, CHECKCAST -> { run.visitInsn(ACONST_NULL); run.visitTypeInsn(CHECKCAST, use.owner()); }
case GETSTATIC, GETFIELD -> run.visitFieldInsn(GETSTATIC, use.owner(), use.name(), use.desc());
default -> run.visitMethodInsn(use.opcode(), use.owner(), use.name(), use.desc(), false);
}
}
run.visitInsn(RETURN);
run.visitMaxs(0, 0);
writer.visitEnd();
return writer.toByteArray();
}
/**
* A stand-in for the Project Zomboid jar: {@code zombie/core/Base} with {@code inherited()V},
* {@code zombie/core/Core} extending it with {@code version()I} and the field
* {@code counter:I}, {@code com/example/Shared}, the annotation
* {@code org/jetbrains/annotations/Nullable}, and {@link Recorder}.
*/
public static Path gameJar(Path jar) throws IOException
{
TestMods.jar(jar, null, Map.of(
"zombie/core/Base", TestMods.type("zombie/core/Base", "java/lang/Object", null, "inherited:()V"),
"zombie/core/Core", TestMods.type("zombie/core/Core", "zombie/core/Base", null, "version:()I", "counter:I"),
"com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null),
"org/jetbrains/annotations/Nullable", TestMods.type("org/jetbrains/annotations/Nullable", "java/lang/Object", null),
Type.getInternalName(Recorder.class), TestMods.classFile(Recorder.class)
));
return jar;
}
/** The class file of a class on the test class path, e.g. to package it into a mod jar. */
public static byte[] classFile(Class<?> type) throws IOException
{
try (InputStream in = type.getResourceAsStream("/" + Type.getInternalName(type) + ".class"))
{
if (in == null) throw new IOException("No class file for '" + type.getName() + "'.");
return in.readAllBytes();
}
}
/** {@code mod.toml} with the required keys and {@code extra} lines appended. */
public static String toml(String id, String entrypoint, String extra)
{
@@ -59,14 +169,25 @@ public final class TestMods
/** {@code <mods>/<id>/<id>.jar} with {@code mod.toml} (unless {@code null}) and {@code classes} (internal name to bytes). */
public static Path folder(Path mods, String id, @Nullable String toml, Map<String, byte[]> classes) throws IOException
{
return TestMods.folder(mods, id, toml, null, classes);
}
/** Like {@link #folder(Path, String, String, Map)}, with default settings in the jar (unless {@code null}). */
public static Path folder(Path mods, String id, @Nullable String toml, @Nullable String defaultConfig, Map<String, byte[]> classes) throws IOException
{
Path directory = Files.createDirectories(mods.resolve(id));
TestMods.jar(directory.resolve(id + ".jar"), toml, classes);
TestMods.jar(directory.resolve(id + ".jar"), toml, defaultConfig, classes);
return directory;
}
public static void jar(Path jar, @Nullable String toml, Map<String, byte[]> classes) throws IOException
{
TestMods.jar(jar, toml, null, classes);
}
public static void jar(Path jar, @Nullable String toml, @Nullable String defaultConfig, Map<String, byte[]> classes) throws IOException
{
try (OutputStream file = Files.newOutputStream(jar); JarOutputStream out = new JarOutputStream(file))
{
@@ -76,6 +197,12 @@ public final class TestMods
out.closeEntry();
}
if (defaultConfig != null) {
out.putNextEntry(new JarEntry("META-INF/zomboidforge/config.toml"));
out.write(defaultConfig.getBytes(StandardCharsets.UTF_8));
out.closeEntry();
}
for (Map.Entry<String, byte[]> entry : new TreeMap<>(classes).entrySet()) {
out.putNextEntry(new JarEntry(entry.getKey() + ".class"));
out.write(entry.getValue());
@@ -0,0 +1,22 @@
package testmods;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.Mod;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
/**
* Entry point that tests package into a mod jar: outside the ZomboidForge packages, so the mod
* class loader loads it from the jar. Records what its context returns in the constructor.
*/
public final class ContextMod extends Mod
{
public record Settings(String greeting, long limit, Optional<String> extra, Map<String, Long> prices) {}
public final String idInConstructor = this.id();
public final GameVersion gameInConstructor = this.gameVersion();
public final Path directoryInConstructor = this.directory();
public final Settings settings = this.config().bind(Settings.class);
}
+18
View File
@@ -0,0 +1,18 @@
package testmods;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Events recorded by generated mod classes, e.g. {@code "shop:onLoad"}. Tests put this class
* into their fake game jar, so mods that declare {@code game} versions can call it.
*/
public final class Recorder
{
public static final List<String> EVENTS = Collections.synchronizedList(new ArrayList<>());
private Recorder() {}
public static void record(String event) { Recorder.EVENTS.add(event); }
}