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