This commit is contained in:
Brian Neumann-Fopiano committed 2026-08-01 22:39:09 -04:00
1 parent 324cf9e095
commit a8217b42e9
220 files changed
+10626 -1661

No files matched your search

@@ -53,5 +53,56 @@ public class IrisClientSessionTest {
IrisProtocol.PROTOCOL_VERSION + 1, 0L, "Iris", true));
assertEquals(IrisClientSession.State.INCOMPATIBLE, session.state());
assertEquals(IrisProtocol.PROTOCOL_VERSION + 1, session.serverProtocolVersion());
assertEquals("Iris", session.serverBrand());
}
@Test
public void helloWithNoSinkStillRetriesAndResolvesToUnsupported() {
AtomicLong clock = new AtomicLong();
IrisClientSession session = new IrisClientSession(clock::get);
// No bind: the loader has not wired the channel yet. Without arming the retry clock on this path,
// nextHelloAt stayed at Long.MAX_VALUE, tick() returned immediately forever and the UI never left
// "connecting".
session.sendHello();
assertEquals(IrisClientSession.State.AWAITING_HELLO, session.state());
for (int attempt = 0; attempt < 5; attempt++) {
clock.addAndGet(2_000L);
session.tick();
}
assertEquals(IrisClientSession.State.UNSUPPORTED, session.state());
}
@Test
public void sinkBoundLateStillCompletesTheHandshake() {
AtomicLong clock = new AtomicLong();
AtomicInteger frames = new AtomicInteger();
IrisClientSession session = new IrisClientSession(clock::get);
session.sendHello();
assertEquals(0, frames.get());
session.bind(frame -> frames.incrementAndGet());
clock.addAndGet(2_000L);
session.tick();
assertEquals(1, frames.get());
assertEquals(IrisClientSession.State.AWAITING_HELLO, session.state());
}
@Test
public void resetClearsTheServerVersion() {
IrisClientSession session = new IrisClientSession();
session.onServerHello(new IrisMessage.ServerHello(
IrisProtocol.PROTOCOL_VERSION, IrisProtocol.CAPABILITY_VISION, "Iris", true));
assertTrue(session.isReady());
session.reset();
assertEquals(IrisClientSession.State.IDLE, session.state());
assertEquals(0, session.serverProtocolVersion());
}
}
@@ -0,0 +1,160 @@
package art.arcane.iris.client;
import art.arcane.iris.core.protocol.IrisTileEncoder;
import art.arcane.iris.spi.protocol.IrisMessage;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Every structure here is filled from the wire, so its size is a dial the server holds. Caps mean a hostile or
* merely buggy server can waste bandwidth but not the client's heap.
*/
public class IrisClientWireBoundsTest {
@Test
public void markerTilesBeyondTheCapEvictTheOldest() {
IrisClientMarkers markers = new IrisClientMarkers();
int overflow = IrisClientMarkers.MAX_TILES + 8;
for (int tileX = 0; tileX < overflow; tileX++) {
markers.onMarkers(new IrisMessage.VisionMarkers(tileX, 0, 0,
List.of(new IrisMessage.VisionMarkers.Marker(tileX, 0, 0, "m" + tileX))));
}
assertEquals(IrisClientMarkers.MAX_TILES, markers.trackedTiles());
assertNull("the oldest marker tile must be gone", markers.forTile(new IrisTileKey(0, 0, 0)));
assertNotNull("the newest marker tile must be retained", markers.forTile(new IrisTileKey(overflow - 1, 0, 0)));
}
@Test
public void markerTileIsReplacedNotAccumulated() {
IrisClientMarkers markers = new IrisClientMarkers();
IrisTileKey key = new IrisTileKey(4, 5, 1);
markers.onMarkers(new IrisMessage.VisionMarkers(4, 5, 1,
List.of(new IrisMessage.VisionMarkers.Marker(1, 1, 0, "first"),
new IrisMessage.VisionMarkers.Marker(2, 2, 0, "second"))));
markers.onMarkers(new IrisMessage.VisionMarkers(4, 5, 1,
List.of(new IrisMessage.VisionMarkers.Marker(3, 3, 0, "third"))));
assertEquals(1, markers.forTile(key).size());
assertEquals(1, markers.trackedTiles());
}
@Test
public void pregenJobsBeyondTheCapEvictTheOldest() {
IrisClientPregenState pregen = new IrisClientPregenState();
int overflow = IrisClientPregenState.MAX_JOBS + 5;
for (int jobId = 0; jobId < overflow; jobId++) {
pregen.onProgress(progress(jobId));
}
assertEquals(IrisClientPregenState.MAX_JOBS, pregen.trackedJobs());
assertEquals(Long.valueOf(overflow - 1L), pregen.activeJobId());
assertNotNull(pregen.active());
}
@Test
public void pregenPanelGoesStaleThenExpiresWithoutUpdates() {
AtomicLong clock = new AtomicLong(10_000L);
IrisClientPregenState pregen = new IrisClientPregenState(clock::get);
pregen.onProgress(progress(1L));
assertEquals(0L, pregen.activeAgeMillis());
assertFalse(pregen.activeStale());
assertFalse(pregen.activeExpired());
clock.addAndGet(IrisClientPregenState.STALE_AFTER_MILLIS);
assertTrue(pregen.activeStale());
assertFalse(pregen.activeExpired());
clock.addAndGet(IrisClientPregenState.EXPIRE_AFTER_MILLIS);
assertTrue(pregen.activeExpired());
pregen.onProgress(progress(1L));
assertFalse("a fresh frame must revive the panel", pregen.activeStale());
}
@Test
public void noActiveJobIsNeitherStaleNorExpired() {
AtomicLong clock = new AtomicLong(0L);
IrisClientPregenState pregen = new IrisClientPregenState(clock::get);
assertEquals(-1L, pregen.activeAgeMillis());
assertFalse(pregen.activeStale());
assertFalse(pregen.activeExpired());
pregen.onProgress(progress(7L));
pregen.onEnd(7L);
assertNull(pregen.active());
assertEquals(-1L, pregen.activeAgeMillis());
assertFalse(pregen.activeExpired());
}
@Test
public void tileCacheKeepsTheDefaultBudgetForASmallViewport() {
assertEquals(IrisClientTileCache.DEFAULT_MAX_CACHED_TILES, retainedTiles(4));
}
@Test
public void tileCacheGrowsForALargeViewportButNotPastTheCeiling() {
assertEquals(IrisClientTileCache.ABSOLUTE_MAX_CACHED_TILES,
retainedTiles(IrisClientTileCache.ABSOLUTE_MAX_CACHED_TILES * 4));
}
@Test
public void malformedTileIsDroppedAndCountedWithoutPoisoningTheCache() {
IrisClientTileCache cache = new IrisClientTileCache(frame -> {
}, () -> 0L);
byte[] garbage = new byte[32];
Arrays.fill(garbage, (byte) 0x7F);
cache.onVisionTile(new IrisMessage.VisionTile(0, 0, 0, 1, 0, 1, garbage));
assertEquals(1L, cache.droppedMalformedCount());
assertNull(cache.get(new IrisTileKey(0, 0, 0)));
cache.onVisionTile(flatTile(0));
assertNotNull("a bad frame must not block later tiles", cache.get(new IrisTileKey(0, 0, 0)));
}
/**
* Capacity is not exposed, so it is measured the only way that matters: how many tiles survive. Tiles go in
* through the real wire path, so each one is a decoded image, not a stub.
*/
private static int retainedTiles(int viewportTiles) {
IrisClientTileCache cache = new IrisClientTileCache(frame -> {
}, () -> 0L);
cache.ensureCapacity(viewportTiles);
int expected = Math.max(IrisClientTileCache.DEFAULT_MAX_CACHED_TILES,
Math.min(IrisClientTileCache.ABSOLUTE_MAX_CACHED_TILES, viewportTiles));
int inserted = expected + 8;
for (int tileX = 0; tileX < inserted; tileX++) {
cache.onVisionTile(flatTile(tileX));
}
int retained = 0;
for (int tileX = 0; tileX < inserted; tileX++) {
if (cache.get(new IrisTileKey(tileX, 0, 0)) != null) {
retained++;
}
}
return retained;
}
private static IrisMessage.VisionTile flatTile(int tileX) {
int[] pixels = new int[4];
Arrays.fill(pixels, 0xFF102030);
return new IrisMessage.VisionTile(tileX, 0, 0, 1, 0, 1, IrisTileEncoder.encodePixels(pixels, 2, 2));
}
private static IrisMessage.PregenProgress progress(long jobId) {
return new IrisMessage.PregenProgress(jobId, 10L, 100L, 5.0D, 1000L, IrisMessage.PregenProgress.STATE_RUNNING);
}
}
@@ -0,0 +1,193 @@
package art.arcane.iris.client;
import art.arcane.iris.core.protocol.IrisTileEncoder;
import art.arcane.iris.spi.protocol.IrisMessage;
import art.arcane.iris.spi.protocol.ProtocolException;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.zip.Deflater;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
/**
* The tile stream is attacker-controlled: any server a player joins picks the sequence, chunk index, chunk
* count and payload. Structurally impossible headers must be dropped without allocating from them, a complete
* set that decodes to garbage must raise {@link ProtocolException} rather than return a half-built image, and a
* deflate stream that cannot make progress must not spin the render thread.
*/
public class IrisTileAssemblerAdversarialTest {
private static final int SIZE = IrisTileEncoder.TILE_PIXELS;
private static final byte[] PAYLOAD = {1, 2, 3, 4};
@Test
public void impossibleChunkHeadersAreDropped() throws ProtocolException {
IrisTileAssembler assembler = new IrisTileAssembler();
assertNull("zero chunk count", assembler.add(tile(0, 0, 1, 0, 0, PAYLOAD)));
assertNull("negative chunk count", assembler.add(tile(0, 0, 1, 0, -1, PAYLOAD)));
assertNull("chunk count beyond the largest legal tile",
assembler.add(tile(0, 0, 1, 0, IrisTileAssembler.MAX_CHUNK_COUNT + 1, PAYLOAD)));
assertNull("index at count", assembler.add(tile(0, 0, 1, 2, 2, PAYLOAD)));
assertNull("index beyond count", assembler.add(tile(0, 0, 1, 9, 2, PAYLOAD)));
assertNull("negative index", assembler.add(tile(0, 0, 1, -1, 2, PAYLOAD)));
assertNull("missing payload", assembler.add(tile(0, 0, 1, 0, 1, null)));
}
@Test
public void rejectedHeaderLeavesNoPartialBehind() throws ProtocolException {
IrisTileAssembler assembler = new IrisTileAssembler();
assertNull(assembler.add(tile(0, 0, 1, 5, 2, PAYLOAD)));
List<IrisMessage.VisionTile> good = IrisTileEncoder.splitIntoChunks(validBlob(), 0, 0, 0, 1);
assertNotNull("a rejected frame must not poison the tile slot",
IrisVisionTileRoundTripTest.assemble(assembler, good));
}
@Test
public void chunkCountFlipMidSetRestartsTheSet() throws ProtocolException {
IrisTileAssembler assembler = new IrisTileAssembler();
// Two chunks promised at sequence 4, then the same sequence claims a single-chunk set. The stale
// half-set must be dropped rather than concatenated into the new one.
assertNull(assembler.add(tile(0, 0, 4, 0, 2, PAYLOAD)));
List<IrisMessage.VisionTile> single = IrisTileEncoder.splitIntoChunks(validBlob(), 0, 0, 0, 4);
assertEquals("a flat tile must deflate into a single chunk", 1, single.size());
assertNotNull(assembler.add(single.get(0)));
}
@Test
public void staleSequenceChunksAreIgnoredAndTheNewerSetStillCompletes() throws ProtocolException {
IrisTileAssembler assembler = new IrisTileAssembler();
byte[] blob = validBlob();
byte[] head = Arrays.copyOfRange(blob, 0, blob.length / 2);
byte[] tail = Arrays.copyOfRange(blob, blob.length / 2, blob.length);
assertNull(assembler.add(tile(0, 0, 9, 0, 2, head)));
assertNull("a chunk from an older sequence must not join the current set",
assembler.add(tile(0, 0, 8, 1, 2, tail)));
assertNotNull(assembler.add(tile(0, 0, 9, 1, 2, tail)));
}
@Test
public void partialsBeyondTheCapAreEvicted() throws ProtocolException {
IrisTileAssembler assembler = new IrisTileAssembler();
byte[] blob = validBlob();
byte[] head = Arrays.copyOfRange(blob, 0, blob.length / 2);
byte[] tail = Arrays.copyOfRange(blob, blob.length / 2, blob.length);
int overflow = IrisTileAssembler.MAX_PENDING_TILES + 1;
for (int tileX = 0; tileX < overflow; tileX++) {
assertNull(assembler.add(tile(tileX, 0, 1, 0, 2, head)));
}
// Tile 0 was the oldest partial and is gone, so its closing chunk opens a fresh incomplete set
// instead of finishing one. Retaining every partial forever would be the alternative.
assertNull("the oldest partial must have been evicted", assembler.add(tile(0, 0, 1, 1, 2, tail)));
assertNotNull("the newest partial must have survived", assembler.add(tile(overflow - 1, 0, 1, 1, 2, tail)));
}
@Test
public void garbagePayloadRaisesProtocolException() {
IrisTileAssembler assembler = new IrisTileAssembler();
byte[] garbage = new byte[64];
Arrays.fill(garbage, (byte) 0x7F);
assertThrows(ProtocolException.class, () -> assembler.add(tile(0, 0, 1, 0, 1, garbage)));
}
@Test
public void truncatedDeflateStreamRaisesProtocolExceptionInsteadOfSpinning() {
IrisTileAssembler assembler = new IrisTileAssembler();
byte[] noisy = new byte[60_000];
new Random(4242L).nextBytes(noisy);
byte[] full = deflate(noisy);
byte[] truncated = Arrays.copyOfRange(full, 0, full.length / 4);
// Zero-progress inflater: input exhausted, stream not finished. The old loop only broke out when
// finished/needsInput/needsDictionary happened to be set, so this shape spun forever on the render
// thread.
assertThrows(ProtocolException.class, () -> assembler.add(tile(0, 0, 1, 0, 1, truncated)));
}
@Test
public void decompressionBombRaisesProtocolException() {
IrisTileAssembler assembler = new IrisTileAssembler();
byte[] bomb = deflate(new byte[IrisTileCodec.MAX_DECODED_BYTES + 1024]);
assertThrows(ProtocolException.class, () -> assembler.add(tile(0, 0, 1, 0, 1, bomb)));
}
@Test
public void impossibleHeaderFieldsRaiseProtocolException() {
IrisTileAssembler assembler = new IrisTileAssembler();
assertThrows("zero width", ProtocolException.class,
() -> assembler.add(tile(0, 0, 1, 0, 1, deflate(header(0, SIZE, IrisTileCodec.MODE_RAW_RGB)))));
assertThrows("oversized height", ProtocolException.class,
() -> assembler.add(tile(1, 0, 1, 0, 1, deflate(header(SIZE, 4096, IrisTileCodec.MODE_RAW_RGB)))));
assertThrows("unknown pixel mode", ProtocolException.class,
() -> assembler.add(tile(2, 0, 1, 0, 1, deflate(header(SIZE, SIZE, 42)))));
}
@Test
public void paletteIndexBeyondPaletteRaisesProtocolException() {
IrisTileAssembler assembler = new IrisTileAssembler();
ByteArrayOutputStream raw = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(raw)) {
out.writeInt(2);
out.writeInt(2);
out.writeByte(IrisTileCodec.MODE_PALETTE);
out.writeInt(1);
out.writeByte(0);
out.writeByte(0);
out.writeByte(0);
for (int pixel = 0; pixel < 4; pixel++) {
out.writeByte(pixel == 3 ? 200 : 0);
}
} catch (IOException failure) {
throw new UncheckedIOException(failure);
}
byte[] blob = deflate(raw.toByteArray());
assertThrows(ProtocolException.class, () -> assembler.add(tile(0, 0, 1, 0, 1, blob)));
}
private static IrisMessage.VisionTile tile(int tileX, int tileZ, int sequence, int chunkIndex, int chunkCount, byte[] data) {
return new IrisMessage.VisionTile(tileX, tileZ, 0, sequence, chunkIndex, chunkCount, data);
}
/** A real encoder output for a flat tile: one chunk, palette mode, decodes cleanly. */
private static byte[] validBlob() {
int[] pixels = new int[SIZE * SIZE];
Arrays.fill(pixels, 0xFF204060);
return IrisTileEncoder.encodePixels(pixels, SIZE, SIZE);
}
private static byte[] header(int width, int height, int mode) {
ByteArrayOutputStream raw = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(raw)) {
out.writeInt(width);
out.writeInt(height);
out.writeByte(mode);
} catch (IOException failure) {
throw new UncheckedIOException(failure);
}
return raw.toByteArray();
}
private static byte[] deflate(byte[] input) {
Deflater deflater = new Deflater(Deflater.BEST_SPEED);
deflater.setInput(input);
deflater.finish();
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(64, input.length / 2));
byte[] buffer = new byte[8192];
while (!deflater.finished()) {
out.write(buffer, 0, deflater.deflate(buffer));
}
deflater.end();
return out.toByteArray();
}
}
@@ -0,0 +1,149 @@
package art.arcane.iris.client;
import art.arcane.iris.core.protocol.IrisTileEncoder;
import art.arcane.iris.spi.protocol.IrisMessage;
import art.arcane.iris.spi.protocol.IrisMessageCodec;
import art.arcane.iris.spi.protocol.IrisProtocol;
import art.arcane.iris.spi.protocol.ProtocolException;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* End-to-end vision tile path: {@link IrisTileEncoder} on the server, the wire codec both ways, then
* {@link IrisTileAssembler} and {@link IrisTileCodec} on the client. Encoder and decoder live in different
* modules and share no code, so pixel equality is the only thing that proves they still agree - a palette
* write order change or a header field added on one side is otherwise silent.
*/
public class IrisVisionTileRoundTripTest {
private static final int SIZE = IrisTileEncoder.TILE_PIXELS;
private static final int OPAQUE = 0xFF000000;
@Test
public void paletteTileRoundTripsToIdenticalPixels() throws ProtocolException {
int[] pixels = bandedPixels(16);
IrisTileImage decoded = roundTrip(pixels, 3, -4, 2, 7);
assertNotNull(decoded);
assertEquals(SIZE, decoded.width());
assertEquals(SIZE, decoded.height());
assertOpaqueRgbEquals(pixels, decoded.argb());
}
@Test
public void rawTileSplitsIntoChunksAndRoundTrips() throws ProtocolException {
int[] pixels = highEntropyPixels();
byte[] blob = IrisTileEncoder.encodePixels(pixels, SIZE, SIZE);
List<IrisMessage.VisionTile> chunks = IrisTileEncoder.splitIntoChunks(blob, 0, 0, 0, 1);
assertTrue("a high-entropy tile must exceed one chunk to exercise reassembly", chunks.size() > 1);
for (IrisMessage.VisionTile chunk : chunks) {
assertTrue("chunk frame must fit the wire cap",
IrisMessageCodec.encode(chunk).length <= IrisProtocol.MAX_FRAME_BYTES);
}
IrisTileImage decoded = assemble(new IrisTileAssembler(), overTheWire(chunks));
assertNotNull(decoded);
assertOpaqueRgbEquals(pixels, decoded.argb());
}
@Test
public void chunksReassembleWhenDeliveredOutOfOrder() throws ProtocolException {
int[] pixels = highEntropyPixels();
byte[] blob = IrisTileEncoder.encodePixels(pixels, SIZE, SIZE);
List<IrisMessage.VisionTile> chunks = new ArrayList<>(overTheWire(IrisTileEncoder.splitIntoChunks(blob, 5, 6, 1, 42)));
assertTrue(chunks.size() > 1);
Collections.reverse(chunks);
IrisTileImage decoded = assemble(new IrisTileAssembler(), chunks);
assertNotNull(decoded);
assertOpaqueRgbEquals(pixels, decoded.argb());
}
@Test
public void incompleteChunkSetProducesNothing() throws ProtocolException {
int[] pixels = highEntropyPixels();
byte[] blob = IrisTileEncoder.encodePixels(pixels, SIZE, SIZE);
List<IrisMessage.VisionTile> chunks = overTheWire(IrisTileEncoder.splitIntoChunks(blob, 1, 1, 0, 1));
assertTrue(chunks.size() > 1);
IrisTileAssembler assembler = new IrisTileAssembler();
assertNull(assemble(assembler, chunks.subList(0, chunks.size() - 1)));
assertNotNull(assembler.add(chunks.get(chunks.size() - 1)));
}
@Test
public void repeatedChunkDoesNotCompleteTheSetEarly() throws ProtocolException {
int[] pixels = highEntropyPixels();
byte[] blob = IrisTileEncoder.encodePixels(pixels, SIZE, SIZE);
List<IrisMessage.VisionTile> chunks = overTheWire(IrisTileEncoder.splitIntoChunks(blob, 2, 2, 0, 1));
assertTrue(chunks.size() > 1);
IrisTileAssembler assembler = new IrisTileAssembler();
for (int repeat = 0; repeat < chunks.size() + 2; repeat++) {
assertNull("a duplicated chunk must not count twice", assembler.add(chunks.get(0)));
}
}
static IrisTileImage assemble(IrisTileAssembler assembler, List<IrisMessage.VisionTile> chunks) throws ProtocolException {
IrisTileImage assembled = null;
for (IrisMessage.VisionTile chunk : chunks) {
IrisTileImage produced = assembler.add(chunk);
if (produced != null) {
assembled = produced;
}
}
return assembled;
}
/** Pushes each chunk through encode/decode so the test covers the wire form, not just the record. */
private static List<IrisMessage.VisionTile> overTheWire(List<IrisMessage.VisionTile> chunks) {
List<IrisMessage.VisionTile> transported = new ArrayList<>(chunks.size());
for (IrisMessage.VisionTile chunk : chunks) {
try {
transported.add((IrisMessage.VisionTile) IrisMessageCodec.decode(IrisMessageCodec.encode(chunk)));
} catch (ProtocolException rejected) {
throw new AssertionError("a chunk the encoder produced must survive the codec", rejected);
}
}
return transported;
}
private static IrisTileImage roundTrip(int[] pixels, int tileX, int tileZ, int zoom, int sequence) throws ProtocolException {
byte[] blob = IrisTileEncoder.encodePixels(pixels, SIZE, SIZE);
return assemble(new IrisTileAssembler(), overTheWire(IrisTileEncoder.splitIntoChunks(blob, tileX, tileZ, zoom, sequence)));
}
private static void assertOpaqueRgbEquals(int[] source, int[] decoded) {
assertEquals(source.length, decoded.length);
for (int index = 0; index < source.length; index++) {
assertEquals("pixel " + index, OPAQUE | source[index] & 0xFFFFFF, decoded[index]);
}
}
/** Few enough distinct colours that the encoder picks palette mode. */
private static int[] bandedPixels(int colors) {
int[] pixels = new int[SIZE * SIZE];
for (int index = 0; index < pixels.length; index++) {
int band = index % colors;
pixels[index] = OPAQUE | band * 16 << 16 | band * 8 << 8 | band * 4;
}
return pixels;
}
/** Enough distinct colours to force raw mode, and enough entropy that deflate cannot fold it into one chunk. */
private static int[] highEntropyPixels() {
Random random = new Random(1337L);
int[] pixels = new int[SIZE * SIZE];
for (int index = 0; index < pixels.length; index++) {
pixels[index] = OPAQUE | random.nextInt() & 0xFFFFFF;
}
return pixels;
}
}
@@ -105,6 +105,23 @@ public class InitialSpawnQueueTest {
assertEquals(Long.valueOf(3L), queue.poll());
}
@Test
public void expireKeepsYoungerOffersWhenReleasingCapacity() {
AtomicLong now = new AtomicLong();
InitialSpawnQueue queue = new InitialSpawnQueue(2, 100L, now::get);
queue.offer(1L);
now.set(60L);
queue.offer(2L);
now.set(100L);
assertTrue(queue.offer(3L));
assertEquals(2, queue.size());
assertEquals(Long.valueOf(2L), queue.poll());
assertEquals(Long.valueOf(3L), queue.poll());
assertNull(queue.poll());
}
@Test
public void expiredInFlightEntryCannotRetry() {
AtomicLong now = new AtomicLong();
@@ -0,0 +1,94 @@
package art.arcane.iris.modded;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class MainWorldServiceInstanceRootTest {
@Test
public void universeOptionIsReadInBothArgumentForms() {
assertEquals("worlds", MainWorldService.commandLineOption(
List.of("nogui", "--universe", "worlds"), "universe"));
assertEquals("worlds", MainWorldService.commandLineOption(
List.of("--universe=worlds", "nogui"), "universe"));
assertEquals("survival", MainWorldService.commandLineOption(
List.of("--universe", "worlds", "--world", "survival"), "world"));
}
@Test
public void missingOrValuelessOptionsResolveToNull() {
assertNull(MainWorldService.commandLineOption(List.of("nogui"), "universe"));
assertNull(MainWorldService.commandLineOption(List.of(), "world"));
assertNull(MainWorldService.commandLineOption(List.of("nogui", "--world"), "world"));
}
@Test
public void universeRootDefaultsToTheInstanceRootAndHonorsTheOption() throws IOException {
Path instanceRoot = Files.createTempDirectory("iris-instance");
Path elsewhere = Files.createTempDirectory("iris-elsewhere");
assertEquals(instanceRoot, MainWorldService.universeRoot(instanceRoot, null));
assertEquals(instanceRoot, MainWorldService.universeRoot(instanceRoot, ""));
assertEquals(instanceRoot.resolve("worlds"), MainWorldService.universeRoot(instanceRoot, "worlds"));
assertEquals(elsewhere, MainWorldService.universeRoot(instanceRoot, elsewhere.toString()));
}
@Test
public void worldRootResolvesInsideTheUniverse() throws IOException {
Path universe = Files.createTempDirectory("iris-universe");
Path world = Files.createDirectory(universe.resolve("survival"));
assertEquals(world.toAbsolutePath().normalize(),
MainWorldService.resolveWorldRoot(universe, "survival"));
}
@Test
public void worldRootRefusesToEscapeTheUniverse() throws IOException {
Path universe = Files.createTempDirectory("iris-universe");
Files.createDirectory(universe.resolve("survival"));
IOException escaped = assertThrows(IOException.class,
() -> MainWorldService.resolveWorldRoot(universe, "../survival"));
IOException empty = assertThrows(IOException.class,
() -> MainWorldService.resolveWorldRoot(universe, "."));
assertTrue(escaped.getMessage().contains("Unsafe world name"));
assertTrue(empty.getMessage().contains("Unsafe world name"));
}
@Test
public void worldRootReportsMissingDirectoriesAsTheRecoverableCase() throws IOException {
Path universe = Files.createTempDirectory("iris-universe");
MainWorldService.MissingWorldRootException missingWorld = assertThrows(
MainWorldService.MissingWorldRootException.class,
() -> MainWorldService.resolveWorldRoot(universe, "survival"));
MainWorldService.MissingWorldRootException missingUniverse = assertThrows(
MainWorldService.MissingWorldRootException.class,
() -> MainWorldService.resolveWorldRoot(universe.resolve("absent"), "survival"));
assertTrue(missingWorld.getMessage().contains("world directory does not exist"));
assertEquals(universe.resolve("survival").toAbsolutePath().normalize(), missingWorld.path());
assertTrue(missingUniverse.getMessage().contains("universe directory does not exist"));
assertEquals(universe.resolve("absent"), missingUniverse.path());
}
@Test
public void unsafeWorldNameIsNotTreatedAsAMissingWorldRoot() throws IOException {
Path universe = Files.createTempDirectory("iris-universe");
IOException escaped = assertThrows(IOException.class,
() -> MainWorldService.resolveWorldRoot(universe, "../survival"));
assertFalse(escaped instanceof MainWorldService.MissingWorldRootException);
}
}
@@ -0,0 +1,33 @@
package art.arcane.iris.modded;
import art.arcane.iris.spi.PlatformBiome;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
public class ModdedBiomeWriterCacheTest {
@Test
public void unavailableServerFallsBackToBiomeIdZero() {
ModdedBiomeWriter writer = new ModdedBiomeWriter(() -> null);
assertEquals(0, writer.biomeIdFor("minecraft:plains"));
assertEquals(0, writer.biomeIdFor("minecraft:plains"));
}
@Test
public void unavailableServerYieldsAnEmptyMutableBiomeList() {
ModdedBiomeWriter writer = new ModdedBiomeWriter(() -> null);
List<PlatformBiome> first = writer.allBiomes();
List<PlatformBiome> second = writer.allBiomes();
assertTrue(first.isEmpty());
assertNotSame("callers must never share the writer cache instance", first, second);
first.add(null);
assertTrue(second.isEmpty());
}
}
@@ -0,0 +1,52 @@
package art.arcane.iris.modded;
import net.minecraft.SharedConstants;
import net.minecraft.server.Bootstrap;
import net.minecraft.world.level.block.Blocks;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* The SPI splits block resolution into a null-returning lookup and an air-falling-back lookup. Modded used to
* collapse both onto air, so an unknown key produced no output at all.
*/
public class ModdedBlockResolutionContractTest {
private static final String UNKNOWN = "minecraft:definitely_not_a_real_block";
@BeforeClass
public static void bootstrapMinecraftRegistries() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
}
@Test
public void getOrNullReturnsNullForUnknownKey() {
assertNull(ModdedBlockResolution.getOrNull(UNKNOWN));
assertNull(ModdedBlockResolution.getOrNull(UNKNOWN, true));
}
@Test
public void getFallsBackToAirForUnknownKey() {
ModdedBlockState state = ModdedBlockResolution.get(UNKNOWN);
assertNotNull(state);
assertEquals(Blocks.AIR, state.handle().getBlock());
}
@Test
public void getOrNullResolvesKnownKeyWithProperties() {
ModdedBlockState state = ModdedBlockResolution.getOrNull("minecraft:oak_log[axis=x]", true);
assertNotNull(state);
assertEquals(Blocks.OAK_LOG, state.handle().getBlock());
}
@Test
public void unknownPropertyFallsBackToDefaultState() {
ModdedBlockState state = ModdedBlockResolution.getOrNull("minecraft:oak_log[not_a_property=x]", true);
assertNotNull(state);
assertEquals(Blocks.OAK_LOG, state.handle().getBlock());
}
}
@@ -0,0 +1,103 @@
package art.arcane.iris.modded;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Dist gate. The loader source sets fold modded-common, minecraft-common and client-common into one output, so
* nothing at compile time stops a server-side class from touching a client-only type. On a dedicated server
* that is a NoClassDefFoundError at the first call, usually deep inside worldgen.
*
* <p>The check is a constant-pool byte scan for the internal (slash) form of the forbidden packages. Slash form
* is the point: a real type reference - supertype, field or local descriptor, method owner, class literal - is
* always stored slash-separated, while a reflective lookup keeps the class name as a dotted string constant.
* {@link ModdedMixinAudit} depends on that distinction: it names client mixin targets as dotted strings on
* purpose so it can audit them from a dedicated server, and this gate must not flag it.
*
* <p>Same style as the core purity gate: read the bytes, do not load the class. Loading is what the gate is
* trying to prove is safe.
*/
public class ModdedClientPackageIsolationTest {
private static final String CLIENT_MINECRAFT = "net/minecraft/client/";
private static final String CLIENT_IRIS = "art/arcane/iris/client/";
private static final List<String> GUARDED_PACKAGES = List.of(
"art/arcane/iris/modded",
"art/arcane/iris/nativegen");
private static final int MINIMUM_SCANNED = 50;
@Test
public void serverSidePackagesNeverReferenceClientOnlyTypes() throws IOException, URISyntaxException {
Path root = classesRoot();
List<String> violations = new ArrayList<>();
int scanned = 0;
for (String guarded : GUARDED_PACKAGES) {
Path directory = root.resolve(guarded);
if (!Files.isDirectory(directory)) {
continue;
}
try (Stream<Path> walk = Files.walk(directory)) {
for (Path classFile : walk.filter(ModdedClientPackageIsolationTest::isClassFile).toList()) {
scanned++;
String bytecode = readAsLatin1(classFile);
String name = root.relativize(classFile).toString();
if (bytecode.contains(CLIENT_MINECRAFT)) {
violations.add(name + " -> " + CLIENT_MINECRAFT);
}
if (bytecode.contains(CLIENT_IRIS)) {
violations.add(name + " -> " + CLIENT_IRIS);
}
}
}
}
assertTrue("guarded packages produced only " + scanned + " classes; the scan root is wrong",
scanned >= MINIMUM_SCANNED);
assertEquals("server-side classes referencing client-only types: " + violations,
List.of(), violations);
}
/**
* Positive control. If the needle ever stops matching - a package rename, a scan that reads the wrong
* bytes - the gate above would pass silently forever. A known client-tainted class must still trip it.
*/
@Test
public void scanDetectsClientReferencesInAKnownClientClass() throws IOException, URISyntaxException {
Path visionScreen = classesRoot().resolve("art/arcane/iris/client/IrisVisionScreen.class");
assertTrue("IrisVisionScreen.class missing from " + visionScreen, Files.isRegularFile(visionScreen));
assertTrue("scan needle no longer matches a known client class",
readAsLatin1(visionScreen).contains(CLIENT_MINECRAFT));
}
private static boolean isClassFile(Path path) {
return Files.isRegularFile(path) && path.getFileName().toString().endsWith(".class");
}
private static String readAsLatin1(Path path) throws IOException {
return new String(Files.readAllBytes(path), StandardCharsets.ISO_8859_1);
}
private static Path classesRoot() throws URISyntaxException {
String anchor = "/art/arcane/iris/modded/ModdedMixinFlags.class";
URL located = ModdedClientPackageIsolationTest.class.getResource(anchor);
assertNotNull("compiled main classes are not on the test classpath as files", located);
assertEquals("expected a directory classpath entry, got " + located, "file", located.getProtocol());
Path root = Path.of(located.toURI());
for (int depth = 0; depth < 5; depth++) {
root = root.getParent();
assertNotNull("walked past the classpath root resolving " + anchor, root);
}
return root;
}
}
@@ -6,10 +6,14 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class ModdedDimensionRegistryStoreTest {
@Test
@@ -84,4 +88,53 @@ public class ModdedDimensionRegistryStoreTest {
Files.deleteIfExists(root);
}
}
@Test
public void startupLoadQuarantinesACorruptRegistryInsteadOfFailingBoot() throws IOException {
Path root = Files.createTempDirectory("iris-dimension-registry-corrupt-boot");
Path file = root.resolve("iris-dimensions.json");
try {
Files.writeString(file, "{\"dimensions\":[{\"id\":\"iris:lost\",", StandardCharsets.UTF_8);
assertEquals(List.of(), ModdedDimensionRegistryStore.loadForStartup(file));
assertFalse(Files.exists(file));
try (Stream<Path> entries = Files.list(root)) {
assertTrue(entries.anyMatch((Path entry) ->
entry.getFileName().toString().startsWith("iris-dimensions.json.broken-")));
}
} finally {
deleteTree(root);
}
}
@Test
public void startupLoadReturnsHealthyEntriesUntouched() throws IOException {
Path root = Files.createTempDirectory("iris-dimension-registry-healthy-boot");
Path file = root.resolve("iris-dimensions.json");
try {
List<ModdedDimensionRegistryStore.PersistentDimension> expected = List.of(
new ModdedDimensionRegistryStore.PersistentDimension(
"iris:first", "overworld", "overworld", 42L));
ModdedDimensionRegistryStore.write(file, expected);
assertEquals(expected, ModdedDimensionRegistryStore.loadForStartup(file));
assertTrue(Files.exists(file));
} finally {
deleteTree(root);
}
}
private static void deleteTree(Path root) throws IOException {
if (!Files.exists(root)) {
return;
}
List<Path> entries;
try (Stream<Path> walk = Files.walk(root)) {
entries = walk.sorted(Comparator.reverseOrder()).toList();
}
for (Path entry : entries) {
Files.deleteIfExists(entry);
}
}
}
@@ -151,7 +151,8 @@ public class ModdedLifecycleFailureContractTest {
assertBefore(stop, "\"services\"", "\"world engines\"");
assertBefore(stop, "\"world engines\"", "\"dimension manager\"");
assertBefore(stop, "\"server state\"", "if (failure != null)");
assertTrue(stop.contains("throw propagateStopFailure(failure);"));
assertFalse(stop.contains("throw"));
assertTrue(stop.contains("LOGGER.error(\"Iris modded shutdown completed with failures\", failure);"));
String runStage = method(source, "private static Throwable runStopStage(");
assertTrue(runStage.contains("catch (Throwable stageFailure)"));
@@ -49,7 +49,7 @@ public class ModdedServiceManagerTest {
}
@Test
public void disableAttemptsEveryServiceInReverseOrderAndAggregatesFailures() {
public void disableAttemptsEveryServiceInReverseOrderAndNeverRethrows() {
ModdedServiceManager manager = new ModdedServiceManager();
RuntimeException firstFailure = new RuntimeException("first disable failed");
RuntimeException secondFailure = new RuntimeException("second disable failed");
@@ -59,13 +59,16 @@ public class ModdedServiceManagerTest {
SecondService.class, new SecondService(null, secondFailure));
manager.enableAll();
IllegalStateException thrown = assertThrows(IllegalStateException.class, manager::disableAll);
manager.disableAll();
assertEquals(1, first.disableCount);
assertEquals(1, second.disableCount);
assertSame(secondFailure, thrown.getCause());
assertEquals(1, secondFailure.getSuppressed().length);
assertSame(firstFailure, secondFailure.getSuppressed()[0]);
manager.disableAll();
assertEquals(1, first.disableCount);
assertEquals(1, second.disableCount);
}
private static final class FirstService implements ModdedService {
@@ -40,6 +40,23 @@ public class ModdedStructureHooksTest {
assertTrue(ModdedStructureHooks.isWithinSpan(box, -1));
}
@Test
public void chunkGridSizeCountsEveryChunkPlacementWouldLoad() {
assertEquals(1, ModdedStructureHooks.chunkGridSize(new BoundingBox(0, 0, 0, 15, 15, 15)));
assertEquals(4, ModdedStructureHooks.chunkGridSize(new BoundingBox(0, 0, 0, 16, 15, 16)));
assertEquals(9, ModdedStructureHooks.chunkGridSize(new BoundingBox(-16, 0, -16, 16, 15, 16)));
}
@Test
public void chunkGridSizeSaturatesInsteadOfOverflowing() {
BoundingBox box = new BoundingBox(
Integer.MIN_VALUE / 2, 0, Integer.MIN_VALUE / 2,
Integer.MAX_VALUE / 2, 15, Integer.MAX_VALUE / 2);
assertEquals(Integer.MAX_VALUE, ModdedStructureHooks.chunkGridSize(box));
assertTrue(ModdedStructureHooks.chunkGridSize(box) > ModdedStructureHooks.MAX_PLACEMENT_CHUNKS);
}
@Test
public void structurePlacementReturnsPaperOrderedBounds() {
BoundingBox box = new BoundingBox(-16, -64, 32, 15, 63, 47);
@@ -0,0 +1,139 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.object.TileData;
import art.arcane.volmlib.util.collection.KMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.SharedConstants;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.IntArrayTag;
import net.minecraft.nbt.Tag;
import net.minecraft.server.Bootstrap;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Mantle tile sections are palette backed and resolve palette ids through equals/hashCode, so two different tiles
* in one section must not share an identity - otherwise the first tile's NBT is written into every other tile.
* The superclass generates equals/hashCode from fields a modded record never populates, which is why this class
* answers identity itself.
*/
public class ModdedTileDataIdentityTest {
private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create();
@BeforeClass
public static void bootstrapMinecraftRegistries() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
}
/**
* The generic map form the Bukkit side reads cannot express an NBT array: ByteArray, IntArray and LongArray all
* collapse to a plain List, and pasting that back produces a ListTag where Minecraft demands an array. A player
* head's {@code profile.id} is an IntArray of four, so a captured head pasted from the map form loses its skin.
* Capture therefore keeps the original SNBT alongside the map, and the modded paste path reads it first.
*/
@Test
public void captureKeepsSnbtSoArrayTypingSurvivesThePasteRoundTrip() throws Exception {
String snbt = "{profile:{id:[I;1,2,3,4],name:\"iris\"}}";
ModdedTileData captured = ModdedTileData.capture("minecraft:player_head", snbt);
assertEquals(snbt, captured.snbt());
assertEquals(snbt, captured.getProperties().get(ModdedTileData.NBT_PROPERTY));
// The Bukkit-readable map form is still written, and is still array-lossy - which is why the SNBT has to stay.
assertTrue(captured.getProperties().get("profile") instanceof KMap);
KMap<?, ?> profile = (KMap<?, ?>) captured.getProperties().get("profile");
assertTrue(profile.get("id") instanceof List);
CompoundTag payload = captured.payload();
assertNotNull(payload);
Tag profileTag = payload.get("profile");
assertTrue(profileTag instanceof CompoundTag);
Tag idTag = ((CompoundTag) profileTag).get("id");
assertTrue("profile.id must paste back as an IntArrayTag, got "
+ (idTag == null ? "null" : idTag.getClass().getSimpleName()),
idTag instanceof IntArrayTag);
assertArrayEquals(new int[]{1, 2, 3, 4}, ((IntArrayTag) idTag).getAsIntArray());
}
@Test
public void differentTilesAreNotEqualAndDoNotShareHashCode() {
ModdedTileData chest = tile("minecraft:chest", "Items", "diamond");
ModdedTileData otherChest = tile("minecraft:chest", "Items", "emerald");
ModdedTileData sign = tile("minecraft:oak_sign", "front_text", "hello");
assertNotEquals(chest, otherChest);
assertNotEquals(chest, sign);
// The inherited identity was a constant hash for every modded record; unequal objects are allowed to
// collide, so assert only that the hash actually varies with the record.
assertTrue(Set.of(chest.hashCode(), otherChest.hashCode(), sign.hashCode()).size() > 1);
}
@Test
public void identicalTilesShareOnePaletteIdentity() {
ModdedTileData first = tile("minecraft:chest", "Items", "diamond");
ModdedTileData second = tile("minecraft:chest", "Items", "diamond");
assertEquals(first, second);
assertEquals(first.hashCode(), second.hashCode());
}
@Test
public void materialKeyReportsTheBlockKeyInsteadOfNull() {
assertEquals("minecraft:chest", tile("minecraft:chest", "Items", "diamond").getMaterialKey());
}
@Test
public void legacyRecordHasNoBlockKey() {
ModdedTileData legacy = new ModdedTileData(new byte[]{0, 1}, new KMap<>(), null, 0);
assertNull(legacy.getMaterialKey());
}
@Test
public void cloneIsEqualButIndependentOfTheSource() {
ModdedTileData source = tile("minecraft:chest", "Items", "diamond");
KMap<String, Object> nested = new KMap<>();
nested.put("id", "minecraft:stone");
source.getProperties().put("nested", nested);
source.getProperties().put("list", List.of("a", "b"));
TileData copy = source.clone();
assertNotSame(source, copy);
assertNotSame(source.getProperties(), copy.getProperties());
assertEquals(source.getProperties(), copy.getProperties());
assertNotSame(source.getProperties().get("nested"), copy.getProperties().get("nested"));
assertTrue(copy.getProperties().get("list") instanceof List);
}
private static ModdedTileData tile(String blockKey, String propertyKey, String propertyValue) {
KMap<String, Object> properties = new KMap<>();
properties.put(propertyKey, propertyValue);
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeUTF(blockKey);
out.writeUTF(GSON.toJson(properties));
}
return new ModdedTileData(bytes.toByteArray(), properties, blockKey, -1);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
@@ -19,11 +19,11 @@ import static org.junit.Assert.assertTrue;
public class ModdedWorldCheckTest {
@Test
public void coordinatorThreadIsNonDaemon() {
public void coordinatorThreadIsDaemonSoItCannotWedgeTheJvm() {
Thread thread = ModdedWorldCheck.coordinatorThread(() -> {
});
assertFalse(thread.isDaemon());
assertTrue(thread.isDaemon());
}
@Test
@@ -33,7 +33,7 @@ public class ModdedWorldCheckTest {
String auditSource = Files.readString(
sourceRoot.resolve("art/arcane/iris/modded/WorldCheckStructureAudit.java"));
int preparationSubmit = source.indexOf(
"WorldCheckPreparation preparation = serverRef.submit(() -> run(serverRef)).join();");
"WorldCheckPreparation preparation = serverRef.submit(() -> run(serverRef))");
int completionSubmit = source.indexOf(
"exitCode = serverRef.submit(() -> runAndRequestStop(", preparationSubmit);
int completionMethod = source.indexOf("private static boolean completeWorldCheck");
@@ -2,10 +2,25 @@ package art.arcane.iris.modded;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ModdedWorldManagerParityTest {
@Test
public void ambientChunkReservoirFillsBeforeSampling() {
assertEquals(0, ModdedWorldManager.reservoirSlot(0, 4, 0));
assertEquals(3, ModdedWorldManager.reservoirSlot(3, 4, 0));
}
@Test
public void ambientChunkReservoirReplacesOnlyOnInRangeRolls() {
assertEquals(2, ModdedWorldManager.reservoirSlot(4, 4, 2));
assertEquals(0, ModdedWorldManager.reservoirSlot(9, 4, 0));
assertEquals(-1, ModdedWorldManager.reservoirSlot(4, 4, 4));
assertEquals(-1, ModdedWorldManager.reservoirSlot(9, 4, 7));
}
@Test
public void normalWorldAlwaysAllowsEntitySpawning() {
assertTrue(ModdedWorldManager.entitySpawningEnabled(false, false));
@@ -7,6 +7,8 @@ import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.Bootstrap;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
@@ -75,6 +77,33 @@ public class IrisModdedCommandParityTest {
assertTrue(ModdedCommandHelp.documents("world", "mainworld"));
}
@Test
public void categoryLiteralsFallBackToHelpWithoutArguments() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
IrisModdedCommands.register(dispatcher);
CommandNode<CommandSourceStack> iris = child(dispatcher.getRoot(), "iris");
assertNotNull("iris", iris.getCommand());
for (String category : new String[]{"help", "find", "goto", "pregen", "pregenerate", "object", "o",
"edit", "studio", "std", "s", "pack", "pk", "world", "w", "datapack", "datapacks", "dp",
"structure", "struct", "str", "developer", "dev"}) {
assertNotNull(category, child(iris, category).getCommand());
}
}
@Test
public void consoleHelpListsEveryEntryWithInlineUsageAndDescription() {
List<String> root = ModdedCommandHelp.consoleLines("");
assertTrue(root.stream().anyMatch((String line) -> line.startsWith("/iris developer (dev) - ")));
assertTrue(root.stream().anyMatch((String line) -> line.startsWith("/iris teleport <dimension> [player] (tp) - ")));
assertTrue(ModdedCommandHelp.consoleLines("pregen").stream().anyMatch((String line) ->
line.startsWith("/iris pregen start <radius> [dimension] [at] [x] [z] [gui] [sync] [nocache] - ")));
}
private static CommandNode<CommandSourceStack> child(
CommandNode<CommandSourceStack> parent, String name) {
CommandNode<CommandSourceStack> child = parent.getChild(name);