@Before public void setUpPlugin() throws IOException { dataFolder = temporaryFolder.newFolder(); // Wire various Bukkit components setField(Bukkit.class, "server", null, server); given(server.getLogger()).willReturn(mock(Logger.class)); given(server.getScheduler()).willReturn(mock(BukkitScheduler.class)); given(server.getPluginManager()).willReturn(pluginManager); given(server.getVersion()).willReturn("1.9.4-RC1"); // SettingsManager always returns the default given(settings.getProperty(any(Property.class))).willAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return ((Property<?>) invocation.getArguments()[0]).getDefaultValue(); } }); // PluginDescriptionFile is final and so cannot be mocked PluginDescriptionFile descriptionFile = new PluginDescriptionFile( "PerWorldInventory", "N/A", PerWorldInventory.class.getCanonicalName()); JavaPluginLoader pluginLoader = new JavaPluginLoader(server); plugin = new PerWorldInventory(pluginLoader, descriptionFile, dataFolder, null); setField(JavaPlugin.class, "logger", plugin, mock(PluginLogger.class)); }
@Before public void setUpPlugin() throws IOException { File dataFolder = temporaryFolder.newFolder(); // Set mock server setField(Bukkit.class, "server", null, server); given(server.getLogger()).willReturn(mock(Logger.class)); // PluginDescriptionFile is final and so cannot be mocked PluginDescriptionFile descriptionFile = new PluginDescriptionFile( "PerWorldInventory", "N/A", PerWorldInventory.class.getCanonicalName()); JavaPluginLoader pluginLoader = new JavaPluginLoader(server); plugin = new PerWorldInventory(pluginLoader, descriptionFile, dataFolder, null); setField(JavaPlugin.class, "logger", plugin, mock(PluginLogger.class)); Injector injector = new InjectorBuilder().addDefaultHandlers("me.gnat008.perworldinventory").create(); injector.register(PermissionManager.class, permissionManager); injector.register(ConvertCommand.class, convertCommand); injector.register(HelpCommand.class, helpCommand); injector.register(PerWorldInventoryCommand.class, pwiCommand); injector.register(ReloadCommand.class, reloadCommand); injector.register(SetWorldDefaultCommand.class, setWorldDefaultsCommand); injector.register(VersionCommand.class, versionCommand); plugin.registerCommands(injector); TestHelper.setField(PerWorldInventory.class, "permissionManager", plugin, permissionManager); }
@Test public void test_default_modules() throws Exception { PluginLoader loader = mock(PluginLoader.class); Server server = mock(Server.class); PluginDescriptionFile pdf = mock(PluginDescriptionFile.class); File file1 = new File("target" + File.separator + "testdatafolder"); PluginLogger logger = mock(PluginLogger.class); when(server.getLogger()).thenReturn(logger); TestPluginDefaultModules plugin = new TestPluginDefaultModules(loader, server, pdf, file1, file1); assertThat(plugin.injectedPlugin).isNull(); plugin.onLoad(); assertThat(plugin.injectedPlugin).isNull(); plugin.onEnable(); assertThat(plugin.injectedPlugin).isSameAs(plugin); }
@Test public void test_extra_modules() throws Exception { PluginLoader loader = mock(PluginLoader.class); Server server = mock(Server.class); PluginDescriptionFile pdf = mock(PluginDescriptionFile.class); File file1 = new File("target" + File.separator + "testdatafolder"); PluginLogger logger = mock(PluginLogger.class); when(server.getLogger()).thenReturn(logger); TestPluginExtraModules plugin = new TestPluginExtraModules(loader, server, pdf, file1, file1); assertThat(plugin.i).isNull(); plugin.onLoad(); assertThat(plugin.i).isNull(); plugin.onEnable(); assertThat(plugin.i).isInstanceOf(TestPluginExtraModules.TestConcrete.class); }
@Test public void test_override_modules() throws Exception { PluginLoader loader = mock(PluginLoader.class); Server server = mock(Server.class); PluginDescriptionFile pdf = mock(PluginDescriptionFile.class); File file1 = new File("target" + File.separator + "testdatafolder"); PluginLogger logger = mock(PluginLogger.class); when(server.getLogger()).thenReturn(logger); TestPluginReplaceModules plugin = new TestPluginReplaceModules(loader, server, pdf, file1, file1); assertThat(plugin.logger).isNull(); plugin.onLoad(); assertThat(plugin.logger).isNull(); plugin.onEnable(); assertThat(plugin.logger).isInstanceOf(TestPluginReplaceModules.TestPluginLogger.class); }
@Before public void onSetUp() { final File dataFolder = new File("target" + File.separator + "testdatafolder"); if (dataFolder.exists()) { deleteDirectory(dataFolder); } dataFolder.mkdir(); englishPlayer = mock(Player.class); frenchPlayer = mock(Player.class); LocaleProvider provider = mock(LocaleProvider.class); when(provider.localeForCommandSender(englishPlayer)).thenReturn(Locale.ENGLISH); when(provider.localeForCommandSender(frenchPlayer)).thenReturn(Locale.FRENCH); translate = new DefaultTranslate( provider, new YamlControl(dataFolder), mock(PluginLogger.class), mock(Plugin.class) ); }
final void init(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { this.loader = loader; this.server = server; this.file = file; this.description = description; this.dataFolder = dataFolder; this.classLoader = classLoader; this.configFile = new File(dataFolder, "config.yml"); this.logger = new PluginLogger(this); if (description.isDatabaseEnabled()) { ServerConfig db = new ServerConfig(); db.setDefaultServer(false); db.setRegister(false); db.setClasses(getDatabaseClasses()); db.setName(description.getName()); server.configureDbConfig(db); DataSourceConfig ds = db.getDataSourceConfig(); ds.setUrl(replaceDatabaseString(ds.getUrl())); dataFolder.mkdirs(); ClassLoader previous = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); ebean = EbeanServerFactory.create(db); Thread.currentThread().setContextClassLoader(previous); } }
@Inject protected DefaultRouter(RoutingMethodParser parser, Injector injector, PluginLogger logger) { this.injector = injector; this.parser = parser; this.logger = logger; }
@Inject protected DefaultTranslate(LocaleProvider localeProvider, YamlControl controller, PluginLogger logger, Plugin plugin) { this.locales = localeProvider; this.controller = controller; this.loader = plugin.getClass().getClassLoader(); }
@Override protected void initialModules(List<Module> modules) { AbstractModule module = new AbstractModule() { @Override protected void configure() { bind(PluginLogger.class).to(TestPluginLogger.class); } }; Module overriden = Modules.override(new PluginModule(this)).with(module); modules.add(overriden); }
@Before public void onStartup() throws Exception { injector = getMockInjector(); childInjector = getMockInjector(); when(injector.createChildInjector(anyListOf(AbstractModule.class))).thenReturn(childInjector); router = new DefaultRouter(new DefaultRoutingMethodParser(), injector, mock(PluginLogger.class)); FancyMessage mockedMessage = mock(FancyMessage.class, new WithSelfAnswer(FancyMessage.class)); whenNew(FancyMessage.class).withAnyArguments().thenReturn(mockedMessage); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ((CommandSender) invocation.getArguments()[0]).sendMessage(""); return null; } }).when(mockedMessage).send(any(CommandSender.class)); PluginCommand command = mock(PluginCommand.class); when(command.getName()).thenReturn("test"); mockStatic(Bukkit.class); when(Bukkit.getPluginCommand("test")).thenReturn(command); }
@Test public void test_no_modules() throws Exception { PluginLoader loader = mock(PluginLoader.class); Server server = mock(Server.class); PluginDescriptionFile pdf = mock(PluginDescriptionFile.class); File file1 = new File("target" + File.separator + "testdatafolder"); PluginLogger logger = mock(PluginLogger.class); when(server.getLogger()).thenReturn(logger); TestPluginNoModules plugin = new TestPluginNoModules(loader, server, pdf, file1, file1); plugin.onLoad(); plugin.onEnable(); }
/** * Create a new feature manager * * @param configManager the config manager * @param plugin the plugin */ @Inject public DefaultFeatureManager(Configurator configManager, Plugin plugin, PluginLogger logger) { this.plugin = plugin; this.logger = logger; Optional<FileConfiguration> mainConfig = configManager.getConfig("main"); if(!mainConfig.isPresent()) { throw new IllegalStateException("Config file 'main' was not found, cannot find configuration values"); } config = mainConfig.get(); }
/** * Initializes this plugin with the given variables. * <p> * This method should never be called manually. * * @param loader PluginLoader that is responsible for this plugin * @param server Server instance that is running this plugin * @param description PluginDescriptionFile containing metadata on this plugin * @param dataFolder Folder containing the plugin's data * @param file File containing this plugin * @param classLoader ClassLoader which holds this plugin */ protected final void initialize(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { if (!initialized) { this.initialized = true; this.loader = loader; this.server = server; this.file = file; this.description = description; this.dataFolder = dataFolder; this.classLoader = classLoader; this.configFile = new File(dataFolder, "config.yml"); this.logger = new PluginLogger(this); if (description.isDatabaseEnabled()) { ServerConfig db = new ServerConfig(); db.setDefaultServer(false); db.setRegister(false); db.setClasses(getDatabaseClasses()); db.setName(description.getName()); server.configureDbConfig(db); DataSourceConfig ds = db.getDataSourceConfig(); ds.setUrl(replaceDatabaseString(ds.getUrl())); dataFolder.mkdirs(); ClassLoader previous = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); ebean = EbeanServerFactory.create(db); Thread.currentThread().setContextClassLoader(previous); } } }
/** * @deprecated use slf4j.debug * */ @Inject public Debug(Plugin plugin, Logger log) { this.pluginLog = log; this.debugLog = log; this.useConsoleLogger = true; if( !(log instanceof PluginLogger) ) { String prefix = plugin.getDescription().getPrefix(); if( prefix == null ) prefix = "["+plugin.getDescription().getName()+"] "; setLogPrefix(prefix); } else setLogPrefix(""); /* this.logPrefix = logPrefix; if( logPrefix != null ) { if( logPrefix.endsWith(" ") ) this.logPrefix = logPrefix; else this.logPrefix = logPrefix + " "; } else this.logPrefix = "["+log.getName()+"] "; setDebug(isDebug); */ }
@Override protected void configure() { bind(File.class).annotatedWith(Names.named("dataFolder")).toInstance(m_plugin.getDataFolder()); bind(PluginLogger.class).to(PluginLoggerInjectable.class); }
@Inject private void setLogger(PluginLogger logger) { this.logger = logger; }
/** * handles frozen players * * @param plugin the plugin * @param configManager the config manager * @param translate the translator */ @Inject private PlayerFreezeFeature(Plugin plugin, Configurator configManager, Translate translate, PluginLogger logger) { this.plugin = plugin; Optional<FileConfiguration> mainConfig = configManager.getConfig("main"); if(!mainConfig.isPresent()) { throw new IllegalStateException("Config file 'main' was not found, cannot find configuration values"); } config = mainConfig.get(); List<String> potionEffectsList = config.getStringList("PlayerFreeze.potion.effects"); int duration = config.getInt("PlayerFreezepotion.duration"); List<PotionEffect> effects = new ArrayList<PotionEffect>(); for(String potionEffectString : potionEffectsList) { String[] parts = potionEffectString.split(":"); if(parts.length != 2) { logger.log(Level.SEVERE, "Potion effect " + potionEffectString + " does not contain a ':', skipping it."); continue; } int amplifier = -1; try { amplifier = Integer.parseInt(parts[1]); } catch(NumberFormatException ignored) { } if(amplifier < 0) { logger.log(Level.SEVERE, "Potion effect " + potionEffectString + " has an invalid potion effect level '" + parts[1] + "', skipping it"); continue; } PotionEffectType type = PotionEffectType.getByName(parts[0]); if(null == type) { logger.log(Level.SEVERE, "Potion effect " + potionEffectString + " has an invalid potion effect type '" + parts[0] + "', skipping it"); continue; } effects.add(new PotionEffect(type, duration, amplifier, true)); } freezer = new FreezeRunnable(effects); Bukkit.getPluginManager().registerEvents(freezer, plugin); }
/** * Setups the wrapped logger * * @throws NoSuchFieldException when something goes wrong */ private void setupWrappedLogger() throws NoSuchFieldException { FieldAccessor<PluginLogger> loggerField = Reflections.getField(JavaPlugin.class, "logger", PluginLogger.class); loggerField.set(this, new WrappedLogger(this)); }