feat(sql+test): sql database+table creation test

This commit is contained in:
aro 2022-12-11 11:21:38 +01:00
parent 7272809044
commit a455b8ea3a
6 changed files with 100 additions and 66 deletions

View file

@ -99,6 +99,13 @@
<version>2.29.0</version> <version>2.29.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- MariaDB JDBC Driver -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View file

@ -27,9 +27,10 @@ import java.io.File;
import java.util.logging.Level; import java.util.logging.Level;
public class NickoBukkit extends JavaPlugin { public class NickoBukkit extends JavaPlugin {
private boolean unitTesting;
private static NickoBukkit plugin; private static NickoBukkit plugin;
private final boolean unitTesting;
private NickoConfiguration nickoConfiguration; private NickoConfiguration nickoConfiguration;
private MojangAPI mojangAPI; private MojangAPI mojangAPI;
private PlayerDataStore dataStore; private PlayerDataStore dataStore;
@ -37,9 +38,10 @@ public class NickoBukkit extends JavaPlugin {
/** /**
* Used by MockBukkit * Used by MockBukkit
*/ */
protected NickoBukkit(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { protected NickoBukkit(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file, NickoConfiguration nickoConfiguration) {
super(loader, description, dataFolder, file); super(loader, description, dataFolder, file);
unitTesting = true; unitTesting = true;
this.nickoConfiguration = nickoConfiguration;
getLogger().info("Unit Testing Mode enabled."); getLogger().info("Unit Testing Mode enabled.");
} }
@ -47,13 +49,48 @@ public class NickoBukkit extends JavaPlugin {
public void onEnable() { public void onEnable() {
plugin = this; plugin = this;
if(!isUnitTesting()) { if (isUnitTesting()) {
getLogger().info("Loading internals..."); onUnitTestingStartup();
if (getInternals() == null) { } else {
getLogger().log(Level.SEVERE, "Nicko could not find a valid implementation for this server version. Is your server supported?"); onPluginStartup();
dataStore.getStorage().setError(true); }
getServer().getPluginManager().disablePlugin(this); }
@Override
public void onDisable() {
if (!dataStore.getStorage().isError()) {
getLogger().info("Closing persistence...");
dataStore.removeAllNames();
if (!dataStore.getStorage().getProvider().close()) {
getLogger().warning("Failed to close persistence!");
} }
dataStore.getStorage().setError(false);
}
if (nickoConfiguration.isBungeecordEnabled()) {
getServer().getMessenger().unregisterIncomingPluginChannel(this);
getServer().getMessenger().unregisterOutgoingPluginChannel(this);
}
getLogger().info("Nicko (Bukkit) has been disabled.");
}
public void onUnitTestingStartup() {
getLogger().info("Loading persistence...");
dataStore = new PlayerDataStore(this);
if (!dataStore.getStorage().getProvider().init()) {
dataStore.getStorage().setError(true);
getLogger().warning("Failed to open persistence, data will NOT be saved!");
}
}
public void onPluginStartup() {
getLogger().info("Loading internals...");
if (getInternals() == null) {
getLogger().log(Level.SEVERE, "Nicko could not find a valid implementation for this server version. Is your server supported?");
dataStore.getStorage().setError(true);
getServer().getPluginManager().disablePlugin(this);
} }
if (getServer().getPluginManager().isPluginEnabled(this)) { if (getServer().getPluginManager().isPluginEnabled(this)) {
@ -84,17 +121,15 @@ public class NickoBukkit extends JavaPlugin {
new PlaceHolderHook(this).hook(); new PlaceHolderHook(this).hook();
if(!isUnitTesting()) { getServer().getPluginManager().registerEvents(new PlayerJoinListener(), this);
getServer().getPluginManager().registerEvents(new PlayerJoinListener(), this); getServer().getPluginManager().registerEvents(new PlayerQuitListener(), this);
getServer().getPluginManager().registerEvents(new PlayerQuitListener(), this);
final ServerUtils serverUtils = new ServerUtils(this); final ServerUtils serverUtils = new ServerUtils(this);
serverUtils.checkSpigotBungeeCordHook(); serverUtils.checkSpigotBungeeCordHook();
if (nickoConfiguration.isBungeecordEnabled()) { if (nickoConfiguration.isBungeecordEnabled()) {
if (serverUtils.checkBungeeCordHook()) { if (serverUtils.checkBungeeCordHook()) {
getLogger().info("Enabling BungeeCord support..."); getLogger().info("Enabling BungeeCord support...");
getServer().getMessenger().registerIncomingPluginChannel(this, NickoBungee.NICKO_PLUGIN_CHANNEL_UPDATE, new PluginMessageHandler()); getServer().getMessenger().registerIncomingPluginChannel(this, NickoBungee.NICKO_PLUGIN_CHANNEL_UPDATE, new PluginMessageHandler());
}
} }
} }
@ -102,25 +137,6 @@ public class NickoBukkit extends JavaPlugin {
} }
} }
@Override
public void onDisable() {
if (!dataStore.getStorage().isError()) {
getLogger().info("Closing persistence...");
dataStore.removeAllNames();
if (!dataStore.getStorage().getProvider().close()) {
getLogger().warning("Failed to close persistence!");
}
dataStore.getStorage().setError(false);
}
if (nickoConfiguration.isBungeecordEnabled()) {
getServer().getMessenger().unregisterIncomingPluginChannel(this);
getServer().getMessenger().unregisterOutgoingPluginChannel(this);
}
getLogger().info("Nicko (Bukkit) has been disabled.");
}
public static NickoBukkit getInstance() { public static NickoBukkit getInstance() {
return plugin; return plugin;
} }

View file

@ -80,7 +80,10 @@ public class NickoConfiguration {
} }
public String getSQLPassword() { public String getSQLPassword() {
return getStorageSection().getString("password"); if (sqlPassword == null) {
return sqlPassword = getStorageSection().getString("password");
}
return sqlPassword;
} }
public void setSQLPassword(String sqlPassword) { public void setSQLPassword(String sqlPassword) {

View file

@ -4,12 +4,18 @@ import net.artelnatif.nicko.NickoBukkit;
import net.artelnatif.nicko.config.NickoConfiguration; import net.artelnatif.nicko.config.NickoConfiguration;
import net.artelnatif.nicko.storage.StorageProvider; import net.artelnatif.nicko.storage.StorageProvider;
import java.sql.*; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SQLStorageProvider implements StorageProvider { public class SQLStorageProvider implements StorageProvider {
private final NickoBukkit instance; private final NickoBukkit instance;
private Connection connection; private Connection connection;
private final String schemaName = "nicko";
private final String tableName = "DATA";
public SQLStorageProvider(NickoBukkit instance) { public SQLStorageProvider(NickoBukkit instance) {
this.instance = instance; this.instance = instance;
} }
@ -18,18 +24,20 @@ public class SQLStorageProvider implements StorageProvider {
public boolean init() { public boolean init() {
try { try {
final NickoConfiguration config = instance.getNickoConfig(); final NickoConfiguration config = instance.getNickoConfig();
connection = DriverManager.getConnection("jdbc://" + config.getSQLAddress(), config.getSQLUsername(), config.getSQLPassword()); connection = DriverManager.getConnection("jdbc:mariadb://" + config.getSQLAddress(), config.getSQLUsername(), config.getSQLPassword());
final boolean initialized = connection != null && !connection.isClosed(); final boolean initialized = connection != null && !connection.isClosed();
if (initialized) { if (initialized) {
if (!doesTableExist()) { instance.getLogger().info("Creating SQL database...");
instance.getLogger().info("Creating SQL tables..."); createDatabase();
return createTables();
} instance.getLogger().info("Creating SQL table...");
createTable();
return true; return true;
} }
return false; return false;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace();
return false; return false;
} }
} }
@ -40,6 +48,7 @@ public class SQLStorageProvider implements StorageProvider {
@Override @Override
public boolean close() { public boolean close() {
if(connection == null) { return true; }
try { try {
connection.close(); connection.close();
return connection.isClosed(); return connection.isClosed();
@ -48,38 +57,42 @@ public class SQLStorageProvider implements StorageProvider {
} }
} }
private boolean createTables() { private void createTable() {
final Connection connection = getConnection(); final Connection connection = getConnection();
final String query = """ final String query = """
CREATE TABLE IF NOT EXISTS 'NICKO' ( CREATE TABLE IF NOT EXISTS %s.%s (
uuid uuid NOT NULL, uuid uuid NOT NULL,
name varchar(16) NOT NULL, name varchar(16) NOT NULL,
skin varchar(16) NOT NULL, skin varchar(16) NOT NULL,
bungeecord boolean NOT NULL, bungeecord boolean NOT NULL,
PRIMARY KEY (UUID) PRIMARY KEY (UUID)
) )
"""; """.formatted(schemaName, tableName);
try { try {
final PreparedStatement statement = connection.prepareStatement(query); final PreparedStatement statement = connection.prepareStatement(query);
ResultSet result = statement.executeQuery(); statement.executeUpdate();
return result.next(); statement.close();
} catch (SQLException e) { } catch (SQLException e) {
// TODO: 12/10/22 Handle error
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private boolean doesTableExist() { private void createDatabase() {
final Connection connection = getConnection(); final Connection connection = getConnection();
final String query = "SELECT UUID FROM 'NICKO'"; final String query = """
CREATE DATABASE IF NOT EXISTS %s
""".formatted(schemaName);
try { try {
final PreparedStatement statement = connection.prepareStatement(query); final PreparedStatement statement = connection.prepareStatement(query);
ResultSet result = statement.executeQuery(); statement.executeUpdate();
return result.next(); statement.close();
} catch (SQLException e) { } catch (SQLException e) {
// TODO: 12/10/22 Handle error
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }

View file

@ -1,6 +0,0 @@
package net.artelnatif.nicko.test.mock;
import be.seeseemelk.mockbukkit.ServerMock;
public class NickoServerMock extends ServerMock {
}

View file

@ -6,7 +6,6 @@ import be.seeseemelk.mockbukkit.entity.PlayerMock;
import net.artelnatif.nicko.NickoBukkit; import net.artelnatif.nicko.NickoBukkit;
import net.artelnatif.nicko.config.NickoConfiguration; import net.artelnatif.nicko.config.NickoConfiguration;
import net.artelnatif.nicko.disguise.NickoProfile; import net.artelnatif.nicko.disguise.NickoProfile;
import net.artelnatif.nicko.test.mock.NickoServerMock;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
import java.util.Optional; import java.util.Optional;
@ -18,17 +17,19 @@ public class SQLStorageTest {
@BeforeAll @BeforeAll
public static void setup() { public static void setup() {
server = MockBukkit.mock(new NickoServerMock()); server = MockBukkit.mock();
plugin = MockBukkit.load(NickoBukkit.class); config = new NickoConfiguration(null);
config = plugin.getNickoConfig(); config.setLocalStorage(false);
config.setBungeecordSupport(false);
config.setSQLAddress("127.0.0.1");
config.setSQLUsername("root");
config.setSQLPassword("12345"); // https://howsecureismypassword.net/ "Your password would be cracked: Instantly"
plugin = MockBukkit.load(NickoBukkit.class, config);
} }
@Test @Test
@DisplayName("Create SQL Tables") @DisplayName("Create SQL Tables")
public void testSQLTables() { public void testSQLTables() {
config.setSQLAddress("localhost");
config.setSQLUsername("root");
config.setSQLPassword("12345"); // https://howsecureismypassword.net/ "Your password would be cracked: Instantly"
final PlayerMock playerMock = server.addPlayer("Aro"); final PlayerMock playerMock = server.addPlayer("Aro");
final Optional<NickoProfile> data = plugin.getDataStore().getData(playerMock.getUniqueId()); final Optional<NickoProfile> data = plugin.getDataStore().getData(playerMock.getUniqueId());