fix: build — add test dependencies, fix ProGuard, remove obfuscation from default build

This commit is contained in:
loki5512344 2026-06-14 16:21:31 +02:00
parent 7c7562a8d4
commit 183df22d13
6 changed files with 1025 additions and 493 deletions

View file

@ -15,6 +15,16 @@ dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.5-R0.1-SNAPSHOT") compileOnly("io.papermc.paper:paper-api:1.21.5-R0.1-SNAPSHOT")
compileOnly("com.comphenix.protocol:ProtocolLib:5.3.0") compileOnly("com.comphenix.protocol:ProtocolLib:5.3.0")
proguardConfig("com.guardsquare:proguard-base:7.4.2") proguardConfig("com.guardsquare:proguard-base:7.4.2")
testImplementation("io.papermc.paper:paper-api:1.21.5-R0.1-SNAPSHOT")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
testImplementation("org.mockito:mockito-core:5.14.2")
testImplementation("org.mockito:mockito-junit-jupiter:5.14.2")
}
tasks.test {
useJUnitPlatform()
} }
java { java {
@ -72,8 +82,9 @@ val obfuscateTask = tasks.register<JavaExec>("obfuscate") {
"-keep", "class dev.loki.config.** { *; }", "-keep", "class dev.loki.config.** { *; }",
"-dontoptimize", "-dontoptimize",
"-dontobfuscate",
"-dontpreverify",
"-allowaccessmodification", "-allowaccessmodification",
"-repackageclasses", "mdbd",
"-keepattributes", "Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,EnclosingMethod" "-keepattributes", "Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,EnclosingMethod"
) )
@ -117,7 +128,5 @@ tasks {
} }
} }
named("build") { // obfuscation is optional — run `gradle obfuscate` manually
dependsOn("replaceWithObfuscated")
}
} }

View file

@ -0,0 +1,145 @@
package dev.loki.gate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
class ExitGateTest {
private ExitGate gate;
@BeforeEach
void setUp() {
gate = new ExitGate(new org.bukkit.Location(null, 100, 64, 200));
}
@Test
void initialState_shouldBeClosedAndNotPowered() {
assertEquals(ExitGate.GateState.CLOSED, gate.getState());
assertEquals(0.0, gate.getProgress());
assertEquals(0, gate.getProgressPercent());
assertFalse(gate.isPowered());
assertTrue(gate.isClosed());
assertFalse(gate.isOpening());
assertFalse(gate.isOpen());
}
@Test
void setPowered_shouldTransitionToOpening() {
gate.setPowered(true);
assertEquals(ExitGate.GateState.OPENING, gate.getState());
assertTrue(gate.isPowered());
assertTrue(gate.isOpening());
assertFalse(gate.isClosed());
assertFalse(gate.isOpen());
}
@Test
void setProgressDirect_shouldIncreaseProgress() {
gate.setPowered(true);
gate.setProgressDirect(0.5);
assertEquals(0.5, gate.getProgress());
assertEquals(50, gate.getProgressPercent());
assertTrue(gate.isOpening());
}
@Test
void setProgressDirect_shouldCompleteWhenReachingOne() {
gate.setPowered(true);
gate.setProgressDirect(1.0);
assertEquals(1.0, gate.getProgress());
assertEquals(ExitGate.GateState.OPEN, gate.getState());
assertTrue(gate.isOpen());
}
@Test
void setProgressDirect_shouldClampToMax() {
gate.setPowered(true);
gate.setProgressDirect(2.0);
assertEquals(1.0, gate.getProgress());
assertTrue(gate.isOpen());
}
@Test
void setProgressDirect_shouldNotExceedMin() {
gate.setPowered(true);
gate.setProgressDirect(-0.5);
assertEquals(0.0, gate.getProgress());
}
@Test
void setProgressDirect_shouldNotWork_whenGateIsClosed() {
// Not powered — still CLOSED
gate.setProgressDirect(0.5);
assertEquals(0.0, gate.getProgress());
assertTrue(gate.isClosed());
}
@Test
void updateProgress_shouldWorkIncrementally() {
gate.setPowered(true);
gate.updateProgress(0.3);
assertEquals(0.3, gate.getProgress());
gate.updateProgress(0.3);
assertEquals(0.6, gate.getProgress());
}
@Test
void reset_shouldRestoreInitialState() {
gate.setPowered(true);
gate.setProgressDirect(0.8);
gate.reset();
assertEquals(ExitGate.GateState.CLOSED, gate.getState());
assertEquals(0.0, gate.getProgress());
assertEquals(0, gate.getProgressPercent());
assertFalse(gate.isPowered());
assertTrue(gate.isClosed());
}
@Test
void saveAndRestoreProgress_shouldPersist() {
gate.setPowered(true);
gate.setProgressDirect(0.4);
assertEquals(0.4, gate.getProgress());
// Simulate player walks away then returns in same session
gate.saveProgress();
gate.setProgressDirect(0.0); // simulate some other state change
gate.restoreProgress();
assertEquals(0.4, gate.getProgress());
}
@Test
void isInRange_shouldCheckDistance() {
org.bukkit.World w = mock(org.bukkit.World.class);
var gateLoc = new org.bukkit.Location(w, 100, 64, 200);
var close = new org.bukkit.Location(w, 101, 64, 200);
var far = new org.bukkit.Location(w, 110, 64, 200);
ExitGate g = new ExitGate(gateLoc);
assertTrue(g.isInRange(close, 3.0));
assertFalse(g.isInRange(far, 3.0));
}
@Test
void startOpening_shouldWork_whenClosedAndPowered() {
gate.setPowered(true);
gate.startOpening();
assertTrue(gate.isOpening());
}
@Test
void startOpening_shouldNotWork_whenNotPowered() {
gate.startOpening();
assertTrue(gate.isClosed());
}
@Test
void spawnAndRemoveGateBlock_shouldNotThrowWithNullWorld() {
// Location has null world so block ops are no-ops — just verify no exception
assertDoesNotThrow(() -> gate.spawnGateBlock());
assertDoesNotThrow(() -> gate.removeGateBlock());
}
}

