This commit is contained in:
Erik C. Thauvin 2020-04-27 23:19:16 -07:00
parent 34636ea9f9
commit aba2633dc4
12 changed files with 145 additions and 164 deletions

View file

@ -54,6 +54,14 @@ public final class Constants {
* The debug command. * The debug command.
*/ */
public static final String DEBUG_CMD = "debug"; public static final String DEBUG_CMD = "debug";
/**
* Default IRC Port.
*/
public static final int DEFAULT_PORT = 6667;
/**
* Default IRC Server.
*/
public static final String DEFAULT_SERVER = "irc.freenode.net";
/** /**
* The die command. * The die command.
*/ */

View file

@ -35,6 +35,7 @@ package net.thauvin.erik.mobibot;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.thauvin.erik.mobibot.commands.AbstractCommand; import net.thauvin.erik.mobibot.commands.AbstractCommand;
import net.thauvin.erik.mobibot.commands.AddLog; import net.thauvin.erik.mobibot.commands.AddLog;
import net.thauvin.erik.mobibot.commands.ChannelFeed;
import net.thauvin.erik.mobibot.commands.Cycle; import net.thauvin.erik.mobibot.commands.Cycle;
import net.thauvin.erik.mobibot.commands.Ignore; import net.thauvin.erik.mobibot.commands.Ignore;
import net.thauvin.erik.mobibot.commands.Info; import net.thauvin.erik.mobibot.commands.Info;
@ -122,16 +123,12 @@ public class Mobibot extends PircBot {
ReleaseInfo.PROJECT + " v" + ReleaseInfo.VERSION ReleaseInfo.PROJECT + " v" + ReleaseInfo.VERSION
+ " (" + Utils.green("https://www.mobitopia.org/mobibot/") + ')', + " (" + Utils.green("https://www.mobitopia.org/mobibot/") + ')',
"Written by Erik C. Thauvin (" + Utils.green("https://erik.thauvin.net/") + ')'); "Written by Erik C. Thauvin (" + Utils.green("https://erik.thauvin.net/") + ')');
// Timer // Logger
public static final Timer timer = new Timer(true); private static final Logger LOGGER = LogManager.getLogger(Mobibot.class);
// Default port
private static final int DEFAULT_PORT = 6667;
// Default server
private static final String DEFAULT_SERVER = "irc.freenode.net";
// Maximum number of times the bot will try to reconnect, if disconnected // Maximum number of times the bot will try to reconnect, if disconnected
private static final int MAX_RECONNECT = 10; private static final int MAX_RECONNECT = 10;
// Logger // Timer
private static final Logger logger = LogManager.getLogger(Mobibot.class); private static final Timer TIMER = new Timer(true);
// Ignore command // Ignore command
public final Ignore ignoreCommand; public final Ignore ignoreCommand;
// Automatically post links to Twitter // Automatically post links to Twitter
@ -179,6 +176,7 @@ public class Mobibot extends PircBot {
// Weblog URL // Weblog URL
private String weblogUrl = ""; private String weblogUrl = "";
/** /**
* Creates a new {@link Mobibot} instance. * Creates a new {@link Mobibot} instance.
* *
@ -196,25 +194,20 @@ public class Mobibot extends PircBot {
setName(nickname); setName(nickname);
ircServer = p.getProperty("server", DEFAULT_SERVER); ircServer = p.getProperty("server", Constants.DEFAULT_SERVER);
ircPort = Utils.getIntProperty(p.getProperty("port"), DEFAULT_PORT); ircPort = Utils.getIntProperty(p.getProperty("port"), Constants.DEFAULT_PORT);
ircChannel = channel; ircChannel = channel;
logsDir = logsDirPath; logsDir = logsDirPath;
// Set the logger level // Set the logger level
loggerLevel = logger.getLevel(); loggerLevel = LOGGER.getLevel();
// Load the current entries and backlogs, if any // Load the current entries and backlogs, if any
try { try {
UrlMgr.startup(logsDir + EntriesMgr.CURRENT_XML, logsDir + EntriesMgr.NAV_XML, ircChannel); UrlMgr.startup(logsDir + EntriesMgr.CURRENT_XML, logsDir + EntriesMgr.NAV_XML, ircChannel);
LOGGER.debug("Last feed: {}", UrlMgr.getStartDate());
if (logger.isDebugEnabled()) {
logger.debug("Last feed: {}", UrlMgr.getStartDate());
}
} catch (Exception e) { } catch (Exception e) {
if (logger.isErrorEnabled()) { LOGGER.error("An error occurred while loading the logs.", e);
logger.error("An error occurred while loading the logs.", e);
}
} }
// Initialize the bot // Initialize the bot
@ -273,15 +266,14 @@ public class Mobibot extends PircBot {
addModule(new Ping()); addModule(new Ping());
addModule(new RockPaperScissors()); addModule(new RockPaperScissors());
addModule(new StockQuote()); addModule(new StockQuote());
// Twitter
twitterModule = new Twitter();
addModule(twitterModule);
addModule(new War()); addModule(new War());
addModule(new Weather2()); addModule(new Weather2());
addModule(new WorldTime()); addModule(new WorldTime());
// Twitter module
twitterModule = new Twitter();
addModule(twitterModule);
// Load the modules properties // Load the modules properties
modules.stream().filter(AbstractModule::hasProperties).forEach(module -> { modules.stream().filter(AbstractModule::hasProperties).forEach(module -> {
for (final String s : module.getPropertyKeys()) { for (final String s : module.getPropertyKeys()) {
@ -295,6 +287,11 @@ public class Mobibot extends PircBot {
Boolean.parseBoolean(p.getProperty(Constants.TWITTER_AUTOPOST_PROP, "false")) Boolean.parseBoolean(p.getProperty(Constants.TWITTER_AUTOPOST_PROP, "false"))
&& twitterModule.isEnabled(); && twitterModule.isEnabled();
// Sort the command & module names
Collections.sort(commandsNames);
Collections.sort(opsCommandsNames);
Collections.sort(modulesNames);
// Save the entries // Save the entries
UrlMgr.saveEntries(this, true); UrlMgr.saveEntries(this, true);
} }
@ -418,6 +415,22 @@ public class Mobibot extends PircBot {
} }
} }
/**
* Adds a command.
*
* @param command The command to add.
*/
private void addCommand(final AbstractCommand command) {
commands.add(command);
if (command.isVisible()) {
if (command.isOp()) {
opsCommandsNames.add(command.getCommand());
} else {
commandsNames.add(command.getCommand());
}
}
}
/** /**
* Adds a module. * Adds a module.
* *
@ -426,6 +439,7 @@ public class Mobibot extends PircBot {
private void addModule(final AbstractModule module) { private void addModule(final AbstractModule module) {
modules.add(module); modules.add(module);
modulesNames.add(module.getClass().getSimpleName()); modulesNames.add(module.getClass().getSimpleName());
commandsNames.addAll(module.getCommands());
} }
/** /**
@ -456,11 +470,7 @@ public class Mobibot extends PircBot {
connect(ircServer, ircPort); connect(ircServer, ircPort);
} catch (Exception ex) { } catch (Exception ex) {
if (retries == MAX_RECONNECT) { if (retries == MAX_RECONNECT) {
if (logger.isDebugEnabled()) { LOGGER.debug("Unable to reconnect to {} after {} retries.", ircServer, MAX_RECONNECT, ex);
logger.debug(
"Unable to reconnect to {} after {} retries.", ircServer, MAX_RECONNECT, ex);
}
e.printStackTrace(System.err); e.printStackTrace(System.err);
System.exit(1); System.exit(1);
} }
@ -526,7 +536,7 @@ public class Mobibot extends PircBot {
* @return The bot's logger. * @return The bot's logger.
*/ */
public final Logger getLogger() { public final Logger getLogger() {
return logger; return LOGGER;
} }
/** /**
@ -567,6 +577,15 @@ public class Mobibot extends PircBot {
return buff.toString(); return buff.toString();
} }
/**
* Returns the bot's timer.
*
* @return The timer.
*/
public final Timer getTimer() {
return TIMER;
}
/** /**
* Get today's date for the feed. * Get today's date for the feed.
* *
@ -616,30 +635,6 @@ public class Mobibot extends PircBot {
Utils.helpIndent(Utils.helpFormat("%c " + Constants.HELP_CMD + " <command>", getNick(), isPrivate)), Utils.helpIndent(Utils.helpFormat("%c " + Constants.HELP_CMD + " <command>", getNick(), isPrivate)),
isPrivate); isPrivate);
send(sender, "The commands are:", isPrivate); send(sender, "The commands are:", isPrivate);
if (commandsNames.isEmpty()) {
// Feed command
commandsNames.add(getChannelName());
// Commands
for (final AbstractCommand command : commands) {
if (command.isVisible()) {
if (command.isOp()) {
opsCommandsNames.add(command.getCommand());
} else {
commandsNames.add(command.getCommand());
}
}
}
// Modules commands
modules.stream().filter(AbstractModule::isEnabled)
.forEach(module -> commandsNames.addAll(module.getCommands()));
Collections.sort(commandsNames);
Collections.sort(opsCommandsNames);
}
sendList(sender, commandsNames, 8, isPrivate, true); sendList(sender, commandsNames, 8, isPrivate, true);
if (isOp) { if (isOp) {
send(sender, "The op commands are:", isPrivate); send(sender, "The op commands are:", isPrivate);
@ -749,15 +744,13 @@ public class Mobibot extends PircBot {
@Override @Override
protected final void onMessage(final String channel, final String sender, final String login, final String hostname, protected final void onMessage(final String channel, final String sender, final String login, final String hostname,
final String message) { final String message) {
if (logger.isDebugEnabled()) { LOGGER.debug(">>> {} : {}", sender, message);
logger.debug(">>> {} : {}", sender, message);
if (tell.isEnabled()) {
tell.send(sender, true);
} }
boolean isCommand = false;
if (message.matches(getNickPattern() + ":.*")) { // mobibot: <command> if (message.matches(getNickPattern() + ":.*")) { // mobibot: <command>
isCommand = true;
final String[] cmds = message.substring(message.indexOf(':') + 1).trim().split(" ", 2); final String[] cmds = message.substring(message.indexOf(':') + 1).trim().split(" ", 2);
final String cmd = lowerCase(cmds[0]); final String cmd = lowerCase(cmds[0]);
@ -808,9 +801,7 @@ public class Mobibot extends PircBot {
@Override @Override
protected final void onPrivateMessage(final String sender, final String login, final String hostname, protected final void onPrivateMessage(final String sender, final String login, final String hostname,
final String message) { final String message) {
if (logger.isDebugEnabled()) { LOGGER.debug(">>> {} : {}", sender, message);
logger.debug(">>> {} : {}", sender, message);
}
final String[] cmds = message.split(" ", 2); final String[] cmds = message.split(" ", 2);
final String cmd = lowerCase(cmds[0]); final String cmd = lowerCase(cmds[0]);
@ -828,15 +819,15 @@ public class Mobibot extends PircBot {
sendRawLine("QUIT : Poof!"); sendRawLine("QUIT : Poof!");
System.exit(0); System.exit(0);
} else if (isOp && Constants.DEBUG_CMD.equals(cmd)) { // debug } else if (isOp && Constants.DEBUG_CMD.equals(cmd)) { // debug
if (logger.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
Configurator.setLevel(logger.getName(), loggerLevel); Configurator.setLevel(LOGGER.getName(), loggerLevel);
} else { } else {
Configurator.setLevel(logger.getName(), Level.DEBUG); Configurator.setLevel(LOGGER.getName(), Level.DEBUG);
} }
send(sender, "Debug logging is " + (logger.isDebugEnabled() ? "enabled." : "disabled."), true); send(sender, "Debug logging is " + (LOGGER.isDebugEnabled() ? "enabled." : "disabled."), true);
} else if (isOp && Constants.DIE_CMD.equals(cmd)) { // die } else if (isOp && Constants.DIE_CMD.equals(cmd)) { // die
send(sender + " has just signed my death sentence."); send(sender + " has just signed my death sentence.");
timer.cancel(); TIMER.cancel();
twitterShutdown(); twitterShutdown();
twitterNotification("killed by " + sender + " on " + ircChannel); twitterNotification("killed by " + sender + " on " + ircChannel);
sleep(3); sleep(3);
@ -869,7 +860,7 @@ public class Mobibot extends PircBot {
@Override @Override
protected final void onAction(final String sender, final String login, final String hostname, final String target, protected final void onAction(final String sender, final String login, final String hostname, final String target,
final String action) { final String action) {
if (target != null && target.equals(ircChannel)) { if (ircChannel.equals(target)) {
Recap.storeRecap(sender, action, true); Recap.storeRecap(sender, action, true);
} }
} }
@ -905,16 +896,10 @@ public class Mobibot extends PircBot {
public final void send(final String sender, final String message, final boolean isPrivate) { public final void send(final String sender, final String message, final boolean isPrivate) {
if (isNotBlank(message) && isNotBlank(sender)) { if (isNotBlank(message) && isNotBlank(sender)) {
if (isPrivate) { if (isPrivate) {
if (logger.isDebugEnabled()) { LOGGER.debug("Sending message to {} : {}", sender, message);
logger.debug("Sending message to {} : {}", sender, message);
}
sendMessage(sender, message); sendMessage(sender, message);
} else { } else {
if (logger.isDebugEnabled()) { LOGGER.debug("Sending notice to {} : {}", sender, message);
logger.debug("Sending notice to {} : {}", sender, message);
}
sendNotice(sender, message); sendNotice(sender, message);
} }
} }
@ -1028,7 +1013,7 @@ public class Mobibot extends PircBot {
} }
/** /**
* Add an entry to be posted on twitter. * Add an entry to be posted on Twitter.
* *
* @param index The entry index. * @param index The entry index.
*/ */
@ -1049,11 +1034,12 @@ public class Mobibot extends PircBot {
entry.getTitle() + ' ' + entry.getLink() + " via " + entry.getNick() + " on " + getChannel(); entry.getTitle() + ' ' + entry.getLink() + " via " + entry.getNick() + " on " + getChannel();
new Thread(() -> { new Thread(() -> {
try { try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Posting {}{} to Twitter.", Constants.LINK_CMD, index + 1);
}
twitterModule.post(twitterHandle, msg, false); twitterModule.post(twitterHandle, msg, false);
} catch (ModuleException e) { } catch (ModuleException e) {
if (logger.isWarnEnabled()) { LOGGER.warn("Failed to post entry on Twitter.", e);
logger.warn("Failed to post entry on twitter.", e);
}
} }
}).start(); }).start();
twitterEntries.remove(index); twitterEntries.remove(index);
@ -1083,16 +1069,14 @@ public class Mobibot extends PircBot {
getName() + ' ' + ReleaseInfo.VERSION + " " + msg, getName() + ' ' + ReleaseInfo.VERSION + " " + msg,
true); true);
} catch (ModuleException e) { } catch (ModuleException e) {
if (logger.isWarnEnabled()) { LOGGER.warn("Failed to notify @{}: {}", twitterHandle, msg, e);
logger.warn("Failed to notify @{}: {}", twitterHandle, msg, e);
}
} }
}).start(); }).start();
} }
} }
/** /**
* Removes entry from twitter auto-post. * Removes entry from Twitter auto-post.
* *
* @param index The entry's index. * @param index The entry's index.
*/ */
@ -1106,6 +1090,7 @@ public class Mobibot extends PircBot {
*/ */
final void twitterShutdown() { final void twitterShutdown() {
if (twitterModule.isEnabled() && isNotBlank(twitterHandle)) { if (twitterModule.isEnabled() && isNotBlank(twitterHandle)) {
LOGGER.debug("Twitter shutdown.");
for (final int i : twitterEntries) { for (final int i : twitterEntries) {
twitterEntryPost(i); twitterEntryPost(i);
} }

View file

@ -237,7 +237,8 @@ class UrlMgr(defaultTags: String, keywords: String) : AbstractCommand() {
private fun twitterPost(bot: Mobibot, index: Int) { private fun twitterPost(bot: Mobibot, index: Int) {
if (bot.isTwitterAutoPost) { if (bot.isTwitterAutoPost) {
bot.twitterAddEntry(index) bot.twitterAddEntry(index)
Mobibot.timer.schedule(TwitterTimer(bot, index), Constants.TIMER_DELAY * 60L * 1000L) bot.logger.debug("Scheduling ${Constants.LINK_CMD}${index + 1} for posting on Twitter.")
bot.timer.schedule(TwitterTimer(bot, index), Constants.TIMER_DELAY * 60L * 1000L)
} }
} }
} }

View file

@ -106,10 +106,7 @@ public class Tell extends AbstractCommand {
*/ */
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
final boolean clean() { final boolean clean() {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Cleaning the messages."); bot.getLogger().debug("Cleaning the messages.");
}
return TellMessagesMgr.clean(messages, maxDays); return TellMessagesMgr.clean(messages, maxDays);
} }

View file

@ -91,9 +91,7 @@ final class TellMessagesMgr {
try { try {
try (final ObjectInput input = new ObjectInputStream( try (final ObjectInput input = new ObjectInputStream(
new BufferedInputStream(Files.newInputStream(Paths.get(file))))) { new BufferedInputStream(Files.newInputStream(Paths.get(file))))) {
if (logger.isDebugEnabled()) {
logger.debug("Loading the messages."); logger.debug("Loading the messages.");
}
return ((List<TellMessage>) input.readObject()); return ((List<TellMessage>) input.readObject());
} }
@ -117,10 +115,7 @@ final class TellMessagesMgr {
try { try {
try (final ObjectOutput output = new ObjectOutputStream( try (final ObjectOutput output = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(Paths.get(file))))) { new BufferedOutputStream(Files.newOutputStream(Paths.get(file))))) {
if (logger.isDebugEnabled()) {
logger.debug("Saving the messages."); logger.debug("Saving the messages.");
}
output.writeObject(messages); output.writeObject(messages);
} }
} catch (IOException e) { } catch (IOException e) {

View file

@ -191,15 +191,14 @@ public final class EntriesMgr {
* @param history The history array. * @param history The history array.
* @param isDayBackup Set the true if the daily backup file should also be created. * @param isDayBackup Set the true if the daily backup file should also be created.
*/ */
@SuppressFBWarnings(value = {"CE_CLASS_ENVY", "CC_CYCLOMATIC_COMPLEXITY"}, justification = "Yes, it does.") @SuppressFBWarnings(value = { "CE_CLASS_ENVY", "CC_CYCLOMATIC_COMPLEXITY" },
justification = "Yes, it does.")
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static void saveEntries(final Mobibot bot, public static void saveEntries(final Mobibot bot,
final List<EntryLink> entries, final List<EntryLink> entries,
final List<String> history, final List<String> history,
final boolean isDayBackup) { final boolean isDayBackup) {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Saving the feeds..."); bot.getLogger().debug("Saving the feeds...");
}
if (StringUtils.isNotBlank(bot.getLogsDir()) && StringUtils.isNotBlank(bot.getWeblogUrl())) { if (StringUtils.isNotBlank(bot.getLogsDir()) && StringUtils.isNotBlank(bot.getWeblogUrl())) {
try { try {
@ -258,7 +257,8 @@ public final class EntriesMgr {
item.setTitle(entry.getTitle()); item.setTitle(entry.getTitle());
item.setPublishedDate(entry.getDate()); item.setPublishedDate(entry.getDate());
item.setAuthor( item.setAuthor(
bot.getChannel().substring(1) + '@' + bot.getIrcServer() + " (" + entry.getNick() + ')'); bot.getChannel().substring(1) + '@' + bot.getIrcServer() + " (" + entry.getNick()
+ ')');
item.setCategories(entry.getTags()); item.setCategories(entry.getTags());
items.add(item); items.add(item);
@ -266,10 +266,7 @@ public final class EntriesMgr {
rss.setEntries(items); rss.setEntries(items);
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Writing the entries feed."); bot.getLogger().debug("Writing the entries feed.");
}
output.output(rss, fw); output.output(rss, fw);
} }
@ -317,10 +314,7 @@ public final class EntriesMgr {
rss.setEntries(items); rss.setEntries(items);
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Writing the backlog feed."); bot.getLogger().debug("Writing the backlog feed.");
}
output.output(rss, fw); output.output(rss, fw);
} }
} else { } else {
@ -331,8 +325,7 @@ public final class EntriesMgr {
bot.getLogger().warn("Unable to generate the entries feed.", e); bot.getLogger().warn("Unable to generate the entries feed.", e);
} }
} else { } else {
bot.getLogger() bot.getLogger().warn("Unable to generate the entries feed. A required property is missing.");
.warn("Unable to generate the entries feed. At least one of the required property is missing.");
} }
} }
} }

View file

@ -180,10 +180,7 @@ public final class Lookup extends AbstractModule {
bot.send("Unknown host."); bot.send("Unknown host.");
} }
} catch (IOException ioe) { } catch (IOException ioe) {
if (bot.getLogger().isDebugEnabled()) {
bot.getLogger().debug("Unable to perform whois IP lookup: {}", args, ioe); bot.getLogger().debug("Unable to perform whois IP lookup: {}", args, ioe);
}
bot.send("Unable to perform whois IP lookup: " + ioe.getMessage()); bot.send("Unable to perform whois IP lookup: " + ioe.getMessage());
} }
} else { } else {

View file

@ -58,8 +58,8 @@ public class GoogleSearchTest extends LocalProperties {
@SuppressWarnings("PMD.PreserveStackTrace") @SuppressWarnings("PMD.PreserveStackTrace")
@Test @Test
public void testSearchGoogle() throws ModuleException { public void testSearchGoogle() throws ModuleException {
final String apiKey = LocalProperties.getProperty(GoogleSearch.GOOGLE_API_KEY_PROP); final String apiKey = getProperty(GoogleSearch.GOOGLE_API_KEY_PROP);
final String cseKey = LocalProperties.getProperty(GoogleSearch.GOOGLE_CSE_KEY_PROP); final String cseKey = getProperty(GoogleSearch.GOOGLE_CSE_KEY_PROP);
try { try {
List<Message> messages = GoogleSearch.searchGoogle("mobibot site:github.com", apiKey, cseKey); List<Message> messages = GoogleSearch.searchGoogle("mobibot site:github.com", apiKey, cseKey);
assertThat(messages).as("mobibot results not empty").isNotEmpty(); assertThat(messages).as("mobibot results not empty").isNotEmpty();

View file

@ -40,18 +40,25 @@ class RockPaperScissorsTest {
@Test @Test
fun testWinLoseOrDraw() { fun testWinLoseOrDraw() {
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("scissors", "paper")).`as`("scissors vs. paper").isEqualTo("win") RockPaperScissors.winLoseOrDraw("scissors", "paper")
).`as`("scissors vs. paper").isEqualTo("win")
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("paper", "rock")).`as`("paper vs. rock").isEqualTo("win") RockPaperScissors.winLoseOrDraw("paper", "rock")
).`as`("paper vs. rock").isEqualTo("win")
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("rock", "scissors")).`as`("rock vs. scissors").isEqualTo("win") RockPaperScissors.winLoseOrDraw("rock", "scissors")
).`as`("rock vs. scissors").isEqualTo("win")
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("paper", "scissors")).`as`("paper vs. scissors").isEqualTo("lose") RockPaperScissors.winLoseOrDraw("paper", "scissors")
).`as`("paper vs. scissors").isEqualTo("lose")
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("rock", "paper")).`as`("rock vs. paper").isEqualTo("lose") RockPaperScissors.winLoseOrDraw("rock", "paper")
).`as`("rock vs. paper").isEqualTo("lose")
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("scissors", "rock")).`as`("scissors vs. rock").isEqualTo("lose") RockPaperScissors.winLoseOrDraw("scissors", "rock")
).`as`("scissors vs. rock").isEqualTo("lose")
assertThat( assertThat(
RockPaperScissors.winLoseOrDraw("scissors", "scissors")).`as`("scissors vs. scissors").isEqualTo("draw") RockPaperScissors.winLoseOrDraw("scissors", "scissors")
).`as`("scissors vs. scissors").isEqualTo("draw")
} }
} }

