| 1 | package net.minecraft.gametest.framework;
|
| 2 |
|
| 3 | import com.google.common.base.Stopwatch;
|
| 4 | import com.mojang.authlib.GameProfile;
|
| 5 | import com.mojang.authlib.services.ServicesKeySet;
|
| 6 | import com.mojang.brigadier.StringReader;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import com.mojang.serialization.Lifecycle;
|
| 9 | import java.net.Proxy;
|
| 10 | import java.util.ArrayList;
|
| 11 | import java.util.Collection;
|
| 12 | import java.util.HashSet;
|
| 13 | import java.util.List;
|
| 14 | import java.util.Optional;
|
| 15 | import java.util.Set;
|
| 16 | import java.util.UUID;
|
| 17 | import java.util.concurrent.TimeUnit;
|
| 18 | import java.util.function.BooleanSupplier;
|
| 19 | import java.util.stream.Stream;
|
| 20 | import java.util.stream.Stream.Builder;
|
| 21 | import net.minecraft.CrashReport;
|
| 22 | import net.minecraft.ReportType;
|
| 23 | import net.minecraft.SystemReport;
|
| 24 | import net.minecraft.commands.Commands;
|
| 25 | import net.minecraft.commands.arguments.ResourceSelectorArgument;
|
| 26 | import net.minecraft.core.BlockPos;
|
| 27 | import net.minecraft.core.Holder;
|
| 28 | import net.minecraft.core.LayeredRegistryAccess;
|
| 29 | import net.minecraft.core.MappedRegistry;
|
| 30 | import net.minecraft.core.Registry;
|
| 31 | import net.minecraft.core.RegistryAccess;
|
| 32 | import net.minecraft.core.registries.Registries;
|
| 33 | import net.minecraft.gizmos.GizmoCollector;
|
| 34 | import net.minecraft.gizmos.Gizmos;
|
| 35 | import net.minecraft.server.MinecraftServer;
|
| 36 | import net.minecraft.server.RegistryLayer;
|
| 37 | import net.minecraft.server.Services;
|
| 38 | import net.minecraft.server.WorldLoader;
|
| 39 | import net.minecraft.server.WorldStem;
|
| 40 | import net.minecraft.server.level.ServerLevel;
|
| 41 | import net.minecraft.server.level.progress.LoggingLevelLoadListener;
|
| 42 | import net.minecraft.server.notifications.EmptyNotificationService;
|
| 43 | import net.minecraft.server.notifications.NotificationManager;
|
| 44 | import net.minecraft.server.packs.repository.PackRepository;
|
| 45 | import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
| 46 | import net.minecraft.server.permissions.PermissionSet;
|
| 47 | import net.minecraft.server.players.NameAndId;
|
| 48 | import net.minecraft.server.players.PlayerList;
|
| 49 | import net.minecraft.server.players.ProfileResolver;
|
| 50 | import net.minecraft.server.players.UserNameToIdResolver;
|
| 51 | import net.minecraft.util.RandomSource;
|
| 52 | import net.minecraft.util.Util;
|
| 53 | import net.minecraft.util.datafix.DataFixers;
|
| 54 | import net.minecraft.util.debugchart.LocalSampleLogger;
|
| 55 | import net.minecraft.util.debugchart.SampleLogger;
|
| 56 | import net.minecraft.world.flag.FeatureFlagSet;
|
| 57 | import net.minecraft.world.flag.FeatureFlags;
|
| 58 | import net.minecraft.world.level.DataPackConfig;
|
| 59 | import net.minecraft.world.level.GameType;
|
| 60 | import net.minecraft.world.level.LevelSettings;
|
| 61 | import net.minecraft.world.level.WorldDataConfiguration;
|
| 62 | import net.minecraft.world.level.block.Rotation;
|
| 63 | import net.minecraft.world.level.dimension.LevelStem;
|
| 64 | import net.minecraft.world.level.gamerules.GameRules;
|
| 65 | import net.minecraft.world.level.levelgen.WorldDimensions;
|
| 66 | import net.minecraft.world.level.levelgen.WorldGenSettings;
|
| 67 | import net.minecraft.world.level.levelgen.WorldOptions;
|
| 68 | import net.minecraft.world.level.levelgen.presets.WorldPresets;
|
| 69 | import net.minecraft.world.level.storage.LevelData;
|
| 70 | import net.minecraft.world.level.storage.LevelDataAndDimensions;
|
| 71 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 72 | import net.minecraft.world.level.storage.PrimaryLevelData;
|
| 73 | import org.jspecify.annotations.Nullable;
|
| 74 | import org.slf4j.Logger;
|
| 75 |
|
| 76 | public class GameTestServer extends MinecraftServer {
|
| 77 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 78 | private static final int PROGRESS_REPORT_INTERVAL = 20;
|
| 79 | private static final int TEST_POSITION_RANGE = 14999992;
|
| 80 | private static final Services NO_SERVICES = new Services(
|
| 81 | null, ServicesKeySet.EMPTY, null, new GameTestServer.MockUserNameToIdResolver(), new GameTestServer.MockProfileResolver()
|
| 82 | );
|
| 83 | private static final FeatureFlagSet ENABLED_FEATURES = FeatureFlags.REGISTRY
|
| 84 | .allFlags()
|
| 85 | .subtract(FeatureFlagSet.of(FeatureFlags.REDSTONE_EXPERIMENTS, FeatureFlags.MINECART_IMPROVEMENTS));
|
| 86 | private final LocalSampleLogger sampleLogger = new LocalSampleLogger(4);
|
| 87 | private final Optional<String> testSelection;
|
| 88 | private final boolean verify;
|
| 89 | private final int repeatCount;
|
| 90 | private List<GameTestBatch> testBatches = new ArrayList<>();
|
| 91 | private final Stopwatch stopwatch = Stopwatch.createUnstarted();
|
| 92 | private static final WorldOptions WORLD_OPTIONS = new WorldOptions(0L, false, false);
|
| 93 | private @Nullable MultipleTestTracker testTracker;
|
| 94 |
|
| 95 | public static GameTestServer create(
|
| 96 | final Thread serverThread,
|
| 97 | final LevelStorageSource.LevelStorageAccess levelStorageSource,
|
| 98 | final PackRepository packRepository,
|
| 99 | final Optional<String> testSelection,
|
| 100 | final boolean verify,
|
| 101 | final int repeatCount
|
| 102 | ) {
|
| 103 | packRepository.reload();
|
| 104 | ArrayList<String> enabledPacks = new ArrayList<>(packRepository.getAvailableIds());
|
| 105 | enabledPacks.remove("vanilla");
|
| 106 | enabledPacks.addFirst("vanilla");
|
| 107 | WorldDataConfiguration defaultTestConfig = new WorldDataConfiguration(new DataPackConfig(enabledPacks, List.of()), ENABLED_FEATURES);
|
| 108 | LevelSettings testSettings = new LevelSettings("Test Level", GameType.CREATIVE, LevelSettings.DifficultySettings.DEFAULT, true, defaultTestConfig);
|
| 109 | WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, defaultTestConfig, false, true);
|
| 110 | WorldLoader.InitConfig initConfig = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER);
|
| 111 |
|
| 112 | try {
|
| 113 | LOGGER.debug("Starting resource loading");
|
| 114 | Stopwatch stopwatch = Stopwatch.createStarted();
|
| 115 | WorldStem worldStem = Util.<WorldStem>blockUntilDone(
|
| 116 | executor -> WorldLoader.load(
|
| 117 | initConfig,
|
| 118 | context -> {
|
| 119 | Registry<LevelStem> noDatapackDimensions = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
|
| 120 | WorldDimensions worldDimensions = context.datapackWorldRegistries()
|
| 121 | .lookupOrThrow(Registries.WORLD_PRESET)
|
| 122 | .getOrThrow(WorldPresets.FLAT_ALL_DIMENSIONS)
|
| 123 | .value()
|
| 124 | .createWorldDimensions();
|
| 125 | WorldDimensions.Complete dimensions = worldDimensions.bake(noDatapackDimensions);
|
| 126 | PrimaryLevelData levelData = new PrimaryLevelData(testSettings, dimensions.specialWorldProperty(), dimensions.lifecycle());
|
| 127 | return new WorldLoader.DataLoadOutput<>(
|
| 128 | new LevelDataAndDimensions.WorldDataAndGenSettings(levelData, new WorldGenSettings(WORLD_OPTIONS, worldDimensions)),
|
| 129 | dimensions.dimensionsRegistryAccess()
|
| 130 | );
|
| 131 | },
|
| 132 | WorldStem::new,
|
| 133 | Util.backgroundExecutor(),
|
| 134 | executor
|
| 135 | )
|
| 136 | )
|
| 137 | .get();
|
| 138 | stopwatch.stop();
|
| 139 | LOGGER.debug("Finished resource loading after {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
|
| 140 | return new GameTestServer(serverThread, levelStorageSource, packRepository, worldStem, testSelection, verify, repeatCount);
|
| 141 | } catch (Exception e) {
|
| 142 | LOGGER.warn("Failed to load vanilla datapack, bit oops", e);
|
| 143 | System.exit(-1);
|
| 144 | throw new IllegalStateException();
|
| 145 | }
|
| 146 | }
|
| 147 |
|
| 148 | private GameTestServer(
|
| 149 | final Thread serverThread,
|
| 150 | final LevelStorageSource.LevelStorageAccess levelStorageSource,
|
| 151 | final PackRepository packRepository,
|
| 152 | final WorldStem worldStem,
|
| 153 | final Optional<String> testSelection,
|
| 154 | final boolean verify,
|
| 155 | final int repeatCount
|
| 156 | ) {
|
| 157 | super(
|
| 158 | serverThread,
|
| 159 | levelStorageSource,
|
| 160 | packRepository,
|
| 161 | worldStem,
|
| 162 | Optional.of(new GameRules(ENABLED_FEATURES)),
|
| 163 | Proxy.NO_PROXY,
|
| 164 | DataFixers.getDataFixer(),
|
| 165 | NO_SERVICES,
|
| 166 | LoggingLevelLoadListener.forDedicatedServer(),
|
| 167 | false,
|
| 168 | new NotificationManager()
|
| 169 | );
|
| 170 | this.testSelection = testSelection;
|
| 171 | this.repeatCount = repeatCount;
|
| 172 | this.verify = verify;
|
| 173 | }
|
| 174 |
|
| 175 | @Override
|
| 176 | protected boolean initServer() {
|
| 177 | this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) {});
|
| 178 | Gizmos.withCollector(GizmoCollector.NOOP);
|
| 179 | this.loadLevel();
|
| 180 | this.testBatches = this.evaluateTestsToRun(this);
|
| 181 | LOGGER.info("Started game test server");
|
| 182 | return true;
|
| 183 | }
|
| 184 |
|
| 185 | private List<GameTestBatch> evaluateTestsToRun(final MinecraftServer server) {
|
| 186 | Registry<GameTestInstance> testRegistry = server.registryAccess().lookupOrThrow(Registries.TEST_INSTANCE);
|
| 187 | Collection<Holder.Reference<GameTestInstance>> tests;
|
| 188 | GameTestBatchFactory.TestDecorator decorator;
|
| 189 | if (this.testSelection.isPresent()) {
|
| 190 | tests = getTestsForSelection(server.registryAccess(), this.testSelection.get()).filter(test -> !test.value().manualOnly()).toList();
|
| 191 | if (tests.isEmpty()) {
|
| 192 | LOGGER.warn("Test selection matcher ({}) found no tests", this.testSelection.get());
|
| 193 | System.exit(-1);
|
| 194 | }
|
| 195 |
|
| 196 | if (this.verify) {
|
| 197 | decorator = GameTestServer::rotateAndMultiply;
|
| 198 | LOGGER.info("Verify requested. Will run each test that matches {} {} times", this.testSelection.get(), 100 * Rotation.values().length);
|
| 199 | } else if (this.repeatCount > 0) {
|
| 200 | decorator = this::multiplyTest;
|
| 201 | LOGGER.info("Each test that matches {} will be run {} times (total: {})", this.testSelection.get(), this.repeatCount, tests.size() * this.repeatCount);
|
| 202 | } else {
|
| 203 | decorator = GameTestBatchFactory.DIRECT;
|
| 204 | LOGGER.info("Will run tests matching {} ({} tests)", this.testSelection.get(), tests.size());
|
| 205 | }
|
| 206 | } else {
|
| 207 | tests = testRegistry.listElements().filter(test -> !test.value().manualOnly()).toList();
|
| 208 | decorator = GameTestBatchFactory.DIRECT;
|
| 209 | }
|
| 210 |
|
| 211 | return GameTestBatchFactory.divideIntoBatches(tests, decorator, server);
|
| 212 | }
|
| 213 |
|
| 214 | private static Stream<GameTestInfo> rotateAndMultiply(final Holder.Reference<GameTestInstance> test, final ServerLevel level) {
|
| 215 | Builder<GameTestInfo> builder = Stream.builder();
|
| 216 |
|
| 217 | for (Rotation rotation : Rotation.values()) {
|
| 218 | for (int i = 0; i < 100; i++) {
|
| 219 | builder.add(new GameTestInfo(test, rotation, level, RetryOptions.noRetries()));
|
| 220 | }
|
| 221 | }
|
| 222 |
|
| 223 | return builder.build();
|
| 224 | }
|
| 225 |
|
| 226 | public static Stream<Holder.Reference<GameTestInstance>> getTestsForSelection(final RegistryAccess registries, final String selection) {
|
| 227 | return ResourceSelectorArgument.parse(new StringReader(selection), registries.lookupOrThrow(Registries.TEST_INSTANCE)).stream();
|
| 228 | }
|
| 229 |
|
| 230 | private Stream<GameTestInfo> multiplyTest(final Holder.Reference<GameTestInstance> test, final ServerLevel level) {
|
| 231 | Builder<GameTestInfo> builder = Stream.builder();
|
| 232 |
|
| 233 | for (int i = 0; i < this.repeatCount; i++) {
|
| 234 | builder.add(new GameTestInfo(test, Rotation.NONE, level, RetryOptions.noRetries()));
|
| 235 | }
|
| 236 |
|
| 237 | return builder.build();
|
| 238 | }
|
| 239 |
|
| 240 | @Override
|
| 241 | protected void tickServer(final BooleanSupplier haveTime) {
|
| 242 | super.tickServer(haveTime);
|
| 243 | ServerLevel level = this.overworld();
|
| 244 | if (!this.haveTestsStarted()) {
|
| 245 | this.startTests(level);
|
| 246 | }
|
| 247 |
|
| 248 | if (level.getGameTime() % 20L == 0L) {
|
| 249 | LOGGER.info("{}", this.testTracker.getProgressBar());
|
| 250 | }
|
| 251 |
|
| 252 | if (this.testTracker.isDone()) {
|
| 253 | this.halt(false);
|
| 254 | LOGGER.info("{}", this.testTracker.getProgressBar());
|
| 255 | GlobalTestReporter.finish();
|
| 256 | LOGGER.info("========= {} GAME TESTS COMPLETE IN {} ======================", this.testTracker.getTotalCount(), this.stopwatch.stop());
|
| 257 | if (this.testTracker.hasFailedRequired()) {
|
| 258 | LOGGER.info("{} required tests failed :(", this.testTracker.getFailedRequiredCount());
|
| 259 | this.testTracker.getFailedRequired().forEach(GameTestServer::logFailedTest);
|
| 260 | } else {
|
| 261 | LOGGER.info("All {} required tests passed :)", this.testTracker.getTotalCount());
|
| 262 | }
|
| 263 |
|
| 264 | if (this.testTracker.hasFailedOptional()) {
|
| 265 | LOGGER.info("{} optional tests failed", this.testTracker.getFailedOptionalCount());
|
| 266 | this.testTracker.getFailedOptional().forEach(GameTestServer::logFailedTest);
|
| 267 | }
|
| 268 |
|
| 269 | LOGGER.info("====================================================");
|
| 270 | }
|
| 271 | }
|
| 272 |
|
| 273 | private static void logFailedTest(final GameTestInfo testInfo) {
|
| 274 | if (testInfo.getRotation() != Rotation.NONE) {
|
| 275 | LOGGER.info(" - {} with rotation {}: {}", testInfo.id(), testInfo.getRotation().getSerializedName(), testInfo.getError().getDescription().getString());
|
| 276 | } else {
|
| 277 | LOGGER.info(" - {}: {}", testInfo.id(), testInfo.getError().getDescription().getString());
|
| 278 | }
|
| 279 | }
|
| 280 |
|
| 281 | @Override
|
| 282 | protected SampleLogger getTickTimeLogger() {
|
| 283 | return this.sampleLogger;
|
| 284 | }
|
| 285 |
|
| 286 | @Override
|
| 287 | public boolean isTickTimeLoggingEnabled() {
|
| 288 | return false;
|
| 289 | }
|
| 290 |
|
| 291 | @Override
|
| 292 | protected void waitUntilNextTick() {
|
| 293 | this.runAllTasks();
|
| 294 | }
|
| 295 |
|
| 296 | @Override
|
| 297 | public SystemReport fillServerSystemReport(final SystemReport systemReport) {
|
| 298 | systemReport.setDetail("Type", "Game test server");
|
| 299 | return systemReport;
|
| 300 | }
|
| 301 |
|
| 302 | @Override
|
| 303 | protected void onServerExit() {
|
| 304 | super.onServerExit();
|
| 305 | LOGGER.info("Game test server shutting down");
|
| 306 | System.exit(this.testTracker != null ? this.testTracker.getFailedRequiredCount() : -1);
|
| 307 | }
|
| 308 |
|
| 309 | @Override
|
| 310 | protected void onServerCrash(final CrashReport report) {
|
| 311 | super.onServerCrash(report);
|
| 312 | LOGGER.error("Game test server crashed\n{}", report.getFriendlyReport(ReportType.CRASH));
|
| 313 | System.exit(1);
|
| 314 | }
|
| 315 |
|
| 316 | private void startTests(final ServerLevel level) {
|
| 317 | RandomSource random = level.getRandom();
|
| 318 | BlockPos startPos = new BlockPos(random.nextIntBetweenInclusive(-14999992, 14999992), 4, random.nextIntBetweenInclusive(-14999992, 14999992));
|
| 319 | level.setRespawnData(LevelData.RespawnData.of(level.dimension(), startPos, 0.0F, 0.0F));
|
| 320 | GameTestRunner runner = GameTestRunner.Builder.fromBatches(this.testBatches, this)
|
| 321 | .newStructureSpawner(new StructureGridSpawner(var1 -> startPos, 8, false))
|
| 322 | .build();
|
| 323 | Collection<GameTestInfo> testInfos = runner.getTestInfos();
|
| 324 | this.testTracker = new MultipleTestTracker(testInfos);
|
| 325 | LOGGER.info("{} tests are now running at position {}!", this.testTracker.getTotalCount(), startPos.toShortString());
|
| 326 | this.stopwatch.reset();
|
| 327 | this.stopwatch.start();
|
| 328 | runner.start();
|
| 329 | }
|
| 330 |
|
| 331 | private boolean haveTestsStarted() {
|
| 332 | return this.testTracker != null;
|
| 333 | }
|
| 334 |
|
| 335 | @Override
|
| 336 | public boolean isHardcore() {
|
| 337 | return false;
|
| 338 | }
|
| 339 |
|
| 340 | @Override
|
| 341 | public LevelBasedPermissionSet operatorUserPermissions() {
|
| 342 | return LevelBasedPermissionSet.ALL;
|
| 343 | }
|
| 344 |
|
| 345 | @Override
|
| 346 | public PermissionSet getFunctionCompilationPermissions() {
|
| 347 | return LevelBasedPermissionSet.OWNER;
|
| 348 | }
|
| 349 |
|
| 350 | @Override
|
| 351 | public boolean shouldRconBroadcast() {
|
| 352 | return false;
|
| 353 | }
|
| 354 |
|
| 355 | @Override
|
| 356 | public boolean isDedicatedServer() {
|
| 357 | return false;
|
| 358 | }
|
| 359 |
|
| 360 | @Override
|
| 361 | public int getRateLimitPacketsPerSecond() {
|
| 362 | return 0;
|
| 363 | }
|
| 364 |
|
| 365 | @Override
|
| 366 | public int getCommandSpamThresholdSeconds() {
|
| 367 | return 0;
|
| 368 | }
|
| 369 |
|
| 370 | @Override
|
| 371 | public int getChatSpamThresholdSeconds() {
|
| 372 | return 0;
|
| 373 | }
|
| 374 |
|
| 375 | @Override
|
| 376 | public boolean useNativeTransport() {
|
| 377 | return false;
|
| 378 | }
|
| 379 |
|
| 380 | @Override
|
| 381 | public boolean isPublished() {
|
| 382 | return false;
|
| 383 | }
|
| 384 |
|
| 385 | @Override
|
| 386 | public boolean shouldInformAdmins() {
|
| 387 | return false;
|
| 388 | }
|
| 389 |
|
| 390 | @Override
|
| 391 | public boolean isSingleplayerOwner(final NameAndId nameAndId) {
|
| 392 | return false;
|
| 393 | }
|
| 394 |
|
| 395 | @Override
|
| 396 | public int getMaxPlayers() {
|
| 397 | return 1;
|
| 398 | }
|
| 399 |
|
| 400 | private static class MockProfileResolver implements ProfileResolver {
|
| 401 | @Override
|
| 402 | public Optional<GameProfile> fetchByName(final String name) {
|
| 403 | return Optional.empty();
|
| 404 | }
|
| 405 |
|
| 406 | @Override
|
| 407 | public Optional<GameProfile> fetchById(final UUID id) {
|
| 408 | return Optional.empty();
|
| 409 | }
|
| 410 | }
|
| 411 |
|
| 412 | private static class MockUserNameToIdResolver implements UserNameToIdResolver {
|
| 413 | private final Set<NameAndId> savedIds = new HashSet<>();
|
| 414 |
|
| 415 | @Override
|
| 416 | public void add(final NameAndId nameAndId) {
|
| 417 | this.savedIds.add(nameAndId);
|
| 418 | }
|
| 419 |
|
| 420 | @Override
|
| 421 | public Optional<NameAndId> get(final String name) {
|
| 422 | return this.savedIds.stream().filter(e -> e.name().equals(name)).findFirst().or(() -> Optional.of(NameAndId.createOffline(name)));
|
| 423 | }
|
| 424 |
|
| 425 | @Override
|
| 426 | public Optional<NameAndId> get(final UUID id) {
|
| 427 | return this.savedIds.stream().filter(e -> e.id().equals(id)).findFirst();
|
| 428 | }
|
| 429 |
|
| 430 | @Override
|
| 431 | public void resolveOfflineUsers(final boolean value) {
|
| 432 | }
|
| 433 |
|
| 434 | @Override
|
| 435 | public void save() {
|
| 436 | }
|
| 437 | }
|
| 438 | }
|
| 439 |
|