Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fabric Game Test API #1622

Merged
merged 23 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions fabric-game-test-api-v1/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
archivesBaseName = "fabric-game-test-api-v1"
version = getSubprojectVersion(project, "1.0.0")

moduleDependencies(project, [
'fabric-api-base',
'fabric-resource-loader-v0'
])


loom {
runs {
gametest {
server()
name "Game Test"
vmArg "-Dfabric-api.gametest.server=true"
runDir "build/gametest"

// Specific to fabric api
source sourceSets.testmod
ideConfigGenerated true
}
}
}
test.dependsOn runGametest
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.api.gametest.v1;

import net.fabricmc.fabric.impl.client.gametest.FabricGameTestHelperImpl;

public interface FabricGameTestRegistry {
/**
* Use in {@link net.minecraft.test.GameTest} structureName to use an empty 8x8 structure for the test.
*/
String EMPTY_STRUCTURE = "fabric-game-test-api-v1:empty";

/**
* Register a class to be used as a test suite.
*
* @param testClass The test suite class
* @param modid The modid of the suite, used to determine the structure resource namespace
*/
static void register(Class<?> testClass, String modid) {
FabricGameTestHelperImpl.register(testClass, modid);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.impl.client.gametest;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.minecraft.resource.ResourcePackManager;
import net.minecraft.resource.ServerResourceManager;
import net.minecraft.server.MinecraftServer;
import net.minecraft.test.GameTestBatch;
import net.minecraft.test.TestContext;
import net.minecraft.test.TestFunction;
import net.minecraft.test.TestFunctions;
import net.minecraft.test.TestServer;
import net.minecraft.test.TestUtil;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.DynamicRegistryManager;
import net.minecraft.world.level.storage.LevelStorage;

import net.fabricmc.loader.FabricLoader;

public class FabricGameTestHelperImpl {
public static final boolean ENABLED = Boolean.getBoolean("fabric-api.gametest.server");

private static final Logger LOGGER = LogManager.getLogger();
private static final Map<Class<?>, String> GAME_TEST_IDS = new HashMap<>();

private FabricGameTestHelperImpl() {
}

public static void runHeadlessServer(LevelStorage.Session session, ResourcePackManager resourcePackManager, ServerResourceManager serverResourceManager, DynamicRegistryManager.Impl registryManager) {
LOGGER.info("Starting test server");
MinecraftServer server = TestServer.startServer(thread -> {
TestServer testServer = new TestServer(thread, session, resourcePackManager, serverResourceManager, getBatches(), BlockPos.ORIGIN, registryManager);
FabricLoader.INSTANCE.setGameInstance(testServer);
return testServer;
});
}

public static void register(Class<?> testClass, String modid) {
GAME_TEST_IDS.put(testClass, modid);
TestFunctions.register(testClass);
}

public static String getModIdForTestClass(Class<?> testClass) {
if (!GAME_TEST_IDS.containsKey(testClass)) {
throw new UnsupportedOperationException("Use FabricGameTestRegistry.register to register your test class");
}

return GAME_TEST_IDS.get(testClass);
}

// Moved out to here as I expect we will want a FabricTestContext, or a way for a mod to provide their own context
// We can also have better error handling.
public static Consumer<TestContext> invokeTestMethod(Method method) {
return testContext -> {
try {
Object object = method.getDeclaringClass().getConstructor().newInstance();
method.invoke(object, testContext);
} catch (Exception e) {
// TODO we can have much better error handling
throw new RuntimeException(e);
}
};
}

private static Collection<GameTestBatch> getBatches() {
return TestUtil.createBatches(getTestFunctions());
}

private static Collection<TestFunction> getTestFunctions() {
return TestFunctions.getTestFunctions();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.mixin.gametest;

import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.mojang.brigadier.CommandDispatcher;

import net.minecraft.SharedConstants;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.command.TestCommand;

@Mixin(CommandManager.class)
public abstract class CommandManagerMixin {
@Shadow
@Final
private CommandDispatcher<ServerCommandSource> dispatcher;

@Inject(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/command/WorldBorderCommand;register(Lcom/mojang/brigadier/CommandDispatcher;)V", shift = At.Shift.AFTER))
private void construct(CommandManager.RegistrationEnvironment environment, CallbackInfo info) {
// Will be registered by vanilla if enabled.
if (!SharedConstants.isDevelopment) {
TestCommand.register(this.dispatcher);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.mixin.gametest;

import java.util.function.BooleanSupplier;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import net.minecraft.SharedConstants;
import net.minecraft.server.MinecraftServer;
import net.minecraft.test.TestManager;

@Mixin(MinecraftServer.class)
public abstract class MinecraftServerMixin {
@Inject(method = "tickWorlds", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;updatePlayerLatency()V", shift = At.Shift.AFTER))
private void tickWorlds(BooleanSupplier shouldKeepTicking, CallbackInfo callbackInfo) {
// Will be invoked by vanilla when enabled
if (!SharedConstants.isDevelopment) {
TestManager.INSTANCE.tick();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.mixin.gametest;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.mojang.brigadier.exceptions.CommandSyntaxException;

import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtHelper;
import net.minecraft.resource.Resource;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.structure.Structure;
import net.minecraft.test.StructureTestUtil;
import net.minecraft.util.Identifier;

@Mixin(StructureTestUtil.class)
public abstract class StructureTestUtilMixin {
private static final String GAMETEST_STRUCTURE_PATH = "gametest/structures/";

// Replace the default test structure loading with something that works a bit better for mods.
@Inject(at = @At("HEAD"), method = "createStructure(Ljava/lang/String;Lnet/minecraft/server/world/ServerWorld;)Lnet/minecraft/structure/Structure;", cancellable = true)
private static void createStructure(String id, ServerWorld world, CallbackInfoReturnable<Structure> cir) {
Identifier baseId = new Identifier(id);
Identifier structureId = new Identifier(baseId.getNamespace(), GAMETEST_STRUCTURE_PATH + baseId.getPath() + ".snbt");

try {
Resource resource = world.getServer().getResourceManager().getResource(structureId);
String snbt;

try (InputStream inputStream = resource.getInputStream()) {
snbt = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}

NbtCompound nbtCompound = NbtHelper.method_32260(snbt);
Structure structure = world.getStructureManager().createStructure(nbtCompound);

cir.setReturnValue(structure);
} catch (IOException | CommandSyntaxException e) {
throw new RuntimeException("Error while trying to load structure: " + structureId, e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.mixin.gametest;

import java.lang.reflect.Method;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import net.minecraft.test.GameTest;
import net.minecraft.test.StructureTestUtil;
import net.minecraft.test.TestFunction;
import net.minecraft.test.TestFunctions;

import net.fabricmc.fabric.impl.client.gametest.FabricGameTestHelperImpl;

@Mixin(TestFunctions.class)
public abstract class TestFunctionsMixin {
@Inject(at = @At("HEAD"), method = "getTestFunction(Ljava/lang/reflect/Method;)Lnet/minecraft/test/TestFunction;", cancellable = true)
private static void getTestFunction(Method method, CallbackInfoReturnable<TestFunction> cir) {
GameTest gameTest = method.getAnnotation(GameTest.class);
String testSuiteName = method.getDeclaringClass().getSimpleName().toLowerCase();
String testCaseName = testSuiteName + "." + method.getName().toLowerCase();

String modId = FabricGameTestHelperImpl.getModIdForTestClass(method.getDeclaringClass());

String structureName = "%s:%s".formatted(modId, testCaseName);

if (!gameTest.structureName().isEmpty()) {
structureName = gameTest.structureName();
}

TestFunction testFunction = new TestFunction(gameTest.batchId(),
testCaseName,
structureName,
StructureTestUtil.getRotation(gameTest.rotation()),
gameTest.tickLimit(),
gameTest.duration(),
gameTest.required(),
gameTest.requiredSuccesses(),
gameTest.maxAttempts(),
FabricGameTestHelperImpl.invokeTestMethod(method)
);

cir.setReturnValue(testFunction);
}
}
Loading