View file

@ -0,0 +1,241 @@
package dev.loki.phase;
import dev.loki.config.ConfigManager;
import dev.loki.config.MessagesConfig;
import dev.loki.core.GameSession;
import dev.loki.mdbd;
import dev.loki.player.BasePlayer;
import dev.loki.player.Killer;
import dev.loki.player.PlayerState;
import dev.loki.player.Survivor;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* Tests win condition logic by spying on GameplayWinConditions and
* stubbing Bukkit-bound announce methods. This avoids loading
* Paper API classes (Material, Sound, GameMode) whose static
* initializers require a running server.
*/
@ExtendWith(MockitoExtension.class)
class GameplayWinConditionsTest {
private GameplayWinConditions conditions;
// Reusable stubs (reflection-based) for allSurvivorsIncapacitated
private java.lang.reflect.Method incapacitatedMethod;
@BeforeEach
void setUp() throws Exception {
conditions = new GameplayWinConditions();
incapacitatedMethod = GameplayWinConditions.class
.getDeclaredMethod("allSurvivorsIncapacitated", GameSession.class);
incapacitatedMethod.setAccessible(true);
}
// =========================================================================
// Helper: build session with player map
// =========================================================================
private GameSession sessionWith(Map<UUID, BasePlayer> players) {
GameSession session = mock(GameSession.class);
lenient().when(session.getPlayers()).thenReturn(players);
// Mock messages chain for GameplayWinConditions
mdbd plugin = mock(mdbd.class);
ConfigManager configManager = mock(ConfigManager.class);
MessagesConfig messages = mock(MessagesConfig.class);
lenient().when(session.getPlugin()).thenReturn(plugin);
lenient().when(plugin.getConfigManager()).thenReturn(configManager);
lenient().when(configManager.getMessages()).thenReturn(messages);
lenient().when(messages.get(anyString())).thenReturn(Component.text("test"));
lenient().when(messages.get(anyString(), any())).thenReturn(Component.text("test"));
return session;
}
private Killer onlineKiller() {
Killer k = mock(Killer.class);
lenient().when(k.isKiller()).thenReturn(true);
Player p = mock(Player.class);
lenient().when(p.isOnline()).thenReturn(true);
lenient().when(k.getPlayer()).thenReturn(p);
return k;
}
private Survivor survivorWithState(PlayerState state) {
Survivor s = mock(Survivor.class);
lenient().when(s.isKiller()).thenReturn(false);
lenient().when(s.getState()).thenReturn(state);
return s;
}
/** Invoke private allSurvivorsIncapacitated via reflection. */
private boolean allIncapacitated(GameSession session) {
try {
return (boolean) incapacitatedMethod.invoke(conditions, session);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// =========================================================================
// Bug #3 — ESCAPED survivor blocks killer win
// =========================================================================
@Test
void incapacitated_withEscapedAndRestDisabled_shouldReturnTrue() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.ESCAPED));
players.put(UUID.randomUUID(), survivorWithState(PlayerState.DOWNED));
assertTrue(allIncapacitated(sessionWith(players)),
"ESCAPED survivors should be counted as incapacitated (bug #3)");
}
@Test
void incapacitated_withEscapedAndHealthy_shouldReturnFalse() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.ESCAPED));
players.put(UUID.randomUUID(), survivorWithState(PlayerState.HEALTHY));
assertFalse(allIncapacitated(sessionWith(players)),
"Healthy survivor means not all incapacitated");
}
@Test
void incapacitated_withAllTerminalStates_shouldReturnTrue() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.DEAD));
players.put(UUID.randomUUID(), survivorWithState(PlayerState.ESCAPED));
assertTrue(allIncapacitated(sessionWith(players)));
}
// =========================================================================
// Bug #4 — Zero survivors → killer win
// =========================================================================
@Test
void zeroSurvivors_shouldNotHaveIncapacitatedTrue() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
assertFalse(allIncapacitated(sessionWith(players)),
"With no survivors, allSurvivorsIncapacitated returns false (bug #4)");
}
// =========================================================================
// Normal incapacitation states
// =========================================================================
@Test
void allDowned_shouldBeIncapacitated() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.DOWNED));
players.put(UUID.randomUUID(), survivorWithState(PlayerState.DOWNED));
assertTrue(allIncapacitated(sessionWith(players)));
}
@Test
void allHoodedCarriedDead_shouldBeIncapacitated() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.HOOKED));
players.put(UUID.randomUUID(), survivorWithState(PlayerState.CARRIED));
players.put(UUID.randomUUID(), survivorWithState(PlayerState.DEAD));
assertTrue(allIncapacitated(sessionWith(players)));
}
@Test
void healthySurvivor_shouldNotBeIncapacitated() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.HEALTHY));
assertFalse(allIncapacitated(sessionWith(players)));
}
@Test
void injuredSurvivor_shouldNotBeIncapacitated() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
players.put(UUID.randomUUID(), survivorWithState(PlayerState.INJURED));
assertFalse(allIncapacitated(sessionWith(players)));
}
// =========================================================================
// checkWinConditions — spy-based tests for bug #4 and bug #9
// These use a spy so announce methods (which load Sound/GameMode) are
// stubbed out to avoid Paper API class loading issues outside a server.
// =========================================================================
/** Helper: run checkWinConditions on a spy with Bukkit broadcast suppressed. */
private void checkOnSpy(GameplayWinConditions spy, GameSession session) {
try (var bukkit = mockStatic(Bukkit.class)) {
bukkit.when(() -> Bukkit.broadcast(any(Component.class))).then(inv -> null);
spy.checkWinConditions(session);
}
}
@Test
void zeroSurvivors_checkWinConditions_shouldEndAsKillerWin() {
Map<UUID, BasePlayer> players = new HashMap<>();
players.put(UUID.randomUUID(), onlineKiller());
GameSession session = sessionWith(players);
GameplayWinConditions spy = spy(new GameplayWinConditions());
doNothing().when(spy).announceKillerWin(any());
checkOnSpy(spy, session);
assertTrue(spy.isShouldEnd(), "checkWinConditions should end with zero survivors (bug #4)");
assertEquals("killer_win", spy.getWinReason());
}
@Test
void killerDisconnectGuard_shouldPreventDoubleProcess() throws Exception {
Map<UUID, BasePlayer> players = new LinkedHashMap<>();
// Offline killer must be first so getKiller() finds it deterministically
Killer offlineK = mock(Killer.class);
when(offlineK.isKiller()).thenReturn(true);
when(offlineK.getPlayer()).thenReturn(null);
players.put(UUID.randomUUID(), offlineK);
players.put(UUID.randomUUID(), survivorWithState(PlayerState.HEALTHY));
GameSession session = sessionWith(players);
GameplayWinConditions spy = spy(new GameplayWinConditions());
doNothing().when(spy).announceSurvivorsWin(any());
// Tick 1 — should process
checkOnSpy(spy, session);
assertTrue(spy.isShouldEnd());
assertEquals("survivors_win", spy.getWinReason());
// Tick 2 — should NOT re-process; guard catches shouldEnd=true
// Use a new static mock that fails if broadcast is called
try (var bukkit = mockStatic(Bukkit.class)) {
bukkit.when(() -> Bukkit.broadcast(any(Component.class)))
.thenThrow(new AssertionError("Second broadcast despite guard (bug #9)"));
spy.checkWinConditions(session);
}
// If we get here, the guard worked correctly
}
}

