TestCommand .java

net.minecraft.gametest.framework.TestCommand (class, 783 lines): members: TEST_INSTANCE_COULD_NOT_BE_FOUND, TEST_POS_Z_OFFSET_FROM_PLAYER, finder.

net.minecraft.gametest.frameworkclass783 linescommon34.8 KB

API Surface (9)

void register(final CommandDispatcher<CommandSourceStack> dispatcher, final CommandBuildContext context)
CompletableFuture<Suggestions> suggestTestFunction(final CommandContext<CommandSourceStack> context, final SuggestionsBuilder builder)
int trackAndStartRunner(final CommandSourceStack source, final GameTestRunner runner)
void testBatchStarting(final GameTestBatch batch)
void testBatchFinished(final GameTestBatch batch)
void testStructureLoaded(final GameTestInfo testInfo)
void testPassed(final GameTestInfo testInfo, final GameTestRunner runner)
void testFailed(final GameTestInfo testInfo, final GameTestRunner runner)
void testAddedForRerun(final GameTestInfo original, final GameTestInfo copy, final GameTestRunner runner)

Fields & Constants (19)

TEST_NEARBY_SEARCH_RADIUS
TEST_FULL_SEARCH_RADIUS
VERIFY_TEST_GRID_AXIS_SIZE
VERIFY_TEST_BATCH_SIZE
DEFAULT_CLEAR_RADIUS
MAX_CLEAR_RADIUS
TEST_POS_Z_OFFSET_FROM_PLAYER
DEFAULT_X_SIZE
DEFAULT_Y_SIZE
DEFAULT_Z_SIZE
CLEAR_NO_TESTS
RESET_NO_TESTS
TEST_INSTANCE_COULD_NOT_BE_FOUND
NO_STRUCTURES_TO_EXPORT
NO_TEST_INSTANCES
NO_TEST_CONTAINING
TOO_LARGE
runArgument
finder

String literals (68)

"commands.test.clear.error.no_tests"
"commands.test.reset.error.no_tests"
"commands.test.error.test_instance_not_found"
"Could not find any structures to export"
"commands.test.error.no_test_instances"
"commands.test.error.no_test_containing_pos"
"commands.test.error.too_large"
"commands.test.reset.success"
"commands.test.clear.success"
"Exported "
" structures"
"commands.test.no_tests"
"commands.test.run.running"
"commands.test.locate.started"
"chat.coordinates"
"chat.coordinates.tooltip"
"commands.test.locate.found"
"commands.test.locate.done"
"numberOfTimes"
"untilFailed"
"rotationSteps"
"testsPerRow"
"onlyRequiredTests"
"test"

Code Graph: Dependencies (50)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

