diff --git a/pom.xml b/pom.xml index c4fc52348..d7ea204ef 100644 --- a/pom.xml +++ b/pom.xml @@ -602,7 +602,7 @@ ch.jalu injector - 1.1-SNAPSHOT + 1.0 true diff --git a/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java b/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java index 994d967b2..02e7c9b41 100644 --- a/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java +++ b/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java @@ -24,7 +24,7 @@ public class HelpMessagesService { private final HelpMessagesFileHandler helpMessagesFileHandler; @Inject - HelpMessagesService(HelpMessagesFileHandler helpMessagesFileHandler) { + public HelpMessagesService(HelpMessagesFileHandler helpMessagesFileHandler) { this.helpMessagesFileHandler = helpMessagesFileHandler; } diff --git a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java index 5e6fc2210..114a58261 100644 --- a/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java @@ -12,7 +12,6 @@ import org.bukkit.configuration.file.YamlConfiguration; import javax.annotation.PostConstruct; -import javax.inject.Inject; import java.io.File; import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; @@ -24,18 +23,16 @@ public abstract class AbstractMessageFileHandler implements Reloadable { private final ConsoleLogger logger = ConsoleLoggerFactory.get(AbstractMessageFileHandler.class); - @DataFolder - @Inject - private File dataFolder; - - @Inject - private Settings settings; + private final File dataFolder; + private final Settings settings; private String filename; private FileConfiguration configuration; private final String defaultFile; - protected AbstractMessageFileHandler() { + protected AbstractMessageFileHandler(@DataFolder File dataFolder, Settings settings) { + this.dataFolder = dataFolder; + this.settings = settings; this.defaultFile = createFilePath(DEFAULT_LANGUAGE); } diff --git a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java index 89dc52245..c0004ec08 100644 --- a/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java @@ -1,12 +1,15 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.FileUtils; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import javax.inject.Inject; +import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; @@ -21,8 +24,9 @@ public class HelpMessagesFileHandler extends AbstractMessageFileHandler { private FileConfiguration defaultConfiguration; - @Inject // Trigger injection in the superclass - HelpMessagesFileHandler() { + @Inject + public HelpMessagesFileHandler(@DataFolder File dataFolder, Settings settings) { + super(dataFolder, settings); } /** diff --git a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java index 18b776464..f7a61ce83 100644 --- a/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java +++ b/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java @@ -1,10 +1,13 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; -import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.message.updater.MessageUpdater; +import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.settings.Settings; import javax.inject.Inject; +import java.io.File; import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; @@ -15,10 +18,12 @@ public class MessagesFileHandler extends AbstractMessageFileHandler { private final ConsoleLogger logger = ConsoleLoggerFactory.get(MessagesFileHandler.class); - @Inject - private MessageUpdater messageUpdater; + private final MessageUpdater messageUpdater; - MessagesFileHandler() { + @Inject + MessagesFileHandler(@DataFolder File dataFolder, Settings settings, MessageUpdater messageUpdater) { + super(dataFolder, settings); + this.messageUpdater = messageUpdater; } @Override diff --git a/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java b/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java index e1c8c5ba7..2d1239244 100644 --- a/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java +++ b/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java @@ -29,18 +29,19 @@ */ public class HelpTranslationGenerator { - @Inject - private CommandInitializer commandInitializer; - - @Inject - private HelpMessagesService helpMessagesService; + private final CommandInitializer commandInitializer; + private final HelpMessagesService helpMessagesService; + private final Settings settings; + private final File dataFolder; @Inject - private Settings settings; - - @DataFolder - @Inject - private File dataFolder; + HelpTranslationGenerator(CommandInitializer commandInitializer, HelpMessagesService helpMessagesService, + Settings settings, @DataFolder File dataFolder) { + this.commandInitializer = commandInitializer; + this.helpMessagesService = helpMessagesService; + this.settings = settings; + this.dataFolder = dataFolder; + } /** * Updates the help file to contain entries for all commands. diff --git a/src/test/java/fr/xephi/authme/command/CommandMapperTest.java b/src/test/java/fr/xephi/authme/command/CommandMapperTest.java index 6155d52fa..88b80cf21 100644 --- a/src/test/java/fr/xephi/authme/command/CommandMapperTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandMapperTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.command; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.command.TestCommandsUtil.TestLoginCommand; import fr.xephi.authme.command.TestCommandsUtil.TestRegisterCommand; import fr.xephi.authme.command.TestCommandsUtil.TestUnregisterCommand; @@ -11,9 +8,11 @@ import fr.xephi.authme.permission.PermissionsManager; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; import java.util.Set; @@ -33,16 +32,16 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; /** * Test for {@link CommandMapper}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class CommandMapperTest { private static List commands; - @InjectDelayed private CommandMapper mapper; @Mock @@ -56,9 +55,10 @@ static void setUpCommandHandler() { commands = TestCommandsUtil.generateCommands(); } - @BeforeInjecting - void setUpMocks() { + @BeforeEach + void setUpMocksAndMapper() { given(commandInitializer.getCommands()).willReturn(commands); + mapper = new CommandMapper(commandInitializer, permissionsManager); } // ----------- @@ -106,12 +106,12 @@ void shouldRejectCommandWithTooManyArguments() { // given List parts = asList("authme", "register", "pass123", "pass123", "pass123"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register"))); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getDifference(), equalTo(0.0)); @@ -124,12 +124,12 @@ void shouldRejectCommandWithTooFewArguments() { // given List parts = asList("authme", "Reg"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register"))); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getDifference(), equalTo(0.0)); @@ -142,12 +142,12 @@ void shouldSuggestCommandWithSimilarLabel() { // given List parts = asList("authme", "reh", "pass123", "pass123"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register"))); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.UNKNOWN_LABEL)); assertThat(result.getDifference() < 0.75, equalTo(true)); @@ -161,12 +161,12 @@ void shouldSuggestMostSimilarCommand() { // given List parts = asList("authme", "asdfawetawty4asdca"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getCommandDescription(), not(nullValue())); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.UNKNOWN_LABEL)); assertThat(result.getDifference() > 0.75, equalTo(true)); @@ -179,12 +179,12 @@ void shouldHandleBaseWithWrongArguments() { // given List parts = singletonList("unregister"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister"))); assertThat(result.getDifference(), equalTo(0.0)); @@ -197,12 +197,12 @@ void shouldHandleUnknownBase() { // given List parts = asList("bogus", "label1", "arg1"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.MISSING_BASE_COMMAND)); assertThat(result.getCommandDescription(), nullValue()); } @@ -240,12 +240,12 @@ void shouldReturnChildlessBaseCommandWithArgCountError() { // given List parts = asList("unregistER", "player1", "wrongArg"); CommandSender sender = mock(CommandSender.class); - given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true); // when FoundCommandResult result = mapper.mapPartsToCommand(sender, parts); // then + verifyNoInteractions(permissionsManager); assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS)); assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister"))); assertThat(result.getDifference(), equalTo(0.0)); @@ -305,7 +305,6 @@ void shouldSupportAuthMePrefix() { assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister"))); } - @SuppressWarnings("unchecked") @Test void shouldReturnExecutableCommandClasses() { // given / when diff --git a/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java index 7516c46b1..8666d76f4 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java @@ -1,25 +1,22 @@ package fr.xephi.authme.command.executable.email; import ch.jalu.datasourcecolumns.data.DataSourceValueImpl; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; -import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.PasswordRecoveryService; import fr.xephi.authme.service.RecoveryCodeService; -import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.Locale; @@ -27,9 +24,9 @@ import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -37,17 +34,14 @@ /** * Test for {@link RecoverEmailCommand}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class RecoverEmailCommandTest { private static final String DEFAULT_EMAIL = "your@email.com"; - @InjectDelayed + @InjectMocks private RecoverEmailCommand command; - @Mock - private PasswordSecurity passwordSecurity; - @Mock private CommonService commonService; @@ -74,11 +68,6 @@ static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - void initSettings() { - given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40); - } - @Test void shouldHandleMissingMailProperties() { // given @@ -90,7 +79,7 @@ void shouldHandleMissingMailProperties() { // then verify(commonService).send(sender, MessageKey.INCOMPLETE_EMAIL_SETTINGS); - verifyNoInteractions(dataSource, passwordSecurity); + verifyNoInteractions(dataSource); } @Test @@ -178,22 +167,17 @@ void shouldGenerateRecoveryCode() { Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); - given(emailService.sendRecoveryCode(anyString(), anyString(), anyString())).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); String email = "v@example.com"; given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(email)); - String code = "a94f37"; given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(true); - given(recoveryCodeService.generateCode(name)).willReturn(code); setBukkitServiceToRunTaskAsynchronously(bukkitService); // when command.executeCommand(sender, Collections.singletonList(email.toUpperCase(Locale.ROOT))); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); - verify(recoveryService).createAndSendRecoveryCode(sender, email); + verify(recoveryService, only()).createAndSendRecoveryCode(sender, email); } @Test @@ -203,7 +187,6 @@ void shouldGenerateNewPasswordWithoutRecoveryCode() { Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); - given(emailService.sendPasswordMail(anyString(), anyString(), anyString())).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); String email = "vulture@example.com"; given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(email)); @@ -214,9 +197,7 @@ void shouldGenerateNewPasswordWithoutRecoveryCode() { command.executeCommand(sender, Collections.singletonList(email)); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); - verify(recoveryService).generateAndSendNewPassword(sender, email); + verify(recoveryService, only()).generateAndSendNewPassword(sender, email); } @Test diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java index b2d970e8c..1c874c552 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java @@ -5,7 +5,6 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.TestCommandsUtil; -import fr.xephi.authme.message.AbstractMessageFileHandler; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.permission.DefaultPermission; @@ -148,9 +147,7 @@ private HelpMessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); - HelpMessagesFileHandler messagesFileHandler = ReflectionTestUtils.newInstance(HelpMessagesFileHandler.class); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); + HelpMessagesFileHandler messagesFileHandler = new HelpMessagesFileHandler(dataFolder, settings); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } diff --git a/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java b/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java index ec4b1c9ce..eca09739f 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpProviderTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.command.help; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.FoundCommandResult; import fr.xephi.authme.command.FoundResultStatus; @@ -13,11 +10,13 @@ import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.internal.stubbing.answers.ReturnsArgumentAt; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Collection; @@ -44,6 +43,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -51,12 +51,11 @@ /** * Test for {@link HelpProvider}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class HelpProviderTest { private static Collection commands; - @InjectDelayed private HelpProvider helpProvider; @Mock private PermissionsManager permissionsManager; @@ -70,9 +69,10 @@ static void setUpCommands() { commands = TestCommandsUtil.generateCommands(); } - @BeforeInjecting - void setInitialSettings() { + @BeforeEach + void initializeHelpProvider() { setDefaultHelpMessages(helpMessagesService); + helpProvider = new HelpProvider(permissionsManager, helpMessagesService); } @Test @@ -444,22 +444,22 @@ private static List getLines(CommandSender sender) { } private static void setDefaultHelpMessages(HelpMessagesService helpMessagesService) { - given(helpMessagesService.buildLocalizedDescription(any(CommandDescription.class))) - .willAnswer(new ReturnsArgumentAt(0)); + lenient().when(helpMessagesService.buildLocalizedDescription(any(CommandDescription.class))) + .thenAnswer(new ReturnsArgumentAt(0)); for (HelpMessage key : HelpMessage.values()) { String text = key.name().replace("_", " ").toLowerCase(Locale.ROOT); - given(helpMessagesService.getMessage(key)) - .willReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); + lenient().when(helpMessagesService.getMessage(key)) + .thenReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); } for (DefaultPermission permission : DefaultPermission.values()) { String text = permission.name().replace("_", " ").toLowerCase(Locale.ROOT); - given(helpMessagesService.getMessage(permission)) - .willReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); + lenient().when(helpMessagesService.getMessage(permission)) + .thenReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); } for (HelpSection section : HelpSection.values()) { String text = section.name().replace("_", " ").toLowerCase(Locale.ROOT); - given(helpMessagesService.getMessage(section)) - .willReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); + lenient().when(helpMessagesService.getMessage(section)) + .thenReturn(text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1)); } } diff --git a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java index 6743a5c4e..158428524 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/LimboServiceTest.java @@ -1,7 +1,5 @@ package fr.xephi.authme.data.limbo; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.persistence.LimboPersistence; @@ -16,10 +14,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; -import java.util.Collection; +import java.util.Arrays; import java.util.Collections; import java.util.Map; @@ -31,6 +31,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; @@ -39,13 +40,13 @@ /** * Test for {@link LimboService}, and {@link LimboServiceHelper}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class LimboServiceTest { - @InjectDelayed + @InjectMocks private LimboService limboService; - @InjectDelayed + @InjectMocks private LimboServiceHelper limboServiceHelper; @Mock @@ -73,7 +74,7 @@ static void initLogger() { @BeforeEach void mockSettings() { - given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); + ReflectionTestUtils.setField(limboService, "helper", limboServiceHelper); } @Test @@ -85,6 +86,7 @@ void shouldCreateLimboPlayer() { given(permissionsManager.hasGroupSupport()).willReturn(true); given(permissionsManager.getGroups(player)).willReturn(Collections.singletonList(new UserGroup("permgrwp"))); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); // when limboService.createLimboPlayer(player, true); @@ -116,6 +118,7 @@ void shouldNotKeepOpStatusForUnregisteredPlayer() { given(spawnLoader.getPlayerLocationOrSpawn(player)).willReturn(playerLoc); given(permissionsManager.hasGroupSupport()).willReturn(false); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.RESTORE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); // when limboService.createLimboPlayer(player, false); @@ -146,6 +149,7 @@ void shouldClearTasksOnAlreadyExistingLimbo() { getLimboMap().put("carlos", existingLimbo); Player player = newPlayer("Carlos"); given(settings.getProperty(LimboSettings.RESTORE_ALLOW_FLIGHT)).willReturn(AllowFlightRestoreType.ENABLE); + given(settings.getProperty(RestrictionSettings.ALLOW_UNAUTHED_MOVEMENT)).willReturn(false); // when limboService.createLimboPlayer(player, false); @@ -161,8 +165,7 @@ void shouldClearTasksOnAlreadyExistingLimbo() { @Test void shouldRestoreData() { // given - LimboPlayer limbo = Mockito.spy(convertToLimboPlayer( - newPlayer("John", true, 0.4f, false, 0.0f), null, Collections.emptyList())); + LimboPlayer limbo = Mockito.spy(newLimboPlayer(null, true, true, 0.4f, 0.0f)); getLimboMap().put("john", limbo); Player player = newPlayer("John", false, 0.2f, false, 0.7f); @@ -234,16 +237,16 @@ private static Player newPlayer(String name) { private static Player newPlayer(String name, boolean isOp, float walkSpeed, boolean canFly, float flySpeed) { Player player = newPlayer(name); - given(player.isOp()).willReturn(isOp); - given(player.getWalkSpeed()).willReturn(walkSpeed); - given(player.getAllowFlight()).willReturn(canFly); - given(player.getFlySpeed()).willReturn(flySpeed); + lenient().when(player.isOp()).thenReturn(isOp); + lenient().when(player.getWalkSpeed()).thenReturn(walkSpeed); + lenient().when(player.getAllowFlight()).thenReturn(canFly); + lenient().when(player.getFlySpeed()).thenReturn(flySpeed); return player; } - private static LimboPlayer convertToLimboPlayer(Player player, Location location, Collection groups) { - return new LimboPlayer(location, player.isOp(), groups, player.getAllowFlight(), - player.getWalkSpeed(), player.getFlySpeed()); + private static LimboPlayer newLimboPlayer(Location location, boolean isOp, + boolean allowFlight, float walkSpeed, float flySpeed, UserGroup... groups) { + return new LimboPlayer(location, isOp, Arrays.asList(groups), allowFlight, walkSpeed, flySpeed); } private Map getLimboMap() { diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java index 4c3b725f3..096b7d6eb 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/DistributedFilesPersistenceHandlerTest.java @@ -1,13 +1,9 @@ package fr.xephi.authme.data.limbo.persistence; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.UserGroup; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.LimboSettings; @@ -16,10 +12,12 @@ import org.bukkit.entity.Player; import org.hamcrest.Matcher; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -37,12 +35,13 @@ import static org.hamcrest.Matchers.nullValue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; /** * Test for {@link DistributedFilesPersistenceHandler}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class DistributedFilesPersistenceHandlerTest { /** Player is in seg32-10110 and should be migrated into seg16-f. */ @@ -72,7 +71,6 @@ class DistributedFilesPersistenceHandlerTest { private static final UUID UNKNOWN_UUID2 = fromString("84d1cc0b-8f12-d04a-e7ba-a067d05cdc39"); - @InjectDelayed private DistributedFilesPersistenceHandler persistenceHandler; @Mock @@ -80,7 +78,6 @@ class DistributedFilesPersistenceHandlerTest { @Mock private BukkitService bukkitService; @TempDir - @DataFolder File dataFolder; private File playerDataFolder; @@ -89,7 +86,7 @@ static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting + @BeforeEach void setUpClasses() throws IOException { given(settings.getProperty(LimboSettings.DISTRIBUTION_SIZE)).willReturn(SegmentSize.SIXTEEN); playerDataFolder = new File(dataFolder, "playerdata"); @@ -104,9 +101,11 @@ void setUpClasses() throws IOException { given(bukkitService.getWorld(anyString())) .willAnswer(invocation -> { World world = mock(World.class); - given(world.getName()).willReturn(invocation.getArgument(0)); + lenient().when(world.getName()).thenReturn(invocation.getArgument(0)); return world; }); + + persistenceHandler = new DistributedFilesPersistenceHandler(dataFolder, bukkitService, settings); } // Note ljacqu 20170314: These tests are a little slow to set up; therefore we sometimes diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java index f9539a577..bef336ce9 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/IndividualFilesPersistenceHandlerTest.java @@ -1,21 +1,19 @@ package fr.xephi.authme.data.limbo.persistence; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.UserGroup; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.util.FileUtils; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -34,30 +32,30 @@ /** * Test for {@link IndividualFilesPersistenceHandler}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class IndividualFilesPersistenceHandlerTest { private static final UUID SAMPLE_UUID = UUID.nameUUIDFromBytes("PersistenceTest".getBytes()); private static final String SOURCE_FOLDER = TestHelper.PROJECT_ROOT + "data/backup/"; - @InjectDelayed private IndividualFilesPersistenceHandler handler; @Mock private BukkitService bukkitService; - @DataFolder @TempDir File dataFolder; - @BeforeInjecting - void copyTestFiles() throws IOException { + @BeforeEach + void copyTestFilesAndInitHandler() throws IOException { File playerFolder = new File(dataFolder, FileUtils.makePath("playerdata", SAMPLE_UUID.toString())); if (!playerFolder.mkdirs()) { throw new IllegalStateException("Cannot create '" + playerFolder.getAbsolutePath() + "'"); } Files.copy(TestHelper.getJarPath(FileUtils.makePath(SOURCE_FOLDER, "sample-folder", "data.json")), new File(playerFolder, "data.json").toPath()); + + handler = new IndividualFilesPersistenceHandler(dataFolder, bukkitService); } @Test diff --git a/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java b/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java index d0eed99bf..9b89a71ed 100644 --- a/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java +++ b/src/test/java/fr/xephi/authme/data/limbo/persistence/LimboPersistenceTest.java @@ -1,9 +1,6 @@ package fr.xephi.authme.data.limbo.persistence; import ch.jalu.injector.factory.Factory; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; @@ -12,9 +9,11 @@ import org.bukkit.entity.Player; import org.hamcrest.Matcher; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.logging.Logger; @@ -37,10 +36,9 @@ /** * Test for {@link LimboPersistence}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class LimboPersistenceTest { - @InjectDelayed private LimboPersistence limboPersistence; @Mock @@ -54,12 +52,13 @@ static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeInjecting + @BeforeEach @SuppressWarnings("unchecked") - void setUpMocks() { + void setUpMocksAndLimboPersistence() { given(settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE)).willReturn(LimboPersistenceType.DISABLED); given(handlerFactory.newInstance(any(Class.class))) .willAnswer(invocation -> mock((Class) invocation.getArgument(0))); + limboPersistence = new LimboPersistence(settings, handlerFactory); } @Test diff --git a/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java b/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java index 07955d59a..0b82dde20 100644 --- a/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java +++ b/src/test/java/fr/xephi/authme/datasource/converter/CrazyLoginConverterTest.java @@ -1,19 +1,18 @@ package fr.xephi.authme.datasource.converter; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.util.List; @@ -32,10 +31,9 @@ /** * Test for {@link CrazyLoginConverter}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class CrazyLoginConverterTest { - @InjectDelayed private CrazyLoginConverter crazyLoginConverter; @Mock @@ -44,7 +42,6 @@ class CrazyLoginConverterTest { @Mock private Settings settings; - @DataFolder private File dataFolder = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "/datasource/converter/"); @BeforeAll @@ -52,6 +49,11 @@ static void initializeLogger() { TestHelper.setupLogger(); } + @BeforeEach + void initConverter() { + crazyLoginConverter = new CrazyLoginConverter(dataFolder, dataSource, settings); + } + @Test void shouldImportUsers() { // given diff --git a/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java b/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java index 7700f27af..db598be02 100644 --- a/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java +++ b/src/test/java/fr/xephi/authme/datasource/converter/LoginSecurityConverterTest.java @@ -1,21 +1,20 @@ package fr.xephi.authme.datasource.converter; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ConverterSettings; import org.bukkit.command.CommandSender; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -39,23 +38,27 @@ /** * Test for {@link LoginSecurityConverter}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class LoginSecurityConverterTest { - @InjectDelayed private LoginSecurityConverter converter; @Mock private DataSource dataSource; @Mock private Settings settings; - @DataFolder + private File dataFolder = new File("."); // not used but required for injection - @BeforeInjecting - void initMocks() { + @BeforeAll + static void initLogger() { TestHelper.setupLogger(); + } + + @BeforeEach + void setUpConverter() { given(settings.getProperty(ConverterSettings.LOGINSECURITY_USE_SQLITE)).willReturn(true); + converter = new LoginSecurityConverter(dataFolder, dataSource, settings); } @Test diff --git a/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java b/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java index 299b70c97..76cc97e8d 100644 --- a/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java +++ b/src/test/java/fr/xephi/authme/listener/ListenerServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.listener; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.service.ValidationService; @@ -13,9 +10,11 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent; import org.bukkit.event.player.PlayerEvent; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -27,10 +26,9 @@ /** * Test for {@link ListenerService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class ListenerServiceTest { - @InjectDelayed private ListenerService listenerService; @Mock @@ -45,9 +43,10 @@ class ListenerServiceTest { @Mock private ValidationService validationService; - @BeforeInjecting - void initializeDefaultSettings() { + @BeforeEach + void setUpMocksAndService() { given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); + listenerService = new ListenerService(settings, dataSource, playerCache, validationService); } @Test diff --git a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java index 7b65a694a..7a426a2ba 100644 --- a/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java +++ b/src/test/java/fr/xephi/authme/mail/EmailServiceTest.java @@ -1,10 +1,6 @@ package fr.xephi.authme.mail; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -12,11 +8,13 @@ import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; @@ -35,17 +33,15 @@ /** * Test for {@link EmailService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class EmailServiceTest { - @InjectDelayed private EmailService emailService; @Mock private Settings settings; @Mock private SendMailSsl sendMailSsl; - @DataFolder @TempDir File dataFolder; @@ -54,17 +50,17 @@ static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - void initFields() { - given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); - given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("mail@example.org"); - given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); - given(sendMailSsl.hasAllInformation()).willReturn(true); + @BeforeEach + void initFieldsAndService() { + emailService = new EmailService(dataFolder, settings, sendMailSsl); } @Test void shouldHaveAllInformation() { - // given / when / then + // given + given(sendMailSsl.hasAllInformation()).willReturn(true); + + // when / then assertThat(emailService.hasAllInformation(), equalTo(true)); } @@ -74,7 +70,9 @@ void shouldSendPasswordMail() throws EmailException { given(settings.getPasswordEmailMessage()) .willReturn("Hi , your new password for is "); given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); HtmlEmail email = mock(HtmlEmail.class); + given(sendMailSsl.hasAllInformation()).willReturn(true); given(sendMailSsl.initializeMail(anyString())).willReturn(email); given(sendMailSsl.sendEmail(anyString(), eq(email))).willReturn(true); @@ -93,6 +91,7 @@ void shouldSendPasswordMail() throws EmailException { @Test void shouldHandleMailCreationError() throws EmailException { // given + given(sendMailSsl.hasAllInformation()).willReturn(true); doThrow(EmailException.class).when(sendMailSsl).initializeMail(anyString()); // when @@ -107,8 +106,10 @@ void shouldHandleMailCreationError() throws EmailException { @Test void shouldHandleMailSendingFailure() throws EmailException { // given + given(sendMailSsl.hasAllInformation()).willReturn(true); given(settings.getPasswordEmailMessage()).willReturn("Hi , your new pass is "); given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); HtmlEmail email = mock(HtmlEmail.class); given(sendMailSsl.initializeMail(anyString())).willReturn(email); given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false); @@ -128,6 +129,7 @@ void shouldHandleMailSendingFailure() throws EmailException { void shouldSendRecoveryCode() throws EmailException { // given given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("serverName"); given(settings.getRecoveryCodeEmailMessage()) .willReturn("Hi , your code on is (valid hours)"); HtmlEmail email = mock(HtmlEmail.class); @@ -163,7 +165,8 @@ void shouldHandleMailCreationErrorForRecoveryCode() throws EmailException { void shouldHandleFailureToSendRecoveryCode() throws EmailException { // given given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7); - given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi , your code is "); + given(settings.getProperty(PluginSettings.SERVER_NAME)).willReturn("Server? I barely know her!"); + given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi , your code is for "); EmailService sendMailSpy = spy(emailService); HtmlEmail email = mock(HtmlEmail.class); given(sendMailSsl.initializeMail(anyString())).willReturn(email); @@ -177,7 +180,6 @@ void shouldHandleFailureToSendRecoveryCode() throws EmailException { verify(sendMailSsl).initializeMail("user@example.com"); ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(String.class); verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email)); - assertThat(messageCaptor.getValue(), equalTo("Hi John, your code is 1DEF77")); + assertThat(messageCaptor.getValue(), equalTo("Hi John, your code is 1DEF77 for Server? I barely know her!")); } - } diff --git a/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java b/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java index 384a26e56..f5cc18078 100644 --- a/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java +++ b/src/test/java/fr/xephi/authme/mail/SendMailSslTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.mail; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.settings.Settings; @@ -13,7 +10,9 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Properties; @@ -27,10 +26,10 @@ /** * Test for {@link SendMailSsl}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class SendMailSslTest { - @InjectDelayed + @InjectMocks private SendMailSsl sendMailSsl; @Mock @@ -41,16 +40,13 @@ static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - void initFields() { + @Test + void shouldHaveAllInformation() { + // given given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn("mail@example.org"); given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); - given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); - } - @Test - void shouldHaveAllInformation() { - // given / when / then + // when / then assertThat(sendMailSsl.hasAllInformation(), equalTo(true)); } @@ -62,8 +58,11 @@ void shouldCreateEmailObject() throws EmailException { given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost); String senderAccount = "sender@example.org"; given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount); + given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(""); + given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); String senderName = "Server administration"; given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName); + given(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT)).willReturn("Recover password"); given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.DEBUG); // when @@ -85,12 +84,15 @@ void shouldCreateEmailObjectWithAddress() throws EmailException { given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(465); String smtpHost = "mail.example.com"; given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost); - String senderAccount = "exampleAccount"; + String senderAccount = "actualsender@example.com"; given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount); String senderAddress = "mail@example.com"; given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(senderAddress); + given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); String senderName = "Server administration"; given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName); + given(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT)).willReturn("Recover password"); + given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); // when HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); @@ -114,6 +116,11 @@ void shouldCreateEmailObjectWithOAuth2() throws EmailException { given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost); String senderMail = "sender@example.org"; given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderMail); + given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(""); + given(settings.getProperty(EmailSettings.MAIL_PASSWORD)).willReturn("pass1234"); + given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn("Admin"); + given(settings.getProperty(EmailSettings.RECOVERY_MAIL_SUBJECT)).willReturn("Ricóber chur pasword ése"); + given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.INFO); // when HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com"); diff --git a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java index 815141626..0e49a4e7e 100644 --- a/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java @@ -305,10 +305,7 @@ private MessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); - MessagesFileHandler messagesFileHandler = new MessagesFileHandler(); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); - ReflectionTestUtils.setField(MessagesFileHandler.class, messagesFileHandler, "messageUpdater", mock(MessageUpdater.class)); + MessagesFileHandler messagesFileHandler = new MessagesFileHandler(dataFolder, settings, mock(MessageUpdater.class)); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } diff --git a/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java b/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java index eb8599cf7..0f8400724 100644 --- a/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java +++ b/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java @@ -3,9 +3,6 @@ import ch.jalu.injector.Injector; import ch.jalu.injector.InjectorBuilder; import ch.jalu.injector.factory.Factory; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -20,10 +17,13 @@ import org.bukkit.event.Event; import org.bukkit.plugin.PluginManager; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.Collections; @@ -48,10 +48,10 @@ /** * Test for {@link PasswordSecurity}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class PasswordSecurityTest { - @InjectDelayed + @InjectMocks private PasswordSecurity passwordSecurity; @Mock @@ -76,7 +76,7 @@ static void setUpTest() { TestHelper.setupLogger(); } - @BeforeInjecting + @BeforeEach void setUpMocks() { caughtClassInEvent = null; @@ -111,6 +111,8 @@ public Void answer(InvocationOnMock invocation) throws Throwable { } return o; }); + + ReflectionTestUtils.invokePostConstructMethods(passwordSecurity); } @Test diff --git a/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java b/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java index 12c489657..a2616b5d2 100644 --- a/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.AdminPermission; @@ -11,10 +8,12 @@ import fr.xephi.authme.settings.properties.ProtectionSettings; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; @@ -35,10 +34,9 @@ /** * Test for {@link AntiBotService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class AntiBotServiceTest { - @InjectDelayed private AntiBotService antiBotService; @Mock @@ -50,14 +48,15 @@ class AntiBotServiceTest { @Mock private BukkitService bukkitService; - @BeforeInjecting - void initSettings() { + @BeforeEach + void initSettingsAndService() { given(settings.getProperty(ProtectionSettings.ANTIBOT_DURATION)).willReturn(10); given(settings.getProperty(ProtectionSettings.ANTIBOT_INTERVAL)).willReturn(5); given(settings.getProperty(ProtectionSettings.ANTIBOT_SENSIBILITY)).willReturn(5); given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(true); given(settings.getProperty(ProtectionSettings.ANTIBOT_DELAY)).willReturn(8); setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + antiBotService = new AntiBotService(settings, messages, permissionsManager, bukkitService); } @Test diff --git a/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java b/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java index dca23ecf6..81d01402f 100644 --- a/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java +++ b/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java @@ -1,15 +1,12 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandInitializer; import fr.xephi.authme.command.help.HelpMessage; import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.command.help.HelpSection; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -17,10 +14,12 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -35,19 +34,11 @@ /** * Integration test for {@link HelpTranslationGenerator}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class HelpTranslationGeneratorIntegrationTest { - @InjectDelayed private HelpTranslationGenerator helpTranslationGenerator; - @InjectDelayed - private HelpMessagesService helpMessagesService; - @InjectDelayed - private HelpMessagesFileHandler helpMessagesFileHandler; - @InjectDelayed - private CommandInitializer commandInitializer; - - @DataFolder + @TempDir File dataFolder; private File helpMessagesFile; @@ -60,13 +51,19 @@ static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeInjecting + @BeforeEach void setUpClasses() throws IOException { File messagesFolder = new File(dataFolder, "messages"); messagesFolder.mkdir(); helpMessagesFile = new File(messagesFolder, "help_test.yml"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/help_test.yml"), helpMessagesFile); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); + + CommandInitializer commandInitializer = new CommandInitializer(); + HelpMessagesFileHandler helpMessagesFileHandler = new HelpMessagesFileHandler(dataFolder, settings); + HelpMessagesService helpMessagesService = new HelpMessagesService(helpMessagesFileHandler); + helpTranslationGenerator = new HelpTranslationGenerator(commandInitializer, helpMessagesService, settings, dataFolder); + ReflectionTestUtils.invokePostConstructMethods(helpMessagesFileHandler); } @Test diff --git a/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java b/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java index 2f71ef731..5c0aad621 100644 --- a/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java @@ -1,8 +1,6 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.mail.EmailService; @@ -11,9 +9,12 @@ import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -24,10 +25,10 @@ /** * Tests for {@link PasswordRecoveryService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class PasswordRecoveryServiceTest { - @InjectDelayed + @InjectMocks private PasswordRecoveryService recoveryService; @Mock @@ -48,10 +49,11 @@ class PasswordRecoveryServiceTest { @Mock private Messages messages; - @BeforeInjecting - void initSettings() { + @BeforeEach + void runPostConstructMethod() { given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40); given(commonService.getProperty(SecuritySettings.PASSWORD_CHANGE_TIMEOUT)).willReturn(2); + ReflectionTestUtils.invokePostConstructMethods(recoveryService); } @Test diff --git a/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java b/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java index b35a50c1f..678a08aa2 100644 --- a/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java @@ -1,15 +1,14 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.expiring.ExpiringMap; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; import static org.hamcrest.MatcherAssert.assertThat; @@ -20,20 +19,21 @@ /** * Test for {@link RecoveryCodeService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class RecoveryCodeServiceTest { - @InjectDelayed private RecoveryCodeService recoveryCodeService; @Mock private Settings settings; - @BeforeInjecting - void initSettings() { + @BeforeEach + void initService() { given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(4); given(settings.getProperty(SecuritySettings.RECOVERY_CODE_LENGTH)).willReturn(5); given(settings.getProperty(SecuritySettings.RECOVERY_CODE_MAX_TRIES)).willReturn(3); + + recoveryCodeService = new RecoveryCodeService(settings); } @Test diff --git a/src/test/java/fr/xephi/authme/service/SessionServiceTest.java b/src/test/java/fr/xephi/authme/service/SessionServiceTest.java index 8a186084e..f9182d29b 100644 --- a/src/test/java/fr/xephi/authme/service/SessionServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/SessionServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -11,9 +8,11 @@ import fr.xephi.authme.settings.properties.PluginSettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; @@ -22,6 +21,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.only; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -31,10 +31,9 @@ /** * Test for {@link SessionService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class SessionServiceTest { - @InjectDelayed private SessionService sessionService; @Mock @@ -49,9 +48,10 @@ static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - void setUpEnabledProperty() { + @BeforeEach + void createSessionService() { given(commonService.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(true); + sessionService = new SessionService(commonService, bukkitService, dataSource); } @Test @@ -83,21 +83,20 @@ void shouldCheckIfUserHasSession() { // then assertThat(result, equalTo(false)); verify(commonService, only()).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource, only()).hasSession(name); } @Test void shouldCheckLastLoginDate() { // given String name = "Bobby"; - String ip = "127.3.12.15"; - Player player = mockPlayerWithNameAndIp(name, ip); + Player player = mock(Player.class); + given(player.getName()).willReturn(name); given(commonService.getProperty(PluginSettings.SESSIONS_TIMEOUT)).willReturn(8); given(dataSource.hasSession(name)).willReturn(true); PlayerAuth auth = PlayerAuth.builder() .name(name) .lastLogin(System.currentTimeMillis() - 10 * 60 * 1000) - .lastIp(ip).build(); + .lastIp("127.3.12.15").build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -105,24 +104,22 @@ void shouldCheckLastLoginDate() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); + verify(player, only()).getName(); } @Test void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { // given String name = "Bobby"; - String ip = "127.3.12.15"; - Player player = mockPlayerWithNameAndIp(name, ip); - given(commonService.getProperty(PluginSettings.SESSIONS_TIMEOUT)).willReturn(8); + Player player = mock(Player.class); + given(player.getName()).willReturn(name); given(dataSource.hasSession(name)).willReturn(true); PlayerAuth auth = PlayerAuth.builder() .name(name) .lastLogin(null) - .lastIp(ip).build(); + .lastIp("127.3.12.15").build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -130,10 +127,9 @@ void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); + verify(player, only()).getName(); } @Test @@ -155,9 +151,7 @@ void shouldCheckLastLoginIp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); verify(commonService).send(player, MessageKey.SESSION_EXPIRED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); } @@ -186,7 +180,6 @@ void shouldEmitEventForValidSession() { verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); verify(commonService).getProperty(PluginSettings.SESSIONS_TIMEOUT); verifyNoMoreInteractions(commonService); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); verify(event).isCancelled(); @@ -196,7 +189,8 @@ void shouldEmitEventForValidSession() { void shouldHandleNullPlayerAuth() { // given String name = "Bobby"; - Player player = mockPlayerWithNameAndIp(name, "127.3.12.15"); + Player player = mock(Player.class); + given(player.getName()).willReturn(name); given(dataSource.hasSession(name)).willReturn(true); given(dataSource.getAuth(name)).willReturn(null); @@ -205,11 +199,9 @@ void shouldHandleNullPlayerAuth() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); - verify(dataSource).getAuth(name); + verify(player, never()).getAddress(); } @Test @@ -222,7 +214,8 @@ void shouldHandlePlayerAuthWithNullLastIp() { PlayerAuth auth = PlayerAuth.builder() .name(name) .lastIp(null) - .lastLogin(System.currentTimeMillis()).build(); + .lastLogin(System.currentTimeMillis() - 2) + .build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -230,11 +223,8 @@ void shouldHandlePlayerAuthWithNullLastIp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); - verify(dataSource).getAuth(name); } private static Player mockPlayerWithNameAndIp(String name, String ip) { diff --git a/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java b/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java index 8de955f64..c18a0a24f 100644 --- a/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java +++ b/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java @@ -1,8 +1,5 @@ package fr.xephi.authme.service; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.base.Strings; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -17,11 +14,14 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; import java.util.Collections; @@ -36,16 +36,17 @@ import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Test for {@link ValidationService}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class ValidationServiceTest { - @InjectDelayed + @InjectMocks private ValidationService validationService; @Mock private Settings settings; @@ -56,20 +57,16 @@ class ValidationServiceTest { @Mock private GeoIpService geoIpService; - @BeforeInjecting - void createService() { + @BeforeEach + void callReload() { given(settings.getProperty(RestrictionSettings.ALLOWED_PASSWORD_REGEX)).willReturn("[a-zA-Z]+"); - given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); - given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); - given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); - given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); - given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc")); given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(false); + validationService.reload(); } @Test void shouldRejectPasswordSameAsUsername() { - // given/when + // given / when ValidationResult error = validationService.validatePassword("bobby", "Bobby"); // then @@ -78,7 +75,7 @@ void shouldRejectPasswordSameAsUsername() { @Test void shouldRejectPasswordNotMatchingPattern() { - // given/when + // given / when // service mock returns pattern a-zA-Z -> numbers should not be accepted ValidationResult error = validationService.validatePassword("invalid1234", "myPlayer"); @@ -88,7 +85,10 @@ void shouldRejectPasswordNotMatchingPattern() { @Test void shouldRejectTooShortPassword() { - // given/when + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + + // when ValidationResult error = validationService.validatePassword("ab", "tester"); // then @@ -97,8 +97,12 @@ void shouldRejectTooShortPassword() { @Test void shouldRejectTooLongPassword() { - // given/when - ValidationResult error = validationService.validatePassword(Strings.repeat("a", 30), "player"); + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + + // when + ValidationResult error = validationService.validatePassword(Strings.repeat("a", 21), "player"); // then assertErrorEquals(error, MessageKey.INVALID_PASSWORD_LENGTH); @@ -106,7 +110,12 @@ void shouldRejectTooLongPassword() { @Test void shouldRejectUnsafePassword() { - // given/when + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); + + // when ValidationResult error = validationService.validatePassword("unsafe", "playertest"); // then @@ -115,7 +124,12 @@ void shouldRejectUnsafePassword() { @Test void shouldAcceptValidPassword() { - // given/when + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); + + // when ValidationResult error = validationService.validatePassword("safePass", "some_user"); // then @@ -140,7 +154,6 @@ void shouldAcceptEmailWithWhitelist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)) .willReturn(asList("domain.tld", "example.com")); - given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); // when boolean result = validationService.validateEmail("TesT@Example.com"); @@ -154,7 +167,6 @@ void shouldRejectEmailNotInWhitelist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)) .willReturn(asList("domain.tld", "example.com")); - given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); // when boolean result = validationService.validateEmail("email@other-domain.abc"); @@ -193,19 +205,19 @@ void shouldRejectEmailInBlacklist() { @Test void shouldRejectInvalidEmail() { - // given/when/then + // given / when / then assertThat(validationService.validateEmail("invalidinput"), equalTo(false)); } @Test void shouldRejectInvalidEmailWithoutDomain() { - // given/when/then + // given / when / then assertThat(validationService.validateEmail("invalidinput@"), equalTo(false)); } @Test void shouldRejectDefaultEmail() { - // given/when/then + // given / when / then assertThat(validationService.validateEmail("your@email.com"), equalTo(false)); } @@ -217,6 +229,7 @@ void shouldAllowRegistration() { given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(false); given(dataSource.countAuthsByEmail(email)).willReturn(2); + given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); @@ -233,6 +246,7 @@ void shouldRejectEmailWithTooManyAccounts() { given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(false); given(dataSource.countAuthsByEmail(email)).willReturn(5); + given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); @@ -248,17 +262,21 @@ void shouldAllowBypassForPresentPermission() { String email = "mail-address@example.com"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(true); - given(dataSource.countAuthsByEmail(email)).willReturn(7); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); // then + verifyNoInteractions(dataSource); assertThat(result, equalTo(true)); } @Test void shouldRecognizeUnrestrictedNames() { + // given + given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc")); + + // when / then assertThat(validationService.isUnrestricted("npc"), equalTo(true)); assertThat(validationService.isUnrestricted("someplayer"), equalTo(false)); assertThat(validationService.isUnrestricted("NAME01"), equalTo(true)); @@ -288,7 +306,6 @@ void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { void shouldAcceptCountryInWhitelist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(asList("ch", "it")); - given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); String ip = "127.0.0.1"; given(geoIpService.getCountryCode(ip)).willReturn("CH"); @@ -297,14 +314,12 @@ void shouldAcceptCountryInWhitelist() { // then assertThat(result, equalTo(true)); - verify(geoIpService).getCountryCode(ip); } @Test void shouldRejectCountryMissingFromWhitelist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(asList("ch", "it")); - given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); String ip = "123.45.67.89"; given(geoIpService.getCountryCode(ip)).willReturn("BR"); @@ -313,7 +328,6 @@ void shouldRejectCountryMissingFromWhitelist() { // then assertThat(result, equalTo(false)); - verify(geoIpService).getCountryCode(ip); } @Test @@ -345,7 +359,6 @@ void shouldRejectCountryInBlacklist() { // then assertThat(result, equalTo(false)); - verify(geoIpService).getCountryCode(ip); } @Test @@ -363,7 +376,8 @@ void shouldCheckNameRestrictions() { Player emanuel = mockPlayer("emanuel", "94.65.24.10"); Player emanuel2 = mockPlayer("emanuel", "94.65.60.10"); Player imYourIsp = mockPlayer("imyourisp", "65.65.65.65"); - Player notRestricted = mockPlayer("notRestricted", "0.0.0.0"); + Player notRestricted = mock(Player.class); + given(notRestricted.getName()).willReturn("notRestricted"); ValidationService validationServiceSpy = Mockito.spy(validationService); willReturn("bogus.tld").given(validationServiceSpy).getHostName(any(InetSocketAddress.class)); @@ -389,6 +403,7 @@ void shouldCheckNameRestrictions() { assertThat(isEmanuel2Admitted, equalTo(false)); assertThat(isImYourIspAdmitted, equalTo(true)); assertThat(isNotRestrictedAdmitted, equalTo(true)); + verify(notRestricted, only()).getName(); } @Test diff --git a/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java b/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java index a04c474af..8e947c085 100644 --- a/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java +++ b/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java @@ -1,20 +1,18 @@ package fr.xephi.authme.settings; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -27,10 +25,9 @@ /** * Test for {@link SpawnLoader}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class SpawnLoaderTest { - @InjectDelayed private SpawnLoader spawnLoader; @Mock @@ -39,11 +36,10 @@ class SpawnLoaderTest { @Mock private PluginHookService pluginHookService; - @DataFolder @TempDir File testFolder; - @BeforeInjecting + @BeforeEach void setup() throws IOException { // Copy test config into a new temporary folder File source = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/spawn-firstspawn.yml"); @@ -53,6 +49,7 @@ void setup() throws IOException { // Create a settings mock with default values given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)) .willReturn("authme, essentials, multiverse, default"); + spawnLoader = new SpawnLoader(testFolder, settings, pluginHookService); } @Test @@ -73,5 +70,4 @@ void shouldSetSpawn() { assertThat(configuration.getDouble("spawn.z"), equalTo(-67.89)); assertThat(configuration.getString("spawn.world"), equalTo("new_world")); } - } diff --git a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java index 969fd3579..4e7496428 100644 --- a/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java +++ b/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java @@ -1,11 +1,8 @@ package fr.xephi.authme.settings; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.DelayedInjectionExtension; -import ch.jalu.injector.testing.InjectDelayed; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.GeoIpService; @@ -14,10 +11,13 @@ import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -36,10 +36,10 @@ /** * Test for {@link WelcomeMessageConfiguration}. */ -@ExtendWith(DelayedInjectionExtension.class) +@ExtendWith(MockitoExtension.class) class WelcomeMessageConfigurationTest { - @InjectDelayed + @InjectMocks private WelcomeMessageConfiguration welcomeMessageConfiguration; @Mock private Server server; @@ -51,17 +51,17 @@ class WelcomeMessageConfigurationTest { private PlayerCache playerCache; @Mock private CommonService service; - @DataFolder @TempDir File testPluginFolder; private File welcomeFile; - @BeforeInjecting - void createPluginFolder() throws IOException { + @BeforeEach + void createWelcomeFileAndSetPluginFolder() throws IOException { welcomeFile = new File(testPluginFolder, "welcome.txt"); welcomeFile.createNewFile(); given(service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE)).willReturn(true); + ReflectionTestUtils.setField(welcomeMessageConfiguration, "pluginFolder", testPluginFolder); } @Test