Merge pull request #280 from Fuzzlemann/master

PR for 4.0.0 (Fuzzlemann) (11)
This commit is contained in:
Rsl1122 2017-08-31 23:09:12 +03:00 committed by GitHub
commit 74970d26c1
58 changed files with 956 additions and 962 deletions

View File

@ -4,11 +4,12 @@
*/ */
package main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import com.google.common.base.Objects;
import main.java.com.djrapitops.plan.database.tables.Actions; import main.java.com.djrapitops.plan.database.tables.Actions;
import main.java.com.djrapitops.plan.utilities.FormatUtils; import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.html.Html; import main.java.com.djrapitops.plan.utilities.html.Html;
import java.util.Objects;
/** /**
* Class that represents an action made by a player. * Class that represents an action made by a player.
* *
@ -54,11 +55,6 @@ public class Action {
return serverID; return serverID;
} }
@Override
public String toString() {
return Html.TABLELINE_3.parse(FormatUtils.formatTimeStampYear(date), doneAction.toString(), additionalInfo);
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -67,11 +63,16 @@ public class Action {
return date == action.date && return date == action.date &&
serverID == action.serverID && serverID == action.serverID &&
doneAction == action.doneAction && doneAction == action.doneAction &&
Objects.equal(additionalInfo, action.additionalInfo); Objects.equals(additionalInfo, action.additionalInfo);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(date, doneAction, additionalInfo, serverID); return Objects.hash(date, doneAction, additionalInfo, serverID);
}
@Override
public String toString() {
return Html.TABLELINE_3.parse(FormatUtils.formatTimeStampYear(date), doneAction.toString(), additionalInfo);
} }
} }

View File

@ -1,6 +1,7 @@
package main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.database.tables.Actions; import main.java.com.djrapitops.plan.database.tables.Actions;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
@ -57,39 +58,31 @@ public class PlayerKill {
return weapon; return weapon;
} }
public Action convertToAction() {
@Override return new Action(time, Actions.KILLED, "name with " + weapon); // TODO Name Cache.
public String toString() {
return "{victim:" + victim + "|time:" + time + "|weapon:" + weapon + '}';
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object o) {
if (this == obj) { if (this == o) return true;
return true; if (o == null || getClass() != o.getClass()) return false;
} PlayerKill that = (PlayerKill) o;
if (obj == null) { return time == that.time &&
return false; Objects.equals(victim, that.victim) &&
} Objects.equals(weapon, that.weapon);
if (getClass() != obj.getClass()) {
return false;
}
final PlayerKill other = (PlayerKill) obj;
return this.time == other.time
&& Objects.equals(this.weapon, other.weapon)
&& Objects.equals(this.victim, other.victim);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 3; return Objects.hash(victim, time, weapon);
hash = 89 * hash + Objects.hashCode(this.victim);
hash = 89 * hash + (int) (this.time ^ (this.time >>> 32));
hash = 89 * hash + Objects.hashCode(this.weapon);
return hash;
} }
public Action convertToAction() { @Override
return new Action(time, Actions.KILLED, "name with " + weapon); // TODO Name Cache. public String toString() {
return new ToStringBuilder(this)
.append("victim", victim)
.append("time", time)
.append("weapon", weapon)
.toString();
} }
} }

View File

@ -1,10 +1,12 @@
package main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.data.time.WorldTimes; import main.java.com.djrapitops.plan.data.time.WorldTimes;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Objects;
/** /**
* Object for storing various information about a player's play session. * Object for storing various information about a player's play session.
@ -162,29 +164,6 @@ public class Session {
return deaths; return deaths;
} }
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Session other = (Session) obj;
return this.sessionStart == other.sessionStart && this.sessionEnd == other.sessionEnd;
}
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + (int) (this.sessionStart ^ (this.sessionStart >>> 32));
hash = 97 * hash + (int) (this.sessionEnd ^ (this.sessionEnd >>> 32));
return hash;
}
public boolean isFetchedFromDB() { public boolean isFetchedFromDB() {
return sessionID != null; return sessionID != null;
} }
@ -202,4 +181,36 @@ public class Session {
public void setSessionID(int sessionID) { public void setSessionID(int sessionID) {
this.sessionID = sessionID; this.sessionID = sessionID;
} }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Session session = (Session) o;
return sessionStart == session.sessionStart &&
sessionEnd == session.sessionEnd &&
mobKills == session.mobKills &&
deaths == session.deaths &&
Objects.equals(sessionID, session.sessionID) &&
Objects.equals(worldTimes, session.worldTimes) &&
Objects.equals(playerKills, session.playerKills);
}
@Override
public int hashCode() {
return Objects.hash(sessionStart, sessionID, worldTimes, sessionEnd, playerKills, mobKills, deaths);
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("sessionStart", sessionStart)
.append("sessionID", sessionID)
.append("worldTimes", worldTimes)
.append("sessionEnd", sessionEnd)
.append("playerKills", playerKills)
.append("mobKills", mobKills)
.append("deaths", deaths)
.toString();
}
} }

View File

@ -5,7 +5,9 @@
*/ */
package main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import com.google.common.base.Objects; import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.Objects;
/** /**
* Class containing single datapoint of TPS / Players online / CPU Usage / Used Memory / Entity Count / Chunks loaded. * Class containing single datapoint of TPS / Players online / CPU Usage / Used Memory / Entity Count / Chunks loaded.
@ -123,19 +125,19 @@ public class TPS {
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(date, ticksPerSecond, players, cpuUsage, usedMemory, entityCount, chunksLoaded); return Objects.hash(date, ticksPerSecond, players, cpuUsage, usedMemory, entityCount, chunksLoaded);
} }
@Override @Override
public String toString() { public String toString() {
return "TPS{" + return new ToStringBuilder(this)
"date=" + date + .append("date", date)
", ticksPerSecond=" + ticksPerSecond + .append("ticksPerSecond", ticksPerSecond)
", players=" + players + .append("players", players)
", cpuUsage=" + cpuUsage + .append("cpuUsage", cpuUsage)
", usedMemory=" + usedMemory + .append("usedMemory", usedMemory)
", entityCount=" + entityCount + .append("entityCount", entityCount)
", chunksLoaded=" + chunksLoaded + .append("chunksLoaded", chunksLoaded)
'}'; .toString();
} }
} }

View File

@ -1,7 +1,6 @@
package main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import com.google.common.base.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
/** /**
@ -79,12 +78,12 @@ public class UserInfo {
lastSeen == userInfo.lastSeen && lastSeen == userInfo.lastSeen &&
banned == userInfo.banned && banned == userInfo.banned &&
opped == userInfo.opped && opped == userInfo.opped &&
Objects.equal(uuid, userInfo.uuid) && Objects.equals(uuid, userInfo.uuid) &&
Objects.equal(name, userInfo.name); Objects.equals(name, userInfo.name);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(uuid, name, registered, lastSeen, banned, opped); return Objects.hash(uuid, name, registered, lastSeen, banned, opped);
} }
} }

View File

@ -1,5 +1,7 @@
package main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import java.util.Objects;
/** /**
* Object containing webserver security user information. * Object containing webserver security user information.
* *
@ -34,19 +36,14 @@ public class WebUser {
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
WebUser webUser = (WebUser) o; WebUser webUser = (WebUser) o;
return permLevel == webUser.permLevel &&
return permLevel == webUser.permLevel Objects.equals(user, webUser.user) &&
&& user.equals(webUser.user) Objects.equals(saltedPassHash, webUser.saltedPassHash);
&& saltedPassHash.equals(webUser.saltedPassHash);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = user.hashCode(); return Objects.hash(user, saltedPassHash, permLevel);
result = 31 * result + saltedPassHash.hashCode();
result = 31 * result + permLevel;
return result;
} }
} }

View File

@ -3,6 +3,7 @@ package main.java.com.djrapitops.plan.data.additional;
import com.djrapitops.pluginbridge.plan.Bridge; import com.djrapitops.pluginbridge.plan.Bridge;
import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.Log;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable; import java.io.Serializable;
import java.util.*; import java.util.*;
@ -52,7 +53,7 @@ public class HookHandler {
configHandler.createSection(dataSource); configHandler.createSection(dataSource);
} }
if (configHandler.isEnabled(dataSource)) { if (configHandler.isEnabled(dataSource)) {
Log.debug("Registered a new datasource: " + dataSource.getPlaceholder("").replace("%", "")); Log.debug("Registered a new datasource: " + StringUtils.remove(dataSource.getPlaceholder(""), '%'));
additionalDataSources.add(dataSource); additionalDataSources.add(dataSource);
} }
} catch (Exception e) { } catch (Exception e) {

View File

@ -1,9 +1,11 @@
package main.java.com.djrapitops.plan.data.time; package main.java.com.djrapitops.plan.data.time;
import com.djrapitops.plugin.utilities.Verify; import com.djrapitops.plugin.utilities.Verify;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* Abstract class for keeping track of time spent in each state. * Abstract class for keeping track of time spent in each state.
@ -140,28 +142,23 @@ public abstract class TimeKeeper {
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
TimeKeeper that = (TimeKeeper) o; TimeKeeper that = (TimeKeeper) o;
return lastStateChange == that.lastStateChange &&
return lastStateChange == that.lastStateChange Objects.equals(times, that.times) &&
&& (times != null ? times.equals(that.times) : that.times == null) Objects.equals(state, that.state);
&& (state != null ? state.equals(that.state) : that.state == null);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = times != null ? times.hashCode() : 0; return Objects.hash(times, state, lastStateChange);
result = 31 * result + (state != null ? state.hashCode() : 0);
result = 31 * result + (int) (lastStateChange ^ (lastStateChange >>> 32));
return result;
} }
@Override @Override
public String toString() { public String toString() {
return getClass().getSimpleName() + "{" + return new ToStringBuilder(this)
"times=" + times + .append("times", times)
", state='" + state + '\'' + .append("state", state)
", lastStateChange=" + lastStateChange + .append("lastStateChange", lastStateChange)
'}'; .toString();
} }
} }

View File

@ -111,19 +111,6 @@ public class WorldTimes {
return worldTimes.getOrDefault(world, new GMTimes()); return worldTimes.getOrDefault(world, new GMTimes());
} }
@Override
public String toString() {
StringBuilder b = new StringBuilder("WorldTimes (Current: " + currentWorld + "){\n");
for (Map.Entry<String, GMTimes> entry : worldTimes.entrySet()) {
b.append("World '").append(entry.getKey()).append("':\n");
GMTimes value = entry.getValue();
b.append(" Total: ").append(value.getTotal()).append("\n");
b.append(" ").append(value.toString()).append("\n");
}
b.append("}");
return b.toString();
}
/** /**
* Used to get the Map for saving. * Used to get the Map for saving.
* *
@ -136,4 +123,19 @@ public class WorldTimes {
public void setGMTimesForWorld(String world, GMTimes gmTimes) { public void setGMTimesForWorld(String world, GMTimes gmTimes) {
worldTimes.put(world, gmTimes); worldTimes.put(world, gmTimes);
} }
@Override
public String toString() {
StringBuilder b = new StringBuilder("WorldTimes (Current: " + currentWorld + "){\n");
for (Map.Entry<String, GMTimes> entry : worldTimes.entrySet()) {
GMTimes value = entry.getValue();
b.append("World '").append(entry.getKey()).append("':\n")
.append(" Total: ").append(value.getTotal()).append("\n")
.append(" ").append(value.toString()).append("\n");
}
b.append("}");
return b.toString();
}
} }

View File

@ -4,6 +4,7 @@ import main.java.com.djrapitops.plan.api.IPlan;
import main.java.com.djrapitops.plan.api.exceptions.DatabaseInitException; import main.java.com.djrapitops.plan.api.exceptions.DatabaseInitException;
import main.java.com.djrapitops.plan.database.tables.*; import main.java.com.djrapitops.plan.database.tables.*;
import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.lang3.StringUtils;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
@ -150,7 +151,7 @@ public abstract class Database {
* @return sqlite/mysql * @return sqlite/mysql
*/ */
public String getConfigName() { public String getConfigName() {
return getName().toLowerCase().replace(" ", ""); return StringUtils.remove(getName().toLowerCase(), ' ');
} }
public abstract boolean isNewDatabase() throws SQLException; public abstract boolean isNewDatabase() throws SQLException;

View File