TestCommand.java783 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.gametest.framework;
2
3
import com.mojang.brigadier.CommandDispatcher;
4
import com.mojang.brigadier.arguments.BoolArgumentType;
5
import com.mojang.brigadier.arguments.IntegerArgumentType;
6
import com.mojang.brigadier.arguments.StringArgumentType;
7
import com.mojang.brigadier.builder.ArgumentBuilder;
8
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
9
import com.mojang.brigadier.context.CommandContext;
10
import com.mojang.brigadier.exceptions.CommandSyntaxException;
11
import com.mojang.brigadier.exceptions.Dynamic3CommandExceptionType;
12
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
13
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
14
import com.mojang.brigadier.suggestion.Suggestions;
15
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
16
import it.unimi.dsi.fastutil.objects.ReferenceArraySet;
17
import java.util.ArrayList;
18
import java.util.Collection;
19
import java.util.Iterator;
20
import java.util.List;
21
import java.util.Locale;
22
import java.util.Optional;
23
import java.util.Set;
24
import java.util.concurrent.CompletableFuture;
25
import java.util.function.Function;
26
import java.util.stream.Collectors;
27
import java.util.stream.Stream;
28
import net.minecraft.ChatFormatting;
29
import net.minecraft.SharedConstants;
30
import net.minecraft.commands.CommandBuildContext;
31
import net.minecraft.commands.CommandSourceStack;
32
import net.minecraft.commands.Commands;
33
import net.minecraft.commands.SharedSuggestionProvider;
34
import net.minecraft.commands.arguments.IdentifierArgument;
35
import net.minecraft.commands.arguments.ResourceArgument;
36
import net.minecraft.commands.arguments.ResourceSelectorArgument;
37
import net.minecraft.core.BlockPos;
38
import net.minecraft.core.Direction;
39
import net.minecraft.core.GlobalPos;
40
import net.minecraft.core.Holder;
41
import net.minecraft.core.Vec3i;
42
import net.minecraft.core.registries.Registries;
43
import net.minecraft.network.chat.ClickEvent;
44
import net.minecraft.network.chat.Component;
45
import net.minecraft.network.chat.ComponentUtils;
46
import net.minecraft.network.chat.HoverEvent;
47
import net.minecraft.network.chat.MutableComponent;
48
import net.minecraft.network.chat.Style;
49
import net.minecraft.network.protocol.game.ClientboundGameTestHighlightPosPacket;
50
import net.minecraft.resources.Identifier;
51
import net.minecraft.resources.ResourceKey;
52
import net.minecraft.server.MinecraftServer;
53
import net.minecraft.server.commands.InCommandFunction;
54
import net.minecraft.server.level.ServerLevel;
55
import net.minecraft.server.level.ServerPlayer;
56
import net.minecraft.util.Mth;
57
import net.minecraft.world.level.Level;
58
import net.minecraft.world.level.block.Blocks;
59
import net.minecraft.world.level.block.Rotation;
60
import net.minecraft.world.level.block.entity.BlockEntityTypes;
61
import net.minecraft.world.level.block.entity.TestInstanceBlockEntity;
62
import net.minecraft.world.level.levelgen.Heightmap;
63
import net.minecraft.world.phys.BlockHitResult;
64
import org.apache.commons.lang3.mutable.MutableInt;
65
import org.jspecify.annotations.Nullable;
66
67
public class TestCommand {
68
	public static final int TEST_NEARBY_SEARCH_RADIUS = 15;
69
	public static final int TEST_FULL_SEARCH_RADIUS = 250;
70
	public static final int VERIFY_TEST_GRID_AXIS_SIZE = 10;
71
	public static final int VERIFY_TEST_BATCH_SIZE = 100;
72
	private static final int DEFAULT_CLEAR_RADIUS = 250;
73
	private static final int MAX_CLEAR_RADIUS = 1024;
74
	private static final int TEST_POS_Z_OFFSET_FROM_PLAYER = 3;
75
	private static final int DEFAULT_X_SIZE = 5;
76
	private static final int DEFAULT_Y_SIZE = 5;
77
	private static final int DEFAULT_Z_SIZE = 5;
78
	private static final SimpleCommandExceptionType CLEAR_NO_TESTS = new SimpleCommandExceptionType(Component.translatable("commands.test.clear.error.no_tests"));
79
	private static final SimpleCommandExceptionType RESET_NO_TESTS = new SimpleCommandExceptionType(Component.translatable("commands.test.reset.error.no_tests"));
80
	private static final SimpleCommandExceptionType TEST_INSTANCE_COULD_NOT_BE_FOUND = new SimpleCommandExceptionType(
81
		Component.translatable("commands.test.error.test_instance_not_found")
82
	);
83
	private static final SimpleCommandExceptionType NO_STRUCTURES_TO_EXPORT = new SimpleCommandExceptionType(
84
		Component.literal("Could not find any structures to export")
85
	);
86
	private static final SimpleCommandExceptionType NO_TEST_INSTANCES = new SimpleCommandExceptionType(
87
		Component.translatable("commands.test.error.no_test_instances")
88
	);
89
	private static final Dynamic3CommandExceptionType NO_TEST_CONTAINING = new Dynamic3CommandExceptionType(
90
		(x, y, z) -> Component.translatableEscape("commands.test.error.no_test_containing_pos", x, y, z)
91
	);
92
	private static final DynamicCommandExceptionType TOO_LARGE = new DynamicCommandExceptionType(
93
		size -> Component.translatableEscape("commands.test.error.too_large", size)
94
	);
95
96
	private static int reset(final TestFinder finder) throws CommandSyntaxException {
97
		stopTests();
98
		int count = toGameTestInfos(finder.source(), RetryOptions.noRetries(), finder).map(info -> resetGameTestInfo(finder.source(), info)).toList().size();
99
		if (count == 0) {
100
			throw CLEAR_NO_TESTS.create();
101
		}
102
103
		finder.source().sendSuccess(() -> Component.translatable("commands.test.reset.success", count), true);
104
		return count;
105
	}
106
107
	private static int clear(final TestFinder finder) throws CommandSyntaxException {
108
		stopTests();
109
		CommandSourceStack source = finder.source();
110
		MinecraftServer server = source.getServer();
111
		List<TestInstanceBlockEntity> tests = finder.findTestPos()
112
			.flatMap(globalPos -> server.getLevel(globalPos.dimension()).getBlockEntity(globalPos.pos(), BlockEntityTypes.TEST_INSTANCE_BLOCK).stream())
113
			.toList();
114
115
		for (TestInstanceBlockEntity testInstanceBlockEntity : tests) {
116
			ServerLevel level = (ServerLevel)testInstanceBlockEntity.getLevel();
117
			StructureUtils.clearSpaceForStructure(testInstanceBlockEntity.getTestBoundingBox(), level);
118
			testInstanceBlockEntity.removeBarriers();
119
			level.destroyBlock(testInstanceBlockEntity.getBlockPos(), false);
120
		}
121
122
		if (tests.isEmpty()) {
123
			throw CLEAR_NO_TESTS.create();
124
		}
125
126
		source.sendSuccess(() -> Component.translatable("commands.test.clear.success", tests.size()), true);
127
		return tests.size();
128
	}
129
130
	private static int export(final TestFinder finder) throws CommandSyntaxException {
131
		CommandSourceStack source = finder.source();
132
		int count = 0;
133
		boolean allGood = true;
134
135
		for (Iterator<GlobalPos> iterator = finder.findTestPos().iterator(); iterator.hasNext(); count++) {
136
			GlobalPos pos = iterator.next();
137
			ServerLevel level = source.getServer().getLevel(pos.dimension());
138
			if (!(level.getBlockEntity(pos.pos()) instanceof TestInstanceBlockEntity blockEntity)) {
139
				throw TEST_INSTANCE_COULD_NOT_BE_FOUND.create();
140
			}
141
142
			if (!blockEntity.exportTest(source::sendSystemMessage)) {
143
				allGood = false;
144
			}
145
		}
146
147
		if (count == 0) {
148
			throw NO_STRUCTURES_TO_EXPORT.create();
149
		}
150
151
		String message = "Exported " + count + " structures";
152
		finder.source().sendSuccess(() -> Component.literal(message), true);
153
		return allGood ? 0 : 1;
154
	}
155
156
	private static int verify(final TestFinder finder) {
157
		stopTests();
158
		CommandSourceStack source = finder.source();
159
		Function<ResourceKey<Level>, BlockPos> testPos = dimension -> createTestPositionAround(source, dimension);
160
		Collection<GameTestInfo> infos = Stream.concat(
161
				toGameTestInfos(source, RetryOptions.noRetries(), finder), toGameTestInfo(source, RetryOptions.noRetries(), finder, 0)
162
			)
163
			.toList();
164
		FailedTestTracker.forgetFailedTests();
165
		Collection<GameTestBatch> batches = new ArrayList<>();
166
167
		for (GameTestInfo info : infos) {
168
			for (Rotation rotation : Rotation.values()) {
169
				Collection<GameTestInfo> transformedInfos = new ArrayList<>();
170
171
				for (int i = 0; i < 100; i++) {
172
					GameTestInfo copyInfo = new GameTestInfo(info.getTestHolder(), rotation, info.getLevel(), new RetryOptions(1, true));
173
					copyInfo.setTestBlockPos(info.getTestBlockPos());
174
					transformedInfos.add(copyInfo);
175
				}
176
177
				GameTestBatch batch = GameTestBatchFactory.toGameTestBatch(transformedInfos, info.getTest().batch(), rotation.ordinal(), info.getLevel().dimension());
178
				batches.add(batch);
179
			}
180
		}
181
182
		StructureGridSpawner spawner = new StructureGridSpawner(testPos, 10, true);
183
		GameTestRunner runner = GameTestRunner.Builder.fromBatches(batches, source.getServer())
184
			.batcher(GameTestBatchFactory.fromGameTestInfo(100))
185
			.newStructureSpawner(spawner)
186
			.existingStructureSpawner(spawner)
187
			.haltOnError()
188
			.clearBetweenBatches()
189
			.build();
190
		return trackAndStartRunner(source, runner);
191
	}
192
193
	private static int run(final TestFinder finder, final RetryOptions retryOptions, final int extraRotationSteps, final int testsPerRow) {
194
		stopTests();
195
		CommandSourceStack source = finder.source();
196
		Collection<GameTestInfo> infos = Stream.concat(
197
				toGameTestInfos(source, retryOptions, finder), toGameTestInfo(source, retryOptions, finder, extraRotationSteps)
198
			)
199
			.toList();
200
		if (infos.isEmpty()) {
201
			source.sendSuccess(() -> Component.translatable("commands.test.no_tests"), false);
202
			return 0;
203
		} else {
204
			FailedTestTracker.forgetFailedTests();
205
			source.sendSuccess(() -> Component.translatable("commands.test.run.running", infos.size()), false);
206
			Function<ResourceKey<Level>, BlockPos> testPos = dimension -> createTestPositionAround(source, dimension);
207
			GameTestRunner runner = GameTestRunner.Builder.fromInfo(infos, source.getServer())
208
				.newStructureSpawner(new StructureGridSpawner(testPos, testsPerRow, false))
209
				.build();
210
			return trackAndStartRunner(source, runner);
211
		}
212
	}
213
214
	private static Stream<GlobalPos> findSelectedTestPositionsAcrossDimensions(final TestFinder finder) {
215
		Set<ResourceKey<GameTestInstance>> selectedTests = finder.findTests().map(Holder.Reference::key).collect(Collectors.toSet());
216
		if (selectedTests.isEmpty()) {
217
			return Stream.empty();
218
		}
219
220
		CommandSourceStack source = finder.source();
221
		MinecraftServer server = source.getServer();
222
		BlockPos sourcePos = BlockPos.containing(source.getPosition());
223
		List<GlobalPos> matches = new ArrayList<>();
224
225
		for (ServerLevel level : server.getAllLevels()) {
226
			StructureUtils.findTestBlocks(sourcePos, 250, level)
227
				.flatMap(pos -> level.getBlockEntity(pos, BlockEntityTypes.TEST_INSTANCE_BLOCK).stream())
228
				.filter(blockEntity -> blockEntity.test().filter(selectedTests::contains).isPresent())
229
				.map(blockEntity -> new GlobalPos(level.dimension(), blockEntity.getBlockPos()))
230
				.forEach(matches::add);
231
		}
232
233
		return matches.stream();
234
	}
235
236
	private static int locate(final TestFinder finder) throws CommandSyntaxException {
237
		CommandSourceStack source = finder.source();
238
		source.sendSystemMessage(Component.translatable("commands.test.locate.started"));
239
		MutableInt structuresFound = new MutableInt(0);
240
		MinecraftServer server = source.getServer();
241
		BlockPos sourcePos = BlockPos.containing(source.getPosition());
242
		ResourceKey<Level> sourceDimension = source.getLevel().dimension();
243
		Set<ResourceKey<Level>> foundTestDimensions = new ReferenceArraySet<>();
244
		Stream.concat(finder.findTestPos(), findSelectedTestPositionsAcrossDimensions(finder))
245
			.distinct()
246
			.forEach(
247
				structurePos -> {
248
					if (server.getLevel(structurePos.dimension()).getBlockEntity(structurePos.pos()) instanceof TestInstanceBlockEntity testBlock) {
249
						foundTestDimensions.add(structurePos.dimension());
250
						Direction var17 = testBlock.getRotation().rotate(Direction.NORTH);
251
						BlockPos teleportPosition = testBlock.getBlockPos().relative(var17, 3);
252
						int teleportYRot = (int)var17.getOpposite().toYRot();
253
						String dimensionId = structurePos.dimension().identifier().toString();
254
						String tpCommand = String.format(
255
							Locale.ROOT,
256
							"/execute in %s run tp @s %d %d %d %d 0",
257
							dimensionId,
258
							teleportPosition.getX(),
259
							teleportPosition.getY(),
260
							teleportPosition.getZ(),
261
							teleportYRot
262
						);
263
						int dx = sourcePos.getX() - structurePos.pos().getX();
264
						int dz = sourcePos.getZ() - structurePos.pos().getZ();
265
						String distance = structurePos.dimension().equals(sourceDimension) ? Integer.toString(Mth.floor(Mth.sqrt(dx * dx + dz * dz))) : "N/A";
266
						Component coordinates = ComponentUtils.wrapInSquareBrackets(
267
								Component.translatable("chat.coordinates", structurePos.pos().getX(), structurePos.pos().getY(), structurePos.pos().getZ())
268
									.append(Component.literal(" ->[" + structurePos.dimension().identifier().getPath() + "]"))
269
							)
270
							.withStyle(
271
								s -> s.withColor(ChatFormatting.GREEN)
272
									.withClickEvent(new ClickEvent.SuggestCommand(tpCommand))
273
									.withHoverEvent(new HoverEvent.ShowText(Component.translatable("chat.coordinates.tooltip")))
274
							);
275
						source.sendSuccess(() -> Component.translatable("commands.test.locate.found", coordinates, distance), false);
276
						structuresFound.increment();
277
					}
278
				}
279
			);
280
		int structures = structuresFound.intValue();
281
		if (structures == 0) {
282
			throw NO_TEST_INSTANCES.create();
283
		}
284
285
		outputPlayerCoordinates(source, foundTestDimensions);
286
		source.sendSuccess(() -> Component.translatable("commands.test.locate.done", structures), true);
287
		return structures;
288
	}
289
290
	private static ArgumentBuilder<CommandSourceStack, ?> runWithRetryOptions(
291
		final ArgumentBuilder<CommandSourceStack, ?> runArgument,
292
		final InCommandFunction<CommandContext<CommandSourceStack>, TestFinder> finder,
293
		final Function<ArgumentBuilder<CommandSourceStack, ?>, ArgumentBuilder<CommandSourceStack, ?>> then
294
	) {
295
		return runArgument.executes(c -> run(finder.apply(c), RetryOptions.noRetries(), 0, 8))
296
			.then(
297
				Commands.argument("numberOfTimes", IntegerArgumentType.integer(0))
298
					.executes(c -> run(finder.apply(c), new RetryOptions(IntegerArgumentType.getInteger(c, "numberOfTimes"), false), 0, 8))
299
					.then(
300
						then.apply(
301
							Commands.argument("untilFailed", BoolArgumentType.bool())
302
								.executes(
303
									c -> run(finder.apply(c), new RetryOptions(IntegerArgumentType.getInteger(c, "numberOfTimes"), BoolArgumentType.getBool(c, "untilFailed")), 0, 8)
304
								)
305
						)
306
					)
307
			);
308
	}
309
310
	private static ArgumentBuilder<CommandSourceStack, ?> runWithRetryOptions(
311
		final ArgumentBuilder<CommandSourceStack, ?> runArgument, final InCommandFunction<CommandContext<CommandSourceStack>, TestFinder> finder
312
	) {
313
		return runWithRetryOptions(runArgument, finder, a -> a);
314
	}
315
316
	private static ArgumentBuilder<CommandSourceStack, ?> runWithRetryOptionsAndBuildInfo(
317
		final ArgumentBuilder<CommandSourceStack, ?> runArgument, final InCommandFunction<CommandContext<CommandSourceStack>, TestFinder> finder
318
	) {
319
		return runWithRetryOptions(
320
			runArgument,
321
			finder,
322
			then -> then.then(
323
				Commands.argument("rotationSteps", IntegerArgumentType.integer())
324
					.executes(
325
						c -> run(
326
							finder.apply(c),
327
							new RetryOptions(IntegerArgumentType.getInteger(c, "numberOfTimes"), BoolArgumentType.getBool(c, "untilFailed")),
328
							IntegerArgumentType.getInteger(c, "rotationSteps"),
329
							8
330
						)
331
					)
332
					.then(
333
						Commands.argument("testsPerRow", IntegerArgumentType.integer())
334
							.executes(
335
								c -> run(
336
									finder.apply(c),
337
									new RetryOptions(IntegerArgumentType.getInteger(c, "numberOfTimes"), BoolArgumentType.getBool(c, "untilFailed")),
338
									IntegerArgumentType.getInteger(c, "rotationSteps"),
339
									IntegerArgumentType.getInteger(c, "testsPerRow")
340
								)
341
							)
342
					)
343
			)
344
		);
345
	}
346
347
	public static void register(final CommandDispatcher<CommandSourceStack> dispatcher, final CommandBuildContext context) {
348
		ArgumentBuilder<CommandSourceStack, ?> runFailedWithRequiredTestsFlag = runWithRetryOptionsAndBuildInfo(
349
			Commands.argument("onlyRequiredTests", BoolArgumentType.bool()), c -> TestFinder.builder().failedTests(c, BoolArgumentType.getBool(c, "onlyRequiredTests"))
350
		);
351
		LiteralArgumentBuilder<CommandSourceStack> testCommand = Commands.literal("test")
352
			.requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
353
			.then(
354
				Commands.literal("run")
355
					.then(
356
						runWithRetryOptionsAndBuildInfo(
357
							Commands.argument("tests", ResourceSelectorArgument.resourceSelector(context, Registries.TEST_INSTANCE)).suggests(TestCommand::suggestTestInstanceIds),
358
							c -> TestFinder.builder().byResourceSelection(c, ResourceSelectorArgument.getSelectedResources(c, "tests"))
359
						)
360
					)
361
			)
362
			.then(
363
				Commands.literal("runmultiple")
364
					.then(
365
						Commands.argument("tests", ResourceSelectorArgument.resourceSelector(context, Registries.TEST_INSTANCE))
366
							.suggests(TestCommand::suggestTestInstanceIds)
367
							.executes(
368
								c -> run(TestFinder.builder().byResourceSelection(c, ResourceSelectorArgument.getSelectedResources(c, "tests")), RetryOptions.noRetries(), 0, 8)
369
							)
370
							.then(
371
								Commands.argument("amount", IntegerArgumentType.integer())
372
									.executes(
373
										c -> run(
374
											TestFinder.builder()
375
												.createMultipleCopies(IntegerArgumentType.getInteger(c, "amount"))
376
												.byResourceSelection(c, ResourceSelectorArgument.getSelectedResources(c, "tests")),
377
											RetryOptions.noRetries(),
378
											0,
379
											8
380
										)
381
									)
382
							)
383
					)
384
			)
385
			.then(runWithRetryOptions(Commands.literal("runthese"), TestFinder.builder()::allNearby))
386
			.then(runWithRetryOptions(Commands.literal("runclosest"), TestFinder.builder()::nearest))
387
			.then(runWithRetryOptions(Commands.literal("runthat"), TestFinder.builder()::lookedAt))
388
			.then(runWithRetryOptionsAndBuildInfo(Commands.literal("runfailed").then(runFailedWithRequiredTestsFlag), TestFinder.builder()::failedTests))
389
			.then(
390
				Commands.literal("verify")
391
					.then(
392
						Commands.argument("tests", ResourceSelectorArgument.resourceSelector(context, Registries.TEST_INSTANCE))
393
							.suggests(TestCommand::suggestTestInstanceIds)
394
							.executes(c -> verify(TestFinder.builder().byResourceSelection(c, ResourceSelectorArgument.getSelectedResources(c, "tests"))))
395
					)
396
			)
397
			.then(
398
				Commands.literal("locate")
399
					.then(
400
						Commands.argument("tests", ResourceSelectorArgument.resourceSelector(context, Registries.TEST_INSTANCE))
401
							.suggests(TestCommand::suggestTestInstanceIds)
402
							.executes(c -> locate(TestFinder.builder().byResourceSelection(c, ResourceSelectorArgument.getSelectedResources(c, "tests"))))
403
					)
404
			)
405
			.then(Commands.literal("resetclosest").executes(c -> reset(TestFinder.builder().nearest(c))))
406
			.then(Commands.literal("resetthese").executes(c -> reset(TestFinder.builder().allNearby(c))))
407
			.then(Commands.literal("resetthat").executes(c -> reset(TestFinder.builder().lookedAt(c))))
408
			.then(Commands.literal("clearthat").executes(c -> clear(TestFinder.builder().lookedAt(c))))
409
			.then(Commands.literal("clearthese").executes(c -> clear(TestFinder.builder().allNearby(c))))
410
			.then(
411
				Commands.literal("clearall")
412
					.executes(c -> clear(TestFinder.builder().radius(c, 250)))
413
					.then(
414
						Commands.argument("radius", IntegerArgumentType.integer())
415
							.executes(c -> clear(TestFinder.builder().radius(c, Mth.clamp(IntegerArgumentType.getInteger(c, "radius"), 0, 1024))))
416
					)
417
			)
418
			.then(Commands.literal("stop").executes(c -> stopTests()))
419
			.then(
420
				Commands.literal("pos")
421
					.executes(c -> showPos(c.getSource(), "pos"))
422
					.then(Commands.argument("var", StringArgumentType.word()).executes(c -> showPos(c.getSource(), StringArgumentType.getString(c, "var"))))
423
			)
424
			.then(
425
				Commands.literal("create")
426
					.then(
427
						Commands.argument("id", IdentifierArgument.id())
428
							.executes(c -> createNewStructure(c.getSource(), IdentifierArgument.getId(c, "id"), 5, 5, 5))
429
							.then(
430
								Commands.argument("width", IntegerArgumentType.integer())
431
									.executes(
432
										c -> createNewStructure(
433
											c.getSource(),
434
											IdentifierArgument.getId(c, "id"),
435
											IntegerArgumentType.getInteger(c, "width"),
436
											IntegerArgumentType.getInteger(c, "width"),
437
											IntegerArgumentType.getInteger(c, "width")
438
										)
439
									)
440
									.then(
441
										Commands.argument("height", IntegerArgumentType.integer())
442
											.then(
443
												Commands.argument("depth", IntegerArgumentType.integer())
444
													.executes(
445
														c -> createNewStructure(
446
															c.getSource(),
447
															IdentifierArgument.getId(c, "id"),
448
															IntegerArgumentType.getInteger(c, "width"),
449
															IntegerArgumentType.getInteger(c, "height"),
450
															IntegerArgumentType.getInteger(c, "depth")
451
														)
452
													)
453
											)
454
									)
455
							)
456
					)
457
			);
458
		if (SharedConstants.IS_RUNNING_IN_IDE) {
459
			testCommand = testCommand.then(
460
					Commands.literal("export")
461
						.then(
462
							Commands.argument("test", ResourceArgument.resource(context, Registries.TEST_INSTANCE))
463
								.suggests(TestCommand::suggestTestInstanceIds)
464
								.executes(c -> exportTestStructure(c.getSource(), ResourceArgument.getResource(c, "test", Registries.TEST_INSTANCE)))
465
						)
466
				)
467
				.then(Commands.literal("exportclosest").executes(c -> export(TestFinder.builder().nearest(c))))
468
				.then(Commands.literal("exportthese").executes(c -> export(TestFinder.builder().allNearby(c))))
469
				.then(Commands.literal("exportthat").executes(c -> export(TestFinder.builder().lookedAt(c))));
470
		}
471
472
		dispatcher.register(testCommand);
473
	}
474
475
	public static CompletableFuture<Suggestions> suggestTestFunction(final CommandContext<CommandSourceStack> context, final SuggestionsBuilder builder) {
476
		Stream<String> testNamesStream = context.getSource().registryAccess().lookupOrThrow(Registries.TEST_FUNCTION).listElements().map(Holder::getRegisteredName);
477
		return SharedSuggestionProvider.suggest(testNamesStream, builder);
478
	}
479
480
	private static String displayTestId(final Identifier id) {
481
		return "minecraft".equals(id.getNamespace()) ? id.getPath() : id.toString();
482
	}
483
484
	private static CompletableFuture<Suggestions> suggestTestInstanceIds(final CommandContext<CommandSourceStack> context, final SuggestionsBuilder builder) {
485
		List<Identifier> testIds = context.getSource()
486
			.registryAccess()
487
			.lookupOrThrow(Registries.TEST_INSTANCE)
488
			.listElementIds()
489
			.map(ResourceKey::identifier)
490
			.toList();
491
		SharedSuggestionProvider.filterResources(testIds, builder.getRemaining().toLowerCase(Locale.ROOT), id -> id, id -> builder.suggest(displayTestId(id)));
492
		return builder.buildFuture();
493
	}
494
495
	private static int resetGameTestInfo(final CommandSourceStack source, final GameTestInfo testInfo) {
496
		TestInstanceBlockEntity blockEntity = testInfo.getTestInstanceBlockEntity();
497
		blockEntity.resetTest(source::sendSystemMessage);
498
		return 1;
499
	}
500
501
	private static Stream<GameTestInfo> toGameTestInfos(final CommandSourceStack source, final RetryOptions retryOptions, final TestPosFinder finder) {
502
		return finder.findTestPos().map(pos -> createGameTestInfo(pos, source, retryOptions)).flatMap(Optional::stream);
503
	}
504
505
	private static Stream<GameTestInfo> toGameTestInfo(
506
		final CommandSourceStack source, final RetryOptions retryOptions, final TestInstanceFinder finder, final int rotationSteps
507
	) {
508
		return finder.findTests()
509
			.filter(test -> verifyStructureExists(source, test.value().structure()))
510
			.flatMap(
511
				test -> {
512
					ResourceKey<Level> dimension = test.value().info().dimension();
513
					ServerLevel level = source.getServer().getLevel(dimension);
514
					if (level == null) {
515
						source.sendFailure(Component.literal("Could not resolve level for dimension: " + dimension.identifier()));
516
						return Stream.empty();
517
					} else {
518
						return Stream.of(
519
							new GameTestInfo((Holder.Reference<GameTestInstance>)test, StructureUtils.getRotationForRotationSteps(rotationSteps), level, retryOptions)
520
						);
521
					}
522
				}
523
			);
524
	}
525
526
	private static Optional<GameTestInfo> createGameTestInfo(final GlobalPos testBlockPos, final CommandSourceStack source, final RetryOptions retryOptions) {
527
		ServerLevel level = source.getServer().getLevel(testBlockPos.dimension());
528
		if (level.getBlockEntity(testBlockPos.pos()) instanceof TestInstanceBlockEntity blockEntity) {
529
			Optional<Holder.Reference<GameTestInstance>> maybeTest = blockEntity.test().flatMap(source.registryAccess().lookupOrThrow(Registries.TEST_INSTANCE)::get);
530
			if (maybeTest.isEmpty()) {
531
				source.sendFailure(Component.translatable("commands.test.error.non_existant_test", blockEntity.getTestName()));
532
				return Optional.empty();
533
			} else {
534
				Holder.Reference<GameTestInstance> test = maybeTest.get();
535
				GameTestInfo testInfo = new GameTestInfo(test, blockEntity.getRotation(), level, retryOptions);
536
				testInfo.setTestBlockPos(testBlockPos.pos());
537
				return !verifyStructureExists(source, testInfo.getStructure()) ? Optional.empty() : Optional.of(testInfo);
538
			}
539
		} else {
540
			source.sendFailure(
541
				Component.translatable(
542
					"commands.test.error.test_instance_not_found.position", testBlockPos.pos().getX(), testBlockPos.pos().getY(), testBlockPos.pos().getZ()
543
				)
544
			);
545
			return Optional.empty();
546
		}
547
	}
548
549
	private static int createNewStructure(final CommandSourceStack source, final Identifier id, final int xSize, final int ySize, final int zSize) throws CommandSyntaxException {
550
		if (xSize <= 48 && ySize <= 48 && zSize <= 48) {
551
			ServerLevel level = source.getLevel();
552
			BlockPos testPos = createTestPositionAround(source, level.dimension());
553
			TestInstanceBlockEntity test = StructureUtils.createNewEmptyTest(id, testPos, new Vec3i(xSize, ySize, zSize), Rotation.NONE, level);
554
			BlockPos low = test.getStructurePos();
555
			BlockPos high = low.offset(xSize - 1, 0, zSize - 1);
556
			BlockPos.betweenClosedStream(low, high).forEach(blockPos -> level.setBlockAndUpdate(blockPos, Blocks.BEDROCK.defaultBlockState()));
557
			source.sendSuccess(() -> Component.translatable("commands.test.create.success", test.getTestName()), true);
558
			return 1;
559
		} else {
560
			throw TOO_LARGE.create(48);
561
		}
562
	}
563
564
	private static int showPos(final CommandSourceStack source, final String varName) throws CommandSyntaxException {
565
		ServerPlayer player = source.getPlayerOrException();
566
		BlockHitResult pick = (BlockHitResult)player.pick(10.0, 1.0F, false);
567
		BlockPos targetPosAbsolute = pick.getBlockPos();
568
		ServerLevel level = source.getLevel();
569
		Optional<BlockPos> testBlockPos = StructureUtils.findTestContainingPos(targetPosAbsolute, 15, level);
570
		if (testBlockPos.isEmpty()) {
571
			testBlockPos = StructureUtils.findTestContainingPos(targetPosAbsolute, 250, level);
572
		}
573
574
		if (testBlockPos.isEmpty()) {
575
			throw NO_TEST_CONTAINING.create(targetPosAbsolute.getX(), targetPosAbsolute.getY(), targetPosAbsolute.getZ());
576
		} else if (level.getBlockEntity(testBlockPos.get()) instanceof TestInstanceBlockEntity testBlockEntity) {
577
			BlockPos var13 = testBlockEntity.getStructurePos();
578
			BlockPos targetPosRelative = targetPosAbsolute.subtract(var13);
579
			String targetPosDescription = targetPosRelative.getX() + ", " + targetPosRelative.getY() + ", " + targetPosRelative.getZ();
580
			String testName = testBlockEntity.getTestName().getString();
581
			MutableComponent coords = Component.translatable("commands.test.coordinates", targetPosRelative.getX(), targetPosRelative.getY(), targetPosRelative.getZ())
582
				.setStyle(
583
					Style.EMPTY
584
						.withBold(true)
585
						.withColor(ChatFormatting.GREEN)
586
						.withHoverEvent(new HoverEvent.ShowText(Component.translatable("commands.test.coordinates.copy")))
587
						.withClickEvent(new ClickEvent.CopyToClipboard("final BlockPos " + varName + " = new BlockPos(" + targetPosDescription + ");"))
588
				);
589
			source.sendSuccess(() -> Component.translatable("commands.test.relative_position", testName, coords), false);
590
			player.connection.send(new ClientboundGameTestHighlightPosPacket(targetPosAbsolute, targetPosRelative));
591
			return 1;
592
		} else {
593
			throw TEST_INSTANCE_COULD_NOT_BE_FOUND.create();
594
		}
595
	}
596
597
	private static int stopTests() {
598
		GameTestTicker.SINGLETON.clear();
599
		return 1;
600
	}
601
602
	public static int trackAndStartRunner(final CommandSourceStack source, final GameTestRunner runner) {
603
		runner.addListener(new TestCommand.TestBatchSummaryDisplayer(source));
604
		MultipleTestTracker tracker = new MultipleTestTracker(runner.getTestInfos());
605
		tracker.addListener(new TestCommand.TestSummaryDisplayer(source, tracker));
606
		tracker.addFailureListener(testInfo -> FailedTestTracker.rememberFailedTest(testInfo.getTestHolder()));
607
		runner.start();
608
		return 1;
609
	}
610
611
	private static int exportTestStructure(final CommandSourceStack source, final Holder<GameTestInstance> test) {
612
		return !TestInstanceBlockEntity.export(source.getLevel(), test.value().structure(), source::sendSystemMessage) ? 0 : 1;
613
	}
614
615
	private static boolean verifyStructureExists(final CommandSourceStack source, final Identifier structure) {
616
		if (source.getLevel().getStructureTemplateManager().get(structure).isEmpty()) {
617
			source.sendFailure(Component.translatable("commands.test.error.structure_not_found", Component.translationArg(structure)));
618
			return false;
619
		} else {
620
			return true;
621
		}
622
	}
623
624
	private static BlockPos createTestPositionAround(final CommandSourceStack source, final ResourceKey<Level> dimension) {
625
		TestCommand.Info info = playerAndTestInfo(source, dimension);
626
		return new BlockPos(info.playerPos.getX(), info.surfaceY, info.playerPos.getZ() + 3);
627
	}
628
629
	private static TestCommand.Info playerAndTestInfo(final CommandSourceStack source, final ResourceKey<Level> dimension) {
630
		ServerPlayer serverPlayer = source.getPlayer();
631
		BlockPos playerPos = BlockPos.containing(serverPlayer == null ? source.getPosition() : serverPlayer.position());
632
		BlockPos testPos = new BlockPos(playerPos.getX(), 384, playerPos.getZ());
633
		ServerLevel level = source.getServer().getLevel(dimension);
634
		level.getChunk(testPos);
635
		int surfaceY = level.getHeightmapPos(Heightmap.Types.WORLD_SURFACE, testPos).getY();
636
		return new TestCommand.Info(source.getPlayer(), playerPos, testPos, surfaceY);
637
	}
638
639
	private static void outputTestCoordinates(final CommandSourceStack source, final Set<ResourceKey<Level>> testDimensions) {
640
		for (ResourceKey<Level> testDimensionKey : testDimensions) {
641
			TestCommand.Info testInfo = playerAndTestInfo(source, testDimensionKey);
642
			TestCommand.Info playerInfo = playerAndTestInfo(source, source.getLevel().dimension());
643
			if (isPlayerInCurrentTestDimension(playerInfo, testDimensions)) {
644
				return;
645
			}
646
647
			String testDimension = testDimensionKey.identifier().toString();
648
			Component testCoordinates = ComponentUtils.wrapInSquareBrackets(
649
					Component.translatable(
650
						"test.run.coordinates", testInfo.playerPos.getX(), testInfo.surfaceY, testInfo.playerPos.getZ(), testDimension.substring(testDimension.indexOf(58) + 1)
651
					)
652
				)
653
				.withStyle(
654
					s -> s.withColor(ChatFormatting.YELLOW)
655
						.withClickEvent(
656
							new ClickEvent.SuggestCommand(
657
								"/execute in " + testDimension + " run tp @s " + testInfo.playerPos.getX() + " " + testInfo.surfaceY + " " + testInfo.playerPos.getZ() + " 0 0"
658
							)
659
						)
660
						.withHoverEvent(new HoverEvent.ShowText(Component.translatable("chat.coordinates.tooltip")))
661
				);
662
			source.sendSuccess(() -> testCoordinates, false);
663
		}
664
	}
665
666
	private static void outputPlayerCoordinates(final CommandSourceStack source, final Set<ResourceKey<Level>> testDimensions) {
667
		TestCommand.Info playerInfo = playerAndTestInfo(source, source.getLevel().dimension());
668
		if (!isPlayerInCurrentTestDimension(playerInfo, testDimensions)) {
669
			ServerPlayer player = playerInfo.player;
670
			if (player != null) {
671
				float playerRotation = player.getYRot();
672
				float playerPitch = player.getXRot();
673
				ResourceKey<Level> playerDimensionKey = player.level().dimension();
674
				String playerDimension = playerDimensionKey.identifier().toString();
675
				Component playerCoordinates = ComponentUtils.wrapInSquareBrackets(
676
						Component.translatable(
677
							"test.player.coordinates",
678
							playerInfo.playerPos.getX(),
679
							playerInfo.playerPos.getY(),
680
							playerInfo.playerPos.getZ(),
681
							playerDimension.substring(playerDimension.indexOf(58) + 1)
682
						)
683
					)
684
					.withStyle(
685
						s -> s.withColor(ChatFormatting.GOLD)
686
							.withClickEvent(
687
								new ClickEvent.SuggestCommand(
688
									"/execute in "
689
										+ playerDimension
690
										+ " run tp @s "
691
										+ playerInfo.playerPos.getX()
692
										+ " "
693
										+ playerInfo.playerPos.getY()
694
										+ " "
695
										+ playerInfo.playerPos.getZ()
696
										+ " "
697
										+ Mth.floor(playerRotation)
698
										+ " "
699
										+ Mth.floor(playerPitch)
700
								)
701
							)
702
							.withHoverEvent(new HoverEvent.ShowText(Component.translatable("chat.coordinates.tooltip")))
703
					);
704
				source.sendSuccess(() -> playerCoordinates, false);
705
			}
706
		}
707
	}
708
709
	private static boolean isPlayerInCurrentTestDimension(final TestCommand.Info playerInfo, final Set<ResourceKey<Level>> testDimensions) {
710
		ServerPlayer player = playerInfo.player;
711
		if (player == null) {
712
			return false;
713
		}
714
715
		ResourceKey<Level> playerDimensionKey = player.level().dimension();
716
		return testDimensions.size() <= 1 && testDimensions.contains(playerDimensionKey) && testDimensions.contains(Level.OVERWORLD);
717
	}
718
719
	private record Info(@Nullable ServerPlayer player, BlockPos playerPos, BlockPos testPos, int surfaceY) {
720
	}
721
722
	private record TestBatchSummaryDisplayer(CommandSourceStack source) implements GameTestBatchListener {
723
		@Override
724
		public void testBatchStarting(final GameTestBatch batch) {
725
			this.source.sendSuccess(() -> Component.translatable("commands.test.batch.starting", batch.environment().getRegisteredName(), batch.index()), true);
726
		}
727
728
		@Override
729
		public void testBatchFinished(final GameTestBatch batch) {
730
		}
731
	}
732
733
	public static final class TestSummaryDisplayer implements GameTestListener {
734
		private final CommandSourceStack source;
735
		private final MultipleTestTracker tracker;
736
		private final Set<ResourceKey<Level>> dimensions = new ReferenceArraySet<>();
737
738
		public TestSummaryDisplayer(final CommandSourceStack source, final MultipleTestTracker tracker) {
739
			this.source = source;
740
			this.tracker = tracker;
741
		}
742
743
		@Override
744
		public void testStructureLoaded(final GameTestInfo testInfo) {
745
		}
746
747
		@Override
748
		public void testPassed(final GameTestInfo testInfo, final GameTestRunner runner) {
749
			this.dimensions.add(testInfo.getTest().dimension());
750
			this.showTestSummaryIfAllDone();
751
		}
752
753
		@Override
754
		public void testFailed(final GameTestInfo testInfo, final GameTestRunner runner) {
755
			this.dimensions.add(testInfo.getTest().dimension());
756
			this.showTestSummaryIfAllDone();
757
		}
758
759
		@Override
760
		public void testAddedForRerun(final GameTestInfo original, final GameTestInfo copy, final GameTestRunner runner) {
761
			this.tracker.addTestToTrack(copy);
762
		}
763
764
		private void showTestSummaryIfAllDone() {
765
			if (this.tracker.isDone()) {
766
				this.source.sendSuccess(() -> Component.translatable("commands.test.summary", this.tracker.getTotalCount()).withStyle(ChatFormatting.WHITE), true);
767
				if (this.tracker.hasFailedRequired()) {
768
					this.source.sendFailure(Component.translatable("commands.test.summary.failed", this.tracker.getFailedRequiredCount()));
769
				} else {
770
					this.source.sendSuccess(() -> Component.translatable("commands.test.summary.all_required_passed").withStyle(ChatFormatting.GREEN), true);
771
				}
772
773
				if (this.tracker.hasFailedOptional()) {
774
					this.source.sendSystemMessage(Component.translatable("commands.test.summary.optional_failed", this.tracker.getFailedOptionalCount()));
775
				}
776
777
				TestCommand.outputPlayerCoordinates(this.source, this.dimensions);
778
				TestCommand.outputTestCoordinates(this.source, this.dimensions);
779
			}
780
		}
781
	}
782
}
783

Decompiled Minecraft 26.3 source of TestCommand (net/minecraft/gametest/framework/TestCommand.java) with Mojang official mappings, stored verbatim on the site.