[AB-57] [AB-61] reworked commands and services to work with completable futures and moved the database operations to the very last operation so we have transaction safety in more areas

added some cache annotations to the default repository functions
reworked how the undo cations are processed within commands, they are executed in a post command listener when the state is error
added a counter id to generate ids to be unique within servers, changed a few tables to be unique within a server
added future utils class for wrapping a list of futures into one
moved abstracto tables to separate schema in the installer
refactored experience gain to work with more futures and delayed database access
This commit is contained in:
Sheldan
2020-09-20 11:11:20 +02:00
parent 552ecc26b8
commit 76adda90a3
220 changed files with 2691 additions and 1498 deletions

View File

@@ -10,6 +10,7 @@ import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.template.commands.serverinfo.ServerInfoModel;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,6 +18,7 @@ import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class ServerInfo extends AbstractConditionableCommand {
@@ -25,11 +27,11 @@ public class ServerInfo extends AbstractConditionableCommand {
private ChannelService channelService;
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
ServerInfoModel model = (ServerInfoModel) ContextConverter.fromCommandContext(commandContext, ServerInfoModel.class);
model.setGuild(commandContext.getGuild());
channelService.sendEmbedTemplateInChannel("serverinfo_response", model, commandContext.getChannel());
return CommandResult.fromSuccess();
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel("serverinfo_response", model, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
@@ -40,6 +42,7 @@ public class ServerInfo extends AbstractConditionableCommand {
.name("serverInfo")
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.async(true)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)

View File

@@ -10,6 +10,7 @@ import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.template.commands.ShowAvatarModel;
import net.dv8tion.jda.api.entities.Member;
@@ -18,6 +19,7 @@ import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class ShowAvatar extends AbstractConditionableCommand {
@@ -27,14 +29,14 @@ public class ShowAvatar extends AbstractConditionableCommand {
private ChannelService channelService;
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
checkParameters(commandContext);
List<Object> parameters = commandContext.getParameters().getParameters();
Member memberToShow = parameters.size() == 1 ? (Member) parameters.get(0) : commandContext.getUserInitiatedContext().getMember();
ShowAvatarModel model = (ShowAvatarModel) ContextConverter.fromCommandContext(commandContext, ShowAvatarModel.class);
model.setMemberInfo(memberToShow);
channelService.sendEmbedTemplateInChannel(SHOW_AVATAR_RESPONSE_TEMPLATE, model, commandContext.getChannel());
return CommandResult.fromSuccess();
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel(SHOW_AVATAR_RESPONSE_TEMPLATE, model, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
@@ -46,6 +48,7 @@ public class ShowAvatar extends AbstractConditionableCommand {
.name("showAvatar")
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.async(true)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)

View File

@@ -8,6 +8,7 @@ import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.execution.*;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.template.commands.ShowEmoteLog;
import net.dv8tion.jda.api.entities.Emote;
@@ -16,6 +17,7 @@ import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class ShowEmote extends AbstractConditionableCommand {
@@ -26,14 +28,14 @@ public class ShowEmote extends AbstractConditionableCommand {
private ChannelService channelService;
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
checkParameters(commandContext);
List<Object> parameters = commandContext.getParameters().getParameters();
Emote emoteParameter = (Emote) parameters.get(0);
ShowEmoteLog emoteLog = (ShowEmoteLog) ContextConverter.fromCommandContext(commandContext, ShowEmoteLog.class);
emoteLog.setEmote(emoteParameter);
channelService.sendEmbedTemplateInChannel(SHOW_EMOTE_RESPONSE_TEMPLATE, emoteLog, commandContext.getChannel());
return CommandResult.fromSuccess();
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel(SHOW_EMOTE_RESPONSE_TEMPLATE, emoteLog, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
@@ -45,6 +47,7 @@ public class ShowEmote extends AbstractConditionableCommand {
.name("showEmote")
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.async(true)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)

View File

@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.template.commands.starboard.StarStatsModel;
import dev.sheldan.abstracto.utility.service.StarboardService;
@@ -17,6 +18,7 @@ import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class StarStats extends AbstractConditionableCommand {
@@ -30,10 +32,10 @@ public class StarStats extends AbstractConditionableCommand {
private ChannelService channelService;
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
StarStatsModel result = starboardService.retrieveStarStats(commandContext.getGuild().getIdLong());
channelService.sendEmbedTemplateInChannel(STARSTATS_RESPONSE_TEMPLATE, result, commandContext.getChannel());
return CommandResult.fromSuccess();
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel(STARSTATS_RESPONSE_TEMPLATE, result, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
@@ -44,6 +46,7 @@ public class StarStats extends AbstractConditionableCommand {
.name("starStats")
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.async(true)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)

View File

@@ -11,6 +11,7 @@ import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.service.BotService;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.template.commands.UserInfoModel;
import net.dv8tion.jda.api.entities.Member;
@@ -20,6 +21,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class UserInfo extends AbstractConditionableCommand {
@@ -34,26 +36,27 @@ public class UserInfo extends AbstractConditionableCommand {
private UserInfo self;
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
checkParameters(commandContext);
List<Object> parameters = commandContext.getParameters().getParameters();
Member memberToShow = parameters.size() == 1 ? (Member) parameters.get(0) : commandContext.getAuthor();
UserInfoModel model = (UserInfoModel) ContextConverter.fromCommandContext(commandContext, UserInfoModel.class);
UserInfoModel model = (UserInfoModel) ContextConverter.slimFromCommandContext(commandContext, UserInfoModel.class);
if(!memberToShow.hasTimeJoined()) {
botService.forceReloadMember(memberToShow).thenAccept(member -> {
return botService.forceReloadMember(memberToShow).thenCompose(member -> {
model.setMemberInfo(member);
self.sendResponse(commandContext, model);
return self.sendResponse(commandContext, model)
.thenApply(aVoid -> CommandResult.fromSuccess());
});
} else {
model.setMemberInfo(memberToShow);
self.sendResponse(commandContext, model);
return self.sendResponse(commandContext, model)
.thenApply(aVoid -> CommandResult.fromSuccess());
}
return CommandResult.fromSuccess();
}
@Transactional
public void sendResponse(CommandContext commandContext, UserInfoModel model) {
channelService.sendEmbedTemplateInChannel("userInfo_response", model, commandContext.getChannel());
public CompletableFuture<Void> sendResponse(CommandContext commandContext, UserInfoModel model) {
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel("userInfo_response", model, commandContext.getChannel()));
}
@Override
@@ -65,6 +68,7 @@ public class UserInfo extends AbstractConditionableCommand {
.name("userInfo")
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.async(true)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)

View File

@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.core.command.execution.*;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.database.Reminder;
import dev.sheldan.abstracto.utility.models.template.commands.reminder.ReminderModel;
@@ -20,6 +21,7 @@ import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class Remind extends AbstractConditionableCommand {
@@ -33,7 +35,7 @@ public class Remind extends AbstractConditionableCommand {
private ChannelService channelService;
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
checkParameters(commandContext);
List<Object> parameters = commandContext.getParameters().getParameters();
Duration remindTime = (Duration) parameters.get(0);
@@ -44,8 +46,8 @@ public class Remind extends AbstractConditionableCommand {
Reminder createdReminder = remindService.createReminderInForUser(aUserInAServer, text, remindTime, commandContext.getMessage());
remindModel.setReminder(createdReminder);
channelService.sendEmbedTemplateInChannel(REMINDER_EMBED_KEY, remindModel, commandContext.getChannel());
return CommandResult.fromSuccess();
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel(REMINDER_EMBED_KEY, remindModel, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
@@ -56,6 +58,7 @@ public class Remind extends AbstractConditionableCommand {
HelpInfo helpInfo = HelpInfo.builder().templated(true).hasExample(true).build();
return CommandConfiguration.builder()
.name("remind")
.async(true)
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.supportsEmbedException(true)

View File

@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureEnum;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.utility.config.features.UtilityFeature;
import dev.sheldan.abstracto.utility.models.database.Reminder;
import dev.sheldan.abstracto.utility.models.template.commands.reminder.RemindersModel;
@@ -17,6 +18,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class Reminders extends AbstractConditionableCommand {
@@ -30,12 +32,12 @@ public class Reminders extends AbstractConditionableCommand {
@Override
public CommandResult execute(CommandContext commandContext) {
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
List<Reminder> activeReminders = reminderManagementService.getActiveRemindersForUser(commandContext.getUserInitiatedContext().getAUserInAServer());
RemindersModel model = (RemindersModel) ContextConverter.fromCommandContext(commandContext, RemindersModel.class);
model.setReminders(activeReminders);
channelService.sendEmbedTemplateInChannel(REMINDERS_RESPONSE_TEMPLATE, model, commandContext.getChannel());
return CommandResult.fromSuccess();
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel(REMINDERS_RESPONSE_TEMPLATE, model, commandContext.getChannel()))
.thenApply(aVoid -> CommandResult.fromSuccess());
}
@Override
@@ -43,6 +45,7 @@ public class Reminders extends AbstractConditionableCommand {
HelpInfo helpInfo = HelpInfo.builder().templated(true).build();
return CommandConfiguration.builder()
.name("reminders")
.async(true)
.module(UtilityModuleInterface.UTILITY)
.templated(true)
.supportsEmbedException(true)

View File

@@ -30,7 +30,7 @@ public class Suggest extends AbstractConditionableCommand {
String text = (String) parameters.get(0);
SuggestionLog suggestLogModel = (SuggestionLog) ContextConverter.fromCommandContext(commandContext, SuggestionLog.class);
suggestLogModel.setSuggester(commandContext.getAuthor());
return suggestionService.createSuggestion(commandContext.getAuthor(), text, suggestLogModel)
return suggestionService.createSuggestionMessage(commandContext.getAuthor(), text, suggestLogModel)
.thenApply(aVoid -> CommandResult.fromSuccess());
}

View File

@@ -143,7 +143,7 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
private List<AUserInAServer> getUsersExcept(List<Long> users, AUserInAServer author) {
return users.stream().filter(user -> !user.equals(author.getUserInServerId())).map(aLong -> {
Optional<AUserInAServer> aUserInAServer = userInServerManagementService.loadUser(aLong);
Optional<AUserInAServer> aUserInAServer = userInServerManagementService.loadUserConditional(aLong);
return aUserInAServer.orElse(null);
}).filter(Objects::nonNull).collect(Collectors.toList());
}

View File

@@ -2,12 +2,15 @@ package dev.sheldan.abstracto.utility.repository;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.utility.models.database.Reminder;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Repository;
import javax.persistence.QueryHint;
import java.util.List;
import java.util.Optional;
@Repository
public interface ReminderRepository extends JpaRepository<Reminder, Long> {
@@ -17,4 +20,9 @@ public interface ReminderRepository extends JpaRepository<Reminder, Long> {
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
Reminder getByIdAndRemindedUserAndRemindedFalse(Long reminderId, AUserInAServer aUserInAServer);
@NotNull
@Override
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
Optional<Reminder> findById(@NonNull Long aLong);
}

View File

@@ -1,9 +1,19 @@
package dev.sheldan.abstracto.utility.repository;
import dev.sheldan.abstracto.utility.models.database.Suggestion;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Repository;
import javax.persistence.QueryHint;
import java.util.Optional;
@Repository
public interface SuggestionRepository extends JpaRepository<Suggestion, Long> {
@NotNull
@Override
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
Optional<Suggestion> findById(@NonNull Long aLong);
}

View File

@@ -111,7 +111,7 @@ public class MessageEmbedServiceBean implements MessageEmbedService {
@Override
@Transactional
public void embedLink(CachedMessage cachedMessage, TextChannel target, Long userEmbeddingUserInServerId, Message embeddingMessage) {
Optional<AUserInAServer> causeOpt = userInServerManagementService.loadUser(userEmbeddingUserInServerId);
Optional<AUserInAServer> causeOpt = userInServerManagementService.loadUserConditional(userEmbeddingUserInServerId);
if(causeOpt.isPresent()) {
AUserInAServer cause = causeOpt.get();
MessageEmbeddedModel messageEmbeddedModel = buildTemplateParameter(embeddingMessage, cachedMessage);
@@ -123,7 +123,7 @@ public class MessageEmbedServiceBean implements MessageEmbedService {
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenAccept(aVoid -> {
try {
Message createdMessage = completableFutures.get(0).get();
Optional<AUserInAServer> innerCauseOpt = userInServerManagementService.loadUser(userInServerId);
Optional<AUserInAServer> innerCauseOpt = userInServerManagementService.loadUserConditional(userInServerId);
innerCauseOpt.ifPresent(aUserInAServer -> {
messageEmbedPostManagementService.createMessageEmbed(cachedMessage, createdMessage, aUserInAServer);
messageService.addReactionToMessage(REMOVAL_EMOTE, cachedMessage.getServerId(), createdMessage);

View File

@@ -102,7 +102,7 @@ public class StarboardServiceBean implements StarboardService {
@Transactional
public void persistPost(CachedMessage message, List<Long> userExceptAuthorIds, List<CompletableFuture<Message>> completableFutures, Long starboardChannelId, Long starredUserId, Long userReactingId) {
AUserInAServer innerStarredUser = userInServerManagementService.loadUser(starredUserId).orElseThrow(() -> new UserInServerNotFoundException(starredUserId));
AUserInAServer innerStarredUser = userInServerManagementService.loadUserConditional(starredUserId).orElseThrow(() -> new UserInServerNotFoundException(starredUserId));
try {
AChannel starboardChannel = channelManagementService.loadChannel(starboardChannelId);
Message message1 = completableFutures.get(0).get();
@@ -117,7 +117,7 @@ public class StarboardServiceBean implements StarboardService {
log.warn("There are no user ids except the author for the reactions in post {} in guild {} for message {} in channel {}.", starboardPost.getId(), message.getChannelId(), message.getMessageId(), message.getChannelId());
}
userExceptAuthorIds.forEach(aLong -> {
AUserInAServer user = userInServerManagementService.loadUser(aLong).orElseThrow(() -> new UserInServerNotFoundException(aLong));
AUserInAServer user = userInServerManagementService.loadUserConditional(aLong).orElseThrow(() -> new UserInServerNotFoundException(aLong));
starboardPostReactorManagementService.addReactor(starboardPost, user);
});
} catch (InterruptedException | ExecutionException e) {

View File

@@ -1,9 +1,9 @@
package dev.sheldan.abstracto.utility.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.exception.GuildNotFoundException;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.service.CounterService;
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
import dev.sheldan.abstracto.templating.model.MessageToSend;
import dev.sheldan.abstracto.core.service.BotService;
@@ -28,7 +28,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@Component
@Slf4j
@@ -37,6 +36,7 @@ public class SuggestionServiceBean implements SuggestionService {
public static final String SUGGESTION_LOG_TEMPLATE = "suggest_log";
public static final String SUGGESTION_YES_EMOTE = "suggestionYes";
public static final String SUGGESTION_NO_EMOTE = "suggestionNo";
public static final String SUGGESTION_COUNTER_KEY = "suggestion";
@Autowired
private SuggestionManagementService suggestionManagementService;
@@ -59,32 +59,34 @@ public class SuggestionServiceBean implements SuggestionService {
@Autowired
private SuggestionServiceBean self;
@Autowired
private CounterService counterService;
@Override
public CompletableFuture<Void> createSuggestion(Member member, String text, SuggestionLog suggestionLog) {
Suggestion suggestion = suggestionManagementService.createSuggestion(member, text);
suggestionLog.setSuggestion(suggestion);
suggestionLog.setSuggesterUser(suggestion.getSuggester());
public CompletableFuture<Void> createSuggestionMessage(Member member, String text, SuggestionLog suggestionLog) {
Long newSuggestionId = counterService.getNextCounterValue(suggestionLog.getServer(), SUGGESTION_COUNTER_KEY);
suggestionLog.setSuggestionId(newSuggestionId);
suggestionLog.setState(SuggestionState.NEW);
suggestionLog.setSuggesterUser(suggestionLog.getAUserInAServer());
suggestionLog.setText(text);
Long suggestionId = suggestion.getId();
MessageToSend messageToSend = templateService.renderEmbedTemplate(SUGGESTION_LOG_TEMPLATE, suggestionLog);
long guildId = member.getGuild().getIdLong();
List<CompletableFuture<Message>> completableFutures = postTargetService.sendEmbedInPostTarget(messageToSend, SuggestionPostTarget.SUGGESTION, guildId);
return CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenCompose(aVoid -> {
Suggestion innerSuggestion = suggestionManagementService.getSuggestion(suggestionId).orElseThrow(() -> new SuggestionNotFoundException(suggestionId));
try {
Message message = completableFutures.get(0).get();
suggestionManagementService.setPostedMessage(innerSuggestion, message);
CompletableFuture<Void> firstReaction = messageService.addReactionToMessageWithFuture(SUGGESTION_YES_EMOTE, guildId, message);
CompletableFuture<Void> secondReaction = messageService.addReactionToMessageWithFuture(SUGGESTION_NO_EMOTE, guildId, message);
return CompletableFuture.allOf(firstReaction, secondReaction);
} catch (InterruptedException | ExecutionException e) {
log.warn("Failed to post suggestion", e);
Thread.currentThread().interrupt();
}
throw new AbstractoRunTimeException();
Message message = completableFutures.get(0).join();
CompletableFuture<Void> firstReaction = messageService.addReactionToMessageWithFuture(SUGGESTION_YES_EMOTE, guildId, message);
CompletableFuture<Void> secondReaction = messageService.addReactionToMessageWithFuture(SUGGESTION_NO_EMOTE, guildId, message);
return CompletableFuture.allOf(firstReaction, secondReaction).thenAccept(aVoid1 ->
self.persistSuggestionInDatabase(member, text, message, newSuggestionId)
);
});
}
@Transactional
public void persistSuggestionInDatabase(Member member, String text, Message message, Long suggestionId) {
suggestionManagementService.createSuggestion(member, text, message, suggestionId);
}
@Override
public CompletableFuture<Void> acceptSuggestion(Long suggestionId, String text, SuggestionLog suggestionLog) {
Suggestion suggestion = suggestionManagementService.getSuggestion(suggestionId).orElseThrow(() -> new SuggestionNotFoundException(suggestionId));
@@ -107,7 +109,8 @@ public class SuggestionServiceBean implements SuggestionService {
Guild guildById = guildByIdOptional.get();
Member memberById = guildById.getMemberById(suggester.getUserReference().getId());
suggestionLog.setSuggester(memberById);
suggestionLog.setSuggestion(suggestion);
suggestionLog.setState(suggestion.getState());
suggestionLog.setSuggestionId(suggestion.getId());
TextChannel textChannelById = guildById.getTextChannelById(channelId);
if(textChannelById != null) {
return textChannelById.retrieveMessageById(originalMessageId).submit().thenCompose(message ->

View File

@@ -32,19 +32,24 @@ public class SuggestionManagementServiceBean implements SuggestionManagementServ
private ServerManagementService serverManagementService;
@Override
public Suggestion createSuggestion(Member suggester, String text) {
public Suggestion createSuggestion(Member suggester, String text, Message message, Long suggestionId) {
AUserInAServer user = userInServerManagementService.loadUser(suggester);
return this.createSuggestion(user, text);
return this.createSuggestion(user, text, message, suggestionId);
}
@Override
public Suggestion createSuggestion(AUserInAServer suggester, String text) {
public Suggestion createSuggestion(AUserInAServer suggester, String text, Message message, Long suggestionId) {
long channelId = message.getChannel().getIdLong();
AChannel channel = channelManagementService.loadChannel(channelId);
Suggestion suggestion = Suggestion
.builder()
.state(SuggestionState.NEW)
.suggester(suggester)
.id(suggestionId)
.server(suggester.getServerReference())
.suggestionDate(Instant.now())
.channel(channel)
.messageId(message.getIdLong())
.build();
suggestionRepository.save(suggestion);
return suggestion;
@@ -56,15 +61,6 @@ public class SuggestionManagementServiceBean implements SuggestionManagementServ
}
@Override
public void setPostedMessage(Suggestion suggestion, Message message) {
long channelId = message.getChannel().getIdLong();
AChannel channel = channelManagementService.loadChannel(channelId);
suggestion.setChannel(channel);
suggestion.setMessageId(message.getIdLong());
suggestionRepository.save(suggestion);
}
@Override
public void setSuggestionState(Suggestion suggestion, SuggestionState newState) {
suggestion.setState(newState);

View File

@@ -12,6 +12,8 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
@@ -26,9 +28,9 @@ public class ServerInfoTest {
@Test
public void executeCommand() {
CommandContext context = CommandTestUtilities.getNoParameters();
CommandResult result = testUnit.execute(context);
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq("serverinfo_response"), any(ServerInfoModel.class), eq(context.getChannel()));
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test

View File

@@ -15,6 +15,7 @@ import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@@ -32,28 +33,28 @@ public class ShowAvatarTest {
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test
public void executeWithoutParameter() {
CommandContext noParameters = CommandTestUtilities.getNoParameters();
CommandResult result = testUnit.execute(noParameters);
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(ShowAvatar.SHOW_AVATAR_RESPONSE_TEMPLATE), argumentCaptor.capture(), eq(noParameters.getChannel()));
ShowAvatarModel usedModel = argumentCaptor.getValue();
Assert.assertEquals(noParameters.getAuthor(), usedModel.getMemberInfo());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test
public void executeWithParameter() {
Member target = Mockito.mock(Member.class);
CommandContext noParameters = CommandTestUtilities.getWithParameters(Arrays.asList(target));
CommandResult result = testUnit.execute(noParameters);
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(ShowAvatar.SHOW_AVATAR_RESPONSE_TEMPLATE), argumentCaptor.capture(), eq(noParameters.getChannel()));
ShowAvatarModel usedModel = argumentCaptor.getValue();
Assert.assertEquals(target, usedModel.getMemberInfo());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test

View File

@@ -16,6 +16,7 @@ import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@@ -33,21 +34,21 @@ public class ShowEmoteTest {
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test(expected = InsufficientParametersException.class)
public void testTooLittleParameters() {
CommandTestUtilities.executeNoParametersTest(testUnit);
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
}
@Test
public void executeCommandWithOneEmote() {
Emote emote = Mockito.mock(Emote.class);
CommandContext noParameters = CommandTestUtilities.getWithParameters(Arrays.asList(emote));
CommandResult result = testUnit.execute(noParameters);
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(ShowEmote.SHOW_EMOTE_RESPONSE_TEMPLATE), emoteLogArgumentCaptor.capture(), eq(noParameters.getChannel()));
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
ShowEmoteLog usedLog = emoteLogArgumentCaptor.getValue();
Assert.assertEquals(emote, usedLog.getEmote());
}
@@ -57,9 +58,9 @@ public class ShowEmoteTest {
Emote emote = Mockito.mock(Emote.class);
Emote secondEmote = Mockito.mock(Emote.class);
CommandContext noParameters = CommandTestUtilities.getWithParameters(Arrays.asList(emote, secondEmote));
CommandResult result = testUnit.execute(noParameters);
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(ShowEmote.SHOW_EMOTE_RESPONSE_TEMPLATE), emoteLogArgumentCaptor.capture(), eq(noParameters.getChannel()));
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
ShowEmoteLog usedLog = emoteLogArgumentCaptor.getValue();
Assert.assertEquals(emote, usedLog.getEmote());
}

View File

@@ -13,6 +13,8 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
@@ -33,9 +35,9 @@ public class StarStatsTest {
when(noParameters.getGuild().getIdLong()).thenReturn(noParameters.getUserInitiatedContext().getChannel().getId());
StarStatsModel starStatsModel = StarStatsModel.builder().build();
when(starboardService.retrieveStarStats(noParameters.getGuild().getIdLong())).thenReturn(starStatsModel);
CommandResult result = testUnit.execute(noParameters);
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
verify(channelService, times(1)).sendEmbedTemplateInChannel(StarStats.STARSTATS_RESPONSE_TEMPLATE, starStatsModel, noParameters.getChannel());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test

View File

@@ -40,18 +40,19 @@ public class UserInfoTest {
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test
public void executeWithoutParameterAndLoadedMember() {
CommandContext noParameters = CommandTestUtilities.getNoParameters();
when(noParameters.getAuthor().hasTimeJoined()).thenReturn(true);
CommandResult result = testUnit.execute(noParameters);
when(self.sendResponse(eq(noParameters),any(UserInfoModel.class))).thenReturn(CompletableFuture.completedFuture(null));
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
verify(self, times(1)).sendResponse(eq(noParameters), modelArgumentCaptor.capture());
UserInfoModel usedModel = modelArgumentCaptor.getValue();
Assert.assertEquals(noParameters.getAuthor(), usedModel.getMemberInfo());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test
@@ -60,11 +61,11 @@ public class UserInfoTest {
when(noParameters.getAuthor().hasTimeJoined()).thenReturn(false);
Member loadedAuthor = Mockito.mock(Member.class);
when(botService.forceReloadMember(noParameters.getAuthor())).thenReturn(CompletableFuture.completedFuture(loadedAuthor));
CommandResult result = testUnit.execute(noParameters);
verify(self, times(1)).sendResponse(eq(noParameters), modelArgumentCaptor.capture());
when(self.sendResponse(eq(noParameters), modelArgumentCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
UserInfoModel usedModel = modelArgumentCaptor.getValue();
Assert.assertEquals(loadedAuthor, usedModel.getMemberInfo());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test
@@ -72,11 +73,11 @@ public class UserInfoTest {
Member member = Mockito.mock(Member.class);
when(member.hasTimeJoined()).thenReturn(true);
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(member));
CommandResult result = testUnit.execute(parameters);
verify(self, times(1)).sendResponse(eq(parameters), modelArgumentCaptor.capture());
when(self.sendResponse(eq(parameters), modelArgumentCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
UserInfoModel usedModel = modelArgumentCaptor.getValue();
Assert.assertEquals(member, usedModel.getMemberInfo());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test
@@ -86,11 +87,11 @@ public class UserInfoTest {
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(member));
Member loadedAuthor = Mockito.mock(Member.class);
when(botService.forceReloadMember(member)).thenReturn(CompletableFuture.completedFuture(loadedAuthor));
CommandResult result = testUnit.execute(parameters);
verify(self, times(1)).sendResponse(eq(parameters), modelArgumentCaptor.capture());
when(self.sendResponse(eq(parameters), modelArgumentCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
UserInfoModel usedModel = modelArgumentCaptor.getValue();
Assert.assertEquals(loadedAuthor, usedModel.getMemberInfo());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test

View File

@@ -20,6 +20,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@@ -40,18 +41,18 @@ public class RemindTest {
@Test(expected = InsufficientParametersException.class)
public void testTooLittleParameters() {
CommandTestUtilities.executeNoParametersTest(testUnit);
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
}
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test(expected = InsufficientParametersException.class)
public void testOnlyRemindDateParameter() {
CommandContext durationParameter = CommandTestUtilities.getWithParameters(Arrays.asList(Duration.ofDays(4)));
testUnit.execute(durationParameter);
testUnit.executeAsync(durationParameter);
}
@Test
@@ -59,13 +60,13 @@ public class RemindTest {
String reminderText = "text";
Duration duration = Duration.ofMinutes(10);
CommandContext withParameters = CommandTestUtilities.getWithParameters(Arrays.asList(duration, reminderText));
CommandResult result = testUnit.execute(withParameters);
CompletableFuture<CommandResult> result = testUnit.executeAsync(withParameters);
verify(remindService, times(1)).createReminderInForUser(withParameters.getUserInitiatedContext().getAUserInAServer(), reminderText, duration, withParameters.getMessage());
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(Remind.REMINDER_EMBED_KEY), captor.capture(), eq(withParameters.getChannel()));
ReminderModel reminderModel = captor.getValue();
Assert.assertEquals(reminderText, reminderModel.getRemindText());
Assert.assertEquals(withParameters.getMessage(), reminderModel.getMessage());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test

View File

@@ -19,6 +19,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@@ -44,13 +45,13 @@ public class RemindersTest {
Reminder secondReminder = Reminder.builder().build();
List<Reminder> reminders = Arrays.asList(reminder, secondReminder);
when(reminderManagementService.getActiveRemindersForUser(context.getUserInitiatedContext().getAUserInAServer())).thenReturn(reminders);
CommandResult result = testUnit.execute(context);
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(Reminders.REMINDERS_RESPONSE_TEMPLATE), modelCaptor.capture(), eq(context.getChannel()));
RemindersModel usedModel = modelCaptor.getValue();
Assert.assertEquals(reminder, usedModel.getReminders().get(0));
Assert.assertEquals(secondReminder, usedModel.getReminders().get(1));
Assert.assertEquals(reminders.size(), usedModel.getReminders().size());
CommandTestUtilities.checkSuccessfulCompletion(result);
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
}
@Test

View File

@@ -33,12 +33,12 @@ public class AcceptTest {
@Test(expected = InsufficientParametersException.class)
public void testTooLittleParameters() {
CommandTestUtilities.executeAsyncNoParametersTest(testUnit);
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
}
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeAsyncWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test

View File

@@ -33,12 +33,12 @@ public class RejectTest {
@Test(expected = InsufficientParametersException.class)
public void testTooLittleParameters() {
CommandTestUtilities.executeAsyncNoParametersTest(testUnit);
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
}
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeAsyncWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test
public void testExecuteCommand() throws ExecutionException, InterruptedException {

View File

@@ -31,21 +31,21 @@ public class SuggestTest {
@Test(expected = InsufficientParametersException.class)
public void testTooLittleParameters() {
CommandTestUtilities.executeAsyncNoParametersTest(testUnit);
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
}
@Test(expected = IncorrectParameterException.class)
public void testIncorrectParameterType() {
CommandTestUtilities.executeAsyncWrongParametersTest(testUnit);
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
}
@Test
public void testExecuteCommand() throws ExecutionException, InterruptedException {
String text = "text";
CommandContext context = CommandTestUtilities.getWithParameters(Arrays.asList(text));
when(suggestionService.createSuggestion(eq(context.getAuthor()), eq(text), any(SuggestionLog.class))).thenReturn(CompletableFuture.completedFuture(null));
when(suggestionService.createSuggestionMessage(eq(context.getAuthor()), eq(text), any(SuggestionLog.class))).thenReturn(CompletableFuture.completedFuture(null));
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
verify(suggestionService, times(1)).createSuggestion(eq(context.getAuthor()), eq(text), any(SuggestionLog.class));
verify(suggestionService, times(1)).createSuggestionMessage(eq(context.getAuthor()), eq(text), any(SuggestionLog.class));
CommandTestUtilities.checkSuccessfulCompletion(result.get());
}

View File

@@ -248,7 +248,7 @@ public class StarboardListenerTest {
when(emoteService.getReactionFromMessageByEmote(cachedMessage, starEmote)).thenReturn(Optional.of(reaction));
when(starboardPostManagementService.findByMessageId(messageId)).thenReturn(Optional.ofNullable(post));
when(userInServerManagementService.loadUser(serverId, author.getUserReference().getId())).thenReturn(author);
when(userInServerManagementService.loadUser(remainingUser.getUserReference().getId())).thenReturn(Optional.of(remainingUser));
when(userInServerManagementService.loadUserConditional(remainingUser.getUserReference().getId())).thenReturn(Optional.of(remainingUser));
when(configManagementService.loadConfig(serverId, StarboardListener.FIRST_LEVEL_THRESHOLD_KEY)).thenReturn(AConfig.builder().longValue(requiredStars).build());
testUnit.executeReactionRemoved(cachedMessage, removeEvent, userRemoving);
verify(emoteService, times(1)).getEmoteOrDefaultEmote(StarboardListener.STAR_EMOTE, serverId);
@@ -272,7 +272,7 @@ public class StarboardListenerTest {
when(emoteService.getReactionFromMessageByEmote(cachedMessage, starEmote)).thenReturn(Optional.of(reaction));
when(starboardPostManagementService.findByMessageId(messageId)).thenReturn(Optional.ofNullable(existingPost));
when(userInServerManagementService.loadUser(serverId, author.getUserReference().getId())).thenReturn(author);
when(userInServerManagementService.loadUser(userAdding.getUserReference().getId())).thenReturn(Optional.of(userAdding));
when(userInServerManagementService.loadUserConditional(userAdding.getUserReference().getId())).thenReturn(Optional.of(userAdding));
when(configManagementService.loadConfig(serverId, StarboardListener.FIRST_LEVEL_THRESHOLD_KEY)).thenReturn(AConfig.builder().longValue(requiredStars).build());
testUnit.executeReactionAdded(cachedMessage, addEvent, userAdding);
verify(emoteService, times(1)).getEmoteOrDefaultEmote(StarboardListener.STAR_EMOTE, serverId);

View File

@@ -202,7 +202,7 @@ public class MessageEmbedServiceBeanTest {
when(guild.getIdLong()).thenReturn(serverId);
when(embeddingMessage.getChannel()).thenReturn(textChannel);
when(userInServerManagementService.loadUser(embeddingMember)).thenReturn(embeddingUser);
when(userInServerManagementService.loadUser(userEmbeddingUserInServerId)).thenReturn(Optional.of(embeddingUser));
when(userInServerManagementService.loadUserConditional(userEmbeddingUserInServerId)).thenReturn(Optional.of(embeddingUser));
when(channelManagementService.loadChannel(channelId)).thenReturn(aChannel);
when(serverManagementService.loadOrCreate(serverId)).thenReturn(server);
when(botService.getMemberInServer(cachedMessage.getServerId(), cachedMessage.getAuthorId())).thenReturn(author);
@@ -223,7 +223,7 @@ public class MessageEmbedServiceBeanTest {
Long firstMessageId = 6L;
CachedMessage cachedMessage = CachedMessage.builder().serverId(serverId).channelId(channelId).messageId(firstMessageId).build();
Long userEmbeddingUserInServerId = 5L;
when(userInServerManagementService.loadUser(userEmbeddingUserInServerId)).thenReturn(Optional.empty());
when(userInServerManagementService.loadUserConditional(userEmbeddingUserInServerId)).thenReturn(Optional.empty());
testUnit.embedLink(cachedMessage, textChannel, userEmbeddingUserInServerId, embeddingMessage);
}

View File

@@ -153,15 +153,15 @@ public class StarboardServiceBeanTest {
Long secondStarrerUserId = 2L;
List<Long> userExceptAuthorIds = Arrays.asList(secondStarrerUserId, userReacting.getUserReference().getId());
List<CompletableFuture<Message>> futures = Arrays.asList(CompletableFuture.completedFuture(sendPost));
when(userInServerManagementService.loadUser(starredUser.getUserInServerId())).thenReturn(Optional.of(starredUser));
when(userInServerManagementService.loadUser(userReacting.getUserInServerId())).thenReturn(Optional.of(userReacting));
when(userInServerManagementService.loadUserConditional(starredUser.getUserInServerId())).thenReturn(Optional.of(starredUser));
when(userInServerManagementService.loadUserConditional(userReacting.getUserInServerId())).thenReturn(Optional.of(userReacting));
AChannel channel = MockUtils.getTextChannel(server, channelId);
when(channelManagementService.loadChannel(channelId)).thenReturn(channel);
StarboardPost post = StarboardPost.builder().build();
when(starboardPostManagementService.createStarboardPost(eq(message), eq(starredUser), any(AServerAChannelMessage.class))).thenReturn(post);
AUserInAServer secondStarrerUserObj = MockUtils.getUserObject(secondStarrerUserId, server);
when(userInServerManagementService.loadUser(secondStarrerUserId)).thenReturn(Optional.of(secondStarrerUserObj));
when(userInServerManagementService.loadUser(userReacting.getUserInServerId())).thenReturn(Optional.of(userReacting));
when(userInServerManagementService.loadUserConditional(secondStarrerUserId)).thenReturn(Optional.of(secondStarrerUserObj));
when(userInServerManagementService.loadUserConditional(userReacting.getUserInServerId())).thenReturn(Optional.of(userReacting));
testUnit.persistPost(message, userExceptAuthorIds, futures, channelId, starredUser.getUserInServerId(), userReacting.getUserInServerId());
verify(starboardPostReactorManagementService, times(2)).addReactor(eq(post), userInAServerArgumentCaptor.capture());
List<AUserInAServer> addedReactors = userInAServerArgumentCaptor.getAllValues();
@@ -218,7 +218,7 @@ public class StarboardServiceBeanTest {
AServer server = MockUtils.getServer();
AUserInAServer userReacting = MockUtils.getUserObject(4L, server);
AUserInAServer starredUser = MockUtils.getUserObject(5L, server);
when(userInServerManagementService.loadUser(starredUser.getUserInServerId())).thenReturn(Optional.empty());
when(userInServerManagementService.loadUserConditional(starredUser.getUserInServerId())).thenReturn(Optional.empty());
executeLoadErrorTest(server, userReacting, starredUser, 10L);
}

View File

@@ -6,6 +6,7 @@ import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.service.BotService;
import dev.sheldan.abstracto.core.service.CounterService;
import dev.sheldan.abstracto.core.service.MessageService;
import dev.sheldan.abstracto.core.service.PostTargetService;
import dev.sheldan.abstracto.templating.model.MessageToSend;
@@ -32,6 +33,7 @@ import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import static dev.sheldan.abstracto.utility.service.SuggestionServiceBean.SUGGESTION_COUNTER_KEY;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
@@ -69,28 +71,39 @@ public class SuggestionServiceBeanTest {
@Mock
private TextChannel textChannel;
@Mock
private CounterService counterService;
@Test
public void testCreateSuggestion() {
public void testCreateSuggestionMessage() {
String suggestionText = "text";
AServer server = MockUtils.getServer();
SuggestionLog log = SuggestionLog.builder().build();
SuggestionLog log = Mockito.mock(SuggestionLog.class);
when(log.getServer()).thenReturn(server);
Long suggestionId = 5L;
Suggestion createdSuggestion = Suggestion.builder().id(suggestionId).build();
when(suggestionCreator.getGuild()).thenReturn(guild);
when(guild.getIdLong()).thenReturn(server.getId());
when(suggestionManagementService.createSuggestion(suggestionCreator, suggestionText)).thenReturn(createdSuggestion);
MessageToSend messageToSend = MessageToSend.builder().build();
when(templateService.renderEmbedTemplate(eq(SuggestionServiceBean.SUGGESTION_LOG_TEMPLATE), any(SuggestionLog.class))).thenReturn(messageToSend);
Message suggestionMessage = Mockito.mock(Message.class);
when(counterService.getNextCounterValue(server, SUGGESTION_COUNTER_KEY)).thenReturn(suggestionId);
List<CompletableFuture<Message>> postingFutures = Arrays.asList(CompletableFuture.completedFuture(suggestionMessage));
when(postTargetService.sendEmbedInPostTarget(messageToSend, SuggestionPostTarget.SUGGESTION, server.getId())).thenReturn(postingFutures);
when(suggestionManagementService.getSuggestion(suggestionId)).thenReturn(Optional.of(createdSuggestion));
testUnit.createSuggestion(suggestionCreator, suggestionText, log);
verify(suggestionManagementService, times(1)).setPostedMessage(createdSuggestion, suggestionMessage);
testUnit.createSuggestionMessage(suggestionCreator, suggestionText, log);
verify( messageService, times(1)).addReactionToMessageWithFuture(SuggestionServiceBean.SUGGESTION_YES_EMOTE, server.getId(), suggestionMessage);
verify( messageService, times(1)).addReactionToMessageWithFuture(SuggestionServiceBean.SUGGESTION_NO_EMOTE, server.getId(), suggestionMessage);
}
@Test
public void testCreateSuggestion() {
Member member = Mockito.mock(Member.class);
String text = "text";
Message message = Mockito.mock(Message.class);
Long suggestionId = 3L;
testUnit.persistSuggestionInDatabase(member, text, message, suggestionId);
verify(suggestionManagementService, times(1)).createSuggestion(member, text, message, suggestionId);
}
@Test
public void testAcceptExistingSuggestion() {
Member suggesterMember = Mockito.mock(Member.class);

View File

@@ -1,6 +1,5 @@
package dev.sheldan.abstracto.utility.service.management;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
@@ -28,6 +27,7 @@ import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class SuggestionManagementServiceBeanTest {
public static final long CHANNEL_ID = 6L;
@InjectMocks
private SuggestionManagementServiceBean testUnit;
@@ -48,7 +48,12 @@ public class SuggestionManagementServiceBeanTest {
AServer server = MockUtils.getServer();
AUserInAServer userInAServer = MockUtils.getUserObject(5L, server);
String text = "text";
Suggestion createdSuggestion = testUnit.createSuggestion(userInAServer, text);
Message message = Mockito.mock(Message.class);
MessageChannel messageChannel = Mockito.mock(MessageChannel.class);
when(messageChannel.getIdLong()).thenReturn(CHANNEL_ID);
when(message.getChannel()).thenReturn(messageChannel);
long suggestionId = 1L;
Suggestion createdSuggestion = testUnit.createSuggestion(userInAServer, text,message, suggestionId);
verify(suggestionRepository, times(1)).save(createdSuggestion);
Assert.assertEquals(SuggestionState.NEW, createdSuggestion.getState());
Assert.assertEquals(userInAServer.getUserInServerId(), createdSuggestion.getSuggester().getUserInServerId());
@@ -61,8 +66,13 @@ public class SuggestionManagementServiceBeanTest {
AServer server = MockUtils.getServer();
AUserInAServer userInAServer = MockUtils.getUserObject(5L, server);
String text = "text";
Message message = Mockito.mock(Message.class);
MessageChannel messageChannel = Mockito.mock(MessageChannel.class);
when(messageChannel.getIdLong()).thenReturn(CHANNEL_ID);
when(message.getChannel()).thenReturn(messageChannel);
when(userInServerManagementService.loadUser(member)).thenReturn(userInAServer);
Suggestion createdSuggestion = testUnit.createSuggestion(member, text);
long suggestionId = 1L;
Suggestion createdSuggestion = testUnit.createSuggestion(member, text, message, suggestionId);
verify(suggestionRepository, times(1)).save(createdSuggestion);
Assert.assertEquals(SuggestionState.NEW, createdSuggestion.getState());
Assert.assertEquals(userInAServer.getUserInServerId(), createdSuggestion.getSuggester().getUserInServerId());
@@ -87,23 +97,6 @@ public class SuggestionManagementServiceBeanTest {
Assert.assertFalse(suggestionOptional.isPresent());
}
@Test
public void testSetPostedMessage() {
Long messageId = 5L;
Long channelId = 6L;
Suggestion suggestion = Suggestion.builder().build();
Message message = Mockito.mock(Message.class);
MessageChannel channel = Mockito.mock(MessageChannel.class);
when(message.getChannel()).thenReturn(channel);
when(channel.getIdLong()).thenReturn(channelId);
when(message.getIdLong()).thenReturn(messageId);
AChannel aChannel = AChannel.builder().id(channelId).build();
when(channelManagementService.loadChannel(channelId)).thenReturn(aChannel);
testUnit.setPostedMessage(suggestion, message);
Assert.assertEquals(messageId, suggestion.getMessageId());
Assert.assertEquals(channelId, suggestion.getChannel().getId());
verify(suggestionRepository, times(1)).save(suggestion);
}
@Test
public void setSuggestionState() {