@ -4,8 +4,7 @@
*/ */
package main.java.com.djrapitops.plan.systems.info.server; package main.java.com.djrapitops.plan.systems.info.server;
import com.google.common.base.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
/** /**
@ -60,13 +59,13 @@ public class ServerInfo {
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
ServerInfo that = (ServerInfo) o; ServerInfo that = (ServerInfo) o;
return id == that.id && return id == that.id &&
Objects.equal(uuid, that.uuid) && Objects.equals(uuid, that.uuid) &&
Objects.equal(name, that.name) && Objects.equals(name, that.name) &&
Objects.equal(webAddress, that.webAddress); Objects.equals(webAddress, that.webAddress);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(id, uuid, name, webAddress); return Objects.hash(uuid, id, name, webAddress);
} }
} }

View File

@ -323,8 +323,6 @@ public class WebServer {
Map<String, String> variables = readVariables(response); Map<String, String> variables = readVariables(response);
String key = variables.get("key"); String key = variables.get("key");
Plan plan = Plan.getInstance();
if (!checkKey(key)) { if (!checkKey(key)) {
String error = "Server Key not given or invalid"; String error = "Server Key not given or invalid";
return PageCache.loadPage(error, () -> { return PageCache.loadPage(error, () -> {
@ -342,7 +340,7 @@ public class WebServer {
} }
try { try {
return api.onResponse(plan, variables); return api.onResponse(Plan.getInstance(), variables);
} catch (Exception ex) { } catch (Exception ex) {
Log.toLog("WebServer.getAPIResponse", ex); Log.toLog("WebServer.getAPIResponse", ex);
return new InternalErrorResponse(ex, "An error while processing the request happened"); return new InternalErrorResponse(ex, "An error while processing the request happened");
@ -350,6 +348,10 @@ public class WebServer {
} }
private boolean checkKey(String key) { private boolean checkKey(String key) {
if (key == null) {
return false;
}
UUID uuid = Plan.getServerUUID(); UUID uuid = Plan.getServerUUID();
UUID keyUUID; UUID keyUUID;
try { try {

View File

@ -1,5 +1,7 @@
package main.java.com.djrapitops.plan.systems.webserver.response; package main.java.com.djrapitops.plan.systems.webserver.response;
import java.util.Objects;
/** /**
* @author Rsl1122 * @author Rsl1122
* @since 3.5.2 * @since 3.5.2
@ -43,17 +45,13 @@ public abstract class Response {
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Response response = (Response) o; Response response = (Response) o;
return Objects.equals(header, response.header) &&
return (header != null ? header.equals(response.header) : response.header == null) Objects.equals(content, response.content);
&& (content != null ? content.equals(response.content) : response.content == null);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = header != null ? header.hashCode() : 0; return Objects.hash(header, content);
result = 31 * result + (content != null ? content.hashCode() : 0);
return result;
} }
} }

View File

@ -3,6 +3,7 @@ package main.java.com.djrapitops.plan.utilities;
import com.djrapitops.plugin.utilities.Format; import com.djrapitops.plugin.utilities.Format;
import com.djrapitops.plugin.utilities.FormattingUtils; import com.djrapitops.plugin.utilities.FormattingUtils;
import main.java.com.djrapitops.plan.Settings; import main.java.com.djrapitops.plan.Settings;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Location; import org.bukkit.Location;
import java.text.DecimalFormat; import java.text.DecimalFormat;
@ -136,7 +137,7 @@ public class FormatUtils {
} }
builder.append(s); builder.append(s);
} }
String formattedTime = builder.toString().replace("%zero%", ""); String formattedTime = StringUtils.remove(builder.toString(), "%zero%");
if (formattedTime.isEmpty()) { if (formattedTime.isEmpty()) {
return Settings.FORMAT_SECONDS.toString().replace("%seconds%", "0"); return Settings.FORMAT_SECONDS.toString().replace("%seconds%", "0");
} }

View File

@ -28,6 +28,7 @@ import main.java.com.djrapitops.plan.utilities.comparators.UserInfoLastPlayedCom
import main.java.com.djrapitops.plan.utilities.html.HtmlStructure; import main.java.com.djrapitops.plan.utilities.html.HtmlStructure;
import main.java.com.djrapitops.plan.utilities.html.HtmlUtils; import main.java.com.djrapitops.plan.utilities.html.HtmlUtils;
import main.java.com.djrapitops.plan.utilities.html.tables.PlayersTableCreator; import main.java.com.djrapitops.plan.utilities.html.tables.PlayersTableCreator;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable; import java.io.Serializable;
import java.sql.SQLException; import java.sql.SQLException;
@ -191,7 +192,7 @@ public class Analysis {
Log.debug("Analysis", "Additional Sources: " + sources.size()); Log.debug("Analysis", "Additional Sources: " + sources.size());
sources.parallelStream().filter(Verify::notNull).forEach(source -> { sources.parallelStream().filter(Verify::notNull).forEach(source -> {
try { try {
Benchmark.start("Source " + source.getPlaceholder("").replace("%", "")); Benchmark.start("Source " + StringUtils.remove(source.getPlaceholder(""), '%'));
final List<AnalysisType> analysisTypes = source.getAnalysisTypes(); final List<AnalysisType> analysisTypes = source.getAnalysisTypes();
if (analysisTypes.isEmpty()) { if (analysisTypes.isEmpty()) {
return; return;
@ -217,11 +218,11 @@ public class Analysis {
replaceMap.put(source.getPlaceholder(boolTot.getPlaceholderModifier()), AnalysisUtils.getBooleanTotal(boolTot, source, uuids)); replaceMap.put(source.getPlaceholder(boolTot.getPlaceholderModifier()), AnalysisUtils.getBooleanTotal(boolTot, source, uuids));
} }
} catch (Exception | NoClassDefFoundError | NoSuchFieldError | NoSuchMethodError e) { } catch (Exception | NoClassDefFoundError | NoSuchFieldError | NoSuchMethodError e) {
Log.error("A PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", "")); Log.error("A PluginData-source caused an exception: " + StringUtils.remove(source.getPlaceholder(""), '%'));
Log.toLog(this.getClass().getName(), e); Log.toLog(this.getClass().getName(), e);
} finally { } finally {
Benchmark.stop("Analysis", "Source " + source.getPlaceholder("").replace("%", "")); Benchmark.stop("Analysis", "Source " + StringUtils.remove(source.getPlaceholder(""), '%'));
} }
}); });
Benchmark.stop("Analysis", "3rd party"); Benchmark.stop("Analysis", "3rd party");

View File

@ -7,6 +7,7 @@ import main.java.com.djrapitops.plan.data.additional.PluginData;
import main.java.com.djrapitops.plan.utilities.FormatUtils; import main.java.com.djrapitops.plan.utilities.FormatUtils;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.comparators.SessionLengthComparator; import main.java.com.djrapitops.plan.utilities.comparators.SessionLengthComparator;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable; import java.io.Serializable;
import java.util.*; import java.util.*;
@ -194,8 +195,10 @@ public class AnalysisUtils {
} }
private static String logPluginDataCausedError(PluginData source, Throwable e) { private static String logPluginDataCausedError(PluginData source, Throwable e) {
Log.error("A PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", "")); String placeholder = StringUtils.remove(source.getPlaceholder(""), '%');
Log.toLog("PluginData-source caused an exception: " + source.getPlaceholder("").replace("%", ""), e);
Log.error("A PluginData-source caused an exception: " + placeholder);
Log.toLog("PluginData-source caused an exception: " + placeholder, e);
return source.parseContainer("", "Exception during calculation."); return source.parseContainer("", "Exception during calculation.");
} }

View File

@ -1,6 +1,8 @@
package main.java.com.djrapitops.plan.utilities.analysis; package main.java.com.djrapitops.plan.utilities.analysis;
import com.google.common.base.Objects; import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.Objects;
/** /**
* @author Rsl1122 * @author Rsl1122
@ -23,11 +25,6 @@ public class Point {
return y; return y;
} }
@Override
public String toString() {
return "{x:" + x + " y:" + y + '}';
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
@ -39,6 +36,14 @@ public class Point {
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(x, y); return Objects.hash(x, y);
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("x", x)
.append("y", y)
.toString();
} }
} }

View File

@ -3,6 +3,7 @@ package main.java.com.djrapitops.plan.utilities.html;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.Settings; import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.systems.webserver.WebServer; import main.java.com.djrapitops.plan.systems.webserver.WebServer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrSubstitutor; import org.apache.commons.lang3.text.StrSubstitutor;
import java.io.Serializable; import java.io.Serializable;
@ -93,10 +94,7 @@ public class HtmlUtils {
* @return * @return
*/ */
public static String removeXSS(String string) { public static String removeXSS(String string) {
return string.replace("<!--", "") return StringUtils.removeAll(string,"(<!--)|(-->)|(</?script>)");
.replace("-->", "")
.replace("<script>", "")
.replace("</script>", "");
} }
/** /**
@ -117,7 +115,7 @@ public class HtmlUtils {
string = Html.SPAN.parse(string); string = Html.SPAN.parse(string);
} }
return string.replace("§r", ""); return StringUtils.remove(string, "§r");
} }
public static String separateWithQuotes(String... strings) { public static String separateWithQuotes(String... strings) {

View File

@ -0,0 +1,27 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package main.java.com.djrapitops.plan;
import org.junit.Test;
import test.java.utils.TestUtils;
import static org.junit.Assert.assertEquals;
/**
* @author Rsl1122
*/
public class PermissionsTest {
@Test
public void testGetPermission() throws NoSuchFieldException, IllegalAccessException {
for (Permissions type : Permissions.values()) {
String exp = TestUtils.getStringFieldValue(type, "permission");
assertEquals(exp, type.getPermission());
assertEquals(exp, type.getPerm());
}
}
}

View File

@ -1,7 +1,7 @@
package test.java.main.java.com.djrapitops.plan; package main.java.com.djrapitops.plan;
import main.java.com.djrapitops.plan.Plan;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
@ -18,14 +18,17 @@ import static junit.framework.TestCase.assertFalse;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class ServerVariableHolderTest { public class ServerVariableHolderTest {
@Test @Before
public void testServerVariable() throws Exception { public void setUp() throws Exception {
TestInit.init(); TestInit.init();
}
@Test
public void testServerVariable() {
boolean usingPaper = Plan.getInstance().getVariable().isUsingPaper(); boolean usingPaper = Plan.getInstance().getVariable().isUsingPaper();
assertFalse(usingPaper); assertFalse(usingPaper);
String ip = Plan.getInstance().getVariable().getIp(); String exp = Plan.getInstance().getVariable().getIp();
assertEquals(ip, "0.0.0.0"); assertEquals(exp, "0.0.0.0");
} }
} }

View File

@ -3,9 +3,8 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan; package main.java.com.djrapitops.plan;
import main.java.com.djrapitops.plan.Settings;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -14,7 +13,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.util.ArrayList; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -26,9 +25,6 @@ import static org.junit.Assert.*;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class SettingsTest { public class SettingsTest {
public SettingsTest() {
}
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit.init(); TestInit.init();
@ -40,7 +36,7 @@ public class SettingsTest {
} }
@Test @Test
public void testIsTrue2() { public void testSetValue() {
Settings gatherCommands = Settings.LOG_UNKNOWN_COMMANDS; Settings gatherCommands = Settings.LOG_UNKNOWN_COMMANDS;
gatherCommands.setValue(false); gatherCommands.setValue(false);
@ -62,9 +58,9 @@ public class SettingsTest {
@Test @Test
public void testGetStringList() { public void testGetStringList() {
List<String> exp = new ArrayList<>(); List<String> exp = Collections.singletonList("ExampleTown");
exp.add("ExampleTown");
List<String> result = Settings.HIDE_TOWNS.getStringList(); List<String> result = Settings.HIDE_TOWNS.getStringList();
assertEquals(exp, result); assertEquals(exp, result);
} }

View File

@ -0,0 +1,38 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package main.java.com.djrapitops.plan.data;
import org.junit.Test;
import test.java.utils.RandomData;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
/**
* @author Rsl1122
*/
public class PlayerKillTest {
private String randomString = RandomData.randomString(10);
private UUID testUUID = UUID.randomUUID();
private PlayerKill playerKill = new PlayerKill(testUUID, randomString, 100L);
@Test
public void testGetVictim() {
assertEquals(playerKill.getVictim(), testUUID);
}
@Test
public void testGetDate() {
assertEquals(playerKill.getTime(), 100L);
}
@Test
public void testGetWeapon() {
assertEquals(playerKill.getWeapon(), randomString);
}
}

View File

@ -3,9 +3,8 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.data.Session;
import org.junit.Before; import org.junit.Before;
/** /**
@ -13,17 +12,8 @@ import org.junit.Before;
*/ */
public class SessionTest { public class SessionTest {
private Session test; private Session session;
/**
*
*/
public SessionTest() {
}
/**
*
*/
@Before @Before
public void setUp() { public void setUp() {
} }

View File

@ -1,37 +1,30 @@
package test.java.main.java.com.djrapitops.plan.data; package main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.UserInfo;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.TestInit;
/** /**
* @author Rsl1122 * @author Rsl1122
*/ */
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
@Ignore
public class UserInfoTest { public class UserInfoTest {
// TODO Rewrite // TODO Rewrite
private UserInfo test; private UserInfo session;
private Plan plan; private Plan plan;
/**
*
*/
public UserInfoTest() {
}
/**
*
*/
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
// TestInit t = TestInit.init(); TestInit.init();
} }
@Test @Test

View File

@ -0,0 +1,31 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package main.java.com.djrapitops.plan.data.additional;
import org.junit.Test;
import test.java.utils.TestUtils;
import static org.junit.Assert.assertEquals;
/**
* @author Rsl1122
*/
public class AnalysisTypeTest {
@Test
public void testGetModifier() throws NoSuchFieldException, IllegalAccessException {
for (AnalysisType type : AnalysisType.values()) {
assertEquals(TestUtils.getStringFieldValue(type, "modifier"), type.getModifier());
}
}
@Test
public void testGetPlaceholderModifier() throws NoSuchFieldException, IllegalAccessException {
for (AnalysisType type : AnalysisType.values()) {
assertEquals(TestUtils.getStringFieldValue(type, "placeholderModifier"), type.getPlaceholderModifier());
}
}
}

View File

@ -2,7 +2,7 @@
* Licence is provided in the jar as license.yml also here: * Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml * https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/ */
package test.java.main.java.com.djrapitops.plan.data.additional.importer; package main.java.com.djrapitops.plan.data.additional.importer;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import main.java.com.djrapitops.plan.data.PlayerKill; import main.java.com.djrapitops.plan.data.PlayerKill;
@ -27,6 +27,9 @@ import static org.junit.Assert.*;
*/ */
public class ImportBuilderTest { public class ImportBuilderTest {
private int randomInt = RandomData.randomInt(0, 10);
private String randomString = RandomData.randomString(randomInt);
@Test @Test
public void testEmptyServerBuilder() { public void testEmptyServerBuilder() {
ServerImportData data = ServerImportData.builder().build(); ServerImportData data = ServerImportData.builder().build();
@ -65,9 +68,6 @@ public class ImportBuilderTest {
public void testServerDataBuilder() { public void testServerDataBuilder() {
ServerImportData.ServerImportDataBuilder builder = ServerImportData.builder(); ServerImportData.ServerImportDataBuilder builder = ServerImportData.builder();
int randomInt = RandomData.randomInt(0, 10);
String randomString = RandomData.randomString(randomInt);
TPS tps = new TPS(randomInt, randomInt, randomInt, randomInt, randomInt, randomInt, randomInt); TPS tps = new TPS(randomInt, randomInt, randomInt, randomInt, randomInt, randomInt, randomInt);
ServerImportData data = builder.tpsData(tps) ServerImportData data = builder.tpsData(tps)
@ -96,9 +96,7 @@ public class ImportBuilderTest {
public void testUserDataBuilder() { public void testUserDataBuilder() {
UserImportData.UserImportDataBuilder builder = UserImportData.builder(); UserImportData.UserImportDataBuilder builder = UserImportData.builder();
int randomInt = RandomData.randomInt(0, 10);
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
String randomString = RandomData.randomString(10);
PlayerKill playerKill = new PlayerKill(uuid, randomString, 1); PlayerKill playerKill = new PlayerKill(uuid, randomString, 1);
GMTimes gmTimes = new GMTimes(randomString, randomInt); GMTimes gmTimes = new GMTimes(randomString, randomInt);

View File

@ -3,7 +3,7 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.data.cache; package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.systems.cache.DataCache; import main.java.com.djrapitops.plan.systems.cache.DataCache;
@ -27,15 +27,6 @@ public class DataCacheTest {
private int callsToSaveUserData; private int callsToSaveUserData;
private int callsToSaveMultiple; private int callsToSaveMultiple;
/**
*
*/
public DataCacheTest() {
}
/**
*
*/
@Before @Before
public void setUp() { public void setUp() {

View File

@ -1,4 +1,4 @@
package test.java.main.java.com.djrapitops.plan.data.cache; package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.systems.cache.GeolocationCache; import main.java.com.djrapitops.plan.systems.cache.GeolocationCache;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -24,8 +24,10 @@ public class GeolocationCacheTest {
private final Map<String, String> ipsToCountries = new HashMap<>(); private final Map<String, String> ipsToCountries = new HashMap<>();
@Before @Before
public void setUp() { public void setUp() throws Exception {
TestInit.init();
GeolocationCache.clearCache(); GeolocationCache.clearCache();
ipsToCountries.put("8.8.8.8", "United States"); ipsToCountries.put("8.8.8.8", "United States");
ipsToCountries.put("8.8.4.4", "United States"); ipsToCountries.put("8.8.4.4", "United States");
ipsToCountries.put("4.4.2.2", "United States"); ipsToCountries.put("4.4.2.2", "United States");
@ -38,9 +40,7 @@ public class GeolocationCacheTest {
} }
@Test @Test
public void testCountryGetting() throws Exception { public void testCountryGetting() {
TestInit.init();
for (Map.Entry<String, String> entry : ipsToCountries.entrySet()) { for (Map.Entry<String, String> entry : ipsToCountries.entrySet()) {
String ip = entry.getKey(); String ip = entry.getKey();
String expCountry = entry.getValue(); String expCountry = entry.getValue();
@ -52,9 +52,7 @@ public class GeolocationCacheTest {
} }
@Test @Test
public void testCaching() throws Exception { public void testCaching() {
TestInit.init();
for (Map.Entry<String, String> entry : ipsToCountries.entrySet()) { for (Map.Entry<String, String> entry : ipsToCountries.entrySet()) {
String ip = entry.getKey(); String ip = entry.getKey();
String expIp = entry.getValue(); String expIp = entry.getValue();

View File

@ -1,4 +1,4 @@
package test.java.main.java.com.djrapitops.plan.data.cache; package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.systems.webserver.PageCache; import main.java.com.djrapitops.plan.systems.webserver.PageCache;
import main.java.com.djrapitops.plan.systems.webserver.PageLoader; import main.java.com.djrapitops.plan.systems.webserver.PageLoader;

View File

@ -3,7 +3,7 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.data.cache; package main.java.com.djrapitops.plan.data.cache;
import main.java.com.djrapitops.plan.systems.cache.SessionCache; import main.java.com.djrapitops.plan.systems.cache.SessionCache;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -23,12 +23,6 @@ public class SessionCacheTest {
private SessionCache test; private SessionCache test;
/**
*
*/
public SessionCacheTest() {
}
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit.init(); TestInit.init();

View File

@ -3,7 +3,7 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.data.cache.queue; package main.java.com.djrapitops.plan.data.cache.queue;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.database.Database; import main.java.com.djrapitops.plan.database.Database;
@ -17,13 +17,11 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.MockUtils;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.when;
@ -32,21 +30,18 @@ import static org.powermock.api.mockito.PowerMockito.when;
@PrepareForTest({JavaPlugin.class}) @PrepareForTest({JavaPlugin.class})
public class QueueTest { public class QueueTest {
private final UUID uuid1 = MockUtils.getPlayerUUID();
private DataCache dataCache; private DataCache dataCache;
private Database db; private Database db;
public QueueTest() {
}
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit t = TestInit.init(); TestInit t = TestInit.init();
Plan plan = t.getPlanMock(); Plan plan = t.getPlanMock();
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()); db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
db.init(); db.init();
when(plan.getDB()).thenReturn(db); when(plan.getDB()).thenReturn(db);
dataCache = new DataCache(plan); dataCache = new DataCache(plan);
when(plan.getDataCache()).thenReturn(dataCache); when(plan.getDataCache()).thenReturn(dataCache);
} }

View File

@ -0,0 +1,125 @@
package main.java.com.djrapitops.plan.data.time;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GMTimesTest {
@Test
public void testSetAllGMTimes() {
GMTimes gmTimes = new GMTimes();
gmTimes.setAllGMTimes(1L, 2L, 3L, 4L);
Map<String, Long> times = gmTimes.getTimes();
assertEquals(times.size(), 4);
assertTrue(times.get("SURVIVAL") == 1L);
assertTrue(times.get("CREATIVE") == 2L);
assertTrue(times.get("ADVENTURE") == 3L);
assertTrue(times.get("SPECTATOR") == 4L);
}
@Test
public void testSetAllGMTimesTooFew() {
GMTimes gmTimes = new GMTimes();
gmTimes.setAllGMTimes(1L, 2L);
Map<String, Long> times = gmTimes.getTimes();
assertEquals(times.size(), 4);
assertTrue(times.get("SURVIVAL") == 1L);
assertTrue(times.get("CREATIVE") == 2L);
assertTrue(times.get("ADVENTURE") == 0L);
assertTrue(times.get("SPECTATOR") == 0L);
}
@Test
public void testSetAllGMTimesTooMany() {
GMTimes gmTimes = new GMTimes();
gmTimes.setAllGMTimes(1L, 2L, 3L, 4L, 5L, 6L);
Map<String, Long> times = gmTimes.getTimes();
assertEquals(times.size(), 4);
assertTrue(times.get("SURVIVAL") == 1L);
assertTrue(times.get("CREATIVE") == 2L);
assertTrue(times.get("ADVENTURE") == 3L);
assertTrue(times.get("SPECTATOR") == 4L);
}
@Test
public void testResetTimes() {
GMTimes gmTimes = new GMTimes();
gmTimes.setAllGMTimes(4, 3, 2, 1);
gmTimes.resetTimes(10);
assertTrue(gmTimes.getTotal() == 10L);
assertTrue(gmTimes.getTime("SURVIVAL") == 10L);
assertTrue(gmTimes.getTime("ADVENTURE") == 0L);
}
@Test
public void testSetTime() {
GMTimes gmTimes = new GMTimes();
gmTimes.setTime("SURVIVAL", 5L);
assertTrue(gmTimes.getTime("SURVIVAL") == 5L);
}
@Test
public void testRenameState() {
GMTimes gmTimes = new GMTimes();
gmTimes.setAllGMTimes(5L);
gmTimes.renameState("SURVIVAL", "Survival");
assertTrue(gmTimes.getTime("SURVIVAL") == 0L);
assertTrue(gmTimes.getTime("Survival") == 5L);
}
@Test
public void testChangeStateNormal() {
GMTimes gmTimes = new GMTimes(new HashMap<>(), "SURVIVAL", 0);
gmTimes.changeState("CREATIVE", 5L);
assertTrue(gmTimes.getTime("SURVIVAL") == 5L);
assertTrue(gmTimes.getTime("CREATIVE") == 0L);
gmTimes.changeState("ADVENTURE", 20L);
assertTrue(gmTimes.getTime("SURVIVAL") == 5L);
assertTrue(gmTimes.getTime("CREATIVE") == 15L);
assertTrue(gmTimes.getTime("ADVENTURE") == 0L);
}
@Test
public void testChangeStateMissingStartTime() {
GMTimes gmTimes = new GMTimes("SURVIVAL");
gmTimes.changeState("CREATIVE", 5L);
assertTrue(5L == gmTimes.getTime("SURVIVAL"));
assertTrue(0L == gmTimes.getTime("CREATIVE"));
gmTimes.changeState("ADVENTURE", 20L);
assertTrue(5L == gmTimes.getTime("SURVIVAL"));
assertTrue(15L == gmTimes.getTime("CREATIVE"));
assertTrue(0L == gmTimes.getTime("ADVENTURE"));
}
@Test
public void testChangeStateMissingStartState() {
GMTimes test = new GMTimes();
test.changeState("CREATIVE", 5L);
assertTrue(5L == test.getTime("CREATIVE"));
test.changeState("ADVENTURE", 20L);
assertTrue(20L == test.getTime("CREATIVE"));
assertTrue(0L == test.getTime("ADVENTURE"));
}
}

View File

@ -1,13 +1,10 @@
package test.java.main.java.com.djrapitops.plan.data.time; package main.java.com.djrapitops.plan.data.time;
import main.java.com.djrapitops.plan.data.time.GMTimes; import com.google.common.collect.ImmutableMap;
import main.java.com.djrapitops.plan.data.time.WorldTimes;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import test.java.utils.RandomData; import test.java.utils.RandomData;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -21,42 +18,42 @@ public class WorldTimesTest {
private final String worldOne = "ONE"; private final String worldOne = "ONE";
private final String worldTwo = "TWO"; private final String worldTwo = "TWO";
private final String[] gms = GMTimes.getGMKeyArray(); private final String[] gms = GMTimes.getGMKeyArray();
private long time; private WorldTimes worldTimes = new WorldTimes(worldOne, gms[0]);
private WorldTimes test; private long time = worldTimes.getGMTimes(worldOne).getLastStateChange();
@Before
public void setUp() throws Exception {
test = new WorldTimes(worldOne, gms[0]);
time = test.getGMTimes(worldOne).getLastStateChange();
}
@Test @Test
public void testWorldChange() { public void testWorldChange() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
test.updateState(worldTwo, gms[0], changeTime); worldTimes.updateState(worldTwo, gms[0], changeTime);
assertEquals(1000L, test.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, worldTimes.getWorldPlaytime(worldOne));
assertEquals(1000L, worldTimes.getGMTimes(worldOne).getTime(gms[0]));
} }
@Test @Test
public void testGMChange() { public void testGMChange() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
test.updateState(worldOne, gms[0], changeTime); worldTimes.updateState(worldOne, gms[0], changeTime);
assertEquals(1000L, test.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0])); assertEquals(1000L, worldTimes.getWorldPlaytime(worldOne));
assertEquals(1000L, worldTimes.getGMTimes(worldOne).getTime(gms[0]));
} }
@Test @Test
public void testBothTwiceChange() { public void testBothTwiceChange() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
long changeTime2 = changeTime + 1000L; long changeTime2 = changeTime + 1000L;
test.updateState(worldTwo, gms[2], changeTime);
assertEquals(1000L, test.getWorldPlaytime(worldOne)); worldTimes.updateState(worldTwo, gms[2], changeTime);
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0]));
test.updateState(worldOne, gms[1], changeTime2); assertEquals(1000L, worldTimes.getWorldPlaytime(worldOne));
assertEquals(1000L, test.getWorldPlaytime(worldOne)); assertEquals(1000L, worldTimes.getGMTimes(worldOne).getTime(gms[0]));
assertEquals(1000L, test.getGMTimes(worldOne).getTime(gms[0]));
assertEquals(1000L, test.getGMTimes(worldTwo).getTime(gms[2])); worldTimes.updateState(worldOne, gms[1], changeTime2);
assertEquals(1000L, worldTimes.getWorldPlaytime(worldOne));
assertEquals(1000L, worldTimes.getGMTimes(worldOne).getTime(gms[0]));
assertEquals(1000L, worldTimes.getGMTimes(worldTwo).getTime(gms[2]));
} }
@Test @Test
@ -64,9 +61,7 @@ public class WorldTimesTest {
long amount = 1000L; long amount = 1000L;
String[] worlds = new String[]{worldOne, worldTwo}; String[] worlds = new String[]{worldOne, worldTwo};
Map<String, List<String>> testedW = new HashMap<>(); Map<String, List<String>> testedW = ImmutableMap.of(worldOne, new ArrayList<>(), worldTwo, new ArrayList<>());
testedW.put(worldOne, new ArrayList<>());
testedW.put(worldTwo, new ArrayList<>());
String lastWorld = worldOne; String lastWorld = worldOne;
String lastGM = gms[0]; String lastGM = gms[0];
@ -82,7 +77,7 @@ public class WorldTimesTest {
long time = i * amount + this.time; long time = i * amount + this.time;
test.updateState(world, gm, time); worldTimes.updateState(world, gm, time);
} }
long worldOneCount = testedW.get(worldOne).size(); long worldOneCount = testedW.get(worldOne).size();
@ -90,8 +85,8 @@ public class WorldTimesTest {
long worldTimeOne = worldOneCount * amount; long worldTimeOne = worldOneCount * amount;
long worldTimeTwo = worldTwoCount * amount; long worldTimeTwo = worldTwoCount * amount;
long time1 = test.getWorldPlaytime(worldOne); long time1 = worldTimes.getWorldPlaytime(worldOne);
long time2 = test.getWorldPlaytime(worldTwo); long time2 = worldTimes.getWorldPlaytime(worldTwo);
// Tests World time calculation. // Tests World time calculation.
assertEquals(amount * 50, time1 + time2); assertEquals(amount * 50, time1 + time2);
@ -103,11 +98,16 @@ public class WorldTimesTest {
public void testGMTrackingSingleWorld() { public void testGMTrackingSingleWorld() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
long changeTime2 = changeTime + 1000L; long changeTime2 = changeTime + 1000L;
GMTimes gmTimes = test.getGMTimes(worldOne);
test.updateState(worldOne, "CREATIVE", changeTime); GMTimes gmTimes = worldTimes.getGMTimes(worldOne);
worldTimes.updateState(worldOne, "CREATIVE", changeTime);
assertEquals(1000L, gmTimes.getTime("SURVIVAL")); assertEquals(1000L, gmTimes.getTime("SURVIVAL"));
assertEquals(0L, gmTimes.getTime("CREATIVE")); assertEquals(0L, gmTimes.getTime("CREATIVE"));
test.updateState(worldOne, "ADVENTURE", changeTime2);
worldTimes.updateState(worldOne, "ADVENTURE", changeTime2);
assertEquals(1000L, gmTimes.getTime("SURVIVAL")); assertEquals(1000L, gmTimes.getTime("SURVIVAL"));
assertEquals(1000L, gmTimes.getTime("CREATIVE")); assertEquals(1000L, gmTimes.getTime("CREATIVE"));
assertEquals(0L, gmTimes.getTime("ADVENTURE")); assertEquals(0L, gmTimes.getTime("ADVENTURE"));
@ -117,15 +117,19 @@ public class WorldTimesTest {
public void testGMTrackingTwoWorlds() { public void testGMTrackingTwoWorlds() {
long changeTime = time + 1000L; long changeTime = time + 1000L;
long changeTime2 = time + 2000L; long changeTime2 = time + 2000L;
GMTimes worldOneGMTimes = test.getGMTimes(worldOne);
test.updateState(worldOne, "CREATIVE", changeTime); GMTimes worldOneGMTimes = worldTimes.getGMTimes(worldOne);
test.updateState(worldOne, "ADVENTURE", changeTime2);
worldTimes.updateState(worldOne, "CREATIVE", changeTime);
worldTimes.updateState(worldOne, "ADVENTURE", changeTime2);
assertEquals(1000L, worldOneGMTimes.getTime("SURVIVAL")); assertEquals(1000L, worldOneGMTimes.getTime("SURVIVAL"));
assertEquals(1000L, worldOneGMTimes.getTime("CREATIVE")); assertEquals(1000L, worldOneGMTimes.getTime("CREATIVE"));
assertEquals(0L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(0L, worldOneGMTimes.getTime("ADVENTURE"));
test.updateState(worldTwo, "SURVIVAL", time + 3000L); worldTimes.updateState(worldTwo, "SURVIVAL", time + 3000L);
GMTimes worldTwoGMTimes = test.getGMTimes(worldTwo); GMTimes worldTwoGMTimes = worldTimes.getGMTimes(worldTwo);
assertEquals(1000L, worldOneGMTimes.getTime("SURVIVAL")); assertEquals(1000L, worldOneGMTimes.getTime("SURVIVAL"));
assertEquals(1000L, worldOneGMTimes.getTime("CREATIVE")); assertEquals(1000L, worldOneGMTimes.getTime("CREATIVE"));
assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE"));
@ -134,7 +138,7 @@ public class WorldTimesTest {
assertEquals(0L, worldTwoGMTimes.getTime("CREATIVE")); assertEquals(0L, worldTwoGMTimes.getTime("CREATIVE"));
assertEquals(0L, worldTwoGMTimes.getTime("ADVENTURE")); assertEquals(0L, worldTwoGMTimes.getTime("ADVENTURE"));
test.updateState(worldTwo, "CREATIVE", time + 4000L); worldTimes.updateState(worldTwo, "CREATIVE", time + 4000L);
assertEquals(1000L, worldOneGMTimes.getTime("SURVIVAL")); assertEquals(1000L, worldOneGMTimes.getTime("SURVIVAL"));
assertEquals(1000L, worldOneGMTimes.getTime("CREATIVE")); assertEquals(1000L, worldOneGMTimes.getTime("CREATIVE"));
@ -143,20 +147,25 @@ public class WorldTimesTest {
assertEquals(1000L, worldTwoGMTimes.getTime("SURVIVAL")); assertEquals(1000L, worldTwoGMTimes.getTime("SURVIVAL"));
assertEquals(0L, worldTwoGMTimes.getTime("CREATIVE")); assertEquals(0L, worldTwoGMTimes.getTime("CREATIVE"));
test.updateState(worldTwo, "CREATIVE", time + 5000L); worldTimes.updateState(worldTwo, "CREATIVE", time + 5000L);
assertEquals(1000L, worldTwoGMTimes.getTime("SURVIVAL")); assertEquals(1000L, worldTwoGMTimes.getTime("SURVIVAL"));
assertEquals(1000L, worldTwoGMTimes.getTime("CREATIVE")); assertEquals(1000L, worldTwoGMTimes.getTime("CREATIVE"));
// No change should occur. // No change should occur.
test.updateState(worldOne, "ADVENTURE", time + 5000L); worldTimes.updateState(worldOne, "ADVENTURE", time + 5000L);
assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE"));
assertEquals(1000L, worldTwoGMTimes.getTime("CREATIVE")); assertEquals(1000L, worldTwoGMTimes.getTime("CREATIVE"));
test.updateState(worldTwo, "CREATIVE", time + 5000L);
test.updateState(worldOne, "ADVENTURE", time + 6000L); worldTimes.updateState(worldTwo, "CREATIVE", time + 5000L);
worldTimes.updateState(worldOne, "ADVENTURE", time + 6000L);
assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(1000L, worldOneGMTimes.getTime("ADVENTURE"));
assertEquals(2000L, worldTwoGMTimes.getTime("CREATIVE")); assertEquals(2000L, worldTwoGMTimes.getTime("CREATIVE"));
test.updateState(worldTwo, "ADVENTURE", time + 7000L); worldTimes.updateState(worldTwo, "ADVENTURE", time + 7000L);
assertEquals(2000L, worldTwoGMTimes.getTime("CREATIVE")); assertEquals(2000L, worldTwoGMTimes.getTime("CREATIVE"));
assertEquals(2000L, worldOneGMTimes.getTime("ADVENTURE")); assertEquals(2000L, worldOneGMTimes.getTime("ADVENTURE"));
} }

View File

@ -3,10 +3,8 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.database; package main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.database.Container;
import main.java.com.djrapitops.plan.database.DBUtils;
import org.junit.Test; import org.junit.Test;
import test.java.utils.RandomData; import test.java.utils.RandomData;
@ -28,7 +26,9 @@ public class DBUtilsTest {
for (int i = 0; i < 21336; i++) { for (int i = 0; i < 21336; i++) {
list.add(i); list.add(i);
} }
List<List<Integer>> result = DBUtils.splitIntoBatches(list); List<List<Integer>> result = DBUtils.splitIntoBatches(list);
assertEquals(3, result.size()); assertEquals(3, result.size());
assertEquals(10192, result.get(0).size()); assertEquals(10192, result.get(0).size());
assertEquals(10192, result.get(1).size()); assertEquals(10192, result.get(1).size());
@ -41,7 +41,9 @@ public class DBUtilsTest {
for (int i = 0; i < 10192; i++) { for (int i = 0; i < 10192; i++) {
list.add(i); list.add(i);
} }
List<List<Integer>> result = DBUtils.splitIntoBatches(list); List<List<Integer>> result = DBUtils.splitIntoBatches(list);
assertEquals(1, result.size()); assertEquals(1, result.size());
assertEquals(10192, result.get(0).size()); assertEquals(10192, result.get(0).size());
} }
@ -55,7 +57,9 @@ public class DBUtilsTest {
map.get(i).add(j); map.get(i).add(j);
} }
} }
List<List<Container<Integer>>> result = DBUtils.splitIntoBatchesId(map); List<List<Container<Integer>>> result = DBUtils.splitIntoBatchesId(map);
assertEquals(3, result.size()); assertEquals(3, result.size());
assertEquals(10192, result.get(0).size()); assertEquals(10192, result.get(0).size());
assertEquals(10192, result.get(1).size()); assertEquals(10192, result.get(1).size());

View File

@ -1,4 +1,4 @@
package test.java.main.java.com.djrapitops.plan.database; package main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.TPS; import main.java.com.djrapitops.plan.data.TPS;
@ -39,20 +39,18 @@ public class DatabaseCommitTest {
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit t = TestInit.init(); TestInit t = TestInit.init();
plan = t.getPlanMock(); plan = t.getPlanMock();
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
File f = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(f).size();
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
db.init(); db.init();
File file = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(file).size();
} }
/**
* @throws IOException
* @throws SQLException
*/
@After @After
public void tearDown() throws IOException, SQLException { public void tearDown() throws IOException, SQLException {
db.close(); db.close();
File f = new File(plan.getDataFolder(), "Errors.txt"); File f = new File(plan.getDataFolder(), "Errors.txt");
List<String> lines = FileUtil.lines(f); List<String> lines = FileUtil.lines(f);
int rowsAgain = lines.size(); int rowsAgain = lines.size();
@ -61,6 +59,7 @@ public class DatabaseCommitTest {
System.out.println(line); System.out.println(line);
} }
} }
assertTrue("Errors were caught.", rows == rowsAgain); assertTrue("Errors were caught.", rows == rowsAgain);
} }

View File

@ -3,14 +3,13 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.database; package main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.Plan; import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.api.exceptions.DatabaseInitException; import main.java.com.djrapitops.plan.api.exceptions.DatabaseInitException;
import main.java.com.djrapitops.plan.data.*; import main.java.com.djrapitops.plan.data.*;
import main.java.com.djrapitops.plan.data.time.GMTimes; import main.java.com.djrapitops.plan.data.time.GMTimes;
import main.java.com.djrapitops.plan.data.time.WorldTimes; import main.java.com.djrapitops.plan.data.time.WorldTimes;
import main.java.com.djrapitops.plan.database.Database;
import main.java.com.djrapitops.plan.database.databases.MySQLDB; import main.java.com.djrapitops.plan.database.databases.MySQLDB;
import main.java.com.djrapitops.plan.database.databases.SQLiteDB; import main.java.com.djrapitops.plan.database.databases.SQLiteDB;
import main.java.com.djrapitops.plan.database.tables.*; import main.java.com.djrapitops.plan.database.tables.*;
@ -26,6 +25,7 @@ import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.MockUtils; import test.java.utils.MockUtils;
import test.java.utils.RandomData;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.io.File; import java.io.File;
@ -52,16 +52,16 @@ public class DatabaseTest {
private Database backup; private Database backup;
private int rows; private int rows;
public DatabaseTest() {
}
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit t = TestInit.init(); TestInit t = TestInit.init();
plan = t.getPlanMock(); plan = t.getPlanMock();
db = new SQLiteDB(plan, "debug" + MiscUtils.getTime()); db = new SQLiteDB(plan, "debug" + MiscUtils.getTime());
db.init(); db.init();
db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, TestInit.getServerUUID(), "ServerName", "")); db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, TestInit.getServerUUID(), "ServerName", ""));
File f = new File(plan.getDataFolder(), "Errors.txt"); File f = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(f).size(); rows = FileUtil.lines(f).size();
} }
@ -72,6 +72,7 @@ public class DatabaseTest {
if (backup != null) { if (backup != null) {
backup.close(); backup.close();
} }
File f = new File(plan.getDataFolder(), "Errors.txt"); File f = new File(plan.getDataFolder(), "Errors.txt");
List<String> lines = FileUtil.lines(f); List<String> lines = FileUtil.lines(f);
@ -81,6 +82,7 @@ public class DatabaseTest {
System.out.println(line); System.out.println(line);
} }
} }
assertTrue("Errors were caught.", rows == rowsAgain); assertTrue("Errors were caught.", rows == rowsAgain);
} }
@ -90,22 +92,22 @@ public class DatabaseTest {
} }
@Test @Test
public void testSqLiteGetConfigName() { public void testSQLiteGetConfigName() {
assertEquals("sqlite", db.getConfigName()); assertEquals("sqlite", db.getConfigName());
} }
@Test @Test
public void testSqLiteGetgName() { public void testSQLiteGetName() {
assertEquals("SQLite", db.getName()); assertEquals("SQLite", db.getName());
} }
@Test @Test
public void testMysqlGetConfigName() { public void testMySQLGetConfigName() {
assertEquals("mysql", new MySQLDB(plan).getConfigName()); assertEquals("mysql", new MySQLDB(plan).getConfigName());
} }
@Test @Test
public void testMysqlGetName() { public void testMySQLGetName() {
assertEquals("MySQL", new MySQLDB(plan).getName()); assertEquals("MySQL", new MySQLDB(plan).getName());
} }
@ -120,15 +122,19 @@ public class DatabaseTest {
expected.put("help", 21); expected.put("help", 21);
commandUseTable.commandUsed("plan"); commandUseTable.commandUsed("plan");
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
commandUseTable.commandUsed("tp"); commandUseTable.commandUsed("tp");
} }
for (int i = 0; i < 7; i++) { for (int i = 0; i < 7; i++) {
commandUseTable.commandUsed("pla"); commandUseTable.commandUsed("pla");
} }
for (int i = 0; i < 21; i++) { for (int i = 0; i < 21; i++) {
commandUseTable.commandUsed("help"); commandUseTable.commandUsed("help");
} }
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
commandUseTable.commandUsed("roiergbnougbierubieugbeigubeigubgierbgeugeg"); commandUseTable.commandUsed("roiergbnougbierubieugbeigubeigubgierbgeugeg");
} }
@ -141,9 +147,11 @@ public class DatabaseTest {
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
commandUseTable.commandUsed("test"); commandUseTable.commandUsed("test");
} }
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
commandUseTable.commandUsed("tp"); commandUseTable.commandUsed("tp");
} }
expected.put("test", 3); expected.put("test", 3);
expected.put("tp", 6); expected.put("tp", 6);
@ -156,21 +164,29 @@ public class DatabaseTest {
public void testCommandUseTableIDSystem() throws SQLException { public void testCommandUseTableIDSystem() throws SQLException {
CommandUseTable commandUseTable = db.getCommandUseTable(); CommandUseTable commandUseTable = db.getCommandUseTable();
commandUseTable.commandUsed("plan"); commandUseTable.commandUsed("plan");
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
commandUseTable.commandUsed("tp"); commandUseTable.commandUsed("tp");
} }
for (int i = 0; i < 7; i++) { for (int i = 0; i < 7; i++) {
commandUseTable.commandUsed("pla"); commandUseTable.commandUsed("pla");
} }
for (int i = 0; i < 21; i++) { for (int i = 0; i < 21; i++) {
commandUseTable.commandUsed("help"); commandUseTable.commandUsed("help");
} }
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
commandUseTable.commandUsed("roiergbnougbierubieugbeigubeigubgierbgeugeg"); commandUseTable.commandUsed("roiergbnougbierubieugbeigubeigubgierbgeugeg");
} }
Optional<Integer> id = commandUseTable.getCommandID("plan"); Optional<Integer> id = commandUseTable.getCommandID("plan");
assertTrue(id.isPresent()); assertTrue(id.isPresent());
Optional<String> commandByID = commandUseTable.getCommandByID(id.get()); Optional<String> commandByID = commandUseTable.getCommandByID(id.get());
assertTrue(commandByID.isPresent()); assertTrue(commandByID.isPresent());
assertEquals("plan", commandByID.get()); assertEquals("plan", commandByID.get());
assertFalse(commandUseTable.getCommandID("roiergbnougbierubieugbeigubeigubgierbgeugeg").isPresent()); assertFalse(commandUseTable.getCommandID("roiergbnougbierubieugbeigubeigubgierbgeugeg").isPresent());
@ -181,20 +197,11 @@ public class DatabaseTest {
TPSTable tpsTable = db.getTpsTable(); TPSTable tpsTable = db.getTpsTable();
Random r = new Random(); Random r = new Random();
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
int availableProcessors = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
final double averageCPUUsage = MathUtils.round(operatingSystemMXBean.getSystemLoadAverage() / availableProcessors * 100.0);
final long usedMemory = 51231251254L;
final int entityCount = 6123;
final int chunksLoaded = 2134;
List<TPS> expected = new ArrayList<>(); List<TPS> expected = new ArrayList<>();
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); for (int i = 0; i < RandomData.randomInt(1, 5); i++) {
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), r.nextDouble(), r.nextLong(), r.nextInt(), r.nextInt()));
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded)); }
expected.add(new TPS(r.nextLong(), r.nextDouble(), r.nextInt(100000000), averageCPUUsage, usedMemory, entityCount, chunksLoaded));
for (TPS tps : expected) { for (TPS tps : expected) {
tpsTable.insertTPS(tps); tpsTable.insertTPS(tps);
@ -581,6 +588,7 @@ public class DatabaseTest {
assertFalse(usersTable.isRegistered(uuid)); assertFalse(usersTable.isRegistered(uuid));
assertFalse(usersTable.isRegistered(uuid2)); assertFalse(usersTable.isRegistered(uuid2));
assertFalse(userInfoTable.isRegistered(uuid)); assertFalse(userInfoTable.isRegistered(uuid));
assertTrue(nicknamesTable.getNicknames(uuid).isEmpty()); assertTrue(nicknamesTable.getNicknames(uuid).isEmpty());
assertTrue(ipsTable.getGeolocations(uuid).isEmpty()); assertTrue(ipsTable.getGeolocations(uuid).isEmpty());
assertTrue(ipsTable.getIps(uuid).isEmpty()); assertTrue(ipsTable.getIps(uuid).isEmpty());

View File

@ -3,52 +3,37 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.ui; package main.java.com.djrapitops.plan.ui;
import main.java.com.djrapitops.plan.utilities.html.Html; import main.java.com.djrapitops.plan.utilities.html.Html;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull;
/** /**
* @author Rsl1122 * @author Rsl1122
*/ */
public class HtmlTest { public class HtmlTest {
/**
*
*/
public HtmlTest() {
}
/**
*
*/
@Test @Test
public void testParseWithZeroArgs() { public void testParseWithZeroArgs() {
Html instance = Html.SPAN;
String expResult = "${0}</span>"; String expResult = "${0}</span>";
String result = instance.parse(); String result = Html.SPAN.parse();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/**
*
*/
@Test @Test
public void testParseStringArr() { public void testParseStringArr() {
Html instance = Html.SPAN;
String expResult = "Test</span>"; String expResult = "Test</span>";
String result = instance.parse("Test"); String result = Html.SPAN.parse("Test");
assertEquals(expResult, result); assertEquals(expResult, result);
} }
/**
*
*/
@Test @Test
public void testNoBackSlash() { public void testNoBackSlash() {
assertTrue("Null for some reason", Html.TABLELINE_2.parse("/\\", "0") != null); assertNotNull(Html.TABLELINE_2.parse("/\\", "0"));
} }
} }

View File

@ -2,13 +2,14 @@
* Licence is provided in the jar as license.yml also here: * Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml * https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/ */
package test.java.main.java.com.djrapitops.plan.ui.graphs; package main.java.com.djrapitops.plan.ui.graphs;
import main.java.com.djrapitops.plan.data.Session; import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS; import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.time.WorldTimes; import main.java.com.djrapitops.plan.data.time.WorldTimes;
import main.java.com.djrapitops.plan.utilities.analysis.Point; import main.java.com.djrapitops.plan.utilities.analysis.Point;
import main.java.com.djrapitops.plan.utilities.html.graphs.*; import main.java.com.djrapitops.plan.utilities.html.graphs.*;
import org.apache.commons.lang3.StringUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import test.java.utils.RandomData; import test.java.utils.RandomData;
@ -57,19 +58,13 @@ public class GraphTest {
@Test @Test
public void testSeriesCreator() { public void testSeriesCreator() {
String result = SeriesCreator.seriesGraph(points, false, false).replaceAll("[\\[\\]]", ""); String result = StringUtils.removeAll(SeriesCreator.seriesGraph(points, false, false), "[\\[\\]]");
String[] splittedResult = result.split(","); String[] splittedResult = result.split(",");
Map<String, String> expected = new LinkedHashMap<>(); Map<String, String> expected = new LinkedHashMap<>();
String key = null; for (int i = 0; i < splittedResult.length; i++) {
for (String resultString : splittedResult) { expected.put(splittedResult[i++], splittedResult[i]);
if (key == null) {
key = resultString;
} else {
expected.put(key, resultString);
key = null;
}
} }
int i2 = 0; int i2 = 0;

View File

@ -1,7 +1,6 @@
package test.java.main.java.com.djrapitops.plan.utilities; package main.java.com.djrapitops.plan.utilities;
import com.djrapitops.plugin.command.ISender; import com.djrapitops.plugin.command.ISender;
import main.java.com.djrapitops.plan.utilities.Check;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;

View File

@ -1,6 +1,5 @@
package test.java.main.java.com.djrapitops.plan.utilities; package main.java.com.djrapitops.plan.utilities;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@ -10,6 +9,7 @@ import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.MockUtils; import test.java.utils.MockUtils;
import test.java.utils.RandomData;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -33,8 +33,10 @@ public class FormatUtilsTest {
@Test @Test
public void testFormatTimeAmount() { public void testFormatTimeAmount() {
long ms = 1000L; long ms = 1000L;
String expResult = "1s"; String expResult = "1s";
String result = FormatUtils.formatTimeAmount(ms); String result = FormatUtils.formatTimeAmount(ms);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -45,6 +47,7 @@ public class FormatUtilsTest {
String expResult = "10s"; String expResult = "10s";
String result = FormatUtils.formatTimeAmountDifference(before.getTime(), now.getTime()); String result = FormatUtils.formatTimeAmountDifference(before.getTime(), now.getTime());
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -59,6 +62,7 @@ public class FormatUtilsTest {
long epochZero = 0L; long epochZero = 0L;
String result = FormatUtils.formatTimeStamp(epochZero); String result = FormatUtils.formatTimeStamp(epochZero);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -73,6 +77,7 @@ public class FormatUtilsTest {
long epochZero = 0L; long epochZero = 0L;
String result = FormatUtils.formatTimeStampYear(epochZero); String result = FormatUtils.formatTimeStampYear(epochZero);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -87,6 +92,7 @@ public class FormatUtilsTest {
long epochZero = 0L; long epochZero = 0L;
String result = FormatUtils.formatTimeStampSecond(epochZero); String result = FormatUtils.formatTimeStampSecond(epochZero);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -94,7 +100,9 @@ public class FormatUtilsTest {
public void testRemoveLetters() { public void testRemoveLetters() {
String dataPoint = "435729847jirggu.eiwb¤#¤%¤#"; String dataPoint = "435729847jirggu.eiwb¤#¤%¤#";
String expResult = "435729847."; String expResult = "435729847.";
String result = FormatUtils.removeLetters(dataPoint); String result = FormatUtils.removeLetters(dataPoint);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -102,7 +110,9 @@ public class FormatUtilsTest {
public void testRemoveNumbers() { public void testRemoveNumbers() {
String dataPoint = "34532453.5 $"; String dataPoint = "34532453.5 $";
String expResult = "$"; String expResult = "$";
String result = FormatUtils.removeNumbers(dataPoint); String result = FormatUtils.removeNumbers(dataPoint);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -110,7 +120,9 @@ public class FormatUtilsTest {
public void testRemoveNumbers2() { public void testRemoveNumbers2() {
String dataPoint = "l43r4545tl43 4.5"; String dataPoint = "l43r4545tl43 4.5";
String expResult = "lrtl"; String expResult = "lrtl";
String result = FormatUtils.removeNumbers(dataPoint); String result = FormatUtils.removeNumbers(dataPoint);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -118,7 +130,9 @@ public class FormatUtilsTest {
public void testParseVersionNumber() { public void testParseVersionNumber() {
String versionString = "2.10.2"; String versionString = "2.10.2";
int expResult = 21002; int expResult = 21002;
int result = FormatUtils.parseVersionNumber(versionString); int result = FormatUtils.parseVersionNumber(versionString);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -126,41 +140,58 @@ public class FormatUtilsTest {
public void testVersionNumber() { public void testVersionNumber() {
String versionString = "2.10.2"; String versionString = "2.10.2";
String versionString2 = "2.9.3"; String versionString2 = "2.9.3";
int result = FormatUtils.parseVersionNumber(versionString); int result = FormatUtils.parseVersionNumber(versionString);
int result2 = FormatUtils.parseVersionNumber(versionString2); int result2 = FormatUtils.parseVersionNumber(versionString2);
assertTrue("Higher version not higher", result > result2); assertTrue("Higher version not higher", result > result2);
} }
@Test @Test
public void testMergeArrays() { public void testMergeArrays() {
String[][] arrays = new String[][]{new String[]{"Test", "One"}, new String[]{"Test", "Two"}}; String randomString1 = RandomData.randomString(10);
String[] expResult = new String[]{"Test", "One", "Test", "Two"}; String randomString2 = RandomData.randomString(10);
String randomString3 = RandomData.randomString(10);
String randomString4 = RandomData.randomString(10);
String[][] arrays = new String[][]{new String[]{randomString1, randomString2}, new String[]{randomString3, randomString4}};
String[] expResult = new String[]{randomString1, randomString2, randomString3, randomString4};
String[] result = FormatUtils.mergeArrays(arrays); String[] result = FormatUtils.mergeArrays(arrays);
assertArrayEquals(expResult, result); assertArrayEquals(expResult, result);
} }
@Test @Test
public void testFormatLocation() { public void testFormatLocation() {
int randomInt = RandomData.randomInt(0, 100);
World mockWorld = MockUtils.mockWorld(); World mockWorld = MockUtils.mockWorld();
Location loc = new Location(mockWorld, 0, 0, 0); Location loc = new Location(mockWorld, randomInt, randomInt, randomInt);
String expResult = "x 0 z 0 in World";
String expResult = "x " + randomInt + " z " + randomInt + " in World";
String result = FormatUtils.formatLocation(loc); String result = FormatUtils.formatLocation(loc);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
public void testCutDecimals() throws Exception { public void testCutDecimalsWhichIsRoundedDown() throws Exception {
double d = 0.05234; double d = 0.05234;
String expResult = "0,05"; String expResult = "0,05";
String result = FormatUtils.cutDecimals(d); String result = FormatUtils.cutDecimals(d);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
public void testCutDecimals2() throws Exception { public void testCutDecimalsWhichIsRoundedUp() throws Exception {
double d = 0.05634; double d = 0.05634;
String expResult = "0,06"; String expResult = "0,06";
String result = FormatUtils.cutDecimals(d); String result = FormatUtils.cutDecimals(d);
assertEquals(expResult, result); assertEquals(expResult, result);
} }

View File

@ -3,7 +3,7 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.utilities; package main.java.com.djrapitops.plan.utilities;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import main.java.com.djrapitops.plan.utilities.html.HtmlUtils; import main.java.com.djrapitops.plan.utilities.html.HtmlUtils;
@ -57,7 +57,7 @@ public class HtmlUtilsTest {
public void testRemoveXSS() { public void testRemoveXSS() {
String randomString = RandomData.randomString(10); String randomString = RandomData.randomString(10);
String xss = "<script>" + randomString + "</script><!--"; String xss = "<script>" + randomString + "</script><!---->";
String result = HtmlUtils.removeXSS(xss); String result = HtmlUtils.removeXSS(xss);
assertEquals(randomString, result); assertEquals(randomString, result);

View File

@ -3,11 +3,10 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.utilities; package main.java.com.djrapitops.plan.utilities;
import com.djrapitops.plugin.command.ISender; import com.djrapitops.plugin.command.ISender;
import com.djrapitops.plugin.command.bukkit.BukkitCMDSender; import com.djrapitops.plugin.command.bukkit.BukkitCMDSender;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Ignore; import org.junit.Ignore;
@ -30,47 +29,59 @@ import static org.junit.Assert.assertEquals;
public class MiscUtilsTest { public class MiscUtilsTest {
@Test @Test
public void testGetPlayerDisplaynameArgsPerm() { public void testGetPlayerDisplayNameArgsPerm() {
String[] args = new String[]{"Rsl1122", "Test"}; String[] args = new String[]{"Rsl1122", "Test"};
ISender sender = new BukkitCMDSender(MockUtils.mockPlayer()); ISender sender = new BukkitCMDSender(MockUtils.mockPlayer());
String expResult = "Rsl1122"; String expResult = "Rsl1122";
String result = MiscUtils.getPlayerName(args, sender); String result = MiscUtils.getPlayerName(args, sender);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
public void testGetPlayerDisplaynameArgsNoPerm() { public void testGetPlayerDisplayNameArgsNoPerm() throws Exception {
TestInit.init();
String[] args = new String[]{"Rsl1122", "Test"}; String[] args = new String[]{"Rsl1122", "Test"};
ISender sender = new BukkitCMDSender(MockUtils.mockPlayer()); ISender sender = new BukkitCMDSender(MockUtils.mockPlayer2());
String expResult = "Rsl1122";
String expResult = "";
String result = MiscUtils.getPlayerName(args, sender); String result = MiscUtils.getPlayerName(args, sender);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
public void testGetPlayerDisplaynameNoArgsPerm() { public void testGetPlayerDisplayNameNoArgsPerm() {
String[] args = new String[]{}; String[] args = new String[]{};
ISender sender = new BukkitCMDSender(MockUtils.mockPlayer()); ISender sender = new BukkitCMDSender(MockUtils.mockPlayer());
String expResult = "TestName"; String expResult = "TestName";
String result = MiscUtils.getPlayerName(args, sender); String result = MiscUtils.getPlayerName(args, sender);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
public void testGetPlayerDisplaynameNoArgsNoPerm() { public void testGetPlayerDisplayNameNoArgsNoPerm() {
String[] args = new String[]{}; String[] args = new String[]{};
ISender sender = new BukkitCMDSender(MockUtils.mockPlayer2()); ISender sender = new BukkitCMDSender(MockUtils.mockPlayer2());
String expResult = "TestName2"; String expResult = "TestName2";
String result = MiscUtils.getPlayerName(args, sender); String result = MiscUtils.getPlayerName(args, sender);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
public void testGetPlayerDisplaynameOwnNameNoPerm() { public void testGetPlayerDisplayNameOwnNameNoPerm() {
String[] args = new String[]{"testname2"}; String[] args = new String[]{"testname2"};
ISender sender = new BukkitCMDSender(MockUtils.mockPlayer2()); ISender sender = new BukkitCMDSender(MockUtils.mockPlayer2());
String expResult = "TestName2"; String expResult = "TestName2";
String result = MiscUtils.getPlayerName(args, sender); String result = MiscUtils.getPlayerName(args, sender);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -78,19 +89,23 @@ public class MiscUtilsTest {
public void testGetPlayerDisplaynameConsole() { public void testGetPlayerDisplaynameConsole() {
String[] args = new String[]{"TestConsoleSender"}; String[] args = new String[]{"TestConsoleSender"};
ISender sender = new BukkitCMDSender(MockUtils.mockConsoleSender()); ISender sender = new BukkitCMDSender(MockUtils.mockConsoleSender());
String expResult = "TestConsoleSender"; String expResult = "TestConsoleSender";
String result = MiscUtils.getPlayerName(args, sender); String result = MiscUtils.getPlayerName(args, sender);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@Test @Test
@Ignore("DB mock") @Ignore("DB mock")
public void testGetMatchingDisplaynames() throws Exception { public void testGetMatchingDisplayNames() throws Exception {
TestInit.init(); TestInit.init();
String search = "testname"; String search = "testname";
String exp1 = "TestName"; String exp1 = "TestName";
String exp2 = "TestName2"; String exp2 = "TestName2";
List<String> result = MiscUtils.getMatchingPlayerNames(search); List<String> result = MiscUtils.getMatchingPlayerNames(search);
assertEquals(2, result.size()); assertEquals(2, result.size());
assertEquals(exp1, result.get(0)); assertEquals(exp1, result.get(0));
assertEquals(exp2, result.get(1)); assertEquals(exp2, result.get(1));
@ -98,11 +113,14 @@ public class MiscUtilsTest {
@Test @Test
@Ignore("DB mock") @Ignore("DB mock")
public void testGetMatchingDisplaynames2() throws Exception { public void testGetMatchingDisplayNames2() throws Exception {
TestInit.init(); TestInit.init();
String search = "2"; String search = "2";
String exp2 = "TestName2"; String exp2 = "TestName2";
List<String> result = MiscUtils.getMatchingPlayerNames(search); List<String> result = MiscUtils.getMatchingPlayerNames(search);
assertEquals(1, result.size()); assertEquals(1, result.size());
assertEquals(exp2, result.get(0)); assertEquals(exp2, result.get(0));
} }

View File

@ -1,6 +1,5 @@
package test.java.main.java.com.djrapitops.plan.utilities; package main.java.com.djrapitops.plan.utilities;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import test.java.utils.RandomData; import test.java.utils.RandomData;
@ -20,8 +19,8 @@ public class PassEncryptTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
for (int i = 0; i < 20; i++) { for (int i = 0; i < RandomData.randomInt(1, 10); i++) {
String password = RandomData.randomString(RandomData.randomInt(1, 20)); String password = RandomData.randomString(RandomData.randomInt(5, 16));
PASSWORD_MAP.put(password, PassEncryptUtil.createHash(password)); PASSWORD_MAP.put(password, PassEncryptUtil.createHash(password));
} }
} }

View File

@ -3,11 +3,10 @@
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package test.java.main.java.com.djrapitops.plan.utilities.analysis; package main.java.com.djrapitops.plan.utilities.analysis;
import main.java.com.djrapitops.plan.data.Session; import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.utilities.MiscUtils; import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.AnalysisUtils;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -16,9 +15,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -29,106 +26,81 @@ import static org.junit.Assert.assertEquals;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class AnalysisUtilsTest { public class AnalysisUtilsTest {
/**
*
*/
public AnalysisUtilsTest() {
}
/**
*
*/
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit.init(); TestInit.init();
} }
/**
*
*/
@Test @Test
public void testIsActive() { public void testIsActive() {
long lastPlayed = MiscUtils.getTime(); long lastPlayed = MiscUtils.getTime();
long playTime = 12638934876L; long playTime = 12638934876L;
int loginTimes = 4; int loginTimes = 4;
boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes); boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes);
assertEquals(true, result); assertEquals(true, result);
} }
/**
*
*/
@Test @Test
public void testIsNotActive2() { public void testIsNotActive2() {
long lastPlayed = MiscUtils.getTime(); long lastPlayed = MiscUtils.getTime();
long playTime = 0L; long playTime = 0L;
int loginTimes = 4; int loginTimes = 4;
boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes); boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes);
assertEquals(false, result); assertEquals(false, result);
} }
/**
*
*/
@Test @Test
public void testIsNotActive3() { public void testIsNotActive3() {
long lastPlayed = MiscUtils.getTime(); long lastPlayed = MiscUtils.getTime();
long playTime = 12638934876L; long playTime = 12638934876L;
int loginTimes = 0; int loginTimes = 0;
boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes); boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes);
assertEquals(false, result); assertEquals(false, result);
} }
/**
*
*/
@Test @Test
public void testIsNotActive() { public void testIsNotActive() {
long lastPlayed = 0L; long lastPlayed = 0L;
long playTime = 12638934876L; long playTime = 12638934876L;
int loginTimes = 4; int loginTimes = 4;
boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes); boolean result = AnalysisUtils.isActive(System.currentTimeMillis(), lastPlayed, playTime, loginTimes);
assertEquals(false, result); assertEquals(false, result);
} }
/**
*
*/
@Test @Test
public void testGetNewPlayers() { public void testGetNewPlayers() {
List<Long> registered = new ArrayList<>(); List<Long> registered = Arrays.asList(5L, 1L);
registered.add(5L);
registered.add(1L);
long scale = 8L; long scale = 8L;
long now = 10L; long now = 10L;
long result = AnalysisUtils.getNewPlayers(registered, scale, now); long result = AnalysisUtils.getNewPlayers(registered, scale, now);
assertEquals(1L, result); assertEquals(1L, result);
} }
/**
*
*/
@Test @Test
public void testGetNewPlayersEmpty() { public void testGetNewPlayersEmpty() {
List<Long> registered = new ArrayList<>();
long scale = 1L; long scale = 1L;
long now = 2L; long now = 2L;
long result = AnalysisUtils.getNewPlayers(registered, scale, now); long result = AnalysisUtils.getNewPlayers(Collections.emptyList(), scale, now);
assertEquals(0L, result); assertEquals(0L, result);
} }
/**
*
*/
@Test @Test
public void testTransformSessionDataToLengths() { public void testTransformSessionDataToLengths() {
Collection<Session> data = new ArrayList<>(); Collection<Session> data = Arrays.asList(
data.add(new Session(1, 0L, 5L, 0, 0)); new Session(1, 0L, 5L, 0, 0),
data.add(new Session(1, 0, 20L, 0, 0)); new Session(1, 0L, 20L, 0, 0)
List<Long> expResult = new ArrayList<>(); );
expResult.add(5L);
expResult.add(20L); List<Long> expResult = Arrays.asList(5L, 20L);
List<Long> result = AnalysisUtils.transformSessionDataToLengths(data); List<Long> result = AnalysisUtils.transformSessionDataToLengths(data);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
} }

View File

@ -0,0 +1,128 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package main.java.com.djrapitops.plan.utilities.analysis;
import org.junit.Test;
import test.java.utils.RandomData;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertTrue;
/**
* @author Rsl1122
*/
public class MathUtilsTest {
@Test
public void testAverageInt() {
List<Integer> integers = Arrays.asList(0, 20, 5, 15);
double exp = 10;
double result = MathUtils.averageInt(integers.stream());
assertTrue(Double.compare(exp, result) == 0);
}
@Test
public void testAverageIntEmpty() {
List<Integer> integers = Collections.emptyList();
double exp = 0;
double result = MathUtils.averageInt(integers.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testAverageLongCollection() {
List<Long> longs = Arrays.asList(0L, 20L, 5L, 15L);
double exp = 10;
double result = MathUtils.averageLong(longs);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testAverageDouble() {
List<Double> doubles = Arrays.asList(0.0, 20.5, 4.5, 15.0);
double exp = 10;
double result = MathUtils.averageDouble(doubles.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testAverage() {
double exp = 10;
double result = MathUtils.average(40, 4);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testCountTrueBoolean() {
List<Boolean> booleans = new ArrayList<>();
int exp = RandomData.randomInt(0, 1000);
for (int i = 0; i < exp; i++) {
booleans.add(true);
}
for (int i = exp; i < RandomData.randomInt(100, 1000); i++) {
booleans.add(false);
}
long result = MathUtils.countTrueBoolean(booleans.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testSumInt() {
List<Serializable> serializable = Arrays.asList(0, 20, 5, 15);
double exp = 40;
double result = MathUtils.sumInt(serializable.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testSumLong() {
List<Serializable> serializable = Arrays.asList(0L, 20L, 5L, 15L);
long exp = 40;
long result = MathUtils.sumLong(serializable.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testSumDouble() {
List<Serializable> serializable = Arrays.asList(0.0, 50.4, 45.0, 5.0531541);
double exp = 100.4531541;
double result = MathUtils.sumDouble(serializable.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testRoundDouble() {
double exp = 412.5123125123;
double result = MathUtils.round(exp);
assertTrue(result + "/" + exp, Double.compare(412.51, result) == 0);
}
}

View File

@ -0,0 +1,137 @@
package main.java.com.djrapitops.plan.utilities.comparators;
import com.google.common.collect.Ordering;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.locale.Message;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
import org.junit.Test;
import test.java.utils.RandomData;
import java.util.*;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
public class ComparatorTest {
@Test
public void testPointComparator() {
List<Point> points = RandomData.randomPoints();
List<Long> longValues = points.stream().map(Point::getX).map(i -> (long) (double) i).collect(Collectors.toList());
longValues.sort(Long::compare);
points.sort(new PointComparator());
List<Long> afterSort = points.stream().map(Point::getX).map(i -> (long) (double) i).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testSessionDataComparator() {
List<Session> sessions = RandomData.randomSessions();
List<Long> longValues = sessions.stream().map(Session::getSessionStart).collect(Collectors.toList());
longValues.sort(Long::compare);
Collections.reverse(longValues);
sessions.sort(new SessionStartComparator());
List<Long> afterSort = sessions.stream().map(Session::getSessionStart).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testTPSComparator() {
List<TPS> tpsList = RandomData.randomTPS();
List<Long> longValues = tpsList.stream().map(TPS::getDate).collect(Collectors.toList());
longValues.sort(Long::compare);
tpsList.sort(new TPSComparator());
List<Long> afterSort = tpsList.stream().map(TPS::getDate).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testUserDataLastPlayedComparator() {
List<UserInfo> userInfo = RandomData.randomUserData();
List<Long> longValues = userInfo.stream().map(UserInfo::getLastSeen).collect(Collectors.toList());
longValues.sort(Long::compare);
Collections.reverse(longValues);
userInfo.sort(new UserInfoLastPlayedComparator());
List<Long> afterSort = userInfo.stream().map(UserInfo::getLastSeen).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testUserDataNameComparator() {
List<UserInfo> userInfo = RandomData.randomUserData();
List<String> stringValues = userInfo.stream().map(UserInfo::getName).collect(Collectors.toList());
Collections.sort(stringValues);
userInfo.sort(new UserDataNameComparator());
List<String> afterSort = userInfo.stream().map(UserInfo::getName).collect(Collectors.toList());
assertEquals(stringValues, afterSort);
}
@Test
public void testWebUserComparator() throws PassEncryptUtil.CannotPerformOperationException {
List<WebUser> webUsers = RandomData.randomWebUsers();
List<Integer> intValues = webUsers.stream().map(WebUser::getPermLevel).collect(Collectors.toList());
intValues.sort(Integer::compare);
Collections.reverse(intValues);
webUsers.sort(new WebUserComparator());
List<Integer> afterSort = webUsers.stream().map(WebUser::getPermLevel).collect(Collectors.toList());
assertEquals(intValues, afterSort);
}
@Test
public void testStringLengthComparator() {
List<String> strings = Ordering.from(new StringLengthComparator())
.sortedCopy(Arrays.asList(
RandomData.randomString(10),
RandomData.randomString(3),
RandomData.randomString(20),
RandomData.randomString(7),
RandomData.randomString(4),
RandomData.randomString(86),
RandomData.randomString(6))
);
assertEquals(86, strings.get(0).length());
assertEquals(20, strings.get(1).length());
assertEquals(3, strings.get(strings.size() - 1).length());
}
@Test
public void testLocaleEntryComparator() {
Map<Msg, Message> messageMap = new HashMap<>();
messageMap.put(Msg.CMD_CONSTANT_FOOTER, new Message(RandomData.randomString(10)));
messageMap.put(Msg.ANALYSIS_3RD_PARTY, new Message(RandomData.randomString(10)));
messageMap.put(Msg.MANAGE_FAIL_NO_PLAYERS, new Message(RandomData.randomString(10)));
List<String> sorted = messageMap.entrySet().stream()
.sorted(new LocaleEntryComparator())
.map(entry -> entry.getKey().name())
.collect(Collectors.toList());
assertEquals(Msg.ANALYSIS_3RD_PARTY.name(), sorted.get(0));
assertEquals(Msg.CMD_CONSTANT_FOOTER.name(), sorted.get(1));
assertEquals(Msg.MANAGE_FAIL_NO_PLAYERS.name(), sorted.get(2));
}
}

View File

@ -1,4 +1,4 @@
package test.java.main.java.com.djrapitops.plan.utilities.dump; package main.java.com.djrapitops.plan.utilities.dump;
import main.java.com.djrapitops.plan.utilities.file.dump.DumpLog; import main.java.com.djrapitops.plan.utilities.file.dump.DumpLog;
import org.junit.Test; import org.junit.Test;

View File

@ -1,4 +1,4 @@
package test.java.main.java.com.djrapitops.plan.utilities.dump; package main.java.com.djrapitops.plan.utilities.dump;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import main.java.com.djrapitops.plan.Log; import main.java.com.djrapitops.plan.Log;
@ -15,7 +15,7 @@ import test.java.utils.RandomData;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicBoolean;
import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull; import static junit.framework.TestCase.assertNotNull;
@ -28,25 +28,26 @@ import static junit.framework.TestCase.assertNotNull;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class HastebinTest { public class HastebinTest {
private final AtomicReference<String> testLink = new AtomicReference<>(null); private final AtomicBoolean testLink = new AtomicBoolean(false);
@Before @Before
public void checkAvailability() throws Exception { public void checkAvailability() throws Exception {
TestInit.init(); TestInit.init();
Thread thread = new Thread(() -> { Thread thread = new Thread(() -> {
String link = null;
try { try {
link = Hastebin.upload(RandomData.randomString(10)); Hastebin.upload(RandomData.randomString(10));
} catch (IOException e) { } catch (IOException e) {
if (e.getMessage().contains("503")) { if (e.getMessage().contains("503")) {
return; return;
} }
Log.toLog("checkAvailability()", e);
} catch (ParseException e) { } catch (ParseException e) {
/* Ignored */ /* Ignored */
} }
testLink.set(link); testLink.set(true);
}); });
thread.start(); thread.start();
@ -57,7 +58,7 @@ public class HastebinTest {
Log.info("Hastebin timed out"); Log.info("Hastebin timed out");
} }
Log.info("Hastebin Availability Test Link: " + testLink.get()); Log.info("Hastebin Available: " + testLink.get());
} }
@Test @Test
@ -72,7 +73,7 @@ public class HastebinTest {
@Test @Test
public void testUpload() throws Exception { public void testUpload() throws Exception {
if (testLink.get() == null) { if (!testLink.get()) {
Log.info("Hastebin not available, skipping testUpload()"); Log.info("Hastebin not available, skipping testUpload()");
return; return;
} }

View File

@ -8,9 +8,13 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.utils.RandomData;
import test.java.utils.TestInit; import test.java.utils.TestInit;
import java.util.*; import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -24,37 +28,35 @@ import static org.junit.Assert.assertEquals;
@PrepareForTest(JavaPlugin.class) @PrepareForTest(JavaPlugin.class)
public class HtmlStructureTest { public class HtmlStructureTest {
private Map<String, List<Session>> sessions; private Map<String, List<Session>> sessions = new HashMap<>();
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
TestInit t = TestInit.init(); TestInit.init();
sessions = new HashMap<>();
sessions.put("World 1", new ArrayList<>()); for (int i = 0; i < RandomData.randomInt(0, 5); i++) {
sessions.get("World 1").add(new Session(1, 12345L, 23455L, 1, 2)); sessions.put(RandomData.randomString(10), RandomData.randomSessions());
sessions.get("World 1").add(new Session(2, 23455L, 23457L, 1, 2)); }
sessions.put("World 2", new ArrayList<>());
sessions.get("World 2").add(new Session(3, 23455L, 23457L, 1, 2));
} }
@Test @Test
public void createServerOverviewColumn() throws Exception { public void createServerOverviewColumn() throws Exception {
String serverOverviewColumn = HtmlStructure.createServerOverviewColumn(sessions); String serverOverviewColumn = HtmlStructure.createServerOverviewColumn(sessions);
int opened = StringUtils.countMatches(serverOverviewColumn, "<div"); int opened = StringUtils.countMatches(serverOverviewColumn, "<div");
int closed = StringUtils.countMatches(serverOverviewColumn, "</div"); int closed = StringUtils.countMatches(serverOverviewColumn, "</div");
System.out.println(opened + " / " + closed);
assertEquals(opened, closed); assertEquals(opened, closed);
} }
@Test @Test
public void createSessionsTabContent() throws Exception { public void createSessionsTabContent() throws Exception {
List<Session> allSessions = sessions.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); List<Session> allSessions = sessions.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
String sessionsTab = HtmlStructure.createSessionsTabContent(sessions, allSessions); String sessionsTab = HtmlStructure.createSessionsTabContent(sessions, allSessions);
int opened = StringUtils.countMatches(sessionsTab, "<div"); int opened = StringUtils.countMatches(sessionsTab, "<div");
int closed = StringUtils.countMatches(sessionsTab, "</div"); int closed = StringUtils.countMatches(sessionsTab, "</div");
System.out.println(opened + " / " + closed);
assertEquals(opened, closed); assertEquals(opened, closed);
} }
} }

View File

@ -1,31 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test.java.main.java.com.djrapitops.plan;
import main.java.com.djrapitops.plan.Permissions;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Rsl1122
*/
public class PermissionsTest {
/**
*
*/
public PermissionsTest() {
}
/**
*
*/
@Test
public void testGetPermission() {
assertEquals("plan.inspect.other", Permissions.INSPECT_OTHER.getPerm());
}
}

View File

@ -1,59 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test.java.main.java.com.djrapitops.plan.data;
import main.java.com.djrapitops.plan.data.PlayerKill;
import org.junit.Before;
import org.junit.Test;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
/**
* @author Rsl1122
*/
public class PlayerKillTest {
private PlayerKill test;
private UUID testUUID;
/**
*
*/
public PlayerKillTest() {
}
@Before
public void setUp() throws Exception {
testUUID = UUID.fromString("71cfb6f0-c3ef-4954-8abe-13fa07afc340");
test = new PlayerKill(testUUID, "TestWeapon", 100L);
}
/**
*
*/
@Test
public void testGetVictim() {
assertEquals(test.getVictim(), testUUID);
}
/**
*
*/
@Test
public void testGetDate() {
assertEquals(test.getTime(), 100L);
}
/**
*
*/
@Test
public void testGetWeapon() {
assertEquals(test.getWeapon(), "TestWeapon");
}
}

View File

@ -1,40 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test.java.main.java.com.djrapitops.plan.data.additional;
import main.java.com.djrapitops.plan.data.additional.AnalysisType;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Rsl1122
*/
public class AnalysisTypeTest {
/**
*
*/
public AnalysisTypeTest() {
}
/**
*
*/
@Test
public void testGetModifier() {
assertEquals("Average ", AnalysisType.INT_AVG.getModifier());
}
/**
*
*/
@Test
public void testGetPlaceholderModifier() {
assertEquals("totalInt_", AnalysisType.INT_TOTAL.getPlaceholderModifier());
}
}

View File

@ -1,103 +0,0 @@
package test.java.main.java.com.djrapitops.plan.data.time;
import main.java.com.djrapitops.plan.data.time.GMTimes;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class GMTimesTest {
@Test
public void setAllGMTimes() throws Exception {
GMTimes test = new GMTimes();
test.setAllGMTimes(1L, 2L, 3L, 4L);
Map<String, Long> times = test.getTimes();
assertTrue(times.get("SURVIVAL") == 1L);
assertTrue(times.get("CREATIVE") == 2L);
assertTrue(times.get("ADVENTURE") == 3L);
assertTrue(times.get("SPECTATOR") == 4L);
}
@Test
public void setAllGMTimesTooFew() throws Exception {
GMTimes test = new GMTimes();
test.setAllGMTimes(1L, 2L);
Map<String, Long> times = test.getTimes();
assertTrue(times.get("SURVIVAL") == 1L);
assertTrue(times.get("CREATIVE") == 2L);
assertTrue(times.get("ADVENTURE") == 0L);
assertTrue(times.get("SPECTATOR") == 0L);
}
@Test
public void setAllGMTimesTooMany() throws Exception {
GMTimes test = new GMTimes();
test.setAllGMTimes(1L, 2L, 3L, 4L, 5L, 6L);
Map<String, Long> times = test.getTimes();
assertTrue(times.get("SURVIVAL") == 1L);
assertTrue(times.get("CREATIVE") == 2L);
assertTrue(times.get("ADVENTURE") == 3L);
assertTrue(times.get("SPECTATOR") == 4L);
}
@Test
public void resetTimes() throws Exception {
GMTimes test = new GMTimes();
test.setAllGMTimes(4, 3, 2, 1);
test.resetTimes(10);
assertTrue(10L == test.getTime("SURVIVAL"));
assertTrue(0L == test.getTime("ADVENTURE"));
}
@Test
public void setTime() throws Exception {
GMTimes test = new GMTimes();
test.setTime("SURVIVAL", 5L);
assertTrue(5L == test.getTime("SURVIVAL"));
}
@Test
public void renameState() throws Exception {
GMTimes test = new GMTimes();
test.setAllGMTimes(5L);
test.renameState("SURVIVAL", "Survival");
assertTrue(0L == test.getTime("SURVIVAL"));
assertTrue(5L == test.getTime("Survival"));
}
@Test
public void changeStateNormal() throws Exception {
GMTimes test = new GMTimes(new HashMap<>(), "SURVIVAL", 0);
test.changeState("CREATIVE", 5L);
assertTrue(5L == test.getTime("SURVIVAL"));
assertTrue(0L == test.getTime("CREATIVE"));
test.changeState("ADVENTURE", 20L);
assertTrue(5L == test.getTime("SURVIVAL"));
assertTrue(15L == test.getTime("CREATIVE"));
assertTrue(0L == test.getTime("ADVENTURE"));
}
@Test
public void changeStateMissingStartTime() throws Exception {
GMTimes test = new GMTimes("SURVIVAL");
test.changeState("CREATIVE", 5L);
assertTrue(5L == test.getTime("SURVIVAL"));
assertTrue(0L == test.getTime("CREATIVE"));
test.changeState("ADVENTURE", 20L);
assertTrue(5L == test.getTime("SURVIVAL"));
assertTrue(15L == test.getTime("CREATIVE"));
assertTrue(0L == test.getTime("ADVENTURE"));
}
@Test
public void changeStateMissingStartState() throws Exception {
GMTimes test = new GMTimes();
test.changeState("CREATIVE", 5L);
assertTrue(5L == test.getTime("CREATIVE"));
test.changeState("ADVENTURE", 20L);
assertTrue(20L == test.getTime("CREATIVE"));
assertTrue(0L == test.getTime("ADVENTURE"));
}
}

View File

@ -1,166 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test.java.main.java.com.djrapitops.plan.utilities.analysis;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import org.junit.Test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertTrue;
/**
* @author Rsl1122
*/
public class MathUtilsTest {
/**
*
*/
public MathUtilsTest() {
}
/**
*
*/
@Test
public void testAverageInt() {
List<Integer> l = new ArrayList<>();
double exp = 10;
l.add(0);
l.add(20);
l.add(5);
l.add(15);
double result = MathUtils.averageInt(l.stream());
assertTrue(Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testAverageIntEmpty() {
List<Integer> l = Collections.emptyList();
double exp = 0;
double result = MathUtils.averageInt(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testAverageLongCollection() {
List<Long> l = new ArrayList<>();
double exp = 10;
l.add(0L);
l.add(20L);
l.add(5L);
l.add(15L);
double result = MathUtils.averageLong(l);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testAverageDouble() {
List<Double> l = new ArrayList<>();
double exp = 10;
l.add(0.0);
l.add(20.5);
l.add(4.5);
l.add(15.0);
double result = MathUtils.averageDouble(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testAverage() {
double exp = 10;
double result = MathUtils.average(40, 4);
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testCountTrueBoolean() {
List<Boolean> l = new ArrayList<>();
int exp = new Random().nextInt(1000);
for (int i = 0; i < exp; i++) {
l.add(true);
}
for (int i = exp; i < 1000; i++) {
l.add(false);
}
long result = MathUtils.countTrueBoolean(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testSumInt() {
List<Serializable> l = new ArrayList<>();
double exp = 40;
l.add(0);
l.add(20);
l.add(5);
l.add(15);
double result = MathUtils.sumInt(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testSumLong() {
List<Serializable> l = new ArrayList<>();
long exp = 40;
l.add(0L);
l.add(20L);
l.add(5L);
l.add(15L);
long result = MathUtils.sumLong(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
/**
*
*/
@Test
public void testSumDouble() {
List<Serializable> l = new ArrayList<>();
double exp = 100.4531541;
l.add(0.0);
l.add(50.4);
l.add(45.0);
l.add(5.0531541);
double result = MathUtils.sumDouble(l.stream());
assertTrue(result + "/" + exp, Double.compare(exp, result) == 0);
}
@Test
public void testRoundDouble() {
double exp = 412.5123125123;
double roundedExp = MathUtils.round(exp);
assertTrue("", Double.compare(412.51, roundedExp) == 0);
}
}

View File

@ -1,121 +0,0 @@
package test.java.main.java.com.djrapitops.plan.utilities.comparators;
import main.java.com.djrapitops.plan.data.Session;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.UserInfo;
import main.java.com.djrapitops.plan.data.WebUser;
import main.java.com.djrapitops.plan.locale.Message;
import main.java.com.djrapitops.plan.locale.Msg;
import main.java.com.djrapitops.plan.utilities.PassEncryptUtil;
import main.java.com.djrapitops.plan.utilities.analysis.Point;
import main.java.com.djrapitops.plan.utilities.comparators.*;
import org.junit.Test;
import test.java.utils.RandomData;
import java.util.*;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
public class ComparatorTest {
@Test
public void testPointComparator() {
List<Point> test = RandomData.randomPoints();
List<Long> longValues = test.stream().map(Point::getX).map(i -> (long) (double) i).collect(Collectors.toList());
longValues.sort(Long::compare);
test.sort(new PointComparator());
List<Long> afterSort = test.stream().map(Point::getX).map(i -> (long) (double) i).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testSessionDataComparator() {
List<Session> test = RandomData.randomSessions();
List<Long> longValues = test.stream().map(Session::getSessionStart).collect(Collectors.toList());
longValues.sort(Long::compare);
Collections.reverse(longValues);
test.sort(new SessionStartComparator());
List<Long> afterSort = test.stream().map(Session::getSessionStart).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testTPSComparator() {
List<TPS> test = RandomData.randomTPS();
List<Long> longValues = test.stream().map(TPS::getDate).collect(Collectors.toList());
longValues.sort(Long::compare);
test.sort(new TPSComparator());
List<Long> afterSort = test.stream().map(TPS::getDate).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testUserDataLastPlayedComparator() {
List<UserInfo> test = RandomData.randomUserData();
List<Long> longValues = test.stream().map(UserInfo::getLastSeen).collect(Collectors.toList());
longValues.sort(Long::compare);
Collections.reverse(longValues);
test.sort(new UserInfoLastPlayedComparator());
List<Long> afterSort = test.stream().map(UserInfo::getLastSeen).collect(Collectors.toList());
assertEquals(longValues, afterSort);
}
@Test
public void testUserDataNameComparator() {
List<UserInfo> test = RandomData.randomUserData();
List<String> stringValues = test.stream().map(UserInfo::getName).collect(Collectors.toList());
Collections.sort(stringValues);
test.sort(new UserDataNameComparator());
List<String> afterSort = test.stream().map(UserInfo::getName).collect(Collectors.toList());
assertEquals(stringValues, afterSort);
}
@Test
public void testWebUserComparator() throws PassEncryptUtil.CannotPerformOperationException {
List<WebUser> test = RandomData.randomWebUsers();
List<Integer> intValues = test.stream().map(WebUser::getPermLevel).collect(Collectors.toList());
intValues.sort(Integer::compare);
Collections.reverse(intValues);
test.sort(new WebUserComparator());
List<Integer> afterSort = test.stream().map(WebUser::getPermLevel).collect(Collectors.toList());
assertEquals(intValues, afterSort);
}
@Test
public void testStringLengthComparator() {
List<String> test = new ArrayList<>();
test.add(RandomData.randomString(10));
test.add(RandomData.randomString(3));
test.add(RandomData.randomString(20));
test.add(RandomData.randomString(7));
test.add(RandomData.randomString(4));
test.add(RandomData.randomString(86));
test.add(RandomData.randomString(6));
test.sort(new StringLengthComparator());
assertEquals(86, test.get(0).length());
assertEquals(20, test.get(1).length());
assertEquals(3, test.get(test.size() - 1).length());
}
@Test
public void testLocaleEntryComparator() {
Map<Msg, Message> test = new HashMap<>();
test.put(Msg.CMD_CONSTANT_FOOTER, new Message(""));
test.put(Msg.ANALYSIS_3RD_PARTY, new Message(""));
test.put(Msg.MANAGE_FAIL_NO_PLAYERS, new Message(""));
List<String> sorted = test.entrySet().stream()
.sorted(new LocaleEntryComparator())
.map(entry -> entry.getKey().name())
.collect(Collectors.toList());
assertEquals("ANALYSIS_3RD_PARTY", sorted.get(0));
assertEquals("CMD_CONSTANT_FOOTER", sorted.get(1));
assertEquals("MANAGE_FAIL_NO_PLAYERS", sorted.get(2));
}
}

View File

@ -8,8 +8,8 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Suite; import org.junit.runners.Suite;
import test.java.main.java.com.djrapitops.plan.database.DatabaseCommitTest; import main.java.com.djrapitops.plan.database.DatabaseCommitTest;
import test.java.main.java.com.djrapitops.plan.database.DatabaseTest; import main.java.com.djrapitops.plan.database.DatabaseTest;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;

View File

@ -26,6 +26,8 @@ import org.powermock.api.mockito.PowerMockito;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -39,9 +41,6 @@ public class TestInit {
private static final UUID serverUUID = UUID.fromString("9a27457b-f1a2-4b71-be7f-daf2170a1b66"); private static final UUID serverUUID = UUID.fromString("9a27457b-f1a2-4b71-be7f-daf2170a1b66");
private Plan planMock; private Plan planMock;
public TestInit() {
}
/** /**
* Init locale with empty messages. * Init locale with empty messages.
* <p> * <p>
@ -132,49 +131,69 @@ public class TestInit {
@Override @Override
public IRunnable createNew(String name, final AbsRunnable runnable) { public IRunnable createNew(String name, final AbsRunnable runnable) {
return new IRunnable() { return new IRunnable() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runnable.run();
}
};
@Override @Override
public String getTaskName() { public String getTaskName() {
return "Test"; return name;
} }
@Override @Override
public void cancel() { public void cancel() {
timer.cancel();
task.cancel();
runnable.cancel();
} }
@Override @Override
public int getTaskId() { public int getTaskId() {
return 0; return runnable.getTaskId();
} }
@Override @Override
public ITask runTask() { public ITask runTask() {
new Thread(runnable::run).start(); task.run();
return null; return null;
} }
@Override @Override
public ITask runTaskAsynchronously() { public ITask runTaskAsynchronously() {
return runTask(); new Thread(this::runTask).start();
return null;
} }
@Override @Override
public ITask runTaskLater(long l) { public ITask runTaskLater(long l) {
return runTask(); timer.schedule(task, convertTicksToMillis(l));
return null;
} }
@Override @Override
public ITask runTaskLaterAsynchronously(long l) { public ITask runTaskLaterAsynchronously(long l) {
return runTask(); new Thread(() -> timer.schedule(task, convertTicksToMillis(l))).start();
return null;
} }
@Override @Override
public ITask runTaskTimer(long l, long l1) { public ITask runTaskTimer(long l, long l1) {
return runTask(); timer.scheduleAtFixedRate(task, convertTicksToMillis(l), convertTicksToMillis(l1));
return null;
} }
@Override @Override
public ITask runTaskTimerAsynchronously(long l, long l1) { public ITask runTaskTimerAsynchronously(long l, long l1) {
return runTask(); new Thread(() -> timer.scheduleAtFixedRate(task, convertTicksToMillis(l), convertTicksToMillis(l1)));
return null;
}
private long convertTicksToMillis(long ticks) {
return ticks * 50;
} }
}; };
} }

View File

@ -0,0 +1,18 @@
/*
* Licence is provided in the jar as license.yml also here:
* https://github.com/Rsl1122/Plan-PlayerAnalytics/blob/master/Plan/src/main/resources/license.yml
*/
package test.java.utils;
import java.lang.reflect.Field;
/**
* @author Fuzzlemann
*/
public class TestUtils {
public static String getStringFieldValue(Enum enumeration, String modifier) throws NoSuchFieldException, IllegalAccessException {
Field field = enumeration.getClass().getDeclaredField(modifier);
field.setAccessible(true);
return (String) field.get(enumeration);
}
}