Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add base framework for database tests #261

Draft
wants to merge 1 commit into
base: v2
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
!/settings.gradle
!/gradle.properties

!/buildSrc/

!/README.md

!/api/
Expand All @@ -18,4 +20,4 @@
!/spigot/
!/sponge/
!/sponge8/
!/velocity/
!/velocity/
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ subprojects {
dependencies {
compileOnly 'com.google.code.findbugs:jsr305:3.0.2'
compileOnly 'org.checkerframework:checker-qual:3.7.0'
testCompileOnly 'org.checkerframework:checker-qual:3.7.0'
}

sourceCompatibility = '1.8'
Expand Down
6 changes: 6 additions & 0 deletions buildSrc/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/*

!/.gitignore

!/build.gradle
!/src/
18 changes: 18 additions & 0 deletions buildSrc/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
sourceSets {
main {
java.srcDirs = ['src']
resources.srcDirs = ['resources']
}
test {
java.srcDirs = ['testSrc']
resources.srcDirs = ['testResources']
}
}

repositories {
mavenCentral()
}

dependencies {
compileOnly 'org.checkerframework:checker-qual:3.7.0'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package com.elikill58.negativity.build;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.checkerframework.checker.nullness.qual.Nullable;
import org.gradle.api.tasks.testing.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestPropertiesCollector {

private static final Logger LOGGER = LoggerFactory.getLogger(TestPropertiesCollector.class);

// Matches NEGATIVITY_DB_MYSQL_URL
// Where MYSQL is a database config name
// and URL is a config key (URL, USER, PASSWORD or TYPE)
private static final Pattern DB_CONFIG_PATTERN = Pattern.compile("^NEGATIVITY_DB_(?<name>\\p{Upper}+)_(?<key>\\p{Upper}+)$");

/**
* Collects environment variables to be used as system properties of a test task.
* <br/>
* The following properties are supported:
* <ul>
* <li>
* {@code NEGATIVITY_DB_<name>_<key>} -> {@code negativity.db.<name>.<key>}. {@code key} can be one of the following:
* <ul>
* <li>{@code URL}: the URL used to connect to the database</li>
* <li>{@code USER}: the user to connect as</li>
* <li>{@code PASSWORD}: the password to use when opening a connection</li>
* <li>{@code TYPE}: the type of database, see {@code Database.DatabaseType} for all supported values</li>
* </ul>
* </li>
* <li>{@code NEGATIVITY_DATABASES}: comma-separated string of all database configuration names</li>
* </ul>
*
* @return system properties to pass to a test task
*
* @see Test#systemProperties
* @see #applyTestProperties(Test)
*/
public static Map<String, String> collectTestProperties() {
Map<String, DatabaseConfig> databaseConfigs = new HashMap<>();
System.getenv().forEach((envKey, value) -> {
Matcher dbConfigMatcher = DB_CONFIG_PATTERN.matcher(envKey);
if (dbConfigMatcher.matches()) {
String configName = dbConfigMatcher.group("name");
String configKey = dbConfigMatcher.group("key");
DatabaseConfig databaseConfig = databaseConfigs.computeIfAbsent(configName, name -> new DatabaseConfig());
switch (configKey) {
case "URL":
databaseConfig.url = value;
break;
case "USER":
databaseConfig.user = value;
break;
case "PASSWORD":
databaseConfig.password = value;
break;
case "TYPE":
databaseConfig.type = value;
break;
default:
LOGGER.warn("Unknown database configuration key '{}'", configKey);
}
}
});

Map<String, String> systemProperties = new HashMap<>();

Set<String> databaseConfigNames = new HashSet<>();
for (Map.Entry<String, DatabaseConfig> entry : databaseConfigs.entrySet()) {
String key = entry.getKey();
DatabaseConfig config = entry.getValue();
if (config.url == null) {
LOGGER.error("Missing url of database configuration '{}'", key);
continue;
} else if (config.user == null) {
LOGGER.error("Missing user of database configuration '{}'", key);
continue;
} else if (config.password == null) {
LOGGER.error("Missing password of database configuration '{}'", key);
continue;
} else if (config.type == null) {
LOGGER.error("Missing password of database configuration '{}'", key);
continue;
}

databaseConfigNames.add(key);
systemProperties.put("negativity.db." + key + ".url", config.url);
systemProperties.put("negativity.db." + key + ".user", config.user);
systemProperties.put("negativity.db." + key + ".password", config.password);
systemProperties.put("negativity.db." + key + ".type", config.type);
}

systemProperties.put("negativity.databases", String.join(",", databaseConfigNames));
return systemProperties;
}

public static void applyTestProperties(Test testTask) {
Map<String, String> testProperties = collectTestProperties();
testTask.getInputs().properties(testProperties);
testTask.systemProperties(testProperties);
}

private static class DatabaseConfig {

public @Nullable String url;
public @Nullable String user;
public @Nullable String password;
public @Nullable String type;
}
}
14 changes: 14 additions & 0 deletions common/build.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import com.elikill58.negativity.build.TestPropertiesCollector
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar

plugins {
Expand All @@ -18,6 +19,7 @@ sourceSets {
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.7.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.7.0")
testRuntimeOnly("mysql:mysql-connector-java:8.0.25")
}

processResources {
Expand Down Expand Up @@ -51,4 +53,16 @@ parent.tasks.named('shadowJar', ShadowJar) {

test {
useJUnitPlatform()

workingDir(file('testRun'))
doFirst {
workingDir.mkdirs()
}

systemProperty 'negativity.testing', 'true'
TestPropertiesCollector.applyTestProperties(test)
}

tasks.named('cleanTest', Delete.class) {
it.delete(test.workingDir)
}
2 changes: 1 addition & 1 deletion common/src/com/elikill58/negativity/universal/Adapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public abstract class Adapter {
private static Adapter adapter = null;

public static void setAdapter(Adapter adapter) {
if(Adapter.adapter != null) {
if(Adapter.adapter != null && !Boolean.getBoolean("negativity.testing")) {
try {
throw new IllegalAccessException("No ! You don't must to change the Adapter !");
} catch (IllegalAccessException e) {
Expand Down
4 changes: 4 additions & 0 deletions common/src/com/elikill58/negativity/universal/Database.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ public static void init() {
}
}

public static DatabaseType getType() {
return databaseType;
}

public static enum DatabaseType {
MARIA("mariadb", "MariaDB", "org.mariadb.jdbc.Driver"),
MYSQL("mysql", "MySQL", "com.mysql.jdbc.Driver");
Expand Down
3 changes: 2 additions & 1 deletion common/src/com/elikill58/negativity/universal/Platform.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ public enum Platform {
BUNGEE("bungee", true),
SPIGOT("spigot", false),
SPONGE("sponge", false),
VELOCITY("velocity", true);
VELOCITY("velocity", true),
TEST("test", true);

private final String name;
private final boolean proxy;
Expand Down
20 changes: 20 additions & 0 deletions common/src/com/elikill58/negativity/universal/ban/BanResult.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.elikill58.negativity.universal.ban;

import java.util.Objects;

public class BanResult {

private final BanResultType resultType;
Expand Down Expand Up @@ -32,6 +34,24 @@ public boolean isSuccess() {
return getResultType().isSuccess();
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BanResult banResult = (BanResult) o;
return resultType == banResult.resultType && Objects.equals(ban, banResult.ban);
}

@Override
public int hashCode() {
return Objects.hash(resultType, ban);
}

@Override
public String toString() {
return "BanResult{resultType=" + resultType + ", ban=" + ban + '}';
}

public enum BanResultType {

ALREADY_BANNED(false, "Already banned"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public DatabaseActiveBanStorage() {
try {
Connection connection = Database.getConnection();
if (connection != null) {
DatabaseMigrator.executeRemainingMigrations(connection, "bans/active");
DatabaseMigrator.executeRemainingMigrations(connection, Database.getType().getType(), "bans/active");
}
} catch (Exception e) {
Adapter.getAdapter().getLogger().error("Failed to execute active bans database migration: " + e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public DatabaseBanLogsStorage() {
try {
Connection connection = Database.getConnection();
if (connection != null) {
DatabaseMigrator.executeRemainingMigrations(connection, "bans/logs");
DatabaseMigrator.executeRemainingMigrations(connection, Database.getType().getType(), "bans/logs");
}
} catch (Exception e) {
Adapter.getAdapter().getLogger().error("Failed to execute ban logs database migration: " + e.getMessage());
Expand Down