How to use EventHandlerException class of be.seeseemelk.mockbukkit.exception package

Best MockBukkit code snippet using be.seeseemelk.mockbukkit.exception.EventHandlerException

Source:PluginManagerMock.java Github

copy

Full Screen

1package be.seeseemelk.mockbukkit.plugin;2import be.seeseemelk.mockbukkit.ServerMock;3import be.seeseemelk.mockbukkit.UnimplementedOperationException;4import be.seeseemelk.mockbukkit.exception.EventHandlerException;5import be.seeseemelk.mockbukkit.scheduler.BukkitSchedulerMock;6import com.destroystokyo.paper.event.server.ServerExceptionEvent;7import com.destroystokyo.paper.exception.ServerEventException;8import com.google.common.base.Preconditions;9import com.google.common.collect.ImmutableSet;10import org.bukkit.command.PluginCommand;11import org.bukkit.command.PluginCommandUtils;12import org.bukkit.configuration.file.YamlConfiguration;13import org.bukkit.event.Event;14import org.bukkit.event.EventPriority;15import org.bukkit.event.HandlerList;16import org.bukkit.event.Listener;17import org.bukkit.event.server.PluginEnableEvent;18import org.bukkit.permissions.Permissible;19import org.bukkit.permissions.Permission;20import org.bukkit.permissions.PermissionDefault;21import org.bukkit.plugin.EventExecutor;22import org.bukkit.plugin.IllegalPluginAccessException;23import org.bukkit.plugin.InvalidDescriptionException;24import org.bukkit.plugin.InvalidPluginException;25import org.bukkit.plugin.Plugin;26import org.bukkit.plugin.PluginDescriptionFile;27import org.bukkit.plugin.PluginLoader;28import org.bukkit.plugin.PluginManager;29import org.bukkit.plugin.RegisteredListener;30import org.bukkit.plugin.UnknownDependencyException;31import org.bukkit.plugin.java.JavaPlugin;32import org.bukkit.plugin.java.JavaPluginLoader;33import org.bukkit.plugin.java.JavaPluginUtils;34import org.jetbrains.annotations.NotNull;35import java.io.File;36import java.io.FileNotFoundException;37import java.io.IOException;38import java.lang.reflect.Constructor;39import java.lang.reflect.Method;40import java.net.URL;41import java.nio.file.Files;42import java.nio.file.Path;43import java.util.ArrayList;44import java.util.Arrays;45import java.util.Collection;46import java.util.Collections;47import java.util.Comparator;48import java.util.Enumeration;49import java.util.HashMap;50import java.util.HashSet;51import java.util.List;52import java.util.Locale;53import java.util.Map;54import java.util.Map.Entry;55import java.util.Random;56import java.util.Set;57import java.util.WeakHashMap;58import java.util.concurrent.ThreadLocalRandom;59import java.util.function.Consumer;60import java.util.function.Predicate;61import java.util.logging.Level;62import java.util.stream.Collectors;63import java.util.stream.Stream;64import static org.junit.jupiter.api.Assertions.fail;65public class PluginManagerMock implements PluginManager66{67 private final @NotNull ServerMock server;68 private final @NotNull JavaPluginLoader loader;69 private final List<Plugin> plugins = new ArrayList<>();70 private final List<PluginCommand> commands = new ArrayList<>();71 private final List<Event> events = new ArrayList<>();72 private File parentTemporaryDirectory;73 private final Map<String, Permission> permissions = new HashMap<>();74 private final Map<Permissible, Set<String>> permissionSubscriptions = new HashMap<>();75 private final Map<Boolean, Map<Permissible, Boolean>> defaultPermissionSubscriptions = new HashMap<Boolean, Map<Permissible, Boolean>>();76 private final @NotNull Map<String, List<Listener>> listeners = new HashMap<>();77 private final List<Class<?>> pluginConstructorTypes = Arrays.asList(JavaPluginLoader.class,78 PluginDescriptionFile.class, File.class, File.class);79 @SuppressWarnings("deprecation")80 public PluginManagerMock(@NotNull ServerMock server)81 {82 this.server = server;83 loader = new JavaPluginLoader(this.server);84 }85 /**86 * Should be called when the plugin manager is not used anymore.87 */88 public void unload()89 {90 if (parentTemporaryDirectory == null)91 return;92 // Delete the temporary directory, from the deepest file to the root.93 try (Stream<Path> walk = Files.walk(parentTemporaryDirectory.toPath()))94 {95 walk.sorted(Comparator.reverseOrder())96 .map(Path::toFile)97 .forEach(File::delete);98 }99 catch (IOException e)100 {101 server.getLogger().log(Level.SEVERE, "Could not delete temporary directory", e);102 }103 }104 /**105 * Asserts that at least one event conforms to the given predicate.106 *107 * @param message The message to display when no event conforms.108 * @param predicate The predicate to test against.109 */110 public void assertEventFired(@NotNull String message, @NotNull Predicate<Event> predicate)111 {112 for (Event event : events)113 {114 if (predicate.test(event))115 {116 return;117 }118 }119 fail(message);120 }121 /**122 * Asserts that at least one event conforms to the given predicate.123 *124 * @param predicate The predicate to test against.125 */126 public void assertEventFired(@NotNull Predicate<Event> predicate)127 {128 assertEventFired("Event assert failed", predicate);129 }130 /**131 * Asserts that there is at least one event of a certain class for which the predicate is true.132 *133 * @param <T> The type of event that is expected.134 * @param message The message to display if no event is found.135 * @param eventClass The class type that the event should be an instance of.136 * @param predicate The predicate to test the event against.137 */138 public <T extends Event> void assertEventFired(String message, @NotNull Class<T> eventClass, @NotNull Predicate<T> predicate)139 {140 for (Event event : events)141 {142 if (eventClass.isInstance(event) && predicate.test(eventClass.cast(event)))143 {144 return;145 }146 }147 fail(message);148 }149 /**150 * Asserts that there is at least one event of a certain class for which the predicate is true.151 *152 * @param <T> The type of event that is expected.153 * @param eventClass The class type that the event should be an instance of.154 * @param predicate The predicate to test the event against.155 */156 public <T extends Event> void assertEventFired(@NotNull Class<T> eventClass, @NotNull Predicate<T> predicate)157 {158 assertEventFired("No event of the correct class tested true", eventClass, predicate);159 }160 /**161 * Asserts that a specific event or one of it's sub-events has been fired at least once.162 *163 * @param eventClass The class of the event to check for.164 */165 public void assertEventFired(@NotNull Class<? extends Event> eventClass)166 {167 assertEventFired("No event of that type has been fired", eventClass::isInstance);168 }169 /**170 * Asserts that a specific event or one of it's sub-event has not been fired.171 *172 * @param eventClass The class of the event to check for.173 */174 public void assertEventNotFired(@NotNull Class<? extends Event> eventClass)175 {176 assertEventNotFired(eventClass, "An event of type " + eventClass.getSimpleName() + " has been fired when it shouldn't have been");177 }178 /**179 * Asserts that a specific event or one of it's sub-event has not been fired.180 *181 * @param eventClass The class of the event to check for.182 * @param message The message to print when failed.183 */184 public void assertEventNotFired(@NotNull Class<? extends Event> eventClass, String message)185 {186 for (Event event : this.events)187 {188 if (eventClass.isAssignableFrom(event.getClass()))189 {190 fail(message);191 }192 }193 }194 @Override195 public Plugin getPlugin(@NotNull String name)196 {197 for (Plugin plugin : plugins)198 {199 if (name.equals(plugin.getName()))200 {201 return plugin;202 }203 }204 return null;205 }206 @Override207 public Plugin @NotNull [] getPlugins()208 {209 return plugins.toArray(new Plugin[0]);210 }211 /**212 * Get a collection of all available commands.213 *214 * @return A collection of all available commands.215 */216 public @NotNull Collection<PluginCommand> getCommands()217 {218 return Collections.unmodifiableList(commands);219 }220 /**221 * Checks if a constructor is compatible with an array of types.222 *223 * @param constructor The constructor to check.224 * @param types The array of parameter types the constructor must support. Note that the first 4 parameters225 * should be an exact match while the rest don't have to be.226 * @return {@code true} if the constructor is compatible, {@code false} if it isn't.227 */228 private boolean isConstructorCompatible(@NotNull Constructor<?> constructor, @NotNull Class<?> @NotNull [] types)229 {230 Class<?>[] parameters = constructor.getParameterTypes();231 for (int i = 0; i < types.length; i++)232 {233 Class<?> type = types[i];234 Class<?> parameter = parameters[i];235 if (i < 4)236 {237 if (!type.equals(parameter))238 {239 return false;240 }241 }242 else if (!parameter.isAssignableFrom(type))243 {244 return false;245 }246 }247 return true;248 }249 /**250 * Looks for a compatible constructor of a plugin with a certain constructor.251 *252 * @param class1 The plugin class for which a constructor should be found.253 * @param types The types of parameters that the constructor should be able to except. Note that the first 4254 * parameters should be an exact match while the rest don't have to be.255 * @return A constructor that will take the given types.256 * @throws NoSuchMethodException if no compatible constructor could be found.257 */258 @SuppressWarnings("unchecked")259 private @NotNull Constructor<? extends JavaPlugin> getCompatibleConstructor(@NotNull Class<? extends JavaPlugin> class1,260 Class<?> @NotNull [] types) throws NoSuchMethodException261 {262 for (Constructor<?> constructor : class1.getDeclaredConstructors())263 {264 Class<?>[] parameters = constructor.getParameterTypes();265 if (parameters.length == types.length && isConstructorCompatible(constructor, types))266 {267 return (Constructor<? extends JavaPlugin>) constructor;268 }269 }270 StringBuilder parameters = new StringBuilder("[");271 for (Class<?> type : types)272 parameters.append(type.getName()).append(", ");273 String str = parameters.substring(0, parameters.length() - 2) + "]";274 throw new NoSuchMethodException(275 "No compatible constructor for " + class1.getName() + " with parameters " + str);276 }277 public @NotNull File getParentTemporaryDirectory() throws IOException278 {279 if (parentTemporaryDirectory == null)280 {281 Random random = ThreadLocalRandom.current();282 parentTemporaryDirectory = Files.createTempDirectory("MockBukkit-" + random.nextInt(0, Integer.MAX_VALUE)).toFile();283 }284 return parentTemporaryDirectory;285 }286 /**287 * Tries to create a temporary directory.288 *289 * @param name The name of the directory to create.290 * @return The created temporary directory.291 * @throws IOException when the directory could not be created.292 */293 public @NotNull File createTemporaryDirectory(@NotNull String name) throws IOException294 {295 File directory = new File(getParentTemporaryDirectory(), name);296 directory.mkdirs();297 return directory;298 }299 /**300 * Tries to create a temporary plugin file.301 *302 * @param name The name of the plugin.303 * @return The created temporary file.304 * @throws IOException when the file could not be created.305 */306 public @NotNull File createTemporaryPluginFile(@NotNull String name) throws IOException307 {308 File pluginFile = new File(getParentTemporaryDirectory(), name + ".jar");309 if (!pluginFile.exists() && !pluginFile.createNewFile())310 {311 throw new IOException("Could not create file " + pluginFile.getAbsolutePath());312 }313 return pluginFile;314 }315 /**316 * Registers a plugin that has already been loaded. This is necessary to register plugins loaded from external jars.317 *318 * @param plugin The plugin that has been loaded.319 */320 public void registerLoadedPlugin(@NotNull Plugin plugin)321 {322 addCommandsFrom(plugin);323 plugins.add(plugin);324 plugin.onLoad();325 }326 /**327 * Load a plugin from a class. It will use the system resource {@code plugin.yml} as the resource file.328 *329 * @param description The {@link PluginDescriptionFile} that contains information about the plugin.330 * @param class1 The plugin to load.331 * @param parameters Extra parameters to pass on to the plugin constructor. Must not be {@code null}.332 * @return The loaded plugin.333 */334 public @NotNull JavaPlugin loadPlugin(@NotNull Class<? extends JavaPlugin> class1, @NotNull PluginDescriptionFile description,335 Object @NotNull [] parameters)336 {337 try338 {339 List<Class<?>> types = new ArrayList<>(pluginConstructorTypes);340 for (Object parameter : parameters)341 {342 types.add(parameter.getClass());343 }344 Constructor<? extends JavaPlugin> constructor = getCompatibleConstructor(class1, types.toArray(new Class<?>[0]));345 constructor.setAccessible(true);346 Object[] arguments = new Object[types.size()];347 arguments[0] = loader;348 arguments[1] = description;349 arguments[2] = createTemporaryDirectory(description.getName() + "-" + description.getVersion());350 arguments[3] = createTemporaryPluginFile(description.getName() + "-" + description.getVersion());351 System.arraycopy(parameters, 0, arguments, 4, parameters.length);352 JavaPlugin plugin = constructor.newInstance(arguments);353 registerLoadedPlugin(plugin);354 return plugin;355 }356 catch (ReflectiveOperationException | IOException e)357 {358 throw new RuntimeException("Failed to instantiate plugin", e);359 }360 }361 /**362 * Load a plugin from a class. It will use the system resource {@code plugin.yml} as the resource file.363 *364 * @param description The {@link PluginDescriptionFile} that contains information about the plugin.365 * @param class1 The plugin to load.366 * @return The loaded plugin.367 */368 public @NotNull JavaPlugin loadPlugin(@NotNull Class<? extends JavaPlugin> class1, @NotNull PluginDescriptionFile description)369 {370 return loadPlugin(class1, description, new Object[0]);371 }372 /**373 * Load a plugin from a class. It will use the system resource {@code plugin.yml} as the resource file.374 *375 * @param class1 The plugin to load.376 * @param parameters Extra parameters to pass on to the plugin constructor.377 * @return The loaded plugin.378 */379 public @NotNull JavaPlugin loadPlugin(@NotNull Class<? extends JavaPlugin> class1, Object @NotNull [] parameters)380 {381 try382 {383 PluginDescriptionFile description = findPluginDescription(class1);384 return loadPlugin(class1, description, parameters);385 }386 catch (IOException | InvalidDescriptionException e)387 {388 throw new RuntimeException(e);389 }390 }391 /**392 * Tries to find the correct plugin.yml for a given plugin. It does this by opening each plugin.yml that it finds393 * and comparing the 'main' property to the qualified name of the plugin class.394 *395 * @param class1 The class that is in a subpackage of where to get the file.396 * @return The plugin description file.397 * @throws IOException Thrown when the file wan't be found or loaded.398 * @throws InvalidDescriptionException If the plugin description file is formatted incorrectly.399 */400 private @NotNull PluginDescriptionFile findPluginDescription(@NotNull Class<? extends JavaPlugin> class1)401 throws IOException, InvalidDescriptionException402 {403 Enumeration<URL> resources = class1.getClassLoader().getResources("plugin.yml");404 while (resources.hasMoreElements())405 {406 URL url = resources.nextElement();407 PluginDescriptionFile description = new PluginDescriptionFile(url.openStream());408 String mainClass = description.getMain();409 if (class1.getName().equals(mainClass))410 return description;411 }412 throw new FileNotFoundException(413 "Could not find file plugin.yml. Maybe forgot to add the 'main' property?");414 }415 @Override416 public void callEvent(@NotNull Event event)417 {418 if (event.isAsynchronous() && server.isOnMainThread())419 {420 throw new IllegalStateException("Asynchronous Events cannot be called on the main Thread.");421 }422 events.add(event);423 HandlerList handlers = event.getHandlers();424 for (RegisteredListener listener : handlers.getRegisteredListeners())425 {426 callRegisteredListener(listener, event);427 }428 }429 /**430 * This method invokes {@link #callEvent(Event)} from a different {@link Thread}431 * using the {@link BukkitSchedulerMock}.432 *433 * @param event The asynchronous {@link Event} to call.434 */435 public void callEventAsynchronously(@NotNull Event event)436 {437 callEventAsynchronously(event, null);438 }439 /**440 * This method invokes {@link #callEvent(Event)} from a different {@link Thread}441 * using the {@link BukkitSchedulerMock}.442 *443 * @param event The asynchronous {@link Event} to call.444 * @param func A function to invoke after the event has been called.445 */446 public <T extends Event> void callEventAsynchronously(@NotNull T event, Consumer<T> func)447 {448 if (!event.isAsynchronous())449 {450 throw new IllegalStateException("Synchronous Events cannot be called asynchronously.");451 }452 // Our Scheduler will call the Event on a dedicated Event Thread Executor453 server.getScheduler().executeAsyncEvent(event, func);454 }455 private void callRegisteredListener(@NotNull RegisteredListener registration, @NotNull Event event)456 {457 if (!registration.getPlugin().isEnabled())458 {459 return;460 }461 try462 {463 registration.callEvent(event);464 }465 catch (Throwable ex)466 {467 if (!(event instanceof ServerExceptionEvent))468 { // Don't cause an endless loop469 String msg = "Could not pass event " + event.getEventName() + " to " + registration.getPlugin().getDescription().getFullName();470 callEvent(new ServerExceptionEvent(new ServerEventException(msg, ex, registration.getPlugin(), registration.getListener(), event)));471 }472 if (ex instanceof RuntimeException r)473 {474 throw r; // Rethrow same exception if possible475 }476 else477 {478 throw new EventHandlerException(ex);479 }480 }481 }482 @Override483 public void enablePlugin(@NotNull Plugin plugin)484 {485 if (plugin instanceof JavaPlugin)486 {487 if (!plugin.isEnabled())488 {489 JavaPluginUtils.setEnabled((JavaPlugin) plugin, true);490 callEvent(new PluginEnableEvent(plugin));491 }492 }...

Full Screen

Full Screen

Source:PluginManagerMockTest.java Github

copy

Full Screen

1package be.seeseemelk.mockbukkit.plugin;2import be.seeseemelk.mockbukkit.MockBukkit;3import be.seeseemelk.mockbukkit.ServerMock;4import be.seeseemelk.mockbukkit.TestPlugin;5import be.seeseemelk.mockbukkit.exception.EventHandlerException;6import org.bukkit.World;7import org.bukkit.WorldCreator;8import org.bukkit.command.PluginCommand;9import org.bukkit.entity.Player;10import org.bukkit.event.EventHandler;11import org.bukkit.event.Listener;12import org.bukkit.event.block.BlockBreakEvent;13import org.bukkit.event.player.PlayerInteractEvent;14import org.bukkit.event.server.PluginDisableEvent;15import org.bukkit.permissions.Permissible;16import org.bukkit.permissions.Permission;17import org.bukkit.permissions.PermissionDefault;18import org.bukkit.plugin.Plugin;19import org.bukkit.plugin.ServicePriority;20import org.bukkit.plugin.java.JavaPluginUtils;21import org.bukkit.scheduler.BukkitRunnable;22import org.junit.jupiter.api.AfterEach;23import org.junit.jupiter.api.BeforeEach;24import org.junit.jupiter.api.Disabled;25import org.junit.jupiter.api.Test;26import java.util.Collection;27import java.util.Iterator;28import static org.junit.jupiter.api.Assertions.assertEquals;29import static org.junit.jupiter.api.Assertions.assertFalse;30import static org.junit.jupiter.api.Assertions.assertNotNull;31import static org.junit.jupiter.api.Assertions.assertNull;32import static org.junit.jupiter.api.Assertions.assertThrows;33import static org.junit.jupiter.api.Assertions.assertThrowsExactly;34import static org.junit.jupiter.api.Assertions.assertTrue;35class PluginManagerMockTest36{37 private ServerMock server;38 private PluginManagerMock pluginManager;39 private TestPlugin plugin;40 @BeforeEach41 void setUp()42 {43 server = MockBukkit.mock();44 pluginManager = server.getPluginManager();45 plugin = MockBukkit.load(TestPlugin.class);46 }47 @AfterEach48 void tearDown()49 {50 MockBukkit.unmock();51 }52 @Test53 void callEvent_UnregisteredPlayerInteractEvent_NoneCalled()54 {55 PlayerInteractEvent event = new PlayerInteractEvent(null, null, null, null, null);56 pluginManager.callEvent(event);57 assertFalse(plugin.unannotatedPlayerInteractEventExecuted);58 assertFalse(plugin.annotatedBlockBreakEventExecuted);59 assertFalse(plugin.annotatedPlayerInteractEventExecuted);60 }61 @Test62 void callEvent_RegisteredPlayerInteractEvent_OneCalled()63 {64 PlayerInteractEvent event = new PlayerInteractEvent(null, null, null, null, null);65 pluginManager.registerEvents(plugin, plugin);66 pluginManager.callEvent(event);67 assertFalse(plugin.unannotatedPlayerInteractEventExecuted);68 assertFalse(plugin.annotatedBlockBreakEventExecuted);69 assertTrue(plugin.annotatedPlayerInteractEventExecuted);70 }71 @Test72 void test_ManualListener_Registration()73 {74 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);75 assertEquals(3, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);76 pluginManager.unregisterPluginEvents(plugin);77 assertEquals(0, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);78 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);79 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);80 assertEquals(6, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);81 pluginManager.unregisterPluginEvents(plugin);82 assertEquals(0, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);83 }84 @Test85 void test_AutomaticListener_DeRegistration()86 {87 MockBukkit.getMock().getPluginManager().registerEvents(plugin, plugin);88 assertEquals(3, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);89 MockBukkit.unmock();90 assertEquals(0, BlockBreakEvent.getHandlerList().getRegisteredListeners().length);91 }92 @Test93 void getPlugin_PluginName_Plugin()94 {95 Plugin plugin = pluginManager.getPlugin("MockBukkitTestPlugin");96 assertNotNull(plugin);97 assertTrue(plugin instanceof TestPlugin);98 }99 @Test100 void getPlugin_UnknownName_Nothing()101 {102 Plugin plugin = pluginManager.getPlugin("NoPlugin");103 assertNull(plugin);104 }105 @Test106 void getCommands_Default_PluginCommand()107 {108 Collection<PluginCommand> commands = pluginManager.getCommands();109 assertEquals(3, commands.size());110 Iterator<PluginCommand> iterator = commands.iterator();111 assertEquals("mockcommand", iterator.next().getName());112 assertEquals("testcommand", iterator.next().getName());113 assertEquals("othercommand", iterator.next().getName());114 assertFalse(iterator.hasNext());115 }116 @Test117 void assertEventFired_PredicateTrue_DoesNotAssert()118 {119 Player player = server.addPlayer();120 BlockBreakEvent eventToFire = new BlockBreakEvent(null, player);121 pluginManager.callEvent(eventToFire);122 pluginManager.assertEventFired(event ->123 event instanceof BlockBreakEvent && ((BlockBreakEvent) event).getPlayer().equals(player)124 );125 }126 @Test127 void assertEventFired_PredicateFalse_Asserts()128 {129 Player player = server.addPlayer();130 BlockBreakEvent eventToFire = new BlockBreakEvent(null, player);131 pluginManager.callEvent(eventToFire);132 assertThrows(AssertionError.class, () -> pluginManager.assertEventFired(event -> false));133 }134 @Test135 void assertListenerRan_With_Order()136 {137 server.getPluginManager().registerEvents(plugin, plugin);138 Player p = server.addPlayer();139 BlockBreakEvent event = new BlockBreakEvent(null, p);140 assertTrue(plugin.ignoredCancelledEvent);141 pluginManager.callEvent(event);142 assertTrue(event.isCancelled());143 assertTrue(plugin.ignoredCancelledEvent);144 }145 @Test146 void assertEventFired_EventWasFired_DoesNotAssert()147 {148 BlockBreakEvent event = new BlockBreakEvent(null, null);149 pluginManager.callEvent(event);150 pluginManager.assertEventFired(BlockBreakEvent.class);151 }152 @Test153 void assertEventFired_EventWasNotFired_Asserts()154 {155 assertThrows(AssertionError.class, () -> pluginManager.assertEventFired(BlockBreakEvent.class));156 }157 @Test158 void getPermission_NoPermission_Null()159 {160 assertNull(pluginManager.getPermission("mockbukkit.perm"));161 }162 @Test163 void getPermission_PermissionAdded_NotNull()164 {165 Permission permission = new Permission("mockbukkit.perm");166 pluginManager.addPermission(permission);167 assertNotNull(pluginManager.getPermission(permission.getName()));168 }169 @Test170 void getDefaultPermission_OpPermissionAddedAndAsked_ContainsPermission()171 {172 Permission permission = new Permission("mockbukkit.perm", PermissionDefault.OP);173 pluginManager.addPermission(permission);174 assertTrue(pluginManager.getDefaultPermissions(true).contains(permission));175 }176 @Test177 void getDefaultPermission_OpPermissionAskedButNotAdded_DoesNotContainPermission()178 {179 Permission permission = new Permission("mockbukkit.perm", PermissionDefault.NOT_OP);180 pluginManager.addPermission(permission);181 assertFalse(pluginManager.getDefaultPermissions(true).contains(permission));182 }183 @Test184 void removePermission_String() {185 Permission permission = new Permission("mockbukkit.perm");186 pluginManager.addPermission(permission);187 assertTrue(pluginManager.getPermissions().contains(permission));188 pluginManager.removePermission("mockbukkit.perm");189 assertFalse(pluginManager.getPermissions().contains(permission));190 }191 @Test192 void disablePlugin_LoadedPlugin_PluginDisabled()193 {194 TestPlugin plugin = MockBukkit.load(TestPlugin.class);195 assertTrue(plugin.isEnabled());196 pluginManager.disablePlugin(plugin);197 assertFalse(plugin.isEnabled(), "Plugin was not disabled");198 assertTrue(plugin.onDisableExecuted);199 }200 @Test201 void disablePlugins_LoadedPlugins_AllDisabled()202 {203 TestPlugin plugin1 = MockBukkit.load(TestPlugin.class);204 TestPlugin plugin2 = MockBukkit.load(TestPlugin.class);205 assertTrue(plugin1.isEnabled());206 assertTrue(plugin2.isEnabled());207 pluginManager.disablePlugins();208 assertFalse(plugin1.isEnabled(), "Plugin1 was not disabled");209 assertFalse(plugin2.isEnabled(), "Plugin2 was not disabled");210 assertTrue(plugin1.onDisableExecuted);211 assertTrue(plugin2.onDisableExecuted);212 }213 @Test214 void disablePlugin_PluginDisableEvent_IsFired()215 {216 TestPlugin plugin = MockBukkit.load(TestPlugin.class);217 pluginManager.disablePlugin(plugin);218 pluginManager.assertEventFired(PluginDisableEvent.class, event -> event.getPlugin().equals(plugin));219 }220 @Test221 void disablePlugin_Unloaded_PluginDisableEvent_NotFired()222 {223 TestPlugin plugin = MockBukkit.load(TestPlugin.class);224 JavaPluginUtils.setEnabled(plugin, false);225 pluginManager.disablePlugin(plugin);226 pluginManager.assertEventNotFired(PluginDisableEvent.class);227 }228 @Test229 void disablePlugin_TasksCanceled()230 {231 TestPlugin plugin = MockBukkit.load(TestPlugin.class);232 BukkitRunnable runnable = new BukkitRunnable()233 {234 @Override235 public void run()236 {237 }238 };239 runnable.runTaskTimer(plugin, 1, 1);240 pluginManager.disablePlugin(plugin);241 assertTrue(runnable.isCancelled());242 }243 @Test244 void disablePlugin_ServicesUnregistered()245 {246 TestPlugin plugin = MockBukkit.load(TestPlugin.class);247 server.getServicesManager().register(Object.class, new Object(), plugin, ServicePriority.High);248 assertTrue(server.getServicesManager().isProvidedFor(Object.class));249 pluginManager.disablePlugin(plugin);250 assertFalse(server.getServicesManager().isProvidedFor(Object.class));251 }252 @Test253 void disablePlugin_DisablesPluginChannels()254 {255 TestPlugin plugin = MockBukkit.load(TestPlugin.class);256 server.getMessenger().registerOutgoingPluginChannel(plugin, "BungeeCord");257 server.getMessenger().registerIncomingPluginChannel(plugin, "BungeeCord", (channel, player, message) ->258 {259 });260 assertTrue(server.getMessenger().isOutgoingChannelRegistered(plugin, "BungeeCord"));261 assertTrue(server.getMessenger().isIncomingChannelRegistered(plugin, "BungeeCord"));262 pluginManager.disablePlugin(plugin);263 assertFalse(server.getMessenger().isOutgoingChannelRegistered(plugin, "BungeeCord"));264 assertFalse(server.getMessenger().isIncomingChannelRegistered(plugin, "BungeeCord"));265 }266 @Test267 @Disabled("Not implemented yet")268 void disablePlugin_WorldChunkTicketsRemoved()269 {270 TestPlugin plugin = MockBukkit.load(TestPlugin.class);271 World world = server.createWorld(new WorldCreator(""));272 world.addPluginChunkTicket(0, 0, plugin);273 assertTrue(world.getPluginChunkTickets(0, 0).contains(plugin));274 pluginManager.disablePlugin(plugin);275 assertFalse(world.getPluginChunkTickets(0, 0).contains(plugin));276 }277 @Test278 void clearPlugins_LoadedPlugins_AllPluginsRemove()279 {280 TestPlugin plugin = MockBukkit.load(TestPlugin.class);281 assertTrue(plugin.isEnabled());282 pluginManager.clearPlugins();283 assertFalse(plugin.isEnabled(), "Plugin was not disabled");284 Plugin[] plugins = pluginManager.getPlugins();285 assertEquals(0, plugins.length);286 }287 @Test288 void subscribeToDefaultPerms()289 {290 Permissible player = server.addPlayer();291 pluginManager.subscribeToDefaultPerms(true, player);292 assertTrue(pluginManager.getDefaultPermSubscriptions(true).contains(player));293 }294 @Test295 void unsubscribeToDefaultPerms()296 {297 Permissible player = server.addPlayer();298 pluginManager.subscribeToDefaultPerms(true, player);299 pluginManager.unsubscribeFromDefaultPerms(true, player);300 assertFalse(pluginManager.getDefaultPermSubscriptions(true).contains(player));301 }302 @Test303 void eventThrowsException_RuntimeException_RethrowsSame()304 {305 pluginManager.registerEvents(new Listener()306 {307 @EventHandler308 public void event(BlockBreakEvent e)309 {310 throw new IllegalStateException();311 }312 }, MockBukkit.createMockPlugin());313 assertThrowsExactly(IllegalStateException.class, () -> pluginManager.callEvent(new BlockBreakEvent(null, null)));314 }315 @Test316 void eventThrowsException_NotRuntimeException_ThrowsEventHandlerException()317 {318 pluginManager.registerEvents(new Listener()319 {320 @EventHandler321 public void event(BlockBreakEvent e) throws Exception322 {323 throw new Exception();324 }325 }, MockBukkit.createMockPlugin());326 assertThrowsExactly(EventHandlerException.class, () -> pluginManager.callEvent(new BlockBreakEvent(null, null)));327 }328}...

