-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathChallengesAddonTest.java
More file actions
412 lines (358 loc) · 15 KB
/
Copy pathChallengesAddonTest.java
File metadata and controls
412 lines (358 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package world.bentobox.challenges;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.mockito.ArgumentCaptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.UnsafeValues;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitScheduler;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockbukkit.mockbukkit.MockBukkit;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import world.bentobox.challenges.panel.PanelTestHelper;
import world.bentobox.bentobox.BentoBox;
import world.bentobox.bentobox.Settings;
import world.bentobox.bentobox.api.addons.Addon;
import world.bentobox.bentobox.api.addons.Addon.State;
import world.bentobox.bentobox.api.addons.AddonDescription;
import world.bentobox.bentobox.api.addons.GameModeAddon;
import world.bentobox.bentobox.api.commands.CompositeCommand;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.database.DatabaseSetup.DatabaseType;
import world.bentobox.bentobox.database.objects.Island;
import world.bentobox.bentobox.managers.AddonsManager;
import world.bentobox.bentobox.managers.CommandsManager;
import world.bentobox.bentobox.managers.FlagsManager;
import world.bentobox.bentobox.managers.IslandWorldManager;
import world.bentobox.bentobox.managers.IslandsManager;
import world.bentobox.bentobox.managers.PlaceholdersManager;
/**
* @author tastybento
*
*/
@SuppressWarnings("deprecation")
class ChallengesAddonTest {
@Mock
private User user;
@Mock
private IslandsManager im;
@Mock
private Island island;
private ChallengesAddon addon;
@Mock
private BentoBox plugin;
@Mock
private FlagsManager fm;
@Mock
private Settings settings;
@Mock
private GameModeAddon gameMode;
@Mock
private AddonsManager am;
@Mock
private BukkitScheduler scheduler;
@Mock
private PlaceholdersManager phm;
private AutoCloseable closeable;
private MockedStatic<Bukkit> mockedBukkit;
@BeforeEach
void setUp() throws Exception {
closeable = MockitoAnnotations.openMocks(this);
// Force Bukkit's Tag.<clinit> to run against a real MockBukkit ServerMock before
// we install the Mockito static mock below. Without this, Tag.<clinit> can later
// fire while Bukkit is statically mocked, permanently null-ing every Tag constant
// for the JVM and corrupting any subsequent test that creates an ItemStack
// (e.g. CommonPagedPanelTest -> ItemType.<clinit> -> MaterialTags.<clinit> ->
// Objects.requireNonNull(Tag.ALL_SIGNS) -> NPE).
MockBukkit.mock();
PanelTestHelper.primeBukkitRegistry();
MockBukkit.unmock();
// Set up plugin
WhiteBox.setInternalState(BentoBox.class, "instance", plugin);
when(plugin.getLogger()).thenReturn(Logger.getAnonymousLogger());
// Command manager
CommandsManager cm = mock(CommandsManager.class);
when(plugin.getCommandsManager()).thenReturn(cm);
// Placeholders manager
when(plugin.getPlaceholdersManager()).thenReturn(phm);
// Player
Player p = mock(Player.class);
when(user.isOp()).thenReturn(false);
UUID uuid = UUID.randomUUID();
when(user.getUniqueId()).thenReturn(uuid);
when(user.getPlayer()).thenReturn(p);
when(user.getName()).thenReturn("tastybento");
User.setPlugin(plugin);
// Island World Manager
IslandWorldManager iwm = mock(IslandWorldManager.class);
when(plugin.getIWM()).thenReturn(iwm);
// Player has island to begin with
island = mock(Island.class);
when(im.getIsland(Mockito.any(), Mockito.any(UUID.class))).thenReturn(island);
when(plugin.getIslands()).thenReturn(im);
// Locales
when(user.getTranslation(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));
// Server
mockedBukkit = Mockito.mockStatic(Bukkit.class);
Server server = mock(Server.class);
mockedBukkit.when(Bukkit::getServer).thenReturn(server);
mockedBukkit.when(Bukkit::getLogger).thenReturn(Logger.getAnonymousLogger());
mockedBukkit.when(Bukkit::getPluginManager).thenReturn(mock(PluginManager.class));
// Addon
addon = new ChallengesAddon();
File jFile = new File("addon.jar");
List<String> lines = Arrays.asList("# ChallengesAddon Configuration", "uniqueId: config");
Path path = Paths.get("config.yml");
Files.write(path, lines, StandardCharsets.UTF_8);
try (JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(jFile))) {
addToJar(tempJarOutputStream, path);
addToJar(tempJarOutputStream, Paths.get("src/main/resources/panels/gamemode_panel.yml"));
addToJar(tempJarOutputStream, Paths.get("src/main/resources/panels/main_panel.yml"));
addToJar(tempJarOutputStream, Paths.get("src/main/resources/panels/multiple_panel.yml"));
addToJar(tempJarOutputStream, Paths.get("src/main/resources/template.yml"));
addToJar(tempJarOutputStream, Paths.get("src/main/resources/default.json"));
}
File dataFolder = new File("addons/Challenges");
addon.setDataFolder(dataFolder);
addon.setFile(jFile);
AddonDescription desc = new AddonDescription.Builder("bentobox", "challenges", "1.3").description("test").authors("BONNe").build();
addon.setDescription(desc);
// Addons manager
when(plugin.getAddonsManager()).thenReturn(am);
// One game mode
when(am.getGameModeAddons()).thenReturn(Collections.singletonList(gameMode));
AddonDescription desc2 = new AddonDescription.Builder("bentobox", "BSkyBlock", "1.3").description("test").authors("tasty").build();
when(gameMode.getDescription()).thenReturn(desc2);
// Player command
CompositeCommand cmd = mock(CompositeCommand.class);
@NonNull
Optional<CompositeCommand> opCmd = Optional.of(cmd);
when(gameMode.getPlayerCommand()).thenReturn(opCmd);
when(gameMode.getAdminCommand()).thenReturn(opCmd);
// Flags manager
when(plugin.getFlagsManager()).thenReturn(fm);
when(fm.getFlags()).thenReturn(Collections.emptyList());
when(plugin.getSettings()).thenReturn(settings);
DatabaseType value = DatabaseType.JSON;
when(settings.getDatabaseType()).thenReturn(value);
// Bukkit
mockedBukkit.when(Bukkit::getScheduler).thenReturn(scheduler);
ItemMeta meta = mock(ItemMeta.class);
ItemFactory itemFactory = mock(ItemFactory.class);
when(itemFactory.getItemMeta(any())).thenReturn(meta);
mockedBukkit.when(Bukkit::getItemFactory).thenReturn(itemFactory);
UnsafeValues unsafe = mock(UnsafeValues.class);
when(unsafe.getDataVersion()).thenReturn(777);
mockedBukkit.when(Bukkit::getUnsafe).thenReturn(unsafe);
}
private void addToJar(JarOutputStream tempJarOutputStream, Path path) throws IOException {
try (FileInputStream fis = new FileInputStream(path.toFile())) {
byte[] buffer = new byte[1024];
int bytesRead = 0;
JarEntry entry = new JarEntry(path.toString().replace("src/main/resources/", ""));
tempJarOutputStream.putNextEntry(entry);
while ((bytesRead = fis.read(buffer)) != -1) {
tempJarOutputStream.write(buffer, 0, bytesRead);
}
}
}
@AfterEach
void tearDown() throws Exception {
mockedBukkit.closeOnDemand();
closeable.close();
Mockito.framework().clearInlineMocks();
new File("addon.jar").delete();
new File("config.yml").delete();
deleteAll(new File("addons"));
deleteAll(new File("database"));
deleteAll(new File("database_backup"));
}
private void deleteAll(File file) throws IOException {
if (file.exists()) {
Files.walk(file.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
@Test
void testOnLoad() {
addon.onLoad();
File check = new File("addons/Challenges", "config.yml");
assertTrue(check.exists());
}
@Test
void testOnEnableDisabledPlugin() {
when(plugin.isEnabled()).thenReturn(false);
addon.onEnable();
verify(plugin).logError("[challenges] BentoBox is not available or disabled!");
assertEquals(Addon.State.DISABLED, addon.getState());
}
@Test
void testOnEnableDisabledAddon() {
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.DISABLED);
addon.onEnable();
verify(plugin).logError("[challenges] Challenges Addon is not available or disabled!");
}
@Test
void testOnEnableIncompatibleDatabase() {
DatabaseType value = DatabaseType.YAML;
when(settings.getDatabaseType()).thenReturn(value);
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.LOADED);
addon.onEnable();
verify(plugin).logError("[challenges] BentoBox database is not compatible with Challenges Addon.");
verify(plugin).logError("[challenges] Please use JSON based database type.");
assertEquals(State.INCOMPATIBLE, addon.getState());
}
@Test
void testOnEnableHooked() {
addon.onLoad();
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.LOADED);
addon.onEnable();
verify(plugin).log("[challenges] Loading challenges...");
verify(plugin, never()).logError("Challenges could not hook into AcidIsland or BSkyBlock so will not do anything!");
}
@Test
void testOnEnableNotHooked() {
addon.onLoad();
when(am.getGameModeAddons()).thenReturn(Collections.emptyList());
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.LOADED);
addon.onEnable();
verify(plugin).log("[challenges] Loading challenges...");
verify(plugin).logError("[challenges] Challenges could not hook into AcidIsland or BSkyBlock so will not do anything!");
}
@Test
void testOnReloadNotHooked() {
addon.onReload();
verify(plugin, never()).log(anyString());
}
@Test
void testOnDisable() {
this.testOnEnableHooked();
addon.onDisable();
File chDir = new File("database", "Challenge");
assertTrue(chDir.exists());
File lvDir = new File("database", "ChallengeLevel");
assertTrue(lvDir.exists());
}
@Test
void testGetChallengesManager() {
assertNull(addon.getChallengesManager());
this.testOnEnableHooked();
assertNotNull(addon.getChallengesManager());
}
@Test
void testGetPermissionPrefix() {
assertEquals("addon.", addon.getPermissionPrefix());
}
@Test
void testGetImportManager() {
assertNull(addon.getImportManager());
this.testOnEnableHooked();
assertNotNull(addon.getImportManager());
}
@Test
void testGetWebManager() {
assertNull(addon.getWebManager());
this.testOnEnableHooked();
assertNotNull(addon.getWebManager());
}
@Test
void testGetChallengesSettings() {
assertNull(addon.getChallengesSettings());
addon.onLoad();
assertNotNull(addon.getChallengesSettings());
}
@Test
void testIsEconomyProvided() {
assertFalse(addon.isEconomyProvided());
}
@Test
void testGetEconomyProvider() {
assertNull(addon.getEconomyProvider());
}
@Test
void testIsLevelProvided() {
assertFalse(addon.isLevelProvided());
}
@Test
void testGetLevelAddon() {
assertNull(addon.getLevelAddon());
}
@Test
void testPlaceholderCompletedPercentRegistered() {
addon.onLoad();
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.LOADED);
// Mock the world
World world = mock(World.class);
when(gameMode.getOverWorld()).thenReturn(world);
addon.onEnable();
// Capture every registered placeholder name; assert the one under test is present without
// pinning the exact total (which changes whenever any placeholder is added or removed).
ArgumentCaptor<String> nameCaptor = ArgumentCaptor.forClass(String.class);
verify(phm, org.mockito.Mockito.atLeastOnce()).registerPlaceholder(any(GameModeAddon.class), nameCaptor.capture(), any());
List<String> names = nameCaptor.getAllValues();
assertTrue(names.contains("challenges_completed_percent"),
"Placeholder 'challenges_completed_percent' was not registered. Registered: " + names);
}
@Test
void testPlaceholderLatestLevelCompletedPercentRegistered() {
addon.onLoad();
when(plugin.isEnabled()).thenReturn(true);
addon.setState(State.LOADED);
// Mock the world
World world = mock(World.class);
when(gameMode.getOverWorld()).thenReturn(world);
addon.onEnable();
// Capture every registered placeholder name; assert the one under test is present without
// pinning the exact total (which changes whenever any placeholder is added or removed).
ArgumentCaptor<String> nameCaptor = ArgumentCaptor.forClass(String.class);
verify(phm, org.mockito.Mockito.atLeastOnce()).registerPlaceholder(any(GameModeAddon.class), nameCaptor.capture(), any());
List<String> names = nameCaptor.getAllValues();
assertTrue(names.contains("challenges_latest_level_completed_percent"),
"Placeholder 'challenges_latest_level_completed_percent' was not registered. Registered: " + names);
}
}