Merge with test branch

This commit is contained in:
Eric Stokes 2011-11-06 10:00:44 -07:00
commit e818b1ee73
17 changed files with 1397 additions and 21 deletions

4
.gitignore vendored
View File

@ -34,3 +34,7 @@
# Fern's utils # Fern's utils
uploadtoserver.sh uploadtoserver.sh
# Testing files:
debug.log

32
pom.xml
View File

@ -185,12 +185,40 @@
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<!-- End of Economy Dependencies --> <!-- End of Economy Dependencies -->
<!-- Start of JUnit Dependencies --> <!-- Start of Test Dependencies -->
<dependency> <dependency>
<groupId>org.junit</groupId> <groupId>org.junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.8.2</version> <version>4.8.2</version>
<scope>test</scope>
</dependency> </dependency>
<!-- End of JUnit Dependencies --> <dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.4.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.4.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.9</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<!-- End of Test Dependencies -->
</dependencies> </dependencies>
</project> </project>

View File

@ -33,6 +33,7 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -52,7 +53,13 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
public static boolean EnforceGameModes; public static boolean EnforceGameModes;
public static boolean PrefixChat; public static boolean PrefixChat;
public static boolean BedRespawn; public static boolean BedRespawn;
private File testConfigDirectory;
private PluginDescriptionFile testDescriptionFile;
@Override
public String toString() {
return "The Multiverse-Core Plugin";
}
@Override @Override
public String dumpVersionInfo(String buffer) { public String dumpVersionInfo(String buffer) {
@ -91,7 +98,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
// Configurations // Configurations
private FileConfiguration multiverseConfig = null; private FileConfiguration multiverseConfig = null;
private WorldManager worldManager = new WorldManager(this); private WorldManager worldManager;
// Setup the block/player/entity listener. // Setup the block/player/entity listener.
private MVPlayerListener playerListener = new MVPlayerListener(this); private MVPlayerListener playerListener = new MVPlayerListener(this);
@ -124,6 +131,28 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
debugLog = new DebugLog("Multiverse-Core", getDataFolder() + File.separator + "debug.log"); debugLog = new DebugLog("Multiverse-Core", getDataFolder() + File.separator + "debug.log");
} }
@Override
public File getDataFolder() {
if (this.testConfigDirectory != null) {
return this.testConfigDirectory;
}
return super.getDataFolder();
}
@Override
public PluginDescriptionFile getDescription() {
if (this.testDescriptionFile != null) {
return this.testDescriptionFile;
}
return super.getDescription(); //To change body of overridden methods use File | Settings | File Templates.
}
public void setTestMode(File configDir, PluginDescriptionFile descriptionFile) {
this.testConfigDirectory = configDir;
this.testDescriptionFile = descriptionFile;
}
public FileConfiguration getMVConfiguration() { public FileConfiguration getMVConfiguration() {
return this.multiverseConfig; return this.multiverseConfig;
} }
@ -133,6 +162,8 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
} }
public void onEnable() { public void onEnable() {
System.out.println("Enabling... Found server... " + this.getServer());
this.worldManager = new WorldManager(this);
// Perform initial checks for AllPay // Perform initial checks for AllPay
if (!this.validateAllpay() || !this.validateCH()) { if (!this.validateAllpay() || !this.validateCH()) {
this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().disablePlugin(this);
@ -230,6 +261,7 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
/** Function to Register all the Events needed. */ /** Function to Register all the Events needed. */
private void registerEvents() { private void registerEvents() {
System.out.print(getServer().getName());
PluginManager pm = getServer().getPluginManager(); PluginManager pm = getServer().getPluginManager();
// pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Highest, this); // Low so it acts above any other. // pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Highest, this); // Low so it acts above any other.
pm.registerEvent(Event.Type.PLAYER_TELEPORT, this.playerListener, Priority.Highest, this); // Cancel Teleports if needed. pm.registerEvent(Event.Type.PLAYER_TELEPORT, this.playerListener, Priority.Highest, this); // Cancel Teleports if needed.
@ -453,6 +485,9 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
private String getAuthors() { private String getAuthors() {
String authors = ""; String authors = "";
ArrayList<String> auths = this.getDescription().getAuthors(); ArrayList<String> auths = this.getDescription().getAuthors();
if (auths.size() == 0) {
return "";
}
if (auths.size() == 1) { if (auths.size() == 1) {
return auths.get(0); return auths.get(0);
@ -560,6 +595,11 @@ public class MultiverseCore extends JavaPlugin implements MVPlugin, Core {
this.getTeleporter().safelyTeleport(teleporter, p, l, false); this.getTeleporter().safelyTeleport(teleporter, p, l, false);
} }
public File getServerFolder() {
return new File(this.getDataFolder().getAbsolutePath()).getParentFile().getParentFile();
}
private void checkServerProps() { private void checkServerProps() {
File serverFolder = new File(this.getDataFolder().getAbsolutePath()).getParentFile().getParentFile(); File serverFolder = new File(this.getDataFolder().getAbsolutePath()).getParentFile().getParentFile();
File serverProperties = new File(serverFolder.getAbsolutePath() + File.separator + "server.properties"); File serverProperties = new File(serverFolder.getAbsolutePath() + File.separator + "server.properties");

View File

@ -141,4 +141,12 @@ public interface MVWorldManager {
* @return A valid {@link PurgeWorlds}. * @return A valid {@link PurgeWorlds}.
*/ */
public PurgeWorlds getWorldPurger(); public PurgeWorlds getWorldPurger();
/**
* Gets the world players will spawn in on first join.
* Currently this always returns worlds.get(0) from Bukkit.
*
* @return A Multiverse world that players will spawn in or null if no MV world has been set.
*/
public MultiverseWorld getSpawnWorld();
} }

View File

@ -25,13 +25,6 @@ public class BlockSafety {
/** /**
* This function checks whether the block at the given coordinates are above air or not. * This function checks whether the block at the given coordinates are above air or not.
*
* @param world
* @param x
* @param y
* @param z
*
* @return
*/ */
public boolean isBlockAboveAir(Location l) { public boolean isBlockAboveAir(Location l) {
Location downOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ()); Location downOne = new Location(l.getWorld(), l.getX(), l.getY(), l.getZ());
@ -53,29 +46,25 @@ public class BlockSafety {
* This function checks whether the block at the coordinates given is safe or not by checking for Laval/Fire/Air * This function checks whether the block at the coordinates given is safe or not by checking for Laval/Fire/Air
* etc. This also ensures there is enough space for a player to spawn! * etc. This also ensures there is enough space for a player to spawn!
* *
* @param world
* @param x
* @param y
* @param z
*
* @return * @return
*/ */
public boolean playerCanSpawnHereSafely(Location l) { public boolean playerCanSpawnHereSafely(Location l) {
World world = l.getWorld();
Location actual = l.clone(); Location actual = l.clone();
Location upOne = l.clone(); Location upOne = l.clone();
Location downOne = l.clone(); Location downOne = l.clone();
upOne.setY(upOne.getY() + 1); upOne.setY(upOne.getY() + 1);
downOne.setY(downOne.getY() - 1); downOne.setY(downOne.getY() - 1);
if (this.isSolidBlock(actual.getBlock().getType()) || this.isSolidBlock(upOne.getBlock().getType())) { if (this.isSolidBlock(world.getBlockAt(actual).getType()) ||
MultiverseCore.staticLog(Level.FINER, "Error Here? (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]"); this.isSolidBlock(upOne.getBlock().getType())) {
MultiverseCore.staticLog(Level.FINER, "Error Here? (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]"); MultiverseCore.staticLog(Level.FINER, "Error Here (Actual)? (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here (upOne)? (" + upOne.getBlock().getType() + ")[" + this.isSolidBlock(upOne.getBlock().getType()) + "]");
return false; return false;
} }
if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) { if (downOne.getBlock().getType() == Material.LAVA || downOne.getBlock().getType() == Material.STATIONARY_LAVA) {
MultiverseCore.staticLog(Level.FINER, "Error Here? (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]"); MultiverseCore.staticLog(Level.FINER, "Error Here (downOne)? (" + downOne.getBlock().getType() + ")[" + this.isSolidBlock(downOne.getBlock().getType()) + "]");
MultiverseCore.staticLog(Level.FINER, "Error Here? (" + actual.getBlock().getType() + ")[" + this.isSolidBlock(actual.getBlock().getType()) + "]");
return false; return false;
} }

View File

@ -351,6 +351,11 @@ public class WorldManager implements MVWorldManager {
// Force the worlds to be loaded, ie don't just load new worlds. // Force the worlds to be loaded, ie don't just load new worlds.
if (forceLoad) { if (forceLoad) {
// Remove all world permissions. // Remove all world permissions.
System.out.println(this.plugin);
System.out.println("Server2: " + this.plugin.getServer());
System.out.println(this.plugin.getServer().getPluginManager());
System.out.println(this.plugin.getServer().getPluginManager().getPermission("multiverse.access.*"));
Permission allAccess = this.plugin.getServer().getPluginManager().getPermission("multiverse.access.*"); Permission allAccess = this.plugin.getServer().getPluginManager().getPermission("multiverse.access.*");
Permission allExempt = this.plugin.getServer().getPluginManager().getPermission("multiverse.exempt.*"); Permission allExempt = this.plugin.getServer().getPluginManager().getPermission("multiverse.exempt.*");
for (MultiverseWorld w : this.worlds.values()) { for (MultiverseWorld w : this.worlds.values()) {
@ -420,4 +425,8 @@ public class WorldManager implements MVWorldManager {
return false; return false;
} }
} }
public MultiverseWorld getSpawnWorld() {
return this.getMVWorld(this.plugin.getServer().getWorlds().get(0));
}
} }

View File

@ -0,0 +1,90 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.test.utils.MVCoreFactory;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.utils.FileUtils;
import junit.framework.Assert;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
import java.lang.reflect.Field;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({MultiverseCore.class})
public class TestDebugMode {
@After
public void tearDown() throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
Field serverField = Bukkit.class.getDeclaredField("server");
serverField.setAccessible(true);
serverField.set(Class.forName("org.bukkit.Bukkit"), null);
if (MVCoreFactory.serverDirectory.exists()) {
MVCoreFactory.serverDirectory.delete();
FileUtils.deleteFolder(MVCoreFactory.serverDirectory);
}
}
@Before
public void setUp() throws Exception {
if (!MVCoreFactory.serverDirectory.exists()) {
MVCoreFactory.serverDirectory.mkdirs();
}
if (!MVCoreFactory.pluginDirectory.exists()) {
MVCoreFactory.pluginDirectory.mkdirs();
}
}
@Test
public void testEnableDebugMode() {
TestInstanceCreator creator = new TestInstanceCreator();
Server mockServer = creator.setupDefaultServerInstance();
CommandSender mockCommandSender = creator.getCommandSender();
// Start actual testing.
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
Assert.assertNotNull(plugin);
// Make sure Core is enabled
Assert.assertTrue(plugin.isEnabled());
// Make a fake server folder to fool MV into thinking a world folder exists.
File serverDirectory = new File(creator.getCore().getServerFolder(), "world");
serverDirectory.mkdirs();
// Initialize a fake command
Command mockCommand = mock(Command.class);
when(mockCommand.getName()).thenReturn("mv");
// Assert debug mode is off
Assert.assertEquals(0, MultiverseCore.GlobalDebug);
// Send the debug command.
String[] debugArgs = new String[]{"debug", "3"};
plugin.onCommand(mockCommandSender, mockCommand, "", debugArgs);
Assert.assertEquals(3, MultiverseCore.GlobalDebug);
}
}

View File

@ -0,0 +1,52 @@
package com.onarandombox.MultiverseCore.test;
import junit.framework.Assert;
import org.bukkit.World;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
public class TestMockWorld {
private World mockWorld;
private World mockNetherWorld;
@Before
public void setUp() throws Exception {
// Initialize a fake world and world_nether.
this.mockWorld = mock(World.class);
when(this.mockWorld.getName()).thenReturn("world");
when(this.mockWorld.getEnvironment()).thenReturn(World.Environment.NORMAL);
this.mockNetherWorld = mock(World.class);
when(this.mockNetherWorld.getName()).thenReturn("world_nether");
when(this.mockNetherWorld.getEnvironment()).thenReturn(World.Environment.NETHER);
}
@Test
public void testWorldInit() {
Assert.assertNotNull(this.mockWorld);
Assert.assertNotNull(this.mockNetherWorld);
}
@Test
public void testWorldNames() {
// Test the mock world objects
Assert.assertEquals(this.mockWorld.getName(), "world");
Assert.assertEquals(this.mockNetherWorld.getName(), "world_nether");
verify(this.mockWorld).getName();
verify(this.mockNetherWorld).getName();
}
@Test
public void testWorldEnvironments() {
// Test the environments
Assert.assertEquals(this.mockWorld.getEnvironment(), World.Environment.NORMAL);
Assert.assertEquals(this.mockNetherWorld.getEnvironment(), World.Environment.NETHER);
verify(this.mockWorld).getEnvironment();
verify(this.mockNetherWorld).getEnvironment();
}
}

View File

@ -0,0 +1,182 @@
package com.onarandombox.MultiverseCore.test;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.test.utils.MVCoreFactory;
import com.onarandombox.MultiverseCore.test.utils.TestInstanceCreator;
import com.onarandombox.MultiverseCore.test.utils.WorldCreatorMatcher;
import com.onarandombox.MultiverseCore.utils.FileUtils;
import junit.framework.Assert;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.verification.VerificationModeFactory;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
import java.lang.reflect.Field;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest({PluginManager.class, MultiverseCore.class, Permission.class, Bukkit.class})
public class TestWorldImport {
@After
public void tearDown() throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
Field serverField = Bukkit.class.getDeclaredField("server");
serverField.setAccessible(true);
serverField.set(Class.forName("org.bukkit.Bukkit"), null);
if (MVCoreFactory.serverDirectory.exists()) {
MVCoreFactory.serverDirectory.delete();
FileUtils.deleteFolder(MVCoreFactory.serverDirectory);
}
}
@Before
public void setUp() throws Exception {
if (!MVCoreFactory.serverDirectory.exists()) {
MVCoreFactory.serverDirectory.mkdirs();
}
if (!MVCoreFactory.pluginDirectory.exists()) {
MVCoreFactory.pluginDirectory.mkdirs();
}
}
@Test
public void testWorldImportWithNoFolder() {
TestInstanceCreator creator = new TestInstanceCreator();
Server mockServer = creator.setupDefaultServerInstance();
CommandSender mockCommandSender = creator.getCommandSender();
// Make sure the world directory do NOT exist
if (new File(MVCoreFactory.serverDirectory, "world").exists()) {
new File(MVCoreFactory.serverDirectory, "world").delete();
}
// Start actual testing.
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
Assert.assertNotNull(plugin);
// Make sure Core is enabled
Assert.assertTrue(plugin.isEnabled());
// Initialize a fake command
Command mockCommand = mock(Command.class);
when(mockCommand.getName()).thenReturn("mv");
String[] normalArgs = new String[]{"import", "world", "normal"};
// Ensure we have a fresh copy of MV, 0 worlds.
Assert.assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Import the first world. The world folder does not exist.
plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);
verify(mockCommandSender).sendMessage(ChatColor.RED + "FAILED.");
verify(mockCommandSender).sendMessage("That world folder does not exist...");
// We should still have no worlds.
Assert.assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
}
@Test
public void testWorldImport() {
TestInstanceCreator creator = new TestInstanceCreator();
Server mockServer = creator.setupDefaultServerInstance();
CommandSender mockCommandSender = creator.getCommandSender();
// Start actual testing.
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
Assert.assertNotNull(plugin);
// Make sure Core is enabled
Assert.assertTrue(plugin.isEnabled());
// Initialize a fake command
Command mockCommand = mock(Command.class);
when(mockCommand.getName()).thenReturn("mv");
// Ensure that there are no worlds imported. This is a fresh setup.
Assert.assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Import the first world.
String[] normalArgs = new String[]{"import", "world", "normal"};
plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);
// We should now have one world imported!
Assert.assertEquals(1, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Import the second world.
String[] netherArgs = new String[]{"import", "world_nether", "nether"};
plugin.onCommand(mockCommandSender, mockCommand, "", netherArgs);
// We should now have 2 worlds imported!
Assert.assertEquals(2, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Import the third world.
String[] skyArgs = new String[]{"import", "world_skylands", "skylands"};
plugin.onCommand(mockCommandSender, mockCommand, "", skyArgs);
// We should now have 2 worlds imported!
Assert.assertEquals(3, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Verify that the commandSender has been called 3 times.
verify(mockCommandSender, VerificationModeFactory.times(3)).sendMessage(ChatColor.AQUA + "Starting world import...");
verify(mockCommandSender, VerificationModeFactory.times(3)).sendMessage(ChatColor.GREEN + "Complete!");
}
@Test
void testWorldImportWithSeed() {
TestInstanceCreator creator = new TestInstanceCreator();
Server mockServer = creator.setupDefaultServerInstance();
CommandSender mockCommandSender = creator.getCommandSender();
// Start actual testing.
// Pull a core instance from the server.
Plugin plugin = mockServer.getPluginManager().getPlugin("Multiverse-Core");
// Make sure Core is not null
Assert.assertNotNull(plugin);
// Make sure Core is enabled
Assert.assertTrue(plugin.isEnabled());
// Initialize a fake command
Command mockCommand = mock(Command.class);
when(mockCommand.getName()).thenReturn("mv");
// Ensure that there are no worlds imported. This is a fresh setup.
Assert.assertEquals(0, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Init a new WorldCreatorMatcher to match our seeded world
WorldCreator seedCreator = new WorldCreator("world");
seedCreator.environment(World.Environment.NORMAL);
WorldCreatorMatcher seedMatcher = new WorldCreatorMatcher(seedCreator);
// For this case, we're testing a seeded import, so we care about the world seed
seedMatcher.careAboutSeeds(true);
// Import the first world.
String[] normalArgs = new String[]{"import", "world", "normal", "-s", "gargamel"};
plugin.onCommand(mockCommandSender, mockCommand, "", normalArgs);
// We should now have one world imported!
Assert.assertEquals(1, creator.getCore().getMVWorldManager().getMVWorlds().size());
// Verify that the commandSender has been called 1 time.
verify(mockCommandSender, VerificationModeFactory.times(1)).sendMessage(ChatColor.AQUA + "Starting world import...");
verify(mockCommandSender, VerificationModeFactory.times(1)).sendMessage(ChatColor.GREEN + "Complete!");
}
}

View File

@ -0,0 +1,41 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.plugin.PluginDescriptionFile;
import org.powermock.api.mockito.PowerMockito;
import java.io.File;
import static org.mockito.Mockito.doReturn;
/**
* Multiverse 2
*
* @author fernferret
*/
public class MVCoreFactory {
public static final File pluginDirectory = new File("bin/test/server/plugins/coretest");
public static final File serverDirectory = new File("bin/test/server");
public MultiverseCore getNewCore() {
MultiverseCore core = PowerMockito.spy(new MultiverseCore());
// Let's let all MV files go to bin/test
doReturn(pluginDirectory).when(core).getDataFolder();
// Return a fake PDF file.
PluginDescriptionFile pdf = new PluginDescriptionFile("Multiverse-Core", "2.1-Test", "com.onarandombox.MultiverseCore.MultiverseCore");
doReturn(pdf).when(core).getDescription();
doReturn(true).when(core).isEnabled();
return core;
}
}

View File

@ -0,0 +1,408 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.*;
/**
* Multiverse 2
*
* @author fernferret
*/
public class MockBlock implements Block{
private Material type;
private Location location;
public MockBlock(Location l, Material type) {
this.type = type;
this.location = l;
}
/**
* Gets the metadata for this block
*
* @return block specific metadata
*/
@Override
public byte getData() {
return 0;
}
/** @deprecated use {@link #getRelative(org.bukkit.block.BlockFace face)} */
@Override
public Block getFace(BlockFace face) {
return null;
}
/** @deprecated use {@link #getRelative(org.bukkit.block.BlockFace face, int distance)} */
@Override
public Block getFace(BlockFace face, int distance) {
return null;
}
/**
* Gets the block at the given offsets
*
* @param modX X-coordinate offset
* @param modY Y-coordinate offset
* @param modZ Z-coordinate offset
*
* @return Block at the given offsets
*/
@Override
public Block getRelative(int modX, int modY, int modZ) {
return null;
}
/**
* Gets the block at the given face<br />
* <br />
* This method is equal to getRelative(face, 1)
*
* @param face Face of this block to return
*
* @return Block at the given face
*
* @see #getRelative(org.bukkit.block.BlockFace, int)
*/
@Override
public Block getRelative(BlockFace face) {
return null;
}
/**
* Gets the block at the given distance of the given face<br />
* <br />
* For example, the following method places water at 100,102,100; two blocks
* above 100,100,100.
* <pre>
* Block block = world.getBlockAt(100,100,100);
* Block shower = block.getFace(BlockFace.UP, 2);
* shower.setType(Material.WATER);
* </pre>
*
* @param face Face of this block to return
* @param distance Distance to get the block at
*
* @return Block at the given face
*/
@Override
public Block getRelative(BlockFace face, int distance) {
return null;
}
/**
* Gets the type of this block
*
* @return block type
*/
@Override
public Material getType() {
return this.type;
}
/**
* Gets the type-id of this block
*
* @return block type-id
*/
@Override
public int getTypeId() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Gets the light level between 0-15
*
* @return light level
*/
@Override
public byte getLightLevel() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Gets the world which contains this Block
*
* @return World containing this block
*/
@Override
public World getWorld() {
return this.location.getWorld();
}
/**
* Gets the x-coordinate of this block
*
* @return x-coordinate
*/
@Override
public int getX() {
return this.location.getBlockX();
}
/**
* Gets the y-coordinate of this block
*
* @return y-coordinate
*/
@Override
public int getY() {
return this.location.getBlockY();
}
/**
* Gets the z-coordinate of this block
*
* @return z-coordinate
*/
@Override
public int getZ() {
return this.location.getBlockZ();
}
/**
* Gets the Location of the block
*
* @return Location of block
*/
@Override
public Location getLocation() {
return this.location;
}
/**
* Gets the chunk which contains this block
*
* @return Containing Chunk
*/
@Override
public Chunk getChunk() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Sets the metadata for this block
*
* @param data New block specific metadata
*/
@Override
public void setData(byte data) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void setData(byte data, boolean applyPhyiscs) {
//To change body of implemented methods use File | Settings | File Templates.
}
/**
* Sets the type of this block
*
* @param type Material to change this block to
*/
@Override
public void setType(Material type) {
this.type = type;
}
/**
* Sets the type-id of this block
*
* @param type Type-Id to change this block to
*
* @return whether the block was changed
*/
@Override
public boolean setTypeId(int type) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean setTypeId(int type, boolean applyPhysics) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean setTypeIdAndData(int type, byte data, boolean applyPhyiscs) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Gets the face relation of this block compared to the given block<br />
* <br />
* For example:
* <pre>
* Block current = world.getBlockAt(100, 100, 100);
* Block target = world.getBlockAt(100, 101, 100);
*
* current.getFace(target) == BlockFace.Up;
* </pre>
* <br />
* If the given block is not connected to this block, null may be returned
*
* @param block Block to compare against this block
*
* @return BlockFace of this block which has the requested block, or null
*/
@Override
public BlockFace getFace(Block block) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Captures the current state of this block. You may then cast that state
* into any accepted type, such as Furnace or Sign.
* <p/>
* The returned object will never be updated, and you are not guaranteed that
* (for example) a sign is still a sign after you capture its state.
*
* @return BlockState with the current state of this block.
*/
@Override
public BlockState getState() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns the biome that this block resides in
*
* @return Biome type containing this block
*/
@Override
public Biome getBiome() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns true if the block is being powered by Redstone.
*
* @return True if the block is powered.
*/
@Override
public boolean isBlockPowered() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns true if the block is being indirectly powered by Redstone.
*
* @return True if the block is indirectly powered.
*/
@Override
public boolean isBlockIndirectlyPowered() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns true if the block face is being powered by Redstone.
*
* @param face The block face
*
* @return True if the block face is powered.
*/
@Override
public boolean isBlockFacePowered(BlockFace face) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns true if the block face is being indirectly powered by Redstone.
*
* @param face The block face
*
* @return True if the block face is indirectly powered.
*/
@Override
public boolean isBlockFaceIndirectlyPowered(BlockFace face) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns the redstone power being provided to this block face
*
* @param face the face of the block to query or BlockFace.SELF for the block itself
*
* @return The power level.
*/
@Override
public int getBlockPower(BlockFace face) {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns the redstone power being provided to this block
*
* @return The power level.
*/
@Override
public int getBlockPower() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Checks if this block is empty.
* <p/>
* A block is considered empty when {@link #getType()} returns {@link org.bukkit.Material#AIR}.
*
* @return true if this block is empty
*/
@Override
public boolean isEmpty() {
return this.type == Material.AIR;
}
/**
* Checks if this block is liquid.
* <p/>
* A block is considered liquid when {@link #getType()} returns {@link org.bukkit.Material#WATER}, {@link
* org.bukkit.Material#STATIONARY_WATER}, {@link org.bukkit.Material#LAVA} or {@link
* org.bukkit.Material#STATIONARY_LAVA}.
*
* @return true if this block is liquid
*/
@Override
public boolean isLiquid() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Gets the temperature of the biome of this block
*
* @return Temperature of this block
*/
@Override
public double getTemperature() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Gets the humidity of the biome of this block
*
* @return Humidity of this block
*/
@Override
public double getHumidity() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Returns the reaction of the block when moved by a piston
*
* @return reaction
*/
@Override
public PistonMoveReaction getPistonMoveReaction() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -0,0 +1,16 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
/**
* Multiverse 2
*
* @author fernferret
*/
public class MockBukkitServer {
}

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import org.bukkit.Server;
import org.bukkit.WorldCreator;
import org.mockito.ArgumentMatcher;
import org.mockito.Matchers;
import java.util.logging.Logger;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Multiverse 2
*
* @author fernferret
*/
public class MockServerFactory {
public Server getMockServer() {
Server server = mock(Server.class);
when(server.getName()).thenReturn("FernCraft");
Logger logger = Logger.getLogger("Multiverse-Core-Test");
when(server.getLogger()).thenReturn(logger);
return server;
}
}

View File

@ -0,0 +1,90 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.generator.ChunkGenerator;
import org.mockito.ArgumentMatcher;
import org.mockito.Matchers;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Multiverse 2
*
* @author fernferret
*/
public class MockWorldFactory {
class LocationMatcher extends ArgumentMatcher<Location> {
private Location l;
public LocationMatcher(Location location) {
this.l = location;
}
public boolean matches(Object creator) {
return creator.equals(l);
}
}
class LocationMatcherAbove extends LocationMatcher {
public LocationMatcherAbove(Location location) {
super(location);
}
public boolean matches(Object creator) {
System.out.println("Checking above...");
if (super.l == null || creator == null) {
return false;
}
boolean equal = ((Location) creator).getBlockY() >= super.l.getBlockY();
System.out.println("Checking equals/\\..." + equal);
return equal;
}
}
class LocationMatcherBelow extends LocationMatcher {
public LocationMatcherBelow(Location location) {
super(location);
}
public boolean matches(Object creator) {
if (super.l == null || creator == null) {
return false;
}
boolean equal = ((Location) creator).getBlockY() < super.l.getBlockY();
System.out.println("Checking equals\\/..." + equal);
return equal;
}
}
public World makeNewMockWorld(String world, World.Environment env) {
World mockWorld = mock(World.class);
when(mockWorld.getName()).thenReturn(world);
when(mockWorld.getEnvironment()).thenReturn(env);
when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 0, 0));
LocationMatcherAbove matchWorldAbove = new LocationMatcherAbove(new Location(mockWorld, 0, 0, 0));
LocationMatcherBelow matchWorldBelow = new LocationMatcherBelow(new Location(mockWorld, 0, 0, 0));
when(mockWorld.getBlockAt(Matchers.argThat(matchWorldAbove))).thenReturn(new MockBlock(new Location(mockWorld, 0, 0, 0), Material.AIR));
when(mockWorld.getBlockAt(Matchers.argThat(matchWorldBelow))).thenReturn(new MockBlock(new Location(mockWorld, 0, 0, 0), Material.STONE));
return mockWorld;
}
public World makeNewMockWorld(String world, World.Environment env, long seed, ChunkGenerator generator) {
World w = this.makeNewMockWorld(world, env);
when(w.getGenerator()).thenReturn(generator);
when(w.getSeed()).thenReturn(seed);
return w;
}
}

View File

@ -0,0 +1,220 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.plugin.Plugin;
import java.util.Set;
/**
* Multiverse 2
*
* @author fernferret
*/
public class TestCommandSender implements CommandSender {
private Server server;
private boolean isOp;
public TestCommandSender(Server server) {
this.server = server;
}
/**
* Sends this sender a message
*
* @param message Message to be displayed
*/
@Override
public void sendMessage(String message) {
System.out.println(ChatColor.stripColor(message));
}
/**
* Returns the server instance that this command is running on
*
* @return Server instance
*/
@Override
public Server getServer() {
return this.server;
}
/**
* Gets the name of this command sender
*
* @return Name of the sender
*/
@Override
public String getName() {
return "CONSOLE";
}
/**
* Checks if this object contains an override for the specified permission, by fully qualified name
*
* @param name Name of the permission
*
* @return true if the permission is set, otherwise false
*/
@Override
public boolean isPermissionSet(String name) {
return true;
}
/**
* Checks if this object contains an override for the specified {@link org.bukkit.permissions.Permission}
*
* @param perm Permission to check
*
* @return true if the permission is set, otherwise false
*/
@Override
public boolean isPermissionSet(Permission perm) {
return true;
}
/**
* Gets the value of the specified permission, if set.
* <p/>
* If a permission override is not set on this object, the default value of the permission will be returned.
*
* @param name Name of the permission
*
* @return Value of the permission
*/
@Override
public boolean hasPermission(String name) {
return true;
}
/**
* Gets the value of the specified permission, if set.
* <p/>
* If a permission override is not set on this object, the default value of the permission will be returned
*
* @param perm Permission to get
*
* @return Value of the permission
*/
@Override
public boolean hasPermission(Permission perm) {
return true;
}
/**
* Adds a new {@link org.bukkit.permissions.PermissionAttachment} with a single permission by name and value
*
* @param plugin Plugin responsible for this attachment, may not be null or disabled
* @param name Name of the permission to attach
* @param value Value of the permission
*
* @return The PermissionAttachment that was just created
*/
@Override
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) {
return null;
}
/**
* Adds a new empty {@link org.bukkit.permissions.PermissionAttachment} to this object
*
* @param plugin Plugin responsible for this attachment, may not be null or disabled
*
* @return The PermissionAttachment that was just created
*/
@Override
public PermissionAttachment addAttachment(Plugin plugin) {
return null;
}
/**
* Temporarily adds a new {@link org.bukkit.permissions.PermissionAttachment} with a single permission by name and
* value
*
* @param plugin Plugin responsible for this attachment, may not be null or disabled
* @param name Name of the permission to attach
* @param value Value of the permission
* @param ticks Amount of ticks to automatically remove this attachment after
*
* @return The PermissionAttachment that was just created
*/
@Override
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) {
return null;
}
/**
* Temporarily adds a new empty {@link org.bukkit.permissions.PermissionAttachment} to this object
*
* @param plugin Plugin responsible for this attachment, may not be null or disabled
* @param ticks Amount of ticks to automatically remove this attachment after
*
* @return The PermissionAttachment that was just created
*/
@Override
public PermissionAttachment addAttachment(Plugin plugin, int ticks) {
return null;
}
/**
* Removes the given {@link org.bukkit.permissions.PermissionAttachment} from this object
*
* @param attachment Attachment to remove
*
* @throws IllegalArgumentException Thrown when the specified attachment isn't part of this object
*/
@Override
public void removeAttachment(PermissionAttachment attachment) {
}
/**
* Recalculates the permissions for this object, if the attachments have changed values.
* <p/>
* This should very rarely need to be called from a plugin.
*/
@Override
public void recalculatePermissions() {
}
/**
* Gets a set containing all of the permissions currently in effect by this object
*
* @return Set of currently effective permissions
*/
@Override
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
return null;
}
/**
* Checks if this object is a server operator
*
* @return true if this is an operator, otherwise false
*/
@Override
public boolean isOp() {
return this.isOp;
}
/**
* Sets the operator status of this object
*
* @param value New operator value
*/
@Override
public void setOp(boolean value) {
this.isOp = value;
}
}

View File

@ -0,0 +1,111 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import com.onarandombox.MultiverseCore.MultiverseCore;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.mockito.Matchers;
import org.powermock.api.mockito.PowerMockito;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.*;
/**
* Multiverse 2
*
* @author fernferret
*/
public class TestInstanceCreator {
MultiverseCore core;
private CommandSender commandSender;
public Server setupDefaultServerInstance() {
MockWorldFactory worldFactory = new MockWorldFactory();
MVCoreFactory coreFactory = new MVCoreFactory();
MockServerFactory serverFactory = new MockServerFactory();
core = coreFactory.getNewCore();
// Add Core to the list of loaded plugins
JavaPlugin[] plugins = new JavaPlugin[]{core};
// Mock the Plugin Manager
PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
when(mockPluginManager.getPlugins()).thenReturn(plugins);
when(mockPluginManager.getPlugin("Multiverse-Core")).thenReturn(core);
// Make some fake folders to fool the fake MV into thinking these worlds exist
new File(core.getServerFolder(), "world").mkdirs();
new File(core.getServerFolder(), "world_nether").mkdirs();
new File(core.getServerFolder(), "world_skylands").mkdirs();
// Initialize the Mock Worlds
World mockWorld = worldFactory.makeNewMockWorld("world", World.Environment.NORMAL);
World mockNetherWorld = worldFactory.makeNewMockWorld("world_nether", World.Environment.NETHER);
World mockSkyWorld = worldFactory.makeNewMockWorld("world_skylands", World.Environment.SKYLANDS);
List<World> worldList = new ArrayList<World>();
worldList.add(mockWorld);
worldList.add(mockNetherWorld);
worldList.add(mockSkyWorld);
// Initialize the Mock server.
Server mockServer = serverFactory.getMockServer();
// Give the server some worlds
when(mockServer.getWorld("world")).thenReturn(mockWorld);
when(mockServer.getWorld("world_nether")).thenReturn(mockNetherWorld);
when(mockServer.getWorld("world_skylands")).thenReturn(mockNetherWorld);
when(mockServer.getWorlds()).thenReturn(worldList);
when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
// Initialize some worldCreatorMatchers (so we can see when a specific creator is called)
WorldCreatorMatcher matchWorld = new WorldCreatorMatcher(new WorldCreator("world"));
WorldCreator netherCreator = new WorldCreator("world_nether");
netherCreator.environment(World.Environment.NETHER);
WorldCreatorMatcher matchNetherWorld = new WorldCreatorMatcher(netherCreator);
WorldCreator skyCreator = new WorldCreator("world_skylands");
skyCreator.environment(World.Environment.SKYLANDS);
WorldCreatorMatcher matchSkyWorld = new WorldCreatorMatcher(skyCreator);
// If a specific creator is called, return the appropreate world.
when(mockServer.createWorld(Matchers.argThat(matchWorld))).thenReturn(mockWorld);
when(mockServer.createWorld(Matchers.argThat(matchNetherWorld))).thenReturn(mockNetherWorld);
when(mockServer.createWorld(Matchers.argThat(matchSkyWorld))).thenReturn(mockSkyWorld);
// Override some methods that bukkit normally provides us with for Core
doReturn(mockServer).when(core).getServer();
// Init our command sender
commandSender = spy(new TestCommandSender(mockServer));
Bukkit.setServer(mockServer);
// Load Multiverse Core
core.onLoad();
// Enable it.
core.onEnable();
return mockServer;
}
public MultiverseCore getCore() {
return this.core;
}
public CommandSender getCommandSender() {
return commandSender;
}
}

View File

@ -0,0 +1,54 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.test.utils;
import org.bukkit.WorldCreator;
import org.mockito.ArgumentMatcher;
public class WorldCreatorMatcher extends ArgumentMatcher<WorldCreator> {
private WorldCreator worldCreator;
private boolean careAboutSeeds = false;
private boolean careAboutGenerators = false;
public WorldCreatorMatcher(WorldCreator creator) {
System.out.println("Creating NEW world matcher.(" + creator.name() + ")");
this.worldCreator = creator;
}
public void careAboutSeeds(boolean doICare) {
this.careAboutSeeds = doICare;
}
public void careAboutGenerators(boolean doICare) {
this.careAboutGenerators = doICare;
}
public boolean matches(Object creator) {
System.out.println("Checking world creators.");
if (creator == null) {
System.out.println("The given creator was null, but I was checking: " + this.worldCreator.name());
return false;
}
System.out.println("Checking Names...(" + ((WorldCreator) creator).name() + ") vs (" + this.worldCreator.name() + ")");
System.out.println("Checking Envs...(" + ((WorldCreator) creator).environment() + ") vs (" + this.worldCreator.environment() + ")");
if (!((WorldCreator) creator).name().equals(this.worldCreator.name())) {
return false;
} else if (!((WorldCreator) creator).environment().equals(this.worldCreator.environment())) {
System.out.println("Checking Environments...");
return false;
} else if (careAboutSeeds && ((WorldCreator) creator).seed() != this.worldCreator.seed()) {
System.out.print("Checking Seeds...");
return false;
} else if (careAboutGenerators && !((WorldCreator) creator).generator().equals(this.worldCreator.generator())) {
System.out.print("Checking Gens...");
return false;
}
System.out.println("Creators matched!!!");
return true;
}
}