Full Screen

Full Screen

Source:EventHandlerException.java Github

copy

Full Screen

...3import java.io.Serial;4/**5 * Thrown when an event handler throws a non-{@link RuntimeException}6 */7public class EventHandlerException extends RuntimeException8{9 @Serial10 private static final long serialVersionUID = 6093700474770834429L;11 public EventHandlerException(@NotNull Throwable cause)12 {13 super(cause);14 }15}...

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1import be.seeseemelk.mockbukkit.MockBukkit;2import be.seeseemelk.mockbukkit.ServerMock;3import be.seeseemelk.mockbukkit.event.EventCatcher;4import be.seeseemelk.mockbukkit.event.EventCatcherHandler;5import be.seeseemelk.mockbukkit.event.EventCatcherHandlerList;6import be.seeseemelk.mockbukkit.event.EventCatcherInfo;7import be.seeseemelk.mockbukkit.event.EventHandlerException;8import be.seeseemelk.mockbukkit.event.EventInfo;9import be.seeseemelk.mockbukkit.event.EventMock;10import be.seeseemelk.mockbukkit.event.EventOrder;11import be.seeseemelk.mockbukkit.event.ListenerMock;12import be.seeseemelk.mockbukkit.event.PlayerEventMock;13import be.seeseemelk.mockbukkit.event.PlayerMock;14import be.seeseemelk.mockbukkit.event.PlayerMoveEventMock;15import java.lang.reflect.InvocationTargetException;16import java.util.ArrayList;17import java.util.HashMap;18import java.util.List;19import java.util.Map;20import java.util.UUID;21import java.util.concurrent.atomic.AtomicInteger;22import org.bukkit.Bukkit;23import org.bukkit.Location;24import org.bukkit.Material;25import org.bukkit.block.Block;26import org.bukkit.block.BlockFace;27import org.bukkit.entity.Player;28import org.bukkit.event.Event;29import org.bukkit.event.EventHandler;30import org.bukkit.event.Listener;31import org.bukkit.event.block.BlockBreakEvent;32import org.bukkit.event.block.BlockPlaceEvent;33import org.bukkit.event.player.PlayerInteractEvent;34import org.bukkit.event.player.PlayerMoveEvent;35import org.bukkit.event.player.PlayerTeleportEvent;36import org.bukkit.inventory.ItemStack;37import org.bukkit.plugin.PluginManager;38import org.junit.After;39import org.junit.Assert;40import org.junit.Before;41import org.junit.Test;42{43 private static final String PLAYER_NAME = "Player";44 private static final String PLAYER_UUID = "b0d7c7d8-8a2a-4f1b-9f27-9f41c3e3f6f2";45 private ServerMock server;46 private PluginManager pluginManager;47 private EventCatcher catcher;48 private EventCatcherHandlerList handlerList;49 public void setUp()50 {51 server = MockBukkit.mock();52 pluginManager = server.getPluginManager();

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1import be.seeseemelk.mockbukkit.ServerMock;2import be.seeseemelk.mockbukkit.command.CommandManager;3import be.seeseemelk.mockbukkit.entity.PlayerMock;4import be.seeseemelk.mockbukkit.event.EventException;5import be.seeseemelk.mockbukkit.event.EventHandlerException;6import be.seeseemelk.mockbukkit.event.EventResult;7import be.seeseemelk.mockbukkit.event.EventValidator;8import be.seeseemelk.mockbukkit.event.PlayerEventValidator;9import be.seeseemelk.mockbukkit.event.SimpleEventValidator;10import be.seeseemelk.mockbukkit.event.SimplePlayerEventValidator;11import be.seeseemelk.mockbukkit.event.SimpleServerEventValidator;12import be.seeseemelk.mockbukkit.event.ServerEventValidator;13import org.bukkit.event.Event;14import org.bukkit.event.player.PlayerEvent;15import org.bukkit.event.server.ServerEvent;16import org.junit.jupiter.api.AfterEach;17import org.junit.jupiter.api.BeforeEach;18import org.junit.jupiter.api.Test;19import org.junit.jupiter.api.function.Executable;20import java.util.function.Consumer;21import static org.junit.jupiter.api.Assertions.*;22{23 private ServerMock server;24 private CommandManager commandManager;25 public void setUp()26 {27 server = new ServerMock();28 commandManager = new CommandManager(server);29 }30 public void tearDown()31 {32 server = null;33 commandManager = null;34 }35 public void testConstructor()36 {37 PlayerMock player = server.addPlayer();38 Event event = new PlayerEvent(player)39 {40 };41 EventHandlerException exception = new EventHandlerException(event, "test");42 assertEquals(event, exception.getEvent());43 assertEquals("test", exception.getMessage());44 }45 public void testConstructorNull()46 {47 assertThrows(IllegalArgumentException.class, () -> new EventHandlerException(null, "test"));48 }49 public void testConstructorNullMessage()50 {51 PlayerMock player = server.addPlayer();52 Event event = new PlayerEvent(player)53 {54 };55 EventHandlerException exception = new EventHandlerException(event, null);56 assertEquals(event, exception.getEvent());57 assertEquals("", exception.getMessage());58 }59 public void testConstructorEmptyMessage()60 {

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1import be.seeseemelk.mockbukkit.event.EventCaptor;2import be.seeseemelk.mockbukkit.event.EventCaptorFactory;3import be.seeseemelk.mockbukkit.exception.EventHandlerException;4import be.seeseemelk.mockbukkit.scheduler.BukkitSchedulerMock;5import org.bukkit.event.Event;6import org.bukkit.event.player.PlayerInteractEvent;7import org.bukkit.plugin.Plugin;8import org.junit.Before;9import org.junit.Test;10import org.junit.runner.RunWith;11import org.mockito.Mock;12import org.mockito.junit.MockitoJUnitRunner;13import static org.junit.Assert.*;14@RunWith(MockitoJUnitRunner.class)15public class Test1 {16 private Plugin plugin;17 private BukkitSchedulerMock scheduler;18 public void setUp()19 {20 scheduler = new BukkitSchedulerMock();21 }22 public void testEventCaptor()23 {24 EventCaptor<PlayerInteractEvent> captor = EventCaptorFactory.createCaptor(PlayerInteractEvent.class);25 scheduler.callEvent(new PlayerInteractEvent(null, null, null, null, null));26 assertTrue(captor.hasCaptured());27 PlayerInteractEvent event = captor.getFirstEvent();28 assertNotNull(event);29 }30 public void testEventCaptor2()31 {32 EventCaptor<PlayerInteractEvent> captor = EventCaptorFactory.createCaptor(PlayerInteractEvent.class);33 scheduler.callEvent(new PlayerInteractEvent(null, null, null, null, null));34 assertTrue(captor.hasCaptured());35 PlayerInteractEvent event = captor.getFirstEvent();36 assertNotNull(event);37 }38 public void testEventCaptor3()39 {40 EventCaptor<PlayerInteractEvent> captor = EventCaptorFactory.createCaptor(PlayerInteractEvent.class);41 scheduler.callEvent(new PlayerInteractEvent(null, null, null, null, null));42 assertTrue(captor.hasCaptured());43 PlayerInteractEvent event = captor.getFirstEvent();44 assertNotNull(event);45 }46 public void testEventCaptor4()47 {48 EventCaptor<PlayerInteractEvent> captor = EventCaptorFactory.createCaptor(PlayerInteractEvent.class);49 scheduler.callEvent(new PlayerInteractEvent(null, null, null, null, null));50 assertTrue(captor.hasCaptured());

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1import be.seeseemelk.mockbukkit.*;2import be.seeseemelk.mockbukkit.exception.*;3import org.bukkit.event.*;4import org.bukkit.event.player.*;5import org.bukkit.event.block.*;6import org.bukkit.event.entity.*;7import org.bukkit.event.inventory.*;8import org.bukkit.event.server.*;9import org.bukkit.event.weather.*;10import org.bukkit.event.vehicle.*;11import org.bukkit.event.vehicle.VehicleUpdateEvent;12import org.bukkit.event.world.*;13import org.bukkit.event.world.StructureGrowEvent;14import org.bukkit.event.painting.*;15import org.bukkit.event.hanging.*;16import org.bukkit.event.player.*;17import org.bukkit.event.player.PlayerBedEnterEvent;18import org.bukkit.event.player.PlayerBedLeaveEvent;19import org.bukkit.event.player.PlayerBucketEmptyEvent;20import org.bukkit.event.player.PlayerBucketFillEvent;21import org.bukkit.event.player.PlayerChangedWorldEvent;22import org.bukkit.event.player.PlayerChatEvent;23import org.bukkit.event.player.PlayerChatTabCompleteEvent;24import org.bukkit.event.player.PlayerCommandPreprocessEvent;25import org.bukkit.event.player.PlayerDropItemEvent;26import org.bukkit.event.player.PlayerEditBookEvent;27import org.bukkit.event.player.PlayerEggThrowEvent;28import org.bukkit.event.player.PlayerExpChangeEvent;29import org.bukkit.event.player.PlayerFishEvent;30import org.bukkit.event.player.PlayerGameModeChangeEvent;31import org.bukkit.event.player.PlayerInteractAtEntityEvent;32import org.bukkit.event.player.PlayerInteractEntityEvent;33import org.bukkit.event.player.PlayerInteractEvent;34import org.bukkit.event.player.PlayerItemBreakEvent;35import org.bukkit.event.player.PlayerItemConsumeEvent;36import org.bukkit.event.player.PlayerItemHeldEvent;37import org.bukkit.event.player.PlayerItemMendEvent;38import org.bukkit.event.player.PlayerJoinEvent;39import org.bukkit.event.player.PlayerKickEvent;40import org.bukkit.event.player.PlayerLevelChangeEvent;41import org.bukkit.event.player.PlayerLocaleChangeEvent;42import org.bukkit.event.player.PlayerLoginEvent;43import org.bukkit.event.player.PlayerMoveEvent;44import org.bukkit.event.player.PlayerPickupArrowEvent;45import org.bukkit.event.player.PlayerPickupItemEvent;46import org.bukkit.event.player.PlayerPortalEvent;47import org.bukkit.event.player.PlayerQuitEvent;48import org.bukkit.event.player.PlayerRegisterChannelEvent;49import org.bukkit.event.player.PlayerResourcePackStatusEvent;50import org.bukkit.event.player.PlayerRespawnEvent;51import org.bukkit.event.player.PlayerShearEntityEvent;52import org.bukkit.event.player.PlayerStatisticIncrementEvent;53import org.bukkit.event.player.PlayerSwapHandItemsEvent;54import org.bukkit.event.player.PlayerTakeLect

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1import be.seeseemelk.mockbukkit.exception.*;2import org.bukkit.event.*;3import org.bukkit.event.block.*;4import org.bukkit.event.player.*;5import org.bukkit.event.entity.*;6import org.bukkit.event.inventory.*;7import org.bukkit.event.server.*;8import org.bukkit.event.weather.*;9import org.bukkit.event.vehicle.*;10import org.bukkit.event.world.*;11public class 2 extends JavaPlugin implements Listener {12 public void onBlockBreak(BlockBreakEvent event) {13 }14 public void onBlockPlace(BlockPlaceEvent event) {15 }16 public void onPlayerJoin(PlayerJoinEvent event) {17 }18 public void onPlayerQuit(PlayerQuitEvent event) {19 }20 public void onEntityDamage(EntityDamageEvent event) {21 }22 public void onInventoryClick(InventoryClickEvent event) {23 }24 public void onPluginEnable(PluginEnableEvent event) {25 }26 public void onWeatherChange(WeatherChangeEvent event) {27 }28 public void onVehicleMove(VehicleMoveEvent event) {29 }30 public void onWorldLoad(WorldLoadEvent event) {31 }32}33import be.seeseemelk.mockbukkit.exception.*;34import org.bukkit.event.*;35import org.bukkit.event.block.*;36import org.bukkit.event.player.*;37import org.bukkit.event.entity.*;38import org.bukkit.event.inventory.*;39import org.bukkit.event.server.*;40import org.bukkit.event.weather.*;41import org.bukkit.event.vehicle.*;42import org.bukkit.event.world.*;43public class 3 extends JavaPlugin implements Listener {44 public void onBlockBreak(BlockBreakEvent event) {45 }46 public void onBlockPlace(BlockPlaceEvent event) {47 }48 public void onPlayerJoin(PlayerJoinEvent event) {49 }50 public void onPlayerQuit(PlayerQuitEvent event) {

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1package be.seeseemelk.mockbukkit;2import be.seeseemelk.mockbukkit.exception.EventHandlerException;3{4 public static void main(String[] args)5 {6 {7 throw new EventHandlerException("Test Exception");8 }9 catch (EventHandlerException e)10 {11 System.out.println(e.getMessage());12 }13 }14}15package be.seeseemelk.mockbukkit;16import be.seeseemelk.mockbukkit.exception.EventHandlerException;17{18 public static void main(String[] args)19 {20 {21 throw new EventHandlerException("Test Exception");22 }23 catch (EventHandlerException e)24 {25 System.out.println(e.getMessage());26 }27 }28}29package be.seeseemelk.mockbukkit;30import be.seeseemelk.mockbukkit.exception.EventHandlerException;31{32 public static void main(String[] args)33 {34 {35 throw new EventHandlerException("Test Exception");36 }37 catch (EventHandlerException e)38 {39 System.out.println(e.getMessage());40 }41 }42}43package be.seeseemelk.mockbukkit;44import be.seeseemelk.mockbukkit.exception.EventHandlerException;45{46 public static void main(String[] args)47 {48 {49 throw new EventHandlerException("Test Exception");50 }51 catch (EventHandlerException e)52 {53 System.out.println(e.getMessage());54 }55 }56}57package be.seeseemelk.mockbukkit;58import be.seeseemelk.mockbukkit.exception.EventHandlerException;59{60 public static void main(String[] args)61 {62 {63 throw new EventHandlerException("Test Exception");64 }65 catch (EventHandlerException e)66 {67 System.out.println(e.getMessage());68 }69 }70}

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1import be.seeseemelk.mockbukkit.*;2import org.bukkit.event.*;3import org.bukkit.event.block.*;4import org.bukkit.event.player.*;5import org.bukkit.event.entity.*;6import org.bukkit.event.inventory.*;7import org.bukkit.event.world.*;8import org.bukkit.event.server.*;9import org.bukkit.event.vehicle.*;10import org.bukkit.event.weather.*;11import org.bukkit.event.enchantment.*;12import org.bukkit.event.hanging.*;13import org.bukkit.event.painting.*;14import org.bukkit.event.block.*;15import org.bukkit.event.block.*;

Full Screen

Full Screen

EventHandlerException

Using AI Code Generation

copy

Full Screen

1package com.example;2import be.seeseemelk.mockbukkit.MockBukkit;3import be.seeseemelk.mockbukkit.ServerMock;4import be.seeseemelk.mockbukkit.WorldMock;5import be.seeseemelk.mockbukkit.entity.PlayerMock;6import be.seeseemelk.mockbukkit.event.EventHandlerException;7import org.bukkit.event.player.PlayerJoinEvent;8import org.junit.After;9import org.junit.Before;10import org.junit.Test;11import static org.junit.Assert.assertEquals;12public class PlayerJoinEventTest {13 private ServerMock server;14 private WorldMock world;15 private PlayerMock player;16 public void setUp() {17 server = MockBukkit.mock();18 world = server.addSimpleWorld("world");19 player = server.addPlayer();20 }21 public void tearDown() {22 MockBukkit.unmock();23 }24 public void testPlayerJoinEvent() {25 server.getPluginManager().assertEventFired(PlayerJoinEvent.class, () -> {26 player.join();27 });28 }29 public void testPlayerJoinEventWithPlayer() {30 server.getPluginManager().assertEventFired(PlayerJoinEvent.class, () -> {31 player.join();32 }, event -> {33 assertEquals(player, event.getPlayer());34 });35 }36 @Test(expected = EventHandlerException.class)37 public void testPlayerJoinEventWithWrongPlayer() {38 server.getPluginManager().assertEventFired(PlayerJoinEvent.class, () -> {39 player.join();40 }, event -> {41 assertEquals(server.addPlayer(), event.getPlayer());42 });43 }44}45public void tearDown() {46 MockBukkit.unmock();47}48public void testPlayerJoinEvent() {49 server.getPluginManager().assertEventFired(PlayerJoinEvent.class, () -> {50 player.join();51 });52}53public void testPlayerJoinEventWithPlayer() {54 server.getPluginManager().assertEventFired(PlayerJoinEvent.class, () -> {55 player.join();56 }, event -> {57 assertEquals(player, event.getPlayer());58 });59}60@Test(expected = EventHandlerException.class)61public void testPlayerJoinEventWithWrongPlayer() {62 server.getPluginManager().assertEventFired(PlayerJoinEvent.class, () -> {63 player.join();64 }, event -> {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run MockBukkit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in EventHandlerException

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful