PageRenderTime 61ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/src/test/java/com/onarandombox/MultiverseCore/utils/TestInstanceCreator.java

https://github.com/main--/Multiverse-Core
Java | 307 lines | 239 code | 42 blank | 26 comment | 2 complexity | 1a44820a359cfd8723a54e600c63befd MD5 | raw file
  1. /******************************************************************************
  2. * Multiverse 2 Copyright (c) the Multiverse Team 2011. *
  3. * Multiverse 2 is licensed under the BSD License. *
  4. * For more information please check the README.md file included *
  5. * with this project. *
  6. ******************************************************************************/
  7. package com.onarandombox.MultiverseCore.utils;
  8. import buscript.Buscript;
  9. import com.onarandombox.MultiverseCore.MultiverseCore;
  10. import com.onarandombox.MultiverseCore.api.MultiverseWorld;
  11. import com.onarandombox.MultiverseCore.listeners.MVEntityListener;
  12. import com.onarandombox.MultiverseCore.listeners.MVPlayerListener;
  13. import com.onarandombox.MultiverseCore.listeners.MVWeatherListener;
  14. import junit.framework.Assert;
  15. import org.bukkit.Bukkit;
  16. import org.bukkit.ChatColor;
  17. import org.bukkit.Server;
  18. import org.bukkit.World;
  19. import org.bukkit.WorldCreator;
  20. import org.bukkit.command.CommandSender;
  21. import org.bukkit.permissions.Permission;
  22. import org.bukkit.plugin.Plugin;
  23. import org.bukkit.plugin.PluginDescriptionFile;
  24. import org.bukkit.plugin.PluginManager;
  25. import org.bukkit.plugin.java.JavaPlugin;
  26. import org.bukkit.scheduler.BukkitScheduler;
  27. import org.mockito.Matchers;
  28. import org.mockito.invocation.InvocationOnMock;
  29. import org.mockito.stubbing.Answer;
  30. import org.powermock.api.mockito.PowerMockito;
  31. import org.powermock.core.MockGateway;
  32. import java.io.File;
  33. import java.lang.reflect.Field;
  34. import java.util.ArrayList;
  35. import java.util.List;
  36. import java.util.UUID;
  37. import java.util.logging.Level;
  38. import java.util.logging.Logger;
  39. import static org.mockito.Matchers.anyString;
  40. import static org.mockito.Mockito.*;
  41. public class TestInstanceCreator {
  42. private MultiverseCore core;
  43. private Server mockServer;
  44. private CommandSender commandSender;
  45. public static final File pluginDirectory = new File("bin/test/server/plugins/coretest");
  46. public static final File serverDirectory = new File("bin/test/server");
  47. public static final File worldsDirectory = new File("bin/test/server");
  48. public boolean setUp() {
  49. try {
  50. pluginDirectory.mkdirs();
  51. Assert.assertTrue(pluginDirectory.exists());
  52. MockGateway.MOCK_STANDARD_METHODS = false;
  53. core = PowerMockito.spy(new MultiverseCore());
  54. PowerMockito.doAnswer(new Answer<Void>() {
  55. @Override
  56. public Void answer(InvocationOnMock invocation) throws Throwable {
  57. return null; // don't run metrics in tests
  58. }
  59. }).when(core, "setupMetrics");
  60. // Let's let all MV files go to bin/test
  61. doReturn(pluginDirectory).when(core).getDataFolder();
  62. // Return a fake PDF file.
  63. PluginDescriptionFile pdf = PowerMockito.spy(new PluginDescriptionFile("Multiverse-Core", "2.2-Test",
  64. "com.onarandombox.MultiverseCore.MultiverseCore"));
  65. when(pdf.getAuthors()).thenReturn(new ArrayList<String>());
  66. doReturn(pdf).when(core).getDescription();
  67. doReturn(true).when(core).isEnabled();
  68. doReturn(Util.logger).when(core).getLogger();
  69. core.setServerFolder(serverDirectory);
  70. // Add Core to the list of loaded plugins
  71. JavaPlugin[] plugins = new JavaPlugin[] { core };
  72. // Mock the Plugin Manager
  73. PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
  74. when(mockPluginManager.getPlugins()).thenReturn(plugins);
  75. when(mockPluginManager.getPlugin("Multiverse-Core")).thenReturn(core);
  76. when(mockPluginManager.getPermission(anyString())).thenReturn(null);
  77. // Tell Buscript Vault is not available.
  78. when(mockPluginManager.getPermission("Vault")).thenReturn(null);
  79. // Make some fake folders to fool the fake MV into thinking these worlds exist
  80. File worldNormalFile = new File(core.getServerFolder(), "world");
  81. Util.log("Creating world-folder: " + worldNormalFile.getAbsolutePath());
  82. worldNormalFile.mkdirs();
  83. File worldNetherFile = new File(core.getServerFolder(), "world_nether");
  84. Util.log("Creating world-folder: " + worldNetherFile.getAbsolutePath());
  85. worldNetherFile.mkdirs();
  86. File worldSkylandsFile = new File(core.getServerFolder(), "world_the_end");
  87. Util.log("Creating world-folder: " + worldSkylandsFile.getAbsolutePath());
  88. worldSkylandsFile.mkdirs();
  89. // Initialize the Mock server.
  90. mockServer = mock(Server.class);
  91. when(mockServer.getName()).thenReturn("TestBukkit");
  92. Logger.getLogger("Minecraft").setParent(Util.logger);
  93. when(mockServer.getLogger()).thenReturn(Util.logger);
  94. when(mockServer.getWorldContainer()).thenReturn(worldsDirectory);
  95. // Give the server some worlds
  96. when(mockServer.getWorld(anyString())).thenAnswer(new Answer<World>() {
  97. @Override
  98. public World answer(InvocationOnMock invocation) throws Throwable {
  99. String arg;
  100. try {
  101. arg = (String) invocation.getArguments()[0];
  102. } catch (Exception e) {
  103. return null;
  104. }
  105. return MockWorldFactory.getWorld(arg);
  106. }
  107. });
  108. when(mockServer.getWorld(any(UUID.class))).thenAnswer(new Answer<World>() {
  109. @Override
  110. public World answer(InvocationOnMock invocation) throws Throwable {
  111. UUID arg;
  112. try {
  113. arg = (UUID) invocation.getArguments()[0];
  114. } catch (Exception e) {
  115. return null;
  116. }
  117. return MockWorldFactory.getWorld(arg);
  118. }
  119. });
  120. when(mockServer.getWorlds()).thenAnswer(new Answer<List<World>>() {
  121. @Override
  122. public List<World> answer(InvocationOnMock invocation) throws Throwable {
  123. return MockWorldFactory.getWorlds();
  124. }
  125. });
  126. when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
  127. when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer(
  128. new Answer<World>() {
  129. @Override
  130. public World answer(InvocationOnMock invocation) throws Throwable {
  131. WorldCreator arg;
  132. try {
  133. arg = (WorldCreator) invocation.getArguments()[0];
  134. } catch (Exception e) {
  135. return null;
  136. }
  137. // Add special case for creating null worlds.
  138. // Not sure I like doing it this way, but this is a special case
  139. if (arg.name().equalsIgnoreCase("nullworld")) {
  140. return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type());
  141. }
  142. return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type());
  143. }
  144. });
  145. when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true);
  146. // add mock scheduler
  147. BukkitScheduler mockScheduler = mock(BukkitScheduler.class);
  148. when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class), anyLong())).
  149. thenAnswer(new Answer<Integer>() {
  150. @Override
  151. public Integer answer(InvocationOnMock invocation) throws Throwable {
  152. Runnable arg;
  153. try {
  154. arg = (Runnable) invocation.getArguments()[1];
  155. } catch (Exception e) {
  156. return null;
  157. }
  158. arg.run();
  159. return null;
  160. }});
  161. when(mockScheduler.scheduleSyncDelayedTask(any(Plugin.class), any(Runnable.class))).
  162. thenAnswer(new Answer<Integer>() {
  163. @Override
  164. public Integer answer(InvocationOnMock invocation) throws Throwable {
  165. Runnable arg;
  166. try {
  167. arg = (Runnable) invocation.getArguments()[1];
  168. } catch (Exception e) {
  169. return null;
  170. }
  171. arg.run();
  172. return null;
  173. }});
  174. when(mockServer.getScheduler()).thenReturn(mockScheduler);
  175. // Set server
  176. Field serverfield = JavaPlugin.class.getDeclaredField("server");
  177. serverfield.setAccessible(true);
  178. serverfield.set(core, mockServer);
  179. // Set buscript
  180. Buscript buscript = PowerMockito.spy(new Buscript(core));
  181. Field buscriptfield = MultiverseCore.class.getDeclaredField("buscript");
  182. buscriptfield.setAccessible(true);
  183. buscriptfield.set(core, buscript);
  184. when(buscript.getPlugin()).thenReturn(core);
  185. // Set worldManager
  186. WorldManager wm = PowerMockito.spy(new WorldManager(core));
  187. Field worldmanagerfield = MultiverseCore.class.getDeclaredField("worldManager");
  188. worldmanagerfield.setAccessible(true);
  189. worldmanagerfield.set(core, wm);
  190. // Set playerListener
  191. MVPlayerListener pl = PowerMockito.spy(new MVPlayerListener(core));
  192. Field playerlistenerfield = MultiverseCore.class.getDeclaredField("playerListener");
  193. playerlistenerfield.setAccessible(true);
  194. playerlistenerfield.set(core, pl);
  195. // Set entityListener
  196. MVEntityListener el = PowerMockito.spy(new MVEntityListener(core));
  197. Field entitylistenerfield = MultiverseCore.class.getDeclaredField("entityListener");
  198. entitylistenerfield.setAccessible(true);
  199. entitylistenerfield.set(core, el);
  200. // Set weatherListener
  201. MVWeatherListener wl = PowerMockito.spy(new MVWeatherListener(core));
  202. Field weatherlistenerfield = MultiverseCore.class.getDeclaredField("weatherListener");
  203. weatherlistenerfield.setAccessible(true);
  204. weatherlistenerfield.set(core, wl);
  205. // Init our command sender
  206. final Logger commandSenderLogger = Logger.getLogger("CommandSender");
  207. commandSenderLogger.setParent(Util.logger);
  208. commandSender = mock(CommandSender.class);
  209. doAnswer(new Answer<Void>() {
  210. @Override
  211. public Void answer(InvocationOnMock invocation) throws Throwable {
  212. commandSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0]));
  213. return null;
  214. }}).when(commandSender).sendMessage(anyString());
  215. when(commandSender.getServer()).thenReturn(mockServer);
  216. when(commandSender.getName()).thenReturn("MockCommandSender");
  217. when(commandSender.isPermissionSet(anyString())).thenReturn(true);
  218. when(commandSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
  219. when(commandSender.hasPermission(anyString())).thenReturn(true);
  220. when(commandSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
  221. when(commandSender.addAttachment(core)).thenReturn(null);
  222. when(commandSender.isOp()).thenReturn(true);
  223. Bukkit.setServer(mockServer);
  224. // Load Multiverse Core
  225. core.onLoad();
  226. // Enable it.
  227. core.onEnable();
  228. return true;
  229. } catch (Exception e) {
  230. e.printStackTrace();
  231. }
  232. return false;
  233. }
  234. public boolean tearDown() {
  235. List<MultiverseWorld> worlds = new ArrayList<MultiverseWorld>(core.getMVWorldManager()
  236. .getMVWorlds());
  237. for (MultiverseWorld world : worlds) {
  238. core.getMVWorldManager().deleteWorld(world.getName());
  239. }
  240. try {
  241. Field serverField = Bukkit.class.getDeclaredField("server");
  242. serverField.setAccessible(true);
  243. serverField.set(Class.forName("org.bukkit.Bukkit"), null);
  244. } catch (Exception e) {
  245. Util.log(Level.SEVERE,
  246. "Error while trying to unregister the server from Bukkit. Has Bukkit changed?");
  247. e.printStackTrace();
  248. Assert.fail(e.getMessage());
  249. return false;
  250. }
  251. core.onDisable();
  252. FileUtils.deleteFolder(serverDirectory);
  253. MockWorldFactory.clearWorlds();
  254. return true;
  255. }
  256. public MultiverseCore getCore() {
  257. return this.core;
  258. }
  259. public Server getServer() {
  260. return this.mockServer;
  261. }
  262. public CommandSender getCommandSender() {
  263. return commandSender;
  264. }
  265. }