View file

@ -61,7 +61,7 @@ public class StockQuoteTest extends LocalProperties {
assertThat(messages.get(0).getText()).as("same stock symbol").contains("AAPL").contains("Apple Inc."); assertThat(messages.get(0).getText()).as("same stock symbol").contains("AAPL").contains("Apple Inc.");
try { try {
StockQuote.getQuote("012", apiKey); StockQuote.getQuote("blahfoo", apiKey);
} catch (ModuleException e) { } catch (ModuleException e) {
assertThat(e.getMessage()).as("invalid symbol").containsIgnoringCase(StockQuote.INVALID_SYMBOL); assertThat(e.getMessage()).as("invalid symbol").containsIgnoringCase(StockQuote.INVALID_SYMBOL);
} }

View file

@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @created 2019-04-19 * @created 2019-04-19
* @since 1.0 * @since 1.0
*/ */
public class TwitterTest { public class TwitterTest extends LocalProperties {
@SuppressFBWarnings("MDM") @SuppressFBWarnings("MDM")
private String getCi() { private String getCi() {
if ("true".equals(System.getenv("CIRCLECI"))) { if ("true".equals(System.getenv("CIRCLECI"))) {
@ -68,11 +68,11 @@ public class TwitterTest {
public void testPostTwitter() throws ModuleException { public void testPostTwitter() throws ModuleException {
final String msg = "Testing Twitter API from " + getCi(); final String msg = "Testing Twitter API from " + getCi();
assertThat(Twitter.twitterPost( assertThat(Twitter.twitterPost(
LocalProperties.getProperty(Twitter.CONSUMER_KEY_PROP), getProperty(Twitter.CONSUMER_KEY_PROP),
LocalProperties.getProperty(Twitter.CONSUMER_SECRET_PROP), getProperty(Twitter.CONSUMER_SECRET_PROP),
LocalProperties.getProperty(Twitter.TOKEN_PROP), getProperty(Twitter.TOKEN_PROP),
LocalProperties.getProperty(Twitter.TOKEN_SECRET_PROP), getProperty(Twitter.TOKEN_SECRET_PROP),
LocalProperties.getProperty(Constants.TWITTER_HANDLE_PROP), getProperty(Constants.TWITTER_HANDLE_PROP),
msg, msg,
true).getText()).as("twitterPost(" + msg + ')').isEqualTo(msg); true).getText()).as("twitterPost(" + msg + ')').isEqualTo(msg);
} }

View file

@ -53,21 +53,19 @@ public class Weather2Test extends LocalProperties {
@SuppressFBWarnings("PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS") @SuppressFBWarnings("PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS")
@Test @Test
public void testWeather() throws ModuleException { public void testWeather() throws ModuleException {
List<Message> messages = Weather2.getWeather("98204", LocalProperties.getProperty(Weather2.OWM_API_KEY_PROP)); List<Message> messages = Weather2.getWeather("98204", getProperty(Weather2.OWM_API_KEY_PROP));
assertThat(messages.get(0).getText()).as("is Everett").contains("Everett").contains("US"); assertThat(messages.get(0).getText()).as("is Everett").contains("Everett").contains("US");
assertThat(messages.get(messages.size() - 1).getText()).as("is City Search").endsWith("98204%2CUS"); assertThat(messages.get(messages.size() - 1).getText()).as("is City Search").endsWith("98204%2CUS");
messages = Weather2.getWeather("London, UK", LocalProperties.getProperty(Weather2.OWM_API_KEY_PROP)); messages = Weather2.getWeather("London, UK", getProperty(Weather2.OWM_API_KEY_PROP));
assertThat(messages.get(0).getText()).as("is UK").contains("London").contains("UK"); assertThat(messages.get(0).getText()).as("is UK").contains("London").contains("UK");
assertThat(messages.get(messages.size() - 1).getText()).as("is City Code").endsWith("4517009"); assertThat(messages.get(messages.size() - 1).getText()).as("is City Code").endsWith("4517009");
assertThatThrownBy( assertThatThrownBy(() -> Weather2.getWeather("Montpellier, FR", getProperty(Weather2.OWM_API_KEY_PROP)))
() -> Weather2.getWeather("Montpellier, FR", LocalProperties.getProperty(Weather2.OWM_API_KEY_PROP))).as( .as("Montpellier not found").hasCauseInstanceOf(APIException.class);
"Montpellier not found").hasCauseInstanceOf(APIException.class);
assertThatThrownBy( assertThatThrownBy(() -> Weather2.getWeather("test", ""))
() -> Weather2.getWeather("test", "")).as( .as("no API key").isInstanceOf(ModuleException.class).hasNoCause();
"no API key").isInstanceOf(ModuleException.class).hasNoCause();
messages = Weather2.getWeather("", "apikey"); messages = Weather2.getWeather("", "apikey");
assertThat(messages.get(0).isError()).as("no query").isTrue(); assertThat(messages.get(0).isError()).as("no query").isTrue();