diff --git a/build.gradle b/build.gradle index 989fcad2e6..1a79161705 100644 --- a/build.gradle +++ b/build.gradle @@ -368,6 +368,9 @@ def sharedFmlonlyForge = { Project prj -> environment 'MCP_MAPPINGS', '{mcp_mappings}' property 'nativesDirectory', '{natives}' + if (prj.name == 'forge') { + property 'forge.enableGameTest', 'true' + } args '--launchTarget', "${launchPrefix}clientuserdev" args '--version', 'MOD_DEV' @@ -379,9 +382,22 @@ def sharedFmlonlyForge = { Project prj -> environment 'MOD_CLASSES', '{source_roots}' environment 'MCP_MAPPINGS', '{mcp_mappings}' + if (prj.name == 'forge') { + property 'forge.enableGameTest', 'true' + } + args '--launchTarget', "${launchPrefix}serveruserdev" } + if (prj.name == 'forge') { + gameTestServer { + environment 'MOD_CLASSES', '{source_roots}' + environment 'MCP_MAPPINGS', '{mcp_mappings}' + + args '--launchTarget', "${launchPrefix}gametestserveruserdev" + } + } + data { environment 'MOD_CLASSES', '{source_roots}' environment 'MCP_MAPPINGS', '{mcp_mappings}' @@ -926,6 +942,7 @@ project(':forge') { parent runs.forge_client taskName 'forge_test_client' + property 'forge.enableGameTest', 'true' environment 'MOD_CLASSES', 'dummy' // Needed to work around FG limitation, FG will replace this! ideaModule "${rootProject.name}.${project.name}.test" @@ -948,6 +965,7 @@ project(':forge') { parent runs.forge_server taskName 'forge_test_server' + property 'forge.enableGameTest', 'true' environment 'MOD_CLASSES', 'dummy' // Needed to work around FG limitation, FG will replace this! ideaModule "${rootProject.name}.${project.name}.test" @@ -957,6 +975,27 @@ project(':forge') { } } + forge_gameTestServer { + taskName 'forge_gameTestServer' + args '--launchTarget', 'forgegametestserverdev' + ideaModule "${rootProject.name}.${project.name}.main" + + mods { + minecraft { source sourceSets.main } + } + } + + forge_test_gameTestServer { + parent runs.forge_gameTestServer + taskName 'forge_test_gameTestServer' + + ideaModule "${rootProject.name}.${project.name}.test" + + mods { + tests { sources sourceSets.test } + } + } + def forgeDataArgs = [ '--mod', 'forge', '--all', diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeGametestDevLaunchHandler.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeGametestDevLaunchHandler.java new file mode 100644 index 0000000000..95e5fd275b --- /dev/null +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeGametestDevLaunchHandler.java @@ -0,0 +1,39 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.loading.targets; + +import net.minecraftforge.api.distmarker.Dist; + +import java.util.concurrent.Callable; + +public class ForgeGametestDevLaunchHandler extends CommonDevLaunchHandler { + @Override public String name() { return "forgegametestserverdev"; } + @Override public Dist getDist() { return Dist.DEDICATED_SERVER; } + + @Override + public Callable launchService(String[] arguments, ModuleLayer layer) { + return () -> { + var args = preLaunch(arguments, layer); + + Class.forName(layer.findModule("forge").orElseThrow(), "net.minecraftforge.gametest.GameTestMain").getMethod("main", String[].class).invoke(null, (Object)args); + return null; + }; + } +} \ No newline at end of file diff --git a/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeGametestUserdevLaunchHandler.java b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeGametestUserdevLaunchHandler.java new file mode 100644 index 0000000000..8127426d27 --- /dev/null +++ b/fmlloader/src/main/java/net/minecraftforge/fml/loading/targets/ForgeGametestUserdevLaunchHandler.java @@ -0,0 +1,39 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.loading.targets; + +import net.minecraftforge.api.distmarker.Dist; + +import java.util.concurrent.Callable; + +public class ForgeGametestUserdevLaunchHandler extends ForgeUserdevLaunchHandler { + @Override public String name() { return "forgegametestserveruserdev"; } + @Override public Dist getDist() { return Dist.DEDICATED_SERVER; } + + @Override + public Callable launchService(String[] arguments, ModuleLayer layer) { + return () -> { + var args = preLaunch(arguments, layer); + + Class.forName(layer.findModule("forge").orElseThrow(), "net.minecraftforge.gametest.GameTestMain").getMethod("main", String[].class).invoke(null, (Object)args); + return null; + }; + } +} \ No newline at end of file diff --git a/fmlloader/src/main/resources/META-INF/services/cpw.mods.modlauncher.api.ILaunchHandlerService b/fmlloader/src/main/resources/META-INF/services/cpw.mods.modlauncher.api.ILaunchHandlerService index 0552d8e423..4958918533 100644 --- a/fmlloader/src/main/resources/META-INF/services/cpw.mods.modlauncher.api.ILaunchHandlerService +++ b/fmlloader/src/main/resources/META-INF/services/cpw.mods.modlauncher.api.ILaunchHandlerService @@ -14,3 +14,5 @@ net.minecraftforge.fml.loading.targets.ForgeServerDevLaunchHandler net.minecraftforge.fml.loading.targets.ForgeServerUserdevLaunchHandler net.minecraftforge.fml.loading.targets.ForgeDataDevLaunchHandler net.minecraftforge.fml.loading.targets.ForgeDataUserdevLaunchHandler +net.minecraftforge.fml.loading.targets.ForgeGametestDevLaunchHandler +net.minecraftforge.fml.loading.targets.ForgeGametestUserdevLaunchHandler diff --git a/mdk/build.gradle b/mdk/build.gradle index bdeae58389..a663f5948a 100644 --- a/mdk/build.gradle +++ b/mdk/build.gradle @@ -55,6 +55,9 @@ minecraft { // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels property 'forge.logging.console.level', 'debug' + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', 'examplemod' + mods { examplemod { source sourceSets.main @@ -77,6 +80,37 @@ minecraft { // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels property 'forge.logging.console.level', 'debug' + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', 'examplemod' + + mods { + examplemod { + source sourceSets.main + } + } + } + + // This run config launches GameTestServer and runs all registered gametests, then exits. + // By default, the server will crash when no gametests are provided. + // The gametest system is also enabled by default for other run configs under the /test command. + gameTestServer { + workingDirectory project.file('run') + + // Recommended logging data for a userdev environment + // The markers can be added/remove as needed separated by commas. + // "SCAN": For mods scan. + // "REGISTRIES": For firing of registry events. + // "REGISTRYDUMP": For getting the contents of all registries. + property 'forge.logging.markers', 'REGISTRIES' + + // Recommended logging level for the console + // You can set various levels here. + // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels + property 'forge.logging.console.level', 'debug' + + // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. + property 'forge.enabledGameTestNamespaces', 'examplemod' + mods { examplemod { source sourceSets.main diff --git a/patches/minecraft/net/minecraft/client/Minecraft.java.patch b/patches/minecraft/net/minecraft/client/Minecraft.java.patch index 4a9e166c99..b07167c744 100644 --- a/patches/minecraft/net/minecraft/client/Minecraft.java.patch +++ b/patches/minecraft/net/minecraft/client/Minecraft.java.patch @@ -67,10 +67,11 @@ this.f_91064_ = new DebugRenderer(this); RenderSystem.m_69900_(this::m_91113_); if (this.f_91042_.f_83915_ == this.f_90990_.m_85441_() && this.f_91042_.f_83916_ == this.f_90990_.m_85442_()) { -@@ -529,6 +_,10 @@ +@@ -529,6 +_,11 @@ TinyFileDialogs.tinyfd_messageBox("Minecraft", stringbuilder.toString(), "ok", "error", false); } ++ net.minecraftforge.gametest.ForgeGameTestHooks.registerGametests(); + net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.RegisterClientReloadListenersEvent(this.f_91036_)); + net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.EntityRenderersEvent.RegisterLayerDefinitions()); + net.minecraftforge.fml.ModLoader.get().postEvent(new net.minecraftforge.client.event.EntityRenderersEvent.RegisterRenderers()); diff --git a/patches/minecraft/net/minecraft/commands/Commands.java.patch b/patches/minecraft/net/minecraft/commands/Commands.java.patch index 14f62b18d1..f7d327c2ee 100644 --- a/patches/minecraft/net/minecraft/commands/Commands.java.patch +++ b/patches/minecraft/net/minecraft/commands/Commands.java.patch @@ -1,5 +1,14 @@ --- a/net/minecraft/commands/Commands.java +++ b/net/minecraft/commands/Commands.java +@@ -175,7 +_,7 @@ + JfrCommand.m_183645_(this.f_82090_); + } + +- if (SharedConstants.f_136183_) { ++ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) { + TestCommand.m_127946_(this.f_82090_); + } + @@ -199,6 +_,7 @@ if (p_82093_.f_82144_) { PublishCommand.m_138184_(this.f_82090_); diff --git a/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypes.java.patch b/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypes.java.patch index f4bbb6c7d4..8c3131b2fa 100644 --- a/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypes.java.patch +++ b/patches/minecraft/net/minecraft/commands/synchronization/ArgumentTypes.java.patch @@ -1,11 +1,21 @@ --- a/net/minecraft/commands/synchronization/ArgumentTypes.java +++ b/net/minecraft/commands/synchronization/ArgumentTypes.java -@@ -257,4 +_,8 @@ +@@ -118,7 +_,7 @@ + m_121601_("dimension", DimensionArgument.class, new EmptyArgumentSerializer<>(DimensionArgument::m_88805_)); + m_121601_("time", TimeArgument.class, new EmptyArgumentSerializer<>(TimeArgument::m_113037_)); + m_121601_("uuid", UuidArgument.class, new EmptyArgumentSerializer<>(UuidArgument::m_113850_)); +- if (SharedConstants.f_136183_) { ++ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) { + m_121601_("test_argument", TestFunctionArgument.class, new EmptyArgumentSerializer<>(TestFunctionArgument::m_128088_)); + m_121601_("test_class", TestClassNameArgument.class, new EmptyArgumentSerializer<>(TestClassNameArgument::m_127917_)); + } +@@ -256,5 +_,9 @@ + this.f_121619_ = p_121623_; this.f_121620_ = p_121624_; } - } ++ } + @javax.annotation.Nullable public static ResourceLocation getId(ArgumentType type) { + Entry entry = m_121616_(type); + return entry == null ? null : entry.f_121620_; -+ } + } } diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTest.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTest.java.patch new file mode 100644 index 0000000000..f5a2e8e461 --- /dev/null +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTest.java.patch @@ -0,0 +1,14 @@ +--- a/net/minecraft/gametest/framework/GameTest.java ++++ b/net/minecraft/gametest/framework/GameTest.java +@@ -16,6 +_,11 @@ + + boolean m_177045_() default true; + ++ /** ++ * The namespace of where to grab the structure from, generally a mod id. ++ */ ++ String templateNamespace() default ""; ++ + String m_177046_() default ""; + + long m_177047_() default 0L; diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch new file mode 100644 index 0000000000..c665054b71 --- /dev/null +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestRegistry.java.patch @@ -0,0 +1,72 @@ +--- a/net/minecraft/gametest/framework/GameTestRegistry.java ++++ b/net/minecraft/gametest/framework/GameTestRegistry.java +@@ -25,21 +_,33 @@ + private static final Map> f_177498_ = Maps.newHashMap(); + private static final Collection f_177499_ = Sets.newHashSet(); + ++ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ ++ @Deprecated + public static void m_177501_(Class p_177502_) { + Arrays.stream(p_177502_.getDeclaredMethods()).forEach(GameTestRegistry::m_177503_); + } + ++ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ ++ @Deprecated + public static void m_177503_(Method p_177504_) { ++ register(p_177504_, java.util.Set.of()); ++ } ++ /** @deprecated Forge: Use {@link net.minecraftforge.event.RegisterGameTestsEvent RegisterGameTestsEvent} to register game tests */ ++ @Deprecated ++ public static void register(Method p_177504_, java.util.Set allowedNamespaces) { + String s = p_177504_.getDeclaringClass().getSimpleName(); + GameTest gametest = p_177504_.getAnnotation(GameTest.class); +- if (gametest != null) { ++ if (gametest != null && (allowedNamespaces.isEmpty() || allowedNamespaces.contains(net.minecraftforge.gametest.ForgeGameTestHooks.getTemplateNamespace(p_177504_)))) { + f_177495_.add(m_177515_(p_177504_)); + f_177496_.add(s); + } + + GameTestGenerator gametestgenerator = p_177504_.getAnnotation(GameTestGenerator.class); + if (gametestgenerator != null) { +- f_177495_.addAll(m_177513_(p_177504_)); ++ Collection testFunctions = new java.util.ArrayList<>(m_177513_(p_177504_)); ++ if (!allowedNamespaces.isEmpty()) ++ testFunctions.removeIf(t -> !allowedNamespaces.contains(new net.minecraft.resources.ResourceLocation(t.m_128078_()).m_135827_())); ++ f_177495_.addAll(testFunctions); + f_177496_.add(s); + } + +@@ -104,7 +_,9 @@ + + private static Collection m_177513_(Method p_177514_) { + try { +- Object object = p_177514_.getDeclaringClass().newInstance(); ++ Object object = null; ++ if (!java.lang.reflect.Modifier.isStatic(p_177514_.getModifiers())) ++ object = p_177514_.getDeclaringClass().newInstance(); + return (Collection)p_177514_.invoke(object); + } catch (ReflectiveOperationException reflectiveoperationexception) { + throw new RuntimeException(reflectiveoperationexception); +@@ -115,8 +_,9 @@ + GameTest gametest = p_177516_.getAnnotation(GameTest.class); + String s = p_177516_.getDeclaringClass().getSimpleName(); + String s1 = s.toLowerCase(); +- String s2 = s1 + "." + p_177516_.getName().toLowerCase(); +- String s3 = gametest.m_177046_().isEmpty() ? s2 : s1 + "." + gametest.m_177046_(); ++ boolean prefixGameTestTemplate = net.minecraftforge.gametest.ForgeGameTestHooks.prefixGameTestTemplate(p_177516_); ++ String s2 = (prefixGameTestTemplate ? s1 + "." : "") + p_177516_.getName().toLowerCase(); ++ String s3 = net.minecraftforge.gametest.ForgeGameTestHooks.getTemplateNamespace(p_177516_) + ":" + (gametest.m_177046_().isEmpty() ? s2 : (prefixGameTestTemplate ? s1 + "." : "") + gametest.m_177046_()); + String s4 = gametest.m_177043_(); + Rotation rotation = StructureUtils.m_127835_(gametest.m_177044_()); + return new TestFunction(s4, s2, s3, rotation, gametest.m_177042_(), gametest.m_177047_(), gametest.m_177045_(), gametest.m_177049_(), gametest.m_177048_(), (Consumer)m_177519_(p_177516_)); +@@ -125,7 +_,9 @@ + private static Consumer m_177519_(Method p_177520_) { + return (p_177512_) -> { + try { +- Object object = p_177520_.getDeclaringClass().newInstance(); ++ Object object = null; ++ if (!java.lang.reflect.Modifier.isStatic(p_177520_.getModifiers())) ++ object = p_177520_.getDeclaringClass().newInstance(); + p_177520_.invoke(object, p_177512_); + } catch (InvocationTargetException invocationtargetexception) { + if (invocationtargetexception.getCause() instanceof RuntimeException) { diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch new file mode 100644 index 0000000000..a32a9c02de --- /dev/null +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch @@ -0,0 +1,17 @@ +--- a/net/minecraft/gametest/framework/GameTestServer.java ++++ b/net/minecraft/gametest/framework/GameTestServer.java +@@ -69,12 +_,13 @@ + public boolean m_7038_() { + this.m_129823_(new PlayerList(this, this.f_129746_, this.f_129745_, 1) { + }); ++ if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; + this.m_130006_(); + ServerLevel serverlevel = this.m_129783_(); + serverlevel.m_8733_(this.f_177588_, 0.0F); + int i = 20000000; + serverlevel.m_8606_(20000000, 20000000, false, false); +- return true; ++ return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); + } + + public void m_5705_(BooleanSupplier p_177619_) { diff --git a/patches/minecraft/net/minecraft/gametest/framework/StructureUtils.java.patch b/patches/minecraft/net/minecraft/gametest/framework/StructureUtils.java.patch new file mode 100644 index 0000000000..e56e9fde1b --- /dev/null +++ b/patches/minecraft/net/minecraft/gametest/framework/StructureUtils.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/gametest/framework/StructureUtils.java ++++ b/net/minecraft/gametest/framework/StructureUtils.java +@@ -238,7 +_,7 @@ + if (optional.isPresent()) { + return optional.get(); + } else { +- String s = p_127881_ + ".snbt"; ++ String s = new ResourceLocation(p_127881_).m_135815_() + ".snbt"; + Path path = Paths.get(f_127833_, s); + CompoundTag compoundtag = m_127902_(path); + if (compoundtag == null) { diff --git a/patches/minecraft/net/minecraft/server/Eula.java.patch b/patches/minecraft/net/minecraft/server/Eula.java.patch new file mode 100644 index 0000000000..f6c6662d8e --- /dev/null +++ b/patches/minecraft/net/minecraft/server/Eula.java.patch @@ -0,0 +1,11 @@ +--- a/net/minecraft/server/Eula.java ++++ b/net/minecraft/server/Eula.java +@@ -16,7 +_,7 @@ + + public Eula(Path p_135943_) { + this.f_135939_ = p_135943_; +- this.f_135940_ = SharedConstants.f_136183_ || this.m_135945_(); ++ this.f_135940_ = SharedConstants.f_136183_ || net.minecraftforge.gametest.ForgeGameTestHooks.isGametestServer() || this.m_135945_(); // Forge: Automatically agree to EULA for gametest servers to aid CI + } + + private boolean m_135945_() { diff --git a/patches/minecraft/net/minecraft/server/Main.java.patch b/patches/minecraft/net/minecraft/server/Main.java.patch index 87d904c1b8..b54d688330 100644 --- a/patches/minecraft/net/minecraft/server/Main.java.patch +++ b/patches/minecraft/net/minecraft/server/Main.java.patch @@ -1,11 +1,18 @@ --- a/net/minecraft/server/Main.java +++ b/net/minecraft/server/Main.java -@@ -76,6 +_,8 @@ +@@ -76,6 +_,15 @@ OptionSpec optionspec12 = optionparser.accepts("serverId").withRequiredArg(); OptionSpec optionspec13 = optionparser.accepts("jfrProfile"); OptionSpec optionspec14 = optionparser.nonOptions(); + optionparser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed + optionparser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side. ++ final OptionSpec spawnPosOpt; ++ boolean gametestEnabled = Boolean.getBoolean("forge.gameTestServer"); ++ if (gametestEnabled) { ++ spawnPosOpt = optionparser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); ++ } else { ++ spawnPosOpt = null; ++ } try { OptionSet optionset = optionparser.parse(p_129699_); @@ -71,9 +78,39 @@ worlddata = new PrimaryLevelData(levelsettings, worldgensettings, Lifecycle.stable()); } -@@ -191,6 +_,7 @@ +@@ -175,22 +_,33 @@ + + levelstoragesource$levelstorageaccess.m_78287_(registryaccess$registryholder, worlddata); + WorldData worlddata1 = worlddata; +- final DedicatedServer dedicatedserver = MinecraftServer.m_129872_((p_129697_) -> { +- DedicatedServer dedicatedserver1 = new DedicatedServer(p_129697_, registryaccess$registryholder, levelstoragesource$levelstorageaccess, packrepository, serverresources, worlddata1, dedicatedserversettings, DataFixers.m_14512_(), minecraftsessionservice, gameprofilerepository, gameprofilecache, LoggerChunkProgressListener::new); ++ final MinecraftServer dedicatedserver = MinecraftServer.m_129872_((p_129697_) -> { ++ MinecraftServer dedicatedserver1; ++ if (gametestEnabled) { ++ net.minecraftforge.gametest.ForgeGameTestHooks.registerGametests(); ++ java.util.Collection testBatches = net.minecraft.gametest.framework.GameTestRunner.m_127724_(net.minecraft.gametest.framework.GameTestRegistry.m_127658_()); ++ net.minecraft.core.BlockPos spawnPos = optionset.valueOf(spawnPosOpt); ++ dedicatedserver1 = new net.minecraft.gametest.framework.GameTestServer(p_129697_, levelstoragesource$levelstorageaccess, packrepository, serverresources, testBatches, spawnPos, registryaccess$registryholder); ++ } else { ++ dedicatedserver1 = new DedicatedServer(p_129697_, registryaccess$registryholder, levelstoragesource$levelstorageaccess, packrepository, serverresources, worlddata1, dedicatedserversettings, DataFixers.m_14512_(), minecraftsessionservice, gameprofilerepository, gameprofilecache, LoggerChunkProgressListener::new); ++ } + dedicatedserver1.m_129981_(optionset.valueOf(optionspec8)); + dedicatedserver1.m_129801_(optionset.valueOf(optionspec11)); + dedicatedserver1.m_129975_(optionset.has(optionspec2)); + dedicatedserver1.m_129948_(optionset.valueOf(optionspec12)); + boolean flag1 = !optionset.has(optionspec) && !optionset.valuesOf(optionspec14).contains("nogui"); +- if (flag1 && !GraphicsEnvironment.isHeadless()) { +- dedicatedserver1.m_139667_(); ++ if (dedicatedserver1 instanceof DedicatedServer dedicatedServer && flag1 && !GraphicsEnvironment.isHeadless()) { ++ dedicatedServer.m_139667_(); + } + + return dedicatedserver1; + }); Thread thread = new Thread("Server Shutdown Thread") { public void run() { ++ // FORGE: Halting as GameTestServer will cause issues as it always calls System#exit on both crash and normal exit, so skip it ++ if (!(dedicatedserver instanceof net.minecraft.gametest.framework.GameTestServer)) dedicatedserver.m_7570_(true); + LogManager.shutdown(); // we're manually managing the logging shutdown on the server. Make sure we do it here at the end. } diff --git a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch index 012b83573f..7d6c9324fd 100644 --- a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch +++ b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch @@ -134,7 +134,7 @@ try { serverlevel.m_8793_(p_129954_); -@@ -854,9 +_,11 @@ +@@ -854,16 +_,18 @@ serverlevel.m_6026_(crashreport); throw new ReportedException(crashreport); } @@ -146,6 +146,14 @@ } this.f_129754_.m_6182_("connection"); + this.m_129919_().m_9721_(); + this.f_129754_.m_6182_("players"); + this.f_129763_.m_11288_(); +- if (SharedConstants.f_136183_) { ++ if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled()) { + GameTestTicker.f_177648_.m_127790_(); + } + @@ -931,7 +_,7 @@ @DontObfuscate diff --git a/src/main/java/net/minecraftforge/event/RegisterGameTestsEvent.java b/src/main/java/net/minecraftforge/event/RegisterGameTestsEvent.java new file mode 100644 index 0000000000..1c0b3d14b1 --- /dev/null +++ b/src/main/java/net/minecraftforge/event/RegisterGameTestsEvent.java @@ -0,0 +1,73 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.event; + +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestGenerator; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; +import net.minecraftforge.gametest.ForgeGameTestHooks; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Set; + +/** + * Game tests are registered on client or server startup. + * It is only run once for a given instance of the game if {@link ForgeGameTestHooks#isGametestEnabled} returns true. + * This is the preferred way to register your game tests. + *

+ * Fired on the Mod bus, see {@link IModBusEvent}. + */ +public class RegisterGameTestsEvent extends Event implements IModBusEvent +{ + private final Set gameTestMethods; + + public RegisterGameTestsEvent(Set gameTestMethods) + { + this.gameTestMethods = gameTestMethods; + } + + /** + * Registers an entire class to the game test registry. + * All methods annotated with {@link GameTest} or {@link GameTestGenerator} will be registered. + * If the set of enabled namespaces is non-empty, + * a method will only be registered if its {@link GameTest#templateNamespace() template namespace} is in an enabled namespace. + * + * @param testClass the test class to register to the game test registry + */ + public void register(Class testClass) + { + Arrays.stream(testClass.getDeclaredMethods()).forEach(this::register); + } + + /** + * Registers a single method to the game test registry. + * The method will only be registered if it is annotated with {@link GameTest} or {@link GameTestGenerator}. + * If the set of enabled namespaces is non-empty, + * the method will only be registered if its {@link GameTest#templateNamespace() template namespace} is an enabled namespace. + * + * @param testMethod the test method to register to the game test registry + */ + public void register(Method testMethod) + { + this.gameTestMethods.add(testMethod); + } +} diff --git a/src/main/java/net/minecraftforge/gametest/BlockPosValueConverter.java b/src/main/java/net/minecraftforge/gametest/BlockPosValueConverter.java new file mode 100644 index 0000000000..cba287e128 --- /dev/null +++ b/src/main/java/net/minecraftforge/gametest/BlockPosValueConverter.java @@ -0,0 +1,45 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.gametest; + +import joptsimple.ValueConverter; +import net.minecraft.core.BlockPos; + +public class BlockPosValueConverter implements ValueConverter +{ + @Override + public BlockPos convert(String value) + { + String[] split = value.split(","); + return new BlockPos(Double.parseDouble(split[0]), Double.parseDouble(split[1]), Double.parseDouble(split[2])); + } + + @Override + public Class valueType() + { + return BlockPos.class; + } + + @Override + public String valuePattern() + { + return null; + } +} diff --git a/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java b/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java new file mode 100644 index 0000000000..d80fd28db7 --- /dev/null +++ b/src/main/java/net/minecraftforge/gametest/ForgeGameTestHooks.java @@ -0,0 +1,143 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.gametest; + +import net.minecraft.SharedConstants; +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestRegistry; +import net.minecraftforge.event.RegisterGameTestsEvent; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.ModLoader; +import net.minecraftforge.fml.loading.FMLLoader; +import net.minecraftforge.forgespi.language.ModFileScanData; +import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.Type; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +public class ForgeGameTestHooks +{ + private static boolean registeredGametests = false; + private static final Logger LOGGER = LogManager.getLogger(); + private static final Type GAME_TEST_HOLDER = Type.getType(GameTestHolder.class); + + public static boolean isGametestEnabled() + { + return !FMLLoader.isProduction() && (SharedConstants.IS_RUNNING_IN_IDE || isGametestServer() || Boolean.getBoolean("forge.enableGameTest")); + } + + public static boolean isGametestServer() + { + return !FMLLoader.isProduction() && Boolean.getBoolean("forge.gameTestServer"); + } + + @SuppressWarnings("deprecation") + public static void registerGametests() + { + if (!registeredGametests && isGametestEnabled()) + { + Set enabledNamespaces = getEnabledNamespaces(); + LOGGER.info("Enabled Gametest Namespaces: {}", enabledNamespaces); + + Set gameTestMethods = new HashSet<>(); + RegisterGameTestsEvent event = new RegisterGameTestsEvent(gameTestMethods); + + ModLoader.get().postEvent(event); + + ModList.get().getAllScanData().stream() + .map(ModFileScanData::getAnnotations) + .flatMap(Collection::stream) + .filter(a -> GAME_TEST_HOLDER.equals(a.annotationType())) + .forEach(a -> addGameTestMethods(a, gameTestMethods)); + + for (Method gameTestMethod : gameTestMethods) + { + GameTestRegistry.register(gameTestMethod, enabledNamespaces); + } + + registeredGametests = true; + } + } + + private static Set getEnabledNamespaces() + { + String enabledNamespacesStr = System.getProperty("forge.enabledGameTestNamespaces"); + if (enabledNamespacesStr == null) + { + return Set.of(); + } + + return Arrays.stream(enabledNamespacesStr.split(",")).filter(s -> !s.isBlank()).collect(Collectors.toUnmodifiableSet()); + } + + private static void addGameTestMethods(AnnotationData annotationData, Set gameTestMethods) + { + try + { + Class clazz = Class.forName(annotationData.clazz().getClassName(), true, ForgeGameTestHooks.class.getClassLoader()); + + gameTestMethods.addAll(Arrays.asList(clazz.getDeclaredMethods())); + } + catch (ClassNotFoundException e) + { + // Should not be possible + throw new RuntimeException(e); + } + } + + public static String getTemplateNamespace(Method method) + { + GameTest gameTest = method.getAnnotation(GameTest.class); + + if (gameTest != null && !gameTest.templateNamespace().isEmpty()) + { + return gameTest.templateNamespace(); + } + + GameTestHolder gameTestHolder = method.getDeclaringClass().getAnnotation(GameTestHolder.class); + + if (gameTestHolder != null) + { + return gameTestHolder.value(); + } + + return "minecraft"; + } + + public static boolean prefixGameTestTemplate(Method method) + { + PrefixGameTestTemplate annotation = method.getAnnotation(PrefixGameTestTemplate.class); + + if (annotation == null) + { + annotation = method.getDeclaringClass().getAnnotation(PrefixGameTestTemplate.class); + } + + // The vanilla game test system prefixes the classname by default, so we preserve that behavior here. + return annotation == null || annotation.value(); + } +} diff --git a/src/main/java/net/minecraftforge/gametest/GameTestHolder.java b/src/main/java/net/minecraftforge/gametest/GameTestHolder.java new file mode 100644 index 0000000000..a966c848cf --- /dev/null +++ b/src/main/java/net/minecraftforge/gametest/GameTestHolder.java @@ -0,0 +1,23 @@ +package net.minecraftforge.gametest; + +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestGenerator; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Marks a class as containing game tests that should be registered automatically. + * All methods annotated with {@link GameTest} or {@link GameTestGenerator} will be registered. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface GameTestHolder +{ + /** + * Used as the default {@link GameTest#templateNamespace() template namespace} for any game tests in the class that do not specify one. + */ + String value() default "minecraft"; +} diff --git a/src/main/java/net/minecraftforge/gametest/GameTestMain.java b/src/main/java/net/minecraftforge/gametest/GameTestMain.java new file mode 100644 index 0000000000..d7feca10be --- /dev/null +++ b/src/main/java/net/minecraftforge/gametest/GameTestMain.java @@ -0,0 +1,32 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.gametest; + +import net.minecraft.server.Main; + +public class GameTestMain +{ + public static void main(String[] args) + { + System.setProperty("forge.enableGameTest", "true"); + System.setProperty("forge.gameTestServer", "true"); + Main.main(args); + } +} diff --git a/src/main/java/net/minecraftforge/gametest/PrefixGameTestTemplate.java b/src/main/java/net/minecraftforge/gametest/PrefixGameTestTemplate.java new file mode 100644 index 0000000000..0d72d8d418 --- /dev/null +++ b/src/main/java/net/minecraftforge/gametest/PrefixGameTestTemplate.java @@ -0,0 +1,33 @@ +package net.minecraftforge.gametest; + +import net.minecraft.gametest.framework.GameTest; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * When used on a class, this sets the default state for whether + * to prefix any contained game test templates with the {@link Class#getSimpleName() simple class name} or not. + *

+ * When used on a method, this defines whether the specific method should be prefixed with the simple class name or not. + *

+ * If this annotation cannot be found on a game test method or its containing class, the default behavior is to prefix the class name. + *

+ * Method annotations override any class annotations. + * + * @see GameTestHolder + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface PrefixGameTestTemplate +{ + /** + * Whether to prefix the game test template with the containing class' {@link Class#getSimpleName() simple name}. + * For example, true in a class named "MyTest" would result in "mytest.structure" while false would result in "structure". + *

+ * Only applies to methods annotated with {@link GameTest}. + */ + boolean value() default true; +} diff --git a/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java b/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java index a565ba0b10..dd955780e0 100644 --- a/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java +++ b/src/main/java/net/minecraftforge/server/ServerLifecycleHooks.java @@ -29,6 +29,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; +import net.minecraft.gametest.framework.GameTestServer; import net.minecraft.server.packs.repository.PackSource; import net.minecraft.server.packs.repository.RepositorySource; import net.minecraft.world.level.storage.LevelResource; @@ -97,7 +98,12 @@ public class ServerLifecycleHooks public static boolean handleServerStarting(final MinecraftServer server) { - DistExecutor.runWhenOn(Dist.DEDICATED_SERVER, ()->()->LanguageHook.loadLanguagesOnServer(server)); + DistExecutor.runWhenOn(Dist.DEDICATED_SERVER, ()->()->{ + LanguageHook.loadLanguagesOnServer(server); + // GameTestServer requires the gametests to be registered earlier, so it is done in main and should not be done twice. + if (!(server instanceof GameTestServer)) + net.minecraftforge.gametest.ForgeGameTestHooks.registerGametests(); + }); PermissionAPI.initializePermissionAPI(); return !MinecraftForge.EVENT_BUS.post(new ServerStartingEvent(server)); } diff --git a/src/main/resources/forge.exc b/src/main/resources/forge.exc index 5f7b231a97..917888b4a9 100644 --- a/src/main/resources/forge.exc +++ b/src/main/resources/forge.exc @@ -20,6 +20,7 @@ net/minecraft/data/tags/GameEventTagsProvider.(Lnet/minecraft/data/DataGen net/minecraft/data/tags/ItemTagsProvider.(Lnet/minecraft/data/DataGenerator;Lnet/minecraft/data/tags/BlockTagsProvider;Ljava/lang/String;Lnet/minecraftforge/common/data/ExistingFileHelper;)V=|p_126530_,p_126531_,modId,existingFileHelper net/minecraft/data/tags/TagsProvider.(Lnet/minecraft/data/DataGenerator;Lnet/minecraft/core/Registry;Ljava/lang/String;Lnet/minecraftforge/common/data/ExistingFileHelper;)V=|p_126546_,p_126547_,modId,existingFileHelper net/minecraft/data/tags/TagsProvider.(Lnet/minecraft/data/DataGenerator;Lnet/minecraft/core/Registry;Ljava/lang/String;Lnet/minecraftforge/common/data/ExistingFileHelper;Ljava/lang/String;)V=|p_126546_,p_126547_,modId,existingFileHelper,folder +net/minecraft/gametest/framework/GameTestRegistry.register(Ljava/lang/reflect/Method;)V=|p_177504_,allowedNamespaces net/minecraft/network/FriendlyByteBuf.writeItemStack(Lnet/minecraft/world/item/ItemStack;Z)Lnet/minecraft/network/FriendlyByteBuf;=|p_130056_,limitedTag net/minecraft/server/dedicated/DedicatedServer.sendMessage(Lnet/minecraft/network/chat/Component;Ljava/util/UUID;)V=|message,p_108776_ net/minecraft/server/level/ServerLevel.removeEntity(Lnet/minecraft/world/entity/Entity;Z)V=|p_8868_,keepData diff --git a/src/test/java/net/minecraftforge/debug/misc/GameTestTest.java b/src/test/java/net/minecraftforge/debug/misc/GameTestTest.java new file mode 100644 index 0000000000..e4b4d1c6c4 --- /dev/null +++ b/src/test/java/net/minecraftforge/debug/misc/GameTestTest.java @@ -0,0 +1,235 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2021. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.debug.misc; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.gametest.framework.GameTest; +import net.minecraft.gametest.framework.GameTestGenerator; +import net.minecraft.gametest.framework.GameTestHelper; +import net.minecraft.gametest.framework.TestFunction; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour.Properties; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.material.MaterialColor; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.util.LazyOptional; +import net.minecraftforge.energy.CapabilityEnergy; +import net.minecraftforge.energy.EnergyStorage; +import net.minecraftforge.energy.IEnergyStorage; +import net.minecraftforge.event.RegisterGameTestsEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.gametest.PrefixGameTestTemplate; +import net.minecraftforge.registries.DeferredRegister; +import net.minecraftforge.registries.ForgeRegistries; +import net.minecraftforge.registries.RegistryObject; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +@Mod(GameTestTest.MODID) +public class GameTestTest +{ + public static final String MODID = "gametest_test"; + public static final boolean ENABLED = true; + private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID); + private static final DeferredRegister ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID); + private static final DeferredRegister> BLOCK_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITIES, MODID); + private static final RegistryObject ENERGY_BLOCK = BLOCKS.register("energy_block", + () -> new EnergyBlock(Properties.of(Material.STONE, MaterialColor.STONE))); + private static final RegistryObject ENERGY_BLOCK_ITEM = ITEMS.register("energy_block", + () -> new BlockItem(ENERGY_BLOCK.get(), new Item.Properties().tab(CreativeModeTab.TAB_MISC))); + private static final RegistryObject> ENERGY_BLOCK_ENTITY = BLOCK_ENTITIES.register("energy", + () -> BlockEntityType.Builder.of(EnergyBlockEntity::new, ENERGY_BLOCK.get()).build(null)); + + public GameTestTest() + { + if (ENABLED) + { + IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus(); + modBus.register(this); + + BLOCKS.register(modBus); + ITEMS.register(modBus); + BLOCK_ENTITIES.register(modBus); + } + } + + @SubscribeEvent + public void onRegisterGameTests(RegisterGameTestsEvent event) + { + // Registers all methods in this class annotated with @GameTest or @GameTestGenerator to the GameTestRegistry + event.register(this.getClass()); + } + + /** + * An example game test + *

    + *
  • Must take one parameter, the {@link GameTestHelper}
  • + *
  • The return type is ignored, so it should be {@code void}
  • + *
  • Can be {@code static} or non-static

    + * WARNING: If made non-static, then it will create an instance of the class every time it is run.

  • + *
+ * The default template name converts the containing class's name to all lowercase, and the method name to all lowercase. + * In this example, the structure name would be "gametesttest.testwood" under the "gametest_test" namespace. + */ + @GameTest(templateNamespace = MODID) + public static void testWood(GameTestHelper helper) + { + // The woodPos is in the bottom center of the 3x3x3 structure + BlockPos woodPos = new BlockPos(1, 1, 1); + + // assertBlockState will convert the relative woodPos into a real world block position and check it with the predicate. + // Relative positions are made absolute by adding their value to the block position of the structure tile entity, + // which is always the lowest northwest corner inside the structure. + // If the predicate fails, the String supplier will be used to construct an exception message, which is thrown + helper.assertBlockState(woodPos, b -> b.is(Blocks.OAK_LOG), () -> "Block was not an oak log"); + + // If we got to this point, the assert succeeded, so the test has succeeded. + // Game tests require explicitly declaring success, otherwise they fail from timeout. + helper.succeed(); + } + + /** + * An example game test generator. + *

+ * A game test generator generates a collection of test functions. + * It is called immediately when registered to GameTestRegistry. + *

    + *
  • Must return {@code Collection} (or a subclass)
  • + *
  • Must take no parameters
  • + *
  • Can be {@code static} or non-static
  • + *

    + * WARNING: If made non-static, then it will create an instance of the class every time it is run. + *

+ */ + @GameTestGenerator + public static List generateTests() + { + // An example test function, run in the default batch, with the test name "teststone", and the structure name "gametesttest.teststone" under the "gametest_test" namespace. + // No rotation, 100 ticks until the test times out if it does not fail or succeed, 0 ticks for setup time, and the actual code to run. + TestFunction testStone = new TestFunction("defaultBatch", "teststone", new ResourceLocation(MODID, "gametesttest.teststone").toString(), Rotation.NONE, + 100, 0, true, + helper -> { + BlockPos stonePos = new BlockPos(1, 1, 1); + + // This should always assert to true, since we set it then directly check it + helper.setBlock(stonePos, Blocks.STONE); + helper.assertBlockState(stonePos, b -> b.is(Blocks.STONE), () -> "Block was not stone"); + + helper.succeed(); + }); + return List.of(testStone); + } + + @PrefixGameTestTemplate(false) + @GameTest(templateNamespace = MODID, template = "empty3x3x3") + public static void testHopperPickup(GameTestHelper helper) + { + BlockPos hopperPos = new BlockPos(1, 1, 1); + + // Sets (1,1,1) to a hopper and spawns a golden apple one block above it + helper.setBlock(hopperPos, Blocks.HOPPER); + helper.spawnItem(Items.GOLDEN_APPLE, 1, 2, 1); + + // Waits 20 ticks before checking that the hopper contains the golden apple + helper.assertAtTickTimeContainerContains(20, hopperPos, Items.GOLDEN_APPLE); + + // Succeeds at 21 ticks if the previous check didn't throw an exception + helper.runAtTickTime(21, helper::succeed); + } + + @PrefixGameTestTemplate(false) + @GameTest(templateNamespace = MODID, template = "empty3x3x3") + public static void testEnergyStorage(GameTestHelper helper) + { + BlockPos energyPos = new BlockPos(1, 1, 1); + + // Sets (1,1,1) to our custom energy block + helper.setBlock(energyPos, ENERGY_BLOCK.get()); + + // Queries the energy capability + LazyOptional energyHolder = helper.getBlockEntity(energyPos).getCapability(CapabilityEnergy.ENERGY); + + // Adds 2000 FE, but our energy storage can only hold 1000 FE + energyHolder.ifPresent(energyStorage -> energyStorage.receiveEnergy(2000, false)); + + // Fails test if stored energy is not equal to 1000 FE + int energy = energyHolder.map(IEnergyStorage::getEnergyStored).orElse(0); + int target = 1000; + if (energy != target) + { + helper.fail("Expected energy=" + target + " but it was energy=" + energy, energyPos); + } + + helper.succeed(); + } + + private static class EnergyBlock extends Block implements EntityBlock + { + public EnergyBlock(Properties properties) + { + super(properties); + } + + @Nullable + @Override + public BlockEntity newBlockEntity(BlockPos pos, BlockState state) + { + return new EnergyBlockEntity(pos, state); + } + } + + private static class EnergyBlockEntity extends BlockEntity + { + private final EnergyStorage energyStorage = new EnergyStorage(1000); + private final LazyOptional energyHolder = LazyOptional.of(() -> energyStorage); + + public EnergyBlockEntity(BlockPos pos, BlockState state) + { + super(ENERGY_BLOCK_ENTITY.get(), pos, state); + } + + @NotNull + @Override + public LazyOptional getCapability(@NotNull Capability capability, @Nullable Direction facing) + { + if (capability == CapabilityEnergy.ENERGY) + return energyHolder.cast(); + + return super.getCapability(capability, facing); + } + } +} diff --git a/src/test/resources/META-INF/mods.toml b/src/test/resources/META-INF/mods.toml index 940683172d..4a26d46301 100644 --- a/src/test/resources/META-INF/mods.toml +++ b/src/test/resources/META-INF/mods.toml @@ -198,5 +198,7 @@ license="LGPL v2.1" modId="registry_object_test" [[mods]] modId="hidden_tooltip_parts" +[[mods]] + modId="gametest_test" # ADD ABOVE THIS LINE diff --git a/src/test/resources/data/gametest_test/structures/empty3x3x3.nbt b/src/test/resources/data/gametest_test/structures/empty3x3x3.nbt new file mode 100644 index 0000000000..ac4f797f1c Binary files /dev/null and b/src/test/resources/data/gametest_test/structures/empty3x3x3.nbt differ diff --git a/src/test/resources/data/gametest_test/structures/gametesttest.teststone.nbt b/src/test/resources/data/gametest_test/structures/gametesttest.teststone.nbt new file mode 100644 index 0000000000..059fb2f74c Binary files /dev/null and b/src/test/resources/data/gametest_test/structures/gametesttest.teststone.nbt differ diff --git a/src/test/resources/data/gametest_test/structures/gametesttest.testwood.nbt b/src/test/resources/data/gametest_test/structures/gametesttest.testwood.nbt new file mode 100644 index 0000000000..b8d2371acc Binary files /dev/null and b/src/test/resources/data/gametest_test/structures/gametesttest.testwood.nbt differ