Skip to content

Commit

Permalink
Fix JUnit warnings on test runs (#7378)
Browse files Browse the repository at this point in the history
* init commit

* fix firework warning

* fix & update purge test

* fix backup cleanup

* fix imports

* change names
  • Loading branch information
Efnilite authored Jan 14, 2025
1 parent 4569e9d commit 1fd0c93
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 86 deletions.
40 changes: 25 additions & 15 deletions src/main/java/ch/njol/skript/events/EvtFirework.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,42 @@
import ch.njol.skript.lang.Literal;
import ch.njol.skript.lang.SkriptEvent;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.SyntaxStringBuilder;
import ch.njol.skript.util.Color;
import java.util.Arrays;
import java.util.List;

import ch.njol.skript.util.ColorRGB;
import org.bukkit.FireworkEffect;
import org.bukkit.event.Event;
import org.bukkit.event.entity.FireworkExplodeEvent;
import org.bukkit.inventory.meta.FireworkMeta;
import org.jetbrains.annotations.Nullable;

import java.util.Set;
import java.util.stream.Collectors;

public class EvtFirework extends SkriptEvent {

static {
if (Skript.classExists("org.bukkit.event.entity.FireworkExplodeEvent"))
//Making the event argument type fireworkeffects, led to Skript having troubles parsing for some reason.
Skript.registerEvent("Firework Explode", EvtFirework.class, FireworkExplodeEvent.class, "[a] firework explo(d(e|ing)|sion) [colo[u]red %-colors%]")
Skript.registerEvent("Firework Explode", EvtFirework.class, FireworkExplodeEvent.class,
"[a] firework explo(d(e|ing)|sion) [colo[u]red %-colors%]")
.description("Called when a firework explodes.")
.examples("on firework explode:",
"\tif event-colors contains red:",
"on firework exploding colored red, light green and black:",
"on firework explosion colored rgb 0, 255, 0:",
"\tbroadcast \"A firework colored %colors% was exploded at %location%!\"")
.examples(
"on firework explode:",
"\tif event-colors contains red:",
"on firework exploding colored red, light green and black:",
"on firework explosion colored rgb 0, 255, 0:",
"\tbroadcast \"A firework colored %colors% was exploded at %location%!\""
)
.since("2.4");
}

private @Nullable Literal<Color> colors;

@SuppressWarnings("unchecked")

@Override
public boolean init(Literal<?>[] args, int matchedPattern, ParseResult parseResult) {
if (args[0] != null)
//noinspection unchecked
colors = (Literal<Color>) args[0];
return true;
}
Expand All @@ -49,13 +52,14 @@ public boolean check(Event event) {
if (colors == null)
return true;

List<org.bukkit.Color> colours = colors.stream(event)
Set<org.bukkit.Color> colours = colors.stream(event)
.map(color -> {
if (color instanceof ColorRGB)
return color.asBukkitColor();
return color.asDyeColor().getFireworkColor();
})
.toList();
.collect(Collectors.toSet());

FireworkMeta meta = fireworkExplodeEvent.getEntity().getFireworkMeta();
for (FireworkEffect effect : meta.getEffects()) {
if (colours.containsAll(effect.getColors()))
Expand All @@ -65,8 +69,14 @@ public boolean check(Event event) {
}

@Override
public String toString(@Nullable Event e, boolean debug) {
return "Firework explode " + (colors != null ? " with colors " + colors.toString(e, debug) : "");
public String toString(@Nullable Event event, boolean debug) {
SyntaxStringBuilder builder = new SyntaxStringBuilder(event, debug);

builder.append("firework explode");
if (colors != null)
builder.append("with colors").append(colors);

return builder.toString();
}

}
4 changes: 1 addition & 3 deletions src/main/java/ch/njol/skript/localization/Adjective.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ protected void onValueChange() {
@Override
public String toString() {
validate();
if (Skript.testing())
Skript.warning("Invalid use of Adjective.toString()");
return "" + def;
return def;
}

public String toString(int gender, int flags) {
Expand Down
65 changes: 32 additions & 33 deletions src/main/java/ch/njol/skript/registrations/Classes.java
Original file line number Diff line number Diff line change
Expand Up @@ -711,58 +711,57 @@ private static byte[] getYggdrasilStart(final ClassInfo<?> c) throws NotSerializ
/**
* Must be called on the appropriate thread for the given value (i.e. the main thread currently)
*/
public static SerializedVariable.@Nullable Value serialize(@Nullable Object o) {
if (o == null)
public static SerializedVariable.@Nullable Value serialize(@Nullable Object object) {
if (object == null)
return null;

// temporary
assert Bukkit.isPrimaryThread();

ClassInfo<?> ci = getSuperClassInfo(o.getClass());
if (ci.getSerializeAs() != null) {
ci = getExactClassInfo(ci.getSerializeAs());
if (ci == null) {
assert false : o.getClass();
ClassInfo<?> classInfo = getSuperClassInfo(object.getClass());
if (classInfo.getSerializeAs() != null) {
classInfo = getExactClassInfo(classInfo.getSerializeAs());
if (classInfo == null) {
assert false : object.getClass();
return null;
}
o = Converters.convert(o, ci.getC());
if (o == null) {
assert false : ci.getCodeName();
object = Converters.convert(object, classInfo.getC());
if (object == null) {
assert false : classInfo.getCodeName();
return null;
}
}

final Serializer<?> s = ci.getSerializer();
if (s == null) // value cannot be saved
Serializer<?> serializer = classInfo.getSerializer();
if (serializer == null) // value cannot be saved
return null;

assert s.mustSyncDeserialization() ? Bukkit.isPrimaryThread() : true;
assert !serializer.mustSyncDeserialization() || Bukkit.isPrimaryThread();

try {
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final YggdrasilOutputStream yout = Variables.yggdrasil.newOutputStream(bout);
yout.writeObject(o);
yout.flush();
yout.close();
final byte[] r = bout.toByteArray();
final byte[] start = getYggdrasilStart(ci);
for (int i = 0; i < start.length; i++)
assert r[i] == start[i] : o + " (" + ci.getC().getName() + "); " + Arrays.toString(start) + ", " + Arrays.toString(r);
final byte[] r2 = new byte[r.length - start.length];
System.arraycopy(r, start.length, r2, 0, r2.length);
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
YggdrasilOutputStream yggdrasilOutputStream = Variables.yggdrasil.newOutputStream(byteOutputStream);

if (o instanceof Date date)
System.out.println(date.getTime());
yggdrasilOutputStream.writeObject(object);
yggdrasilOutputStream.flush();
yggdrasilOutputStream.close();

Object d = deserialize(ci, new ByteArrayInputStream(r2));
if (d instanceof Date date)
System.out.println(date.getTime());
byte[] byteArray = byteOutputStream.toByteArray();
byte[] start = getYggdrasilStart(classInfo);
for (int i = 0; i < start.length; i++)
assert byteArray[i] == start[i] : object + " (" + classInfo.getC().getName() + "); " + Arrays.toString(start) + ", " + Arrays.toString(byteArray);
byte[] byteArrayCopy = new byte[byteArray.length - start.length];
System.arraycopy(byteArray, start.length, byteArrayCopy, 0, byteArrayCopy.length);

assert equals(o, d) : o + " (" + o.getClass() + ") != " + d + " (" + (d == null ? null : d.getClass()) + "): " + Arrays.toString(r);
Object deserialized;
assert equals(object,
deserialized = deserialize(classInfo, new ByteArrayInputStream(byteArrayCopy)))
: object + " (" + object.getClass() + ") != " + deserialized + " ("
+ (deserialized == null ? null : deserialized.getClass()) + "): " + Arrays.toString(byteArray);

return new SerializedVariable.Value(ci.getCodeName(), r2);
} catch (final IOException e) { // shouldn't happen
Skript.exception(e);
return new SerializedVariable.Value(classInfo.getCodeName(), byteArrayCopy);
} catch (IOException ex) { // shouldn't happen
Skript.exception(ex);
return null;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,51 +1,77 @@
package org.skriptlang.skript.test.tests.files;

import ch.njol.skript.util.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

import static org.junit.Assert.*;

public class BackupPurgeTest {

@Test
public void testPurge() throws IOException {
File dir = new File("plugins/Skript/backups/");
if (!dir.exists()) {
dir.mkdir();
}
private static final Path FOLDER = Path.of("plugins", "Skript", "backups");
private static final Path VARIABLES = Path.of("plugins", "Skript", "variables.csv");

File vars = new File("plugins/Skript/variables.csv");
if (!vars.exists()) {
vars.createNewFile();
@Before
public void setup() throws IOException {
if (Files.exists(FOLDER)) {
clearFolder();
} else {
Files.createDirectory(FOLDER);
}

// Create Filler Files to be used for testing
for (int i = 0; i < 100; i++) {
(new File(dir, ("PurgeTest_"+i))).createNewFile();
Files.createFile(FOLDER.resolve("purge test " + i));
}

if (!Files.exists(VARIABLES)) {
Files.createFile(VARIABLES);
}
}

@Test
public void testPurge() throws IOException {
try (Stream<Path> files = Files.list(FOLDER)) {
assertEquals(100, files.count());
}
// Test 100 filler files were created
assertEquals("Filler Files != 100", 100, (new ArrayList<File>(Arrays.asList(dir.listFiles()))).size());

// Test 'backupPurge' method deleting to 50
FileUtils.backupPurge(vars, 50);
assertEquals("Backup Purge did not delete down to 50", 50, (new ArrayList<File>(Arrays.asList(dir.listFiles()))).size());
testBackupPurge(50);
testBackupPurge(20);
testBackupPurge(0);

assertThrows(IllegalArgumentException.class, () -> FileUtils.backupPurge(VARIABLES.toFile(), -1));
}

@After
public void cleanUp() throws IOException {
clearFolder();
}

// Test 'backupPurge' method deleting to 20
FileUtils.backupPurge(vars, 20);
assertEquals("Backup Purge did not delete down to 20", 20, (new ArrayList<File>(Arrays.asList(dir.listFiles()))).size());
private static void clearFolder() throws IOException {
try (Stream<Path> list = Files.list(FOLDER)) {
list.forEach(path -> {
try {
Files.delete(path);
} catch (IOException ignored) {

// Test 'backupPurge' method deleting all files
FileUtils.backupPurge(vars, 0);
assertEquals("Backup Purge did not delete all files", 0, (new ArrayList<File>(Arrays.asList(dir.listFiles()))).size());
}
});
}
}

// Test calling with invalid input
assertThrows("Backup Purge did not throw exception for invalid input", IllegalArgumentException.class, () -> FileUtils.backupPurge(vars, -1));
private static void testBackupPurge(int toKeep) throws IOException {
FileUtils.backupPurge(VARIABLES.toFile(), toKeep);

try (Stream<Path> files = Files.list(FOLDER)) {
long count = files.count();
assertNotNull(files);
assertEquals("backup purge did not delete all files", toKeep, count);
}
}

}
6 changes: 3 additions & 3 deletions src/test/skript/junit/CancelledEventTest.sk
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ test "ExprDropsJUnit" when running JUnit:
ensure junit test {@test} completes {_tests::*}

on load:
set {-cancelled-event-test::call-count} to 0
set {cancelled-event-test::call-count} to 0

on form:
junit test is {@test}
Expand All @@ -26,7 +26,7 @@ on cancelled form:
on any form:
junit test is {@test}

add 1 to {-cancelled-event-test::call-count}
add 1 to {cancelled-event-test::call-count}

if {-cancelled-event-test::call-count} is 2:
if {cancelled-event-test::call-count} is 2:
complete objective "listen for any event" for {@test}
1 change: 0 additions & 1 deletion src/test/skript/junit/EvtFurnaceTest.sk
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ on load:
on smelt:
junit test is {@EvtFurnaceTest}
complete objective "smelt event" for junit test {@EvtFurnaceTest}
broadcast "%smelted item%"
if smelted item is an iron ingot:
complete objective "smelt - got smelted item" for junit test {@EvtFurnaceTest}

Expand Down
2 changes: 1 addition & 1 deletion src/test/skript/junit/PlayerElytraBoostEventTest.sk
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
options:
test: "org.skriptlang.skript.test.tests.syntaxes.events.PlayerElytraBoostEventTest"

test "PlayerElytraBoosEventTest" when running JUnit:
test "PlayerElytraBoostEventTest" when running JUnit:
set {_tests::*} to "boost event called", "boost event - firework item", "boost event - player" and "boost event - firework entity"
ensure junit test {@test} completes {_tests::*}

Expand Down

0 comments on commit 1fd0c93

Please sign in to comment.