Skip to content

Add fabric-loader-junit to allow unit testing of transformed classes. #767

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

Merged
merged 18 commits into from
Feb 18, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@
!/settings.gradle
!/proguard.conf

!/minecraft
!/minecraft
!/junit
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ plugins {
id 'maven-publish'
id 'checkstyle'
id 'com.diffplug.spotless' version "6.12.0"
id 'fabric-loom' version '1.0-SNAPSHOT' apply false
id 'fabric-loom' version '1.1-SNAPSHOT' apply false
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'me.modmuss50.remotesign' version "0.4.0"
}
Expand Down Expand Up @@ -84,7 +84,7 @@ dependencies {
testCompileOnly 'org.jetbrains:annotations:23.0.0'

// Unit testing for mod metadata
testImplementation('org.junit.jupiter:junit-jupiter:5.8.2')
testImplementation('org.junit.jupiter:junit-jupiter:5.9.2')
}

processResources {
Expand Down
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
4 changes: 2 additions & 2 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,15 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down
6 changes: 6 additions & 0 deletions junit/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Ignore everything
/*

!/src
!/build.gradle
!/.gitignore
61 changes: 61 additions & 0 deletions junit/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
apply plugin: 'maven-publish'
apply plugin: 'me.modmuss50.remotesign'

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

archivesBaseName = "fabric-loader-junit"
version = rootProject.version
group = rootProject.group

def ENV = System.getenv()
def signingEnabled = ENV.SIGNING_SERVER

repositories {
mavenCentral()
}

dependencies {
api project(":")

api platform("org.junit:junit-bom:5.9.2")
api "org.junit.jupiter:junit-jupiter-engine"
implementation "org.junit.platform:junit-platform-launcher"
}

java {
withSourcesJar()
}

if (signingEnabled) {
remoteSign {
requestUrl = ENV.SIGNING_SERVER
pgpAuthKey = ENV.SIGNING_PGP_KEY
jarAuthKey = ENV.SIGNING_JAR_KEY

afterEvaluate {
sign publishing.publications.maven
}
}
}

publishing {
publications {
mavenJava(MavenPublication) {
artifactId project.archivesBaseName
from components.java
}
}

repositories {
if (ENV.MAVEN_URL) {
maven {
url ENV.MAVEN_URL
credentials {
username ENV.MAVEN_USERNAME
password ENV.MAVEN_PASSWORD
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2016 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.loader.impl.junit;

import org.junit.platform.launcher.LauncherSession;
import org.junit.platform.launcher.LauncherSessionListener;

import net.fabricmc.api.EnvType;
import net.fabricmc.loader.impl.launch.knot.Knot;
import net.fabricmc.loader.impl.util.SystemProperties;

public class FabricLoaderLauncherSessionListener implements LauncherSessionListener {
static {
System.setProperty(SystemProperties.DEVELOPMENT, "true");
System.setProperty(SystemProperties.UNIT_TEST, "true");
}

private final Knot knot;
private final ClassLoader classLoader;

private ClassLoader launcherSessionClassLoader;

public FabricLoaderLauncherSessionListener() {
final Thread currentThread = Thread.currentThread();
final ClassLoader originalClassLoader = currentThread.getContextClassLoader();

try {
knot = new Knot(EnvType.CLIENT);
classLoader = knot.init(new String[]{});
} finally {
// Knot.init sets the context class loader, revert it back for now.
currentThread.setContextClassLoader(originalClassLoader);
}
}

@Override
public void launcherSessionOpened(LauncherSession session) {
final Thread currentThread = Thread.currentThread();
launcherSessionClassLoader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(classLoader);
}

@Override
public void launcherSessionClosed(LauncherSession session) {
final Thread currentThread = Thread.currentThread();
currentThread.setContextClassLoader(launcherSessionClassLoader);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
net.fabricmc.loader.impl.junit.FabricLoaderLauncherSessionListener
12 changes: 12 additions & 0 deletions minecraft/minecraft-test/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ loom {

def minecraft_version = "1.19.3";

repositories {
mavenCentral()
}

dependencies {
minecraft "com.mojang:minecraft:${minecraft_version}"
mappings "net.fabricmc:yarn:${minecraft_version}+build.3:v2"

implementation project(":minecraft")
implementation project(":minecraft").sourceSets.main.output
implementation project(":").sourceSets.main.output

// Required for mixin annotation processor
annotationProcessor "org.ow2.asm:asm:${project.asm_version}"
Expand All @@ -32,6 +38,12 @@ dependencies {
exclude module: 'launchwrapper'
exclude module: 'guava'
}

testImplementation project(":junit")
}

test {
useJUnitPlatform()
}

tasks.withType(JavaCompile).configureEach {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,18 @@
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 org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.TitleScreen;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import net.minecraft.block.BlockState;
import net.minecraft.block.GrassBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.World;

@Mixin(value = TitleScreen.class, remap = false)
public abstract class MixinGuiMain extends Screen {
protected MixinGuiMain(Text textComponent_1) {
super(textComponent_1);
}

@Inject(method = "render", at = @At("RETURN"))
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float delta, CallbackInfo info) {
this.textRenderer.draw(matrixStack, "Fabric Test Mod", 2, this.height - 30, -1);
@Mixin(GrassBlock.class)
public class MixinGrassBlock {
@Inject(method = "canGrow", at = @At("HEAD"), cancellable = true)
public void canGrow(World world, Random random, BlockPos pos, BlockState state, CallbackInfoReturnable<Boolean> cir) {
cir.setReturnValue(false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"package": "net.fabricmc.minecraft.test.mixin",
"compatibilityLevel": "JAVA_8",
"mixins": [
"MixinGrassBlock"
],
"injectors": {
"defaultRequire": 1
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2016 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.minecraft.test.junit;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import net.minecraft.Bootstrap;
import net.minecraft.SharedConstants;
import net.minecraft.block.Blocks;
import net.minecraft.block.GrassBlock;
import net.minecraft.item.Items;
import net.minecraft.registry.Registries;
import net.minecraft.util.Identifier;

import net.fabricmc.loader.api.FabricLoader;

public class JunitTest {
@BeforeAll
public static void setup() {
SharedConstants.createGameVersion();
Bootstrap.initialize();
}

@Test
public void testItems() {
Identifier id = Registries.ITEM.getId(Items.DIAMOND);
assertEquals(id.toString(), "minecraft:diamond");

System.out.println(id);
}

@Test
public void testMixin() {
// MixinGrassBlock sets canGrow to false
GrassBlock grassBlock = (GrassBlock) Blocks.GRASS_BLOCK;
boolean canGrow = grassBlock.canGrow(null, null, null, null);
assertFalse(canGrow);
}

@Test
public void testAccessLoader() {
FabricLoader.getInstance().getAllMods();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,8 @@ public void initialize(FabricLauncher launcher) {
realmsJar = obfJars.get("realms");
}

if (!logJars.isEmpty()) {
// Load the logger libraries on the platform CL when in a unit test
if (!logJars.isEmpty() && !Boolean.getBoolean(SystemProperties.UNIT_TEST)) {
for (Path jar : logJars) {
if (gameJars.contains(jar)) {
launcher.addToClassPath(jar, ALLOWED_EARLY_CLASS_PREFIXES);
Expand Down
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pluginManagement {
rootProject.name='fabric-loader'

include "minecraft"
include "junit"

if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_17)) {
include "minecraft:minecraft-test"
Expand Down
Loading