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

Unit Testing #19

Merged
merged 53 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
73ff8a8
Draft Unit Testing
gmitch215 Nov 14, 2024
fa68c8f
Update Workflows
gmitch215 Nov 18, 2024
f638f5a
Rename to `Mock` Classes
gmitch215 Nov 18, 2024
0925194
Separate Bot Stages into Methods
gmitch215 Nov 18, 2024
76fa5bf
Add Test `config.json`, Update Mock Bot
gmitch215 Nov 18, 2024
c7c8ca4
Update build.yml
gmitch215 Nov 18, 2024
69242eb
Update .gitignore
gmitch215 Nov 18, 2024
fd166df
Add Test Task & JaCoCo Configuration
gmitch215 Nov 18, 2024
7215d71
Improve Null Safety, Add More Logging
gmitch215 Nov 18, 2024
f0049fb
Fix Build Workflow
gmitch215 Nov 18, 2024
86c6f8b
Update test.sh
gmitch215 Nov 18, 2024
9bbfd14
Add Mockito Dependency
gmitch215 Nov 19, 2024
47d4c94
Remove Redundant Initializers
gmitch215 Nov 19, 2024
a14dfbd
Create MockJDA, TestAPIUtil
gmitch215 Nov 19, 2024
9b51a60
Fix Server Script
gmitch215 Nov 19, 2024
1ab4905
Update test.sh
gmitch215 Nov 19, 2024
b55351f
Enable Standard Logging
gmitch215 Nov 19, 2024
0999ab2
Split Configuration Loading
gmitch215 Nov 19, 2024
9686f66
Fix JDA Mocking
gmitch215 Nov 19, 2024
d132747
Fix Incorrect Tests
gmitch215 Nov 19, 2024
e1d9d5f
Add Unit Tests for `/codemc jenkins` and `/codemc nexus`
gmitch215 Nov 26, 2024
7bb7911
Create Unit Tests for `CommandUtil#hasRole` and `CommandUtil.EmbedRep…
gmitch215 Nov 26, 2024
e39f4c4
Add Unit Testing for `/submit`
gmitch215 Nov 26, 2024
9a52bcb
Upgrade to Gradle 8.11.1
gmitch215 Nov 26, 2024
93a18b8
Merge branch 'master' into feat/unit-testing
gmitch215 Nov 26, 2024
828d25d
Merge branch 'master' of https://github.com/CodeMC/Bot into feat/unit…
gmitch215 Dec 3, 2024
84683ad
Fix Username Collision
gmitch215 Dec 3, 2024
8342f25
Add `trigger` Parameter to Jenkins Build
gmitch215 Dec 3, 2024
b0b9a59
Add Tests for `/codemc remove` and `/codemc validate`
gmitch215 Dec 3, 2024
2aa73c5
Add Random Member IDs
gmitch215 Dec 3, 2024
88a2a23
Add Tests for `/codemc link` and `/codemc unlink`
gmitch215 Dec 3, 2024
93fb237
Add Rest of Tests for `/codemc`
gmitch215 Dec 3, 2024
0f97c91
Remove Unused Imports
gmitch215 Dec 3, 2024
d360680
Create `CommandUtil#requestEmbed`
gmitch215 Dec 5, 2024
8418318
Add Database Cleanup
gmitch215 Dec 5, 2024
1810864
Create TestApplicationHandler.java
gmitch215 Dec 5, 2024
a7aef3f
Increase Coverage for `CmdCodeMC.java`
gmitch215 Dec 5, 2024
c3f311b
Test Messages from ApplicationHandler
gmitch215 Dec 5, 2024
7c59a2e
Add Tests for `/application`
gmitch215 Dec 6, 2024
a58030a
Add Test for `/reload`, Soft Test for `/disable`
gmitch215 Dec 6, 2024
187e59b
Improve APIUtil Coverage
gmitch215 Dec 6, 2024
c3bb904
Rework Message & Event IDs
gmitch215 Dec 7, 2024
0b01379
Create `TestButtonListener.java`
gmitch215 Dec 7, 2024
8a8f1df
Prevent Negative IDs
gmitch215 Dec 7, 2024
f6b8197
Improve Exception Logging, Make Unit Test Compatible
gmitch215 Dec 7, 2024
73069dc
Create TestModalListener.java
gmitch215 Dec 7, 2024
75411d0
Update to API v1.2.0
gmitch215 Dec 8, 2024
1f44a84
Create `TestCmdMsg.java`
gmitch215 Dec 8, 2024
26f13de
Create `TestBotCommand.java`
gmitch215 Dec 8, 2024
aa0eea8
Update MockJDA.java
gmitch215 Dec 8, 2024
39bb2a5
Improve Coverage, Use `#exists` Functions from API
gmitch215 Dec 8, 2024
9e66f7b
Loosen Coverage Requirements
gmitch215 Dec 8, 2024
55da8c0
Code Cleanup
gmitch215 Dec 8, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash

# Setup API Server
git clone https://github.com/CodeMC/API build/tmp/CodeMC-API
chmod +x ./build/tmp/CodeMC-API/.github/test.sh

# Run API Server
cd build/tmp/CodeMC-API
./.github/test.sh
cd ../../../
103 changes: 101 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Build Project
on: [push, pull_request, workflow_dispatch]

jobs:
build:
setup:
runs-on: ubuntu-latest
timeout-minutes: 30

Expand All @@ -21,5 +21,104 @@ jobs:
run: chmod +x ./gradlew
- name: Gradle Information
run: ./gradlew tasks project dependencies

build:
needs: setup
runs-on: ubuntu-latest
timeout-minutes: 30

name: Gradle Build
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: 'gradle'
- name: Change Permissions
run: chmod +x ./gradlew
- name: Gradle Build
run: ./gradlew build
run: ./gradlew build -x test

test:
needs: setup
runs-on: ubuntu-latest
timeout-minutes: 30

name: Gradle Test
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: 'gradle'
- name: Change Permissions
run: chmod +x ./gradlew
- name: Setup Servers
run: bash .github/test.sh
- name: Gradle Test
run: ./gradlew test
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Stop Servers
if: success() || failure()
run: |
rm -rf /tmp/admin.password

docker stop jenkins-rest
docker rm jenkins-rest

docker stop nexus-rest
docker rm nexus-rest

docker stop mariadb
docker rm mariadb

docker network rm codemc
- name: Archive Test Reports
uses: actions/upload-artifact@v4
with:
name: test-report
path: build/reports/tests/test/
- name: Collect JaCoCo Report
if: ${{ github.event_name != 'pull_request' }}
id: jacoco_reporter
uses: PavanMudigonda/[email protected]
with:
coverage_results_path: build/jacoco.xml
coverage_report_name: Code Coverage
github_token: ${{ secrets.GITHUB_TOKEN }}
skip_check_run: false
minimum_coverage: 80
fail_below_threshold: false
publish_only_summary: false

- name: Print JaCoCo Report
if: ${{ github.event_name != 'pull_request' }}
run: |
echo "| Outcome | Value |" >> $GITHUB_STEP_SUMMARY
echo "| --- | --- |" >> $GITHUB_STEP_SUMMARY
echo "| Code Coverage % | ${{ steps.jacoco_reporter.outputs.coverage_percentage }} |" >> $GITHUB_STEP_SUMMARY
echo "| :heavy_check_mark: Number of Lines Covered | ${{ steps.jacoco_reporter.outputs.covered_lines }} |" >> $GITHUB_STEP_SUMMARY
echo "| :x: Number of Lines Missed | ${{ steps.jacoco_reporter.outputs.missed_lines }} |" >> $GITHUB_STEP_SUMMARY
echo "| Total Number of Lines | ${{ steps.jacoco_reporter.outputs.total_lines }} |" >> $GITHUB_STEP_SUMMARY

- name: Upload Code Coverage Artifacts (Push)
if: ${{ github.event_name != 'pull_request' }}
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: "*/coverage-results.md"

- name: Upload Code Coverage Artifacts (Pull Request)
if: ${{ github.event_name == 'pull_request' }}
uses: madrapps/[email protected]
with:
paths: build/jacoco.xml
token: ${{ secrets.GITHUB_TOKEN }}
pass-emoji: ✅
min-coverage-overall: 80
min-coverage-changed-files: 85
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,4 @@ build/
.vscode/

# Copied configuration
config.json
/config.json
39 changes: 38 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ plugins {
id "java"
id "application"
id "com.github.johnrengelman.shadow" version "8.1.1"
id "jacoco"
}

group 'io.codemc'
Expand All @@ -34,6 +35,7 @@ repositories {
maven { url = 'https://repo.codemc.io/repository/codemc' }
maven { url = 'https://repo.codemc.io/repository/codemc' }
maven { url = 'https://m2.chew.pro/releases' }
maven { url = 'https://m2.coly.dev/releases' }
}

dependencies {
Expand All @@ -45,12 +47,47 @@ dependencies {
implementation group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0'
implementation group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2'

implementation group: 'io.codemc.api', name: 'codemc-api', version: '1.1.1'
implementation group: 'io.codemc.api', name: 'codemc-api', version: '1.2.0'
implementation group: 'org.jetbrains.kotlinx', name: 'kotlinx-coroutines-core', version: '1.9.0'
implementation group: 'org.jetbrains.kotlinx', name: 'kotlinx-serialization-json', version: '1.7.3'
implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '3.5.1'
implementation group: 'org.jetbrains.exposed', name: 'exposed-core', version: '0.56.0'
implementation group: 'org.jetbrains.exposed', name: 'exposed-jdbc', version: '0.56.0'

testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.11.3'
testImplementation group: 'dev.coly', name: 'JDATesting', version: '0.7.0'
testImplementation group: 'org.mockito', name: 'mockito-core', version: '5.14.2'
}

tasks {
clean {
delete "logs"
}

test {
useJUnitPlatform()

testLogging {
events "passed", "skipped", "failed"
showStandardStreams = true
}

finalizedBy jacocoTestReport
}

jacocoTestReport {
dependsOn test

reports {
csv.required = false

xml.required = true
xml.outputLocation = layout.buildDirectory.file("jacoco.xml").get().asFile

html.required = true
html.outputLocation = layout.buildDirectory.dir("jacocoHtml").get().asFile
}
}
}

artifacts {
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
81 changes: 53 additions & 28 deletions src/main/java/io/codemc/bot/CodeMCBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.MemberCachePolicy;

import org.jetbrains.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -42,8 +44,11 @@

public class CodeMCBot{

private final Logger logger = LoggerFactory.getLogger(CodeMCBot.class);
private final ConfigHandler configHandler = new ConfigHandler();
@VisibleForTesting
Logger logger = LoggerFactory.getLogger(CodeMCBot.class);

@VisibleForTesting
ConfigHandler configHandler = new ConfigHandler();

public static void main(String[] args){
try{
Expand All @@ -53,51 +58,69 @@ public static void main(String[] args){
}
}

private void start() throws LoginException{
@VisibleForTesting
void start() throws LoginException{
loadConfig();
validateConfig();

String token = configHandler.getString("bot_token");
long owner = configHandler.getLong("users", "owner");
long guildId = configHandler.getLong("server");

CommandClientBuilder clientBuilder = new CommandClientBuilder().setActivity(null).forceGuildOnly(guildId);

clientBuilder.setOwnerId(owner);

List<Long> coOwners = configHandler.getLongList("users", "co_owners");

if(coOwners != null && !coOwners.isEmpty()){
logger.info("Adding {} Co-Owner(s) to the bot.", coOwners.size());
// Annoying, but setCoOwnerIds has no overload with a Collection<Long>...
long[] coOwnerIds = new long[coOwners.size()];
for(int i = 0; i < coOwnerIds.length; i++){
coOwnerIds[i] = coOwners.get(i);
}

clientBuilder.setCoOwnerIds(coOwnerIds);
}

initializeAPI();
login(clientBuilder, token);
}

private void loadConfig() {
if(!configHandler.loadConfig()){
logger.warn("Unable to load config.json! See previous logs for any errors.");
System.exit(1);
return;
}

logger.info("Loaded config.json");
}

@VisibleForTesting
public final void validateConfig() {
String token = configHandler.getString("bot_token");
if(token == null || token.isEmpty()){
logger.warn("Received invalid Bot Token!");
System.exit(1);
return;
}

long owner = configHandler.getLong("users", "owner");
if(owner == -1L){
if(configHandler.getLong("users", "owner") == -1L){
logger.warn("Unable to retrieve Owner ID. This value is required!");
System.exit(1);
return;
}

long guildId = configHandler.getLong("server");
if(guildId == -1L){
if(configHandler.getLong("server") == -1L){
logger.warn("Unable to retrieve Server ID. This value is required!");
System.exit(1);
return;
}

CommandClientBuilder clientBuilder = new CommandClientBuilder().setActivity(null).forceGuildOnly(guildId);

clientBuilder.setOwnerId(owner);

List<Long> coOwners = configHandler.getLongList("users", "co_owners");

if(coOwners != null && !coOwners.isEmpty()){
logger.info("Adding {} Co-Owner(s) to the bot.", coOwners.size());
// Annoying, but setCoOwnerIds has no overload with a Collection<Long>...
long[] coOwnerIds = new long[coOwners.size()];
for(int i = 0; i < coOwnerIds.length; i++){
coOwnerIds[i] = coOwners.get(i);
}

clientBuilder.setCoOwnerIds(coOwnerIds);
}
}

@VisibleForTesting
final void initializeAPI() {
logger.info("Initializing API...");
JenkinsConfig jenkins = new JenkinsConfig(
configHandler.getString("jenkins", "url"),
Expand All @@ -124,15 +147,15 @@ private void start() throws LoginException{

boolean jenkinsPing = JenkinsAPI.ping();
if (!jenkinsPing) {
logger.error("Failed to connect to Jenkins at {}!", jenkins.getUrl());
logger.error("Failed to connect to Jenkins at '{}'!", jenkins.getUrl());
System.exit(1);
return;
}
logger.info("Connected to Jenkins at {}", jenkins.getUrl());

boolean nexusPing = NexusAPI.ping();
if (!nexusPing) {
logger.error("Failed to connect to Nexus at {}!", nexus.getUrl());
logger.error("Failed to connect to Nexus at '{}'!", nexus.getUrl());
System.exit(1);
return;
}
Expand All @@ -143,7 +166,9 @@ private void start() throws LoginException{
logger.warn("GitHub API Token is empty! This may cause issues with GitHub API requests.");
else
logger.info("GitHub API Token set");

}

private void login(CommandClientBuilder clientBuilder, String token) throws LoginException{
logger.info("Adding commands...");
clientBuilder.addSlashCommands(
new CmdApplication(this),
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/io/codemc/bot/commands/CmdApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@

import java.util.List;

import org.jetbrains.annotations.VisibleForTesting;

public class CmdApplication extends BotCommand{

public CmdApplication(CodeMCBot bot){
Expand All @@ -54,7 +56,8 @@ public void withModalReply(SlashCommandEvent event){}
@Override
public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member){}

private static class Accept extends BotCommand{
@VisibleForTesting
static class Accept extends BotCommand{

public Accept(CodeMCBot bot){
super(bot);
Expand All @@ -81,7 +84,7 @@ public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild g
}

try {
long messageId = -1L;
long messageId;
if (message.contains("-"))
messageId = Long.parseLong(message.split("-")[1]);
else
Expand All @@ -99,7 +102,8 @@ public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild g
}
}

private static class Deny extends BotCommand{
@VisibleForTesting
static class Deny extends BotCommand{

public Deny(CodeMCBot bot){
super(bot);
Expand Down Expand Up @@ -127,7 +131,7 @@ public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild g
}

try {
long messageId = -1L;
long messageId;
if (message.contains("-"))
messageId = Long.parseLong(message.split("-")[1]);
else
Expand Down
Loading
Loading