Database Tests

This commit is contained in:
Rsl1122 2017-08-23 21:53:17 +03:00
parent c84e8f434e
commit 6cd18c8d30
22 changed files with 610 additions and 148 deletions

View File

@ -454,6 +454,6 @@ public class Plan extends BukkitPlugin<Plan> {
}
public static UUID getServerUUID() {
return getInstance().serverInfoManager.getServerUUID();
return getInstance().getServerInfoManager().getServerUUID();
}
}

View File

@ -4,6 +4,7 @@
*/
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.ui.html.Html;
import main.java.com.djrapitops.plan.utilities.FormatUtils;
@ -57,4 +58,20 @@ public class Action {
public String toString() {
return Html.TABLELINE_3.parse(FormatUtils.formatTimeStampYear(date), doneAction.toString(), additionalInfo);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Action action = (Action) o;
return date == action.date &&
serverID == action.serverID &&
doneAction == action.doneAction &&
Objects.equal(additionalInfo, action.additionalInfo);
}
@Override
public int hashCode() {
return Objects.hashCode(date, doneAction, additionalInfo, serverID);
}
}

View File

@ -1,5 +1,7 @@
package main.java.com.djrapitops.plan.data;
import com.google.common.base.Objects;
import java.util.UUID;
/**
@ -67,4 +69,22 @@ public class UserInfo {
public boolean isOpped() {
return opped;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
return registered == userInfo.registered &&
lastSeen == userInfo.lastSeen &&
banned == userInfo.banned &&
opped == userInfo.opped &&
Objects.equal(uuid, userInfo.uuid) &&
Objects.equal(name, userInfo.name);
}
@Override
public int hashCode() {
return Objects.hashCode(uuid, name, registered, lastSeen, banned, opped);
}
}

View File

@ -30,7 +30,7 @@ public class IPUpdateProcessor extends PlayerProcessor {
UUID uuid = getUUID();
String country = GeolocationCacheHandler.getCountry(ip);
try {
Plan.getInstance().getDB().getIpsTable().updateIP(uuid, ip, country);
Plan.getInstance().getDB().getIpsTable().saveIP(uuid, ip, country);
} catch (SQLException e) {
Log.toLog(this.getClass().getName(), e);
}

View File

@ -4,6 +4,8 @@
*/
package main.java.com.djrapitops.plan.data.server;
import com.google.common.base.Objects;
import java.util.UUID;
/**
@ -51,4 +53,20 @@ public class ServerInfo {
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ServerInfo that = (ServerInfo) o;
return id == that.id &&
Objects.equal(uuid, that.uuid) &&
Objects.equal(name, that.name) &&
Objects.equal(webAddress, that.webAddress);
}
@Override
public int hashCode() {
return Objects.hashCode(id, uuid, name, webAddress);
}
}

View File

@ -337,4 +337,8 @@ public abstract class Database {
public ActionsTable getActionsTable() {
return actionsTable;
}
public UserInfoTable getUserInfoTable() {
return userInfoTable;
}
}

View File

@ -203,7 +203,8 @@ public abstract class SQLDB extends Database {
ipsTable, nicknamesTable, killsTable,
worldTimesTable, sessionsTable, actionsTable,
worldTable, userInfoTable, usersTable,
commandUseTable, tpsTable, serverTable
commandUseTable, tpsTable, securityTable,
serverTable
};
}

View File

@ -1,7 +1,5 @@
package main.java.com.djrapitops.plan.database.sql;
import main.java.com.djrapitops.plan.Log;
public class Select extends WhereParser {
public Select(String start) {
@ -19,7 +17,6 @@ public class Select extends WhereParser {
}
parser.append(" FROM ").append(table);
Log.debug(parser.toString());
return parser;
}

View File

@ -39,8 +39,11 @@ public class ActionsTable extends UserIDTable {
private final String columnActionID = "action_id";
private final String columnAdditionalInfo = "additional_info";
private ServerTable serverTable;
public ActionsTable(SQLDB db, boolean usingMySQL) {
super("plan_actions", db, usingMySQL);
serverTable = db.getServerTable();
}
@Override
@ -60,7 +63,6 @@ public class ActionsTable extends UserIDTable {
public void insertAction(UUID uuid, Action action) throws SQLException {
PreparedStatement statement = null;
try {
ServerTable serverTable = db.getServerTable();
statement = prepareStatement("INSERT INTO " + tableName + " ("
+ columnUserID + ", "
+ columnServerID + ", "
@ -95,10 +97,10 @@ public class ActionsTable extends UserIDTable {
PreparedStatement statement = null;
ResultSet set = null;
try {
ServerTable serverTable = db.getServerTable();
statement = prepareStatement(Select.from(tableName, "*")
.where(columnUserID + "=" + usersTable.statementSelectID)
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
while (set.next()) {
int serverID = set.getInt(columnServerID);

View File

@ -79,7 +79,7 @@ public class IPsTable extends UserIDTable {
}
}
public void updateIP(UUID uuid, String ip, String geolocation) throws SQLException {
public void saveIP(UUID uuid, String ip, String geolocation) throws SQLException {
List<String> ips = getIps(uuid);
if (ips.contains(ip)) {
return;

View File

@ -119,8 +119,8 @@ public class KillsTable extends UserIDTable {
columnWeapon + ", " +
usersUUIDColumn +
" FROM " + tableName +
" WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID); // Might not work TODO TEST
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnVictimUserID +
" WHERE " + columnKillerUserID + "=" + usersTable.statementSelectID);
statement.setString(1, uuid.toString());
set = statement.executeQuery();
while (set.next()) {

View File

@ -180,7 +180,7 @@ public class ServerTable extends Table {
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName,
columnServerName)
columnServerID, columnServerName)
.toString());
set = statement.executeQuery();
while (set.next()) {

View File

@ -170,10 +170,15 @@ public class SessionsTable extends UserIDTable {
long end = set.getLong(columnSessionEnd);
String serverName = serverNames.get(set.getInt(columnServerID));
if (serverName == null) {
throw new IllegalStateException("Server not present");
}
int deaths = set.getInt(columnDeaths);
int mobKills = set.getInt(columnMobKills);
List<Session> sessions = sessionsByServer.getOrDefault(serverName, new ArrayList<>());
sessions.add(new Session(id, start, end, deaths, mobKills));
sessionsByServer.put(serverName, sessions);
}
return sessionsByServer;
} finally {
@ -201,6 +206,18 @@ public class SessionsTable extends UserIDTable {
return getPlaytime(uuid, Plan.getServerUUID());
}
/**
* Get Playtime of a Player after Epoch ms on THIS server.
*
* @param uuid UUID of the player.
* @param afterDate Epoch ms (Playtime after this date is calculated)
* @return Milliseconds played on THIS server. 0 if player or server not found.
* @throws SQLException
*/
public long getPlaytime(UUID uuid, long afterDate) throws SQLException {
return getPlaytime(uuid, Plan.getServerUUID(), afterDate);
}
/**
* Get Total Playtime of a Player on a server.
*
@ -379,9 +396,9 @@ public class SessionsTable extends UserIDTable {
ResultSet set = null;
try {
statement = prepareStatement("SELECT" +
" (COUNT(" + columnID + ") - SUM(" + columnSessionStart + ")) as logintimes" +
" COUNT(*) as logintimes" +
" FROM " + tableName +
" WHERE " + columnSessionStart + ">?" +
" WHERE (" + columnSessionStart + " >= ?)" +
" AND " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID);
statement.setLong(1, afterDate);

View File

@ -73,6 +73,7 @@ public class TPSTable extends Table {
.where(columnServerID + "=" + serverTable.statementSelectServerID)
.toString());
statement.setFetchSize(5000);
statement.setString(1, Plan.getServerUUID().toString());
set = statement.executeQuery();
while (set.next()) {
long date = set.getLong(columnDate);

View File

@ -119,6 +119,7 @@ public abstract class Table {
* @throws SQLException
*/
protected PreparedStatement prepareStatement(String sql) throws SQLException {
System.out.println(sql);
return getConnection().prepareStatement(sql);
}