View file

@ -0,0 +1,44 @@
package dev.loki.player;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PlayerStateTest {
@Test
void values_shouldContainAllExpectedStates() {
PlayerState[] states = PlayerState.values();
assertArrayEquals(new PlayerState[]{
PlayerState.HEALTHY,
PlayerState.INJURED,
PlayerState.DOWNED,
PlayerState.HOOKED,
PlayerState.CARRIED,
PlayerState.DEAD,
PlayerState.ESCAPED
}, states);
}
@Test
void deadAndEscaped_shouldBeTerminal() {
assertTrue(PlayerState.DEAD.isDeadOrEscaped());
assertTrue(PlayerState.ESCAPED.isDeadOrEscaped());
}
@Test
void aliveStates_shouldNotBeTerminal() {
assertFalse(PlayerState.HEALTHY.isDeadOrEscaped());
assertFalse(PlayerState.INJURED.isDeadOrEscaped());
assertFalse(PlayerState.DOWNED.isDeadOrEscaped());
assertFalse(PlayerState.HOOKED.isDeadOrEscaped());
assertFalse(PlayerState.CARRIED.isDeadOrEscaped());
}
@Test
void displayNames_shouldNotBeEmpty() {
for (PlayerState state : PlayerState.values()) {
assertNotNull(state.getDisplayName());
assertFalse(state.getDisplayName().isEmpty());
}
}
}

View file

@ -0,0 +1,93 @@
package dev.loki.util;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SpawnUtilTest {
@Mock World world;
@Test
void resolveStandingLocation_shouldReturnNull_whenInputIsNull() {
assertNull(SpawnUtil.resolveStandingLocation(null));
}
@Test
void resolveStandingLocation_shouldReturnRaw_whenWorldIsNull() {
Location loc = new Location(null, 0, 64, 0);
Location result = SpawnUtil.resolveStandingLocation(loc);
assertSame(loc, result, "Should return raw location when world is null");
}
@Test
void resolveStandingLocation_shouldFallbackToHighestBlock_whenConfiguredYIsInAir() {
Block anyBlock = stubBlockAsAir();
when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(anyBlock);
when(world.getHighestBlockYAt(anyInt(), anyInt())).thenReturn(64);
when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(true);
when(world.getMinHeight()).thenReturn(-64);
Location input = new Location(world, 0.5, 100, 0.5);
Location result = SpawnUtil.resolveStandingLocation(input);
assertNotNull(result);
assertEquals(65.0, result.getY(), "Highest block (64) + 1 = 65");
assertEquals(0.5, result.getX());
assertEquals(0.5, result.getZ());
}
@Test
void resolveStandingLocation_shouldUseConfiguredY_whenChunkNotLoaded() {
Block anyBlock = stubBlockAsAir();
when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(anyBlock);
when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(false);
when(world.getHighestBlockYAt(anyInt(), anyInt())).thenReturn(0);
when(world.getMinHeight()).thenReturn(0);
Location input = new Location(world, 0.5, 50, 0.5);
Location result = SpawnUtil.resolveStandingLocation(input);
assertNotNull(result);
assertEquals(65.0, result.getY(), "Fallback should use 64 when configured Y is low");
}
/** Create a Block mock whose getType() returns a Mockito mock of Material. */
private static Block stubBlockAsAir() {
Block b = mock(Block.class);
Material mat = mock(Material.class);
lenient().when(mat.isAir()).thenReturn(true);
lenient().when(mat.isSolid()).thenReturn(false);
lenient().when(b.getType()).thenReturn(mat);
return b;
}
@Test
void blockBreakSpawn_shouldCenterOnBlockAndAddOne() {
Location blockLoc = new Location(world, 10, 64, 20);
Location result = SpawnUtil.blockBreakSpawn(blockLoc, 90f);
assertEquals(10.5, result.getX(), "Should be centered X");
assertEquals(65.0, result.getY(), "Should be block Y + 1");
assertEquals(20.5, result.getZ(), "Should be centered Z");
assertEquals(90f, result.getYaw());
assertEquals(0f, result.getPitch());
}
@Test
void blockBreakSpawn_shouldPreserveWorld() {
Location blockLoc = new Location(world, 0, 0, 0);
Location result = SpawnUtil.blockBreakSpawn(blockLoc, 0f);
assertSame(world, result.getWorld());
}
}