View File

@ -23,22 +23,6 @@ public abstract class UserIDTable extends Table {
usersTable = db.getUsersTable();
}
@Deprecated
protected boolean removeDataOf(int userID) {
PreparedStatement statement = null;
try {
statement = prepareStatement("DELETE FROM " + tableName + " WHERE (" + columnUserID + "=?)");
statement.setInt(1, userID);
statement.execute();
return true;
} catch (SQLException ex) {
Log.toLog(this.getClass().getName(), ex);
return false;
} finally {
close(statement);
}
}
public boolean removeUser(UUID uuid) {
PreparedStatement statement = null;
try {

View File

@ -117,14 +117,14 @@ public class UserInfoTable extends UserIDTable {
String usersIDColumn = usersTable + "." + usersTable.getColumnID();
String usersNameColumn = usersTable + "." + usersTable.getColumnName() + " as name";
statement = prepareStatement("SELECT " +
columnRegistered + ", " +
tableName + "." + columnRegistered + ", " +
columnOP + ", " +
columnBanned + ", " +
usersNameColumn +
" FROM " + tableName +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnUserID +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID +
" AND " + columnServerID + "=" + serverTable.statementSelectServerID +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnUserID
" AND " + columnServerID + "=" + serverTable.statementSelectServerID
);
statement.setString(1, uuid.toString());
statement.setString(2, serverUUID.toString());
@ -160,14 +160,14 @@ public class UserInfoTable extends UserIDTable {
String usersUUIDColumn = usersTable + "." + usersTable.getColumnUUID() + " as uuid";
String usersNameColumn = usersTable + "." + usersTable.getColumnName() + " as name";
statement = prepareStatement("SELECT " +
columnRegistered + ", " +
tableName + "." + columnRegistered + ", " +
columnOP + ", " +
columnBanned + ", " +
usersNameColumn + ", " +
usersUUIDColumn +
" FROM " + tableName +
" WHERE " + columnServerID + "=" + serverTable.statementSelectServerID +
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnUserID
" JOIN " + usersTable + " on " + usersIDColumn + "=" + columnUserID +
" WHERE " + columnServerID + "=" + serverTable.statementSelectServerID
);
statement.setFetchSize(2000);
statement.setString(1, serverUUID.toString());

View File

@ -214,17 +214,34 @@ public class UsersTable extends UserIDTable {
public void kicked(UUID uuid) throws SQLException {
PreparedStatement statement = null;
try {
statement = prepareStatement(Update.values(tableName, columnTimesKicked)
.where(columnUUID + "=?")
.toString());
statement.setInt(1, getTimesKicked(uuid) + 1);
statement.setString(2, uuid.toString());
statement = prepareStatement("UPDATE " + tableName + " SET "
+ columnTimesKicked + "=" + columnTimesKicked + "+ 1" +
" WHERE " + columnUUID + "=?");
statement.setString(1, uuid.toString());
statement.execute();
} finally {
close(statement);
}
}
public String getPlayerName(UUID uuid) throws SQLException {
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = prepareStatement(Select.from(tableName, columnName)
.where(columnUUID + "=?")
.toString());
statement.setString(1, uuid.toString());
set = statement.executeQuery();
if (set.next()) {
return set.getString(columnName);
}
return null;
} finally {
close(set, statement);
}
}
public String getColumnName() {
return columnName;
}

View File

@ -117,8 +117,8 @@ public class WorldTimesTable extends UserIDTable {
columnSpectator + ", " +
worldNameColumn +
" FROM " + tableName +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID +
" JOIN " + worldTable + " on " + worldIDColumn + "=" + columnWorldId // TODO TEST
" JOIN " + worldTable + " on " + worldIDColumn + "=" + columnWorldId +
" WHERE " + columnUserID + "=" + usersTable.statementSelectID
);
statement.setString(1, uuid.toString());
set = statement.executeQuery();

View File

@ -6,18 +6,20 @@
package test.java.main.java.com.djrapitops.plan.database;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.data.TPS;
import main.java.com.djrapitops.plan.data.*;
import main.java.com.djrapitops.plan.data.server.ServerInfo;
import main.java.com.djrapitops.plan.data.time.GMTimes;
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.SQLiteDB;
import main.java.com.djrapitops.plan.database.tables.TPSTable;
import main.java.com.djrapitops.plan.database.tables.*;
import main.java.com.djrapitops.plan.utilities.MiscUtils;
import main.java.com.djrapitops.plan.utilities.analysis.MathUtils;
import main.java.com.djrapitops.plan.utilities.file.FileUtil;
import org.bukkit.plugin.java.JavaPlugin;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@ -32,8 +34,7 @@ import java.lang.management.OperatingSystemMXBean;
import java.sql.SQLException;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;
/**
* @author Rsl1122
@ -46,17 +47,13 @@ public class DatabaseTest {
private Database db;
private Database backup;
private int rows;
private UUID uuid = MockUtils.getPlayerUUID();
private List<String> worlds = Arrays.asList("TestWorld", "TestWorld2");
private UUID uuid2 = MockUtils.getPlayer2UUID();
/**
*
*/
public DatabaseTest() {
}
/**
* @throws IOException
* @throws Exception
*/
@Before
public void setUp() throws Exception {
TestInit t = TestInit.init();
@ -67,14 +64,12 @@ public class DatabaseTest {
}
};
db.init();
db.getServerTable().saveCurrentServerInfo(new ServerInfo(-1, t.getServerUUID(), "ServerName", ""));
File f = new File(plan.getDataFolder(), "Errors.txt");
rows = FileUtil.lines(f).size();
}
/**
* @throws IOException
* @throws SQLException
*/
@After
public void tearDown() throws IOException, SQLException {
db.close();
@ -93,33 +88,21 @@ public class DatabaseTest {
assertTrue("Errors were caught.", rows == rowsAgain);
}
/**
*
*/
@Test
public void testInit() {
assertTrue("Database failed to init.", db.init());
}
/**
*
*/
@Test
public void testSqLiteGetConfigName() {
assertEquals("sqlite", db.getConfigName());
}
/**
*
*/
@Test
public void testSqLiteGetgName() {
assertEquals("SQLite", db.getName());
}
/**
*
*/
@Test
public void testMysqlGetConfigName() {
assertEquals("mysql", new MySQLDB(plan) {
@ -130,9 +113,6 @@ public class DatabaseTest {
}.getConfigName());
}
/**
*
*/
@Test
public void testMysqlGetName() {
assertEquals("MySQL", new MySQLDB(plan) {
@ -143,84 +123,55 @@ public class DatabaseTest {
}.getName());
}
/**
* @throws SQLException
*/
@Ignore("")
@Test // TODO Rewrite
public void testRemoveAll() throws SQLException {
db.init();
// UserInfo data = MockUtils.mockUser();
// db.saveUserData(data);
HashMap<String, Integer> c = new HashMap<>();
c.put("/plan", 1);
c.put("/tp", 4);
c.put("/pla", 7);
c.put("/help", 21);
c.put("/roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(c);
assertTrue(db.removeAllData());
assertTrue("Contains the user", db.getUserDataForUUIDS(Arrays.asList(MockUtils.getPlayerUUID(), MockUtils.getPlayer2UUID())).isEmpty());
assertTrue("Contains commandUse", db.getCommandUse().isEmpty());
}
/**
* @throws SQLException
*/
@Ignore("//TODO")
@Test
public void testSaveCommandUse() throws SQLException {
db.init();
HashMap<String, Integer> c = new HashMap<>();
c.put("/plan", 1);
c.put("/tp", 4);
c.put("/pla", 7);
c.put("/help", 21);
c.put("/roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(c);
c.remove("/roiergbnougbierubieugbeigubeigubgierbgeugeg");
Map<String, Integer> expected = new HashMap<>();
expected.put("plan", 1);
expected.put("tp", 4);
expected.put("pla", 7);
expected.put("help", 21);
expected.put("roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(expected);
expected.remove("roiergbnougbierubieugbeigubeigubgierbgeugeg");
Map<String, Integer> commandUse = db.getCommandUse();
assertEquals(c, commandUse);
c.put("/test", 3);
c.put("/tp", 6);
c.put("/pla", 4);
db.saveCommandUse(c);
c.put("/pla", 7);
assertEquals(expected, commandUse);
expected.put("test", 3);
expected.put("tp", 6);
expected.put("pla", 4);
db.saveCommandUse(expected);
expected.put("pla", 7);
commandUse = db.getCommandUse();
assertEquals(c, commandUse);
assertEquals(expected, commandUse);
}
/**
* @throws SQLException
*/
@Test // TODO Rewrite
public void testRemove() throws SQLException {
db.init();
// UserInfo data = MockUtils.mockUser();
// db.saveUserData(data);
// assertTrue(db.removeAccount(data.getUuid().toString()));
// assertTrue("Contains the user", !db.wasSeenBefore(data.getUuid()));
}
/**
* @throws SQLException
*/
@Test
@Ignore("Backup has to be rewritten")
public void testBackup() throws SQLException {
public void testCommandUseTableIDSystem() throws SQLException {
Map<String, Integer> save = new HashMap<>();
save.put("plan", 1);
save.put("tp", 4);
save.put("pla", 7);
save.put("help", 21);
save.put("roiergbnougbierubieugbeigubeigubgierbgeugeg", 3);
db.saveCommandUse(save);
CommandUseTable commandUseTable = db.getCommandUseTable();
Optional<Integer> id = commandUseTable.getCommandID("plan");
assertTrue(id.isPresent());
Optional<String> commandByID = commandUseTable.getCommandByID(id.get());
assertTrue(commandByID.isPresent());
assertEquals("plan", commandByID.get());
assertFalse(commandUseTable.getCommandID("roiergbnougbierubieugbeigubeigubgierbgeugeg").isPresent());
}
/**
* @throws SQLException
*/
// Big test because
@Test
@Ignore("Backup has to be rewritten")
public void testRestore() throws SQLException {
}
@Ignore("//TODO")
@Test
public void testTPSSaving() throws SQLException {
db.init();
@ -241,7 +192,431 @@ public class DatabaseTest {
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));
// tpsTable.saveTPSData(expected);
for (TPS tps : expected) {
tpsTable.insertTPS(tps);
}
assertEquals(expected, tpsTable.getTPSData());
}
private void saveUserOne() throws SQLException {
db.getUsersTable().registerUser(uuid, 123456789L, "Test");
}
private void saveUserTwo() throws SQLException {
db.getUsersTable().registerUser(uuid2, 123456789L, "Test");
}
@Test
public void testActionsTable() throws SQLException {
saveUserOne();
ActionsTable actionsTable = db.getActionsTable();
Action save = new Action(234567890L, Actions.REGISTERED, "Additional Info");
Action expected = new Action(234567890L, Actions.REGISTERED, "Additional Info", 1);
actionsTable.insertAction(uuid, save);
List<Action> actions = actionsTable.getActions(uuid);
assertEquals(expected, actions.get(0));
}
@Test
public void testIPTable() throws SQLException {
saveUserOne();
IPsTable ipsTable = db.getIpsTable();
String expectedIP = "1.2.3.4";
String expectedGeoLoc = "TestLocation";
ipsTable.saveIP(uuid, expectedIP, expectedGeoLoc);
ipsTable.saveIP(uuid, expectedIP, expectedGeoLoc);
List<String> ips = ipsTable.getIps(uuid);
assertEquals(1, ips.size());
assertEquals(expectedIP, ips.get(0));
List<String> geolocations = ipsTable.getGeolocations(uuid);
assertEquals(1, geolocations.size());
assertEquals(expectedGeoLoc, geolocations.get(0));
Optional<String> result = ipsTable.getGeolocation(expectedIP);
assertTrue(result.isPresent());
assertEquals(expectedGeoLoc, result.get());
}
@Test // Does not test getting sessions from another server.
public void testNicknamesTable() throws SQLException {
saveUserOne();
NicknamesTable nickTable = db.getNicknamesTable();
String expected = "TestNickname";
nickTable.saveUserName(uuid, expected);
nickTable.saveUserName(uuid, expected);
List<String> nicknames = nickTable.getNicknames(uuid);
assertEquals(1, nicknames.size());
assertEquals(expected, nicknames.get(0));
List<String> allNicknames = nickTable.getAllNicknames(uuid);
assertEquals(nicknames, allNicknames);
}
@Test
public void testSecurityTable() throws SQLException {
SecurityTable securityTable = db.getSecurityTable();
WebUser expected = new WebUser("Test", "RandomGarbageBlah", 0);
securityTable.addNewUser(expected);
assertTrue(securityTable.userExists("Test"));
WebUser test = securityTable.getWebUser("Test");
assertEquals(expected, test);
assertFalse(securityTable.userExists("NotExist"));
assertNull(securityTable.getWebUser("NotExist"));
assertEquals(1, securityTable.getUsers().size());
securityTable.removeUser("Test");
assertFalse(securityTable.userExists("Test"));
assertNull(securityTable.getWebUser("Test"));
assertEquals(0, securityTable.getUsers().size());
}
@Test
public void testWorldTable() throws SQLException {
WorldTable worldTable = db.getWorldTable();
List<String> worlds = Arrays.asList("Test", "Test2", "Test3");
worldTable.saveWorlds(worlds);
List<String> saved = worldTable.getWorlds();
assertEquals(worlds, saved);
}
private void saveTwoWorlds() throws SQLException {
db.getWorldTable().saveWorlds(worlds);
}
private WorldTimes createWorldTimes() {
Map<String, GMTimes> times = new HashMap<>();
Map<String, Long> gm = new HashMap<>();
String[] gms = GMTimes.getGMKeyArray();
gm.put(gms[0], 1000L);
gm.put(gms[1], 2000L);
gm.put(gms[2], 3000L);
gm.put(gms[3], 4000L);
times.put(worlds.get(0), new GMTimes(gm));
return new WorldTimes(times);
}
private List<KillData> createKills() {
List<KillData> kills = new ArrayList<>();
kills.add(new KillData(uuid2, "Iron Sword", 4321L));
kills.add(new KillData(uuid2, "Gold Sword", 5321L));
return kills;
}
@Test
public void testSessionPlaytimeSaving() throws SQLException {
saveTwoWorlds();
saveUserOne();
saveUserTwo();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
long expectedLength = 10000L;
assertEquals(expectedLength, session.getLength());
assertEquals(expectedLength, session.getWorldTimes().getTotal());
SessionsTable sessionsTable = db.getSessionsTable();
sessionsTable.saveSession(uuid, session);
assertEquals(expectedLength, sessionsTable.getPlaytime(uuid));
assertEquals(0L, sessionsTable.getPlaytime(uuid, 30000L));
long playtimeOfServer = sessionsTable.getPlaytimeOfServer(TestInit.getServerUUID());
assertEquals(expectedLength, playtimeOfServer);
assertEquals(0L, sessionsTable.getPlaytimeOfServer(TestInit.getServerUUID(), 30000L));
assertEquals(1, sessionsTable.getSessionCount(uuid));
assertEquals(0, sessionsTable.getSessionCount(uuid, 30000L));
}
@Test
public void testSessionSaving() throws SQLException {
saveTwoWorlds();
saveUserOne();
saveUserTwo();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
SessionsTable sessionsTable = db.getSessionsTable();
sessionsTable.saveSession(uuid, session);
Map<String, List<Session>> sessions = sessionsTable.getSessions(uuid);
for (Map.Entry<String, List<Session>> entry : sessions.entrySet()) {
String key = entry.getKey();
if (key == null) {
System.out.print("null");
} else if (key.isEmpty()) {
System.out.print("empty");
} else {
System.out.print(key);
}
System.out.println(" " + entry.getValue());
}
List<Session> savedSessions = sessions.get("ServerName");
assertNotNull(savedSessions);
assertEquals(1, savedSessions.size());
assertNull(sessions.get(worlds.get(1)));
assertEquals(session, savedSessions.get(0));
}
@Test
public void testUserInfoTableRegisterUnRegistered() throws SQLException {
UserInfoTable userInfoTable = db.getUserInfoTable();
assertFalse(userInfoTable.isRegistered(uuid));
UsersTable usersTable = db.getUsersTable();
assertFalse(usersTable.isRegistered(uuid));
userInfoTable.registerUserInfo(uuid, 123456789L);
assertTrue(usersTable.isRegistered(uuid));
assertTrue(userInfoTable.isRegistered(uuid));
UserInfo userInfo = userInfoTable.getUserInfo(uuid);
assertEquals(uuid, userInfo.getUuid());
assertEquals(123456789L, (long) usersTable.getRegisterDates().get(0));
assertEquals(123456789L, userInfo.getRegistered());
assertEquals("Waiting for Update..", userInfo.getName());
assertFalse(userInfo.isBanned());
assertFalse(userInfo.isOpped());
}
@Test
public void testUserInfoTableRegisterRegistered() throws SQLException {
saveUserOne();
UsersTable usersTable = db.getUsersTable();
assertTrue(usersTable.isRegistered(uuid));
UserInfoTable userInfoTable = db.getUserInfoTable();
assertFalse(userInfoTable.isRegistered(uuid));
userInfoTable.registerUserInfo(uuid, 223456789L);
assertTrue(usersTable.isRegistered(uuid));
assertTrue(userInfoTable.isRegistered(uuid));
UserInfo userInfo = userInfoTable.getUserInfo(uuid);
assertEquals(uuid, userInfo.getUuid());
assertEquals(123456789L, (long) usersTable.getRegisterDates().get(0));
assertEquals(223456789L, userInfo.getRegistered());
assertEquals("Test", userInfo.getName());
assertFalse(userInfo.isBanned());
assertFalse(userInfo.isOpped());
assertEquals(userInfo, userInfoTable.getAllUserInfo().get(0));
}
@Test
public void testUserInfoTableUpdateBannedOpped() throws SQLException {
UserInfoTable userInfoTable = db.getUserInfoTable();
userInfoTable.registerUserInfo(uuid, 223456789L);
assertTrue(userInfoTable.isRegistered(uuid));
userInfoTable.updateOpAndBanStatus(uuid, true, true);
UserInfo userInfo = userInfoTable.getUserInfo(uuid);
assertTrue(userInfo.isBanned());
assertTrue(userInfo.isOpped());
userInfoTable.updateOpAndBanStatus(uuid, false, true);
userInfo = userInfoTable.getUserInfo(uuid);
assertTrue(userInfo.isBanned());
assertFalse(userInfo.isOpped());
userInfoTable.updateOpAndBanStatus(uuid, false, false);
userInfo = userInfoTable.getUserInfo(uuid);
assertFalse(userInfo.isBanned());
assertFalse(userInfo.isOpped());
}
@Test
public void testUsersTableUpdateName() throws SQLException {
saveUserOne();
UsersTable usersTable = db.getUsersTable();
assertEquals(uuid, usersTable.getUuidOf("Test"));
usersTable.updateName(uuid, "NewName");
assertNull(usersTable.getUuidOf("Test"));
assertEquals("NewName", usersTable.getPlayerName(uuid));
assertEquals(uuid, usersTable.getUuidOf("NewName"));
}
@Test
public void testUsersTableKickSaving() throws SQLException {
saveUserOne();
UsersTable usersTable = db.getUsersTable();
assertEquals(0, usersTable.getTimesKicked(uuid));
int random = new Random().nextInt(20);
for (int i = 0; i < random + 1; i++) {
usersTable.kicked(uuid);
}
assertEquals(random + 1, usersTable.getTimesKicked(uuid));
}
@Test
public void testRemovalSingleUser() throws SQLException {
saveUserTwo();
UserInfoTable userInfoTable = db.getUserInfoTable();
UsersTable usersTable = db.getUsersTable();
SessionsTable sessionsTable = db.getSessionsTable();
NicknamesTable nicknamesTable = db.getNicknamesTable();
IPsTable ipsTable = db.getIpsTable();
ActionsTable actionsTable = db.getActionsTable();
userInfoTable.registerUserInfo(uuid, 223456789L);
saveTwoWorlds();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
sessionsTable.saveSession(uuid, session);
nicknamesTable.saveUserName(uuid, "TestNick");
ipsTable.saveIP(uuid, "1.2.3.4", "TestLoc");
actionsTable.insertAction(uuid, new Action(1324L, Actions.REGISTERED, "Add"));
assertTrue(usersTable.isRegistered(uuid));
db.removeAccount(uuid);
assertFalse(usersTable.isRegistered(uuid));
assertFalse(userInfoTable.isRegistered(uuid));
assertTrue(nicknamesTable.getNicknames(uuid).isEmpty());
assertTrue(ipsTable.getGeolocations(uuid).isEmpty());
assertTrue(ipsTable.getIps(uuid).isEmpty());
assertTrue(sessionsTable.getSessions(uuid).isEmpty());
assertTrue(actionsTable.getActions(uuid).isEmpty());
}
@Test
public void testRemovalEverything() throws SQLException {
saveUserTwo();
UserInfoTable userInfoTable = db.getUserInfoTable();
UsersTable usersTable = db.getUsersTable();
SessionsTable sessionsTable = db.getSessionsTable();
NicknamesTable nicknamesTable = db.getNicknamesTable();
IPsTable ipsTable = db.getIpsTable();
ActionsTable actionsTable = db.getActionsTable();
userInfoTable.registerUserInfo(uuid, 223456789L);
saveTwoWorlds();
Session session = new Session(12345L, "", "");
session.endSession(22345L);
session.setWorldTimes(createWorldTimes());
session.setPlayerKills(createKills());
sessionsTable.saveSession(uuid, session);
nicknamesTable.saveUserName(uuid, "TestNick");
ipsTable.saveIP(uuid, "1.2.3.4", "TestLoc");
actionsTable.insertAction(uuid, new Action(1324L, Actions.REGISTERED, "Add"));
assertTrue(usersTable.isRegistered(uuid));
Map<String, Integer> save = new HashMap<>();
save.put("plan", 1);
save.put("tp", 4);
save.put("pla", 7);
save.put("help", 21);
db.saveCommandUse(save);
TPSTable tpsTable = db.getTpsTable();
List<TPS> expected = new ArrayList<>();
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;
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));
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) {
tpsTable.insertTPS(tps);
}
SecurityTable securityTable = db.getSecurityTable();
securityTable.addNewUser(new WebUser("Test", "RandomGarbageBlah", 0));
db.removeAllData();
assertFalse(usersTable.isRegistered(uuid));
assertFalse(usersTable.isRegistered(uuid2));
assertFalse(userInfoTable.isRegistered(uuid));
assertTrue(nicknamesTable.getNicknames(uuid).isEmpty());
assertTrue(ipsTable.getGeolocations(uuid).isEmpty());
assertTrue(ipsTable.getIps(uuid).isEmpty());
assertTrue(sessionsTable.getSessions(uuid).isEmpty());
assertTrue(actionsTable.getActions(uuid).isEmpty());
assertTrue(db.getCommandUse().isEmpty());
assertTrue(db.getWorldTable().getWorlds().isEmpty());
assertTrue(tpsTable.getTPSData().isEmpty());
assertTrue(db.getServerTable().getBukkitServers().isEmpty());
assertTrue(securityTable.getUsers().isEmpty());
}
@Test
public void testServerTableBungeeSave() throws SQLException {
ServerTable serverTable = db.getServerTable();
Optional<ServerInfo> bungeeInfo = serverTable.getBungeeInfo();
assertFalse(bungeeInfo.isPresent());
UUID bungeeUUID = UUID.randomUUID();
ServerInfo bungeeCord = new ServerInfo(-1, bungeeUUID, "BungeeCord", "Random:1234");
serverTable.saveCurrentServerInfo(bungeeCord);
bungeeCord.setId(2);
bungeeInfo = serverTable.getBungeeInfo();
assertTrue(bungeeInfo.isPresent());
assertEquals(bungeeCord, bungeeInfo.get());
Optional<Integer> serverID = serverTable.getServerID(bungeeUUID);
assertTrue(serverID.isPresent());
assertEquals(2, (int) serverID.get());
}
@Test
public void testServerTableBungee() throws SQLException {
testServerTableBungeeSave();
ServerTable serverTable = db.getServerTable();
List<ServerInfo> bukkitServers = serverTable.getBukkitServers();
assertEquals(1, bukkitServers.size());
}
}

View File

@ -22,7 +22,7 @@ public class RandomData {
}
public static String randomString(int size) {
return RandomStringUtils.random(size);
return RandomStringUtils.randomAlphanumeric(size);
}
public static List<WebUser> randomWebUsers() throws PassEncryptUtil.CannotPerformOperationException {

View File

@ -12,6 +12,7 @@ import com.djrapitops.plugin.utilities.player.Fetch;
import main.java.com.djrapitops.plan.Plan;
import main.java.com.djrapitops.plan.ServerVariableHolder;
import main.java.com.djrapitops.plan.Settings;
import main.java.com.djrapitops.plan.data.server.ServerInfoManager;
import main.java.com.djrapitops.plan.locale.Locale;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
@ -24,6 +25,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;
import java.util.logging.Logger;
import static org.powermock.api.mockito.PowerMockito.when;
@ -34,10 +36,8 @@ import static org.powermock.api.mockito.PowerMockito.when;
public class TestInit {
private Plan planMock;
private static final UUID serverUUID = UUID.fromString("9a27457b-f1a2-4b71-be7f-daf2170a1b66");
/**
*
*/
public TestInit() {
}
@ -111,6 +111,10 @@ public class TestInit {
when(planMock.benchmark()).thenReturn(bench);
when(planMock.getVariable()).thenReturn(serverVariableHolder);
when(planMock.fetch()).thenReturn(fetch);
ServerInfoManager serverInfoManager = PowerMockito.mock(ServerInfoManager.class);
when(serverInfoManager.getServerUUID()).thenReturn(serverUUID);
when(planMock.getServerInfoManager()).thenReturn(serverInfoManager);
RunnableFactory<Plan> runnableFactory = mockRunnableFactory();
when(planMock.getRunnableFactory()).thenReturn(runnableFactory);
ColorScheme cs = new ColorScheme(ChatColor.BLACK, ChatColor.BLACK, ChatColor.BLACK, ChatColor.BLACK);
@ -216,4 +220,8 @@ public class TestInit {
public Plan getPlanMock() {
return planMock;
}
public static UUID getServerUUID() {
return serverUUID;
}
}