diff --git a/build.gradle.kts b/build.gradle.kts index 863d28d098..cab68f5e66 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -135,6 +135,7 @@ dependencies { testImplementation("org.junit.jupiter:junit-jupiter:5.10.1") testImplementation("org.reflections:reflections:0.10.2") testImplementation("org.mockito:mockito-core:5.8.0") + testImplementation("org.assertj:assertj-core:3.25.3") } val compileJava: JavaCompile by tasks diff --git a/src/main/java/net/dv8tion/jda/api/utils/data/DataArray.java b/src/main/java/net/dv8tion/jda/api/utils/data/DataArray.java index 6c2bb1a0ad..bd8ab473e5 100644 --- a/src/main/java/net/dv8tion/jda/api/utils/data/DataArray.java +++ b/src/main/java/net/dv8tion/jda/api/utils/data/DataArray.java @@ -17,9 +17,9 @@ package net.dv8tion.jda.api.utils.data; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.CollectionType; import net.dv8tion.jda.api.exceptions.ParsingException; @@ -218,7 +218,7 @@ public static DataArray fromETF(@Nonnull byte[] data) */ public boolean isNull(int index) { - return data.get(index) == null; + return index >= length() || data.get(index) == null; } /** @@ -782,12 +782,12 @@ public String toString() @Nonnull public String toPrettyString() { - DefaultPrettyPrinter.Indenter indent = new DefaultIndenter(" ", DefaultIndenter.SYS_LF); - DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); - printer.withObjectIndenter(indent).withArrayIndenter(indent); try { - return mapper.writer(printer).writeValueAsString(data); + return mapper.writer(new DefaultPrettyPrinter()) + .with(SerializationFeature.INDENT_OUTPUT) + .with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) + .writeValueAsString(data); } catch (JsonProcessingException e) { @@ -820,7 +820,9 @@ private T get(@Nonnull Class type, int index) @Nullable private T get(@Nonnull Class type, int index, @Nullable Function stringMapper, @Nullable Function numberMapper) { - Object value = data.get(index); + if (index < 0) + throw new IndexOutOfBoundsException("Index out of range: " + index); + Object value = index < data.size() ? data.get(index) : null; if (value == null) return null; if (type.isInstance(value)) @@ -857,4 +859,21 @@ public DataArray toDataArray() { return this; } + + @Override + public boolean equals(Object o) + { + if (this == o) + return true; + if (!(o instanceof DataArray)) + return false; + DataArray objects = (DataArray) o; + return Objects.equals(data, objects.data); + } + + @Override + public int hashCode() + { + return Objects.hash(data); + } } diff --git a/src/main/java/net/dv8tion/jda/api/utils/data/DataObject.java b/src/main/java/net/dv8tion/jda/api/utils/data/DataObject.java index fed87b68d9..a935ee64b4 100644 --- a/src/main/java/net/dv8tion/jda/api/utils/data/DataObject.java +++ b/src/main/java/net/dv8tion/jda/api/utils/data/DataObject.java @@ -16,10 +16,14 @@ package net.dv8tion.jda.api.utils.data; +import com.fasterxml.jackson.core.FormatFeature; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.json.JsonWriteFeature; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.MapType; import net.dv8tion.jda.api.exceptions.ParsingException; @@ -850,12 +854,12 @@ public String toString() @Nonnull public String toPrettyString() { - DefaultPrettyPrinter.Indenter indent = new DefaultIndenter(" ", DefaultIndenter.SYS_LF); - DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); - printer.withObjectIndenter(indent).withArrayIndenter(indent); try { - return mapper.writer(printer).writeValueAsString(data); + return mapper.writer(new DefaultPrettyPrinter()) + .with(SerializationFeature.INDENT_OUTPUT) + .with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) + .writeValueAsString(data); } catch (JsonProcessingException e) { diff --git a/src/main/java/net/dv8tion/jda/api/utils/data/etf/ExTermEncoder.java b/src/main/java/net/dv8tion/jda/api/utils/data/etf/ExTermEncoder.java index cfb550804b..ceb8d10645 100644 --- a/src/main/java/net/dv8tion/jda/api/utils/data/etf/ExTermEncoder.java +++ b/src/main/java/net/dv8tion/jda/api/utils/data/etf/ExTermEncoder.java @@ -88,16 +88,15 @@ private static ByteBuffer pack(ByteBuffer buffer, Object value) if (value instanceof Byte) return packSmallInt(buffer, (byte) value); if (value instanceof Integer || value instanceof Short) - return packInt(buffer, (int) value); + return packInt(buffer, ((Number) value).intValue()); if (value instanceof Long) return packLong(buffer, (long) value); if (value instanceof Float || value instanceof Double) - return packFloat(buffer, (double) value); + return packFloat(buffer, ((Number) value).doubleValue()); if (value instanceof Boolean) return packAtom(buffer, String.valueOf(value)); if (value == null) return packAtom(buffer, "nil"); - // imagine we had templates :O if (value instanceof long[]) return packArray(buffer, (long[]) value); if (value instanceof int[]) diff --git a/src/test/java/CommandDataTest.java b/src/test/java/CommandDataTest.java deleted file mode 100644 index 5352c72047..0000000000 --- a/src/test/java/CommandDataTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.interactions.commands.Command; -import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; -import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import net.dv8tion.jda.api.interactions.commands.build.OptionData; -import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; -import net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData; -import net.dv8tion.jda.api.utils.data.DataArray; -import net.dv8tion.jda.api.utils.data.DataObject; -import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -public class CommandDataTest -{ - @Test - public void testNormal() - { - CommandData command = new CommandDataImpl("ban", "Ban a user from this server") - .setGuildOnly(true) - .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS)) - .addOption(OptionType.USER, "user", "The user to ban", true) // required before non-required - .addOption(OptionType.STRING, "reason", "The ban reason") // test that default is false - .addOption(OptionType.INTEGER, "days", "The duration of the ban", false); // test with explicit false - - DataObject data = command.toData(); - Assertions.assertEquals("ban", data.getString("name")); - Assertions.assertEquals("Ban a user from this server", data.getString("description")); - Assertions.assertFalse(data.getBoolean("dm_permission")); - Assertions.assertEquals(Permission.BAN_MEMBERS.getRawValue(), data.getUnsignedLong("default_member_permissions")); - - DataArray options = data.getArray("options"); - - DataObject option = options.getObject(0); - Assertions.assertTrue(option.getBoolean("required")); - Assertions.assertEquals("user", option.getString("name")); - Assertions.assertEquals("The user to ban", option.getString("description")); - - option = options.getObject(1); - Assertions.assertFalse(option.getBoolean("required")); - Assertions.assertEquals("reason", option.getString("name")); - Assertions.assertEquals("The ban reason", option.getString("description")); - - option = options.getObject(2); - Assertions.assertFalse(option.getBoolean("required")); - Assertions.assertEquals("days", option.getString("name")); - Assertions.assertEquals("The duration of the ban", option.getString("description")); - } - - @Test - public void testDefaultMemberPermissions() - { - CommandData command = new CommandDataImpl("ban", "Ban a user from this server") - .setDefaultPermissions(DefaultMemberPermissions.DISABLED); - DataObject data = command.toData(); - - Assertions.assertEquals(0, data.getUnsignedLong("default_member_permissions")); - - command.setDefaultPermissions(DefaultMemberPermissions.ENABLED); - data = command.toData(); - Assertions.assertTrue(data.isNull("default_member_permissions")); - } - - @Test - public void testSubcommand() - { - CommandDataImpl command = new CommandDataImpl("mod", "Moderation commands") - .addSubcommands(new SubcommandData("ban", "Ban a user from this server") - .addOption(OptionType.USER, "user", "The user to ban", true) // required before non-required - .addOption(OptionType.STRING, "reason", "The ban reason") // test that default is false - .addOption(OptionType.INTEGER, "days", "The duration of the ban", false)); // test with explicit false - - DataObject data = command.toData(); - Assertions.assertEquals("mod", data.getString("name")); - Assertions.assertEquals("Moderation commands", data.getString("description")); - - DataObject subdata = data.getArray("options").getObject(0); - Assertions.assertEquals("ban", subdata.getString("name")); - Assertions.assertEquals("Ban a user from this server", subdata.getString("description")); - - DataArray options = subdata.getArray("options"); - - DataObject option = options.getObject(0); - Assertions.assertTrue(option.getBoolean("required")); - Assertions.assertEquals("user", option.getString("name")); - Assertions.assertEquals("The user to ban", option.getString("description")); - - option = options.getObject(1); - Assertions.assertFalse(option.getBoolean("required")); - Assertions.assertEquals("reason", option.getString("name")); - Assertions.assertEquals("The ban reason", option.getString("description")); - - option = options.getObject(2); - Assertions.assertFalse(option.getBoolean("required")); - Assertions.assertEquals("days", option.getString("name")); - Assertions.assertEquals("The duration of the ban", option.getString("description")); - } - - @Test - public void testSubcommandGroup() - { - CommandDataImpl command = new CommandDataImpl("mod", "Moderation commands") - .addSubcommandGroups(new SubcommandGroupData("ban", "Ban or unban a user from this server") - .addSubcommands(new SubcommandData("add", "Ban a user from this server") - .addOption(OptionType.USER, "user", "The user to ban", true) // required before non-required - .addOption(OptionType.STRING, "reason", "The ban reason") // test that default is false - .addOption(OptionType.INTEGER, "days", "The duration of the ban", false))); // test with explicit false - - DataObject data = command.toData(); - Assertions.assertEquals("mod", data.getString("name")); - Assertions.assertEquals("Moderation commands", data.getString("description")); - - DataObject group = data.getArray("options").getObject(0); - Assertions.assertEquals("ban", group.getString("name")); - Assertions.assertEquals("Ban or unban a user from this server", group.getString("description")); - - DataObject subdata = group.getArray("options").getObject(0); - Assertions.assertEquals("add", subdata.getString("name")); - Assertions.assertEquals("Ban a user from this server", subdata.getString("description")); - DataArray options = subdata.getArray("options"); - - DataObject option = options.getObject(0); - Assertions.assertTrue(option.getBoolean("required")); - Assertions.assertEquals("user", option.getString("name")); - Assertions.assertEquals("The user to ban", option.getString("description")); - - option = options.getObject(1); - Assertions.assertFalse(option.getBoolean("required")); - Assertions.assertEquals("reason", option.getString("name")); - Assertions.assertEquals("The ban reason", option.getString("description")); - - option = options.getObject(2); - Assertions.assertFalse(option.getBoolean("required")); - Assertions.assertEquals("days", option.getString("name")); - Assertions.assertEquals("The duration of the ban", option.getString("description")); - } - - @Test - public void testRequiredThrows() - { - CommandDataImpl command = new CommandDataImpl("ban", "Simple ban command"); - command.addOption(OptionType.STRING, "opt", "desc"); - - Assertions.assertThrows(IllegalArgumentException.class, () -> command.addOption(OptionType.STRING, "other", "desc", true)); - - SubcommandData subcommand = new SubcommandData("sub", "Simple subcommand"); - subcommand.addOption(OptionType.STRING, "opt", "desc"); - Assertions.assertThrows(IllegalArgumentException.class, () -> subcommand.addOption(OptionType.STRING, "other", "desc", true)); - } - - @Test - public void testNameChecks() - { - Assertions.assertThrows(IllegalArgumentException.class, () -> new CommandDataImpl("invalid name", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> new CommandDataImpl("invalidName", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> new CommandDataImpl("valid_name", "")); - - Assertions.assertThrows(IllegalArgumentException.class, () -> new SubcommandData("invalid name", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> new SubcommandData("invalidName", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> new SubcommandData("valid_name", "")); - - Assertions.assertThrows(IllegalArgumentException.class, () -> new SubcommandGroupData("invalid name", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> new SubcommandGroupData("invalidName", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> new SubcommandGroupData("valid_name", "")); - } - - @Test - public void testChoices() - { - OptionData option = new OptionData(OptionType.INTEGER, "choice", "Option with choices!"); - Assertions.assertThrows(IllegalArgumentException.class, () -> option.addChoice("invalid name", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> option.addChoice("invalidName", "Valid description")); - Assertions.assertThrows(IllegalArgumentException.class, () -> option.addChoice("valid_name", "")); - - List choices = new ArrayList<>(); - for (int i = 0; i < 25; i++) - { - option.addChoice("choice_" + i, i); - choices.add(new Command.Choice("choice_" + i, i)); - } - Assertions.assertThrows(IllegalArgumentException.class, () -> option.addChoice("name", 100)); - Assertions.assertEquals(25, option.getChoices().size()); - Assertions.assertEquals(choices, option.getChoices()); - } -} diff --git a/src/test/java/DataPathTest.java b/src/test/java/DataPathTest.java deleted file mode 100644 index 9f79294722..0000000000 --- a/src/test/java/DataPathTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import net.dv8tion.jda.api.exceptions.ParsingException; -import net.dv8tion.jda.api.utils.data.DataArray; -import net.dv8tion.jda.api.utils.data.DataObject; -import net.dv8tion.jda.api.utils.data.DataPath; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class DataPathTest -{ - @Test - void testSimple() - { - DataObject object = DataObject.empty() - .put("foo", "10"); // string to also test parsing - - Assertions.assertEquals(10, DataPath.getInt(object, "foo")); - - DataArray array = DataArray.empty().add("20"); - Assertions.assertEquals(20, DataPath.getInt(array, "[0]")); - } - - @Test - void testSimpleMissing() - { - DataObject object = DataObject.empty(); - - Assertions.assertEquals(0L, DataPath.getLong(object, "foo?", 0)); - Assertions.assertThrows(ParsingException.class, () -> DataPath.getLong(object, "foo")); - - DataArray array = DataArray.empty(); - - Assertions.assertTrue(DataPath.getBoolean(array, "[0]?", true)); - Assertions.assertThrows(ParsingException.class, () -> DataPath.getObject(array, "[0]")); - } - - @Test - void testObjectInArray() - { - DataObject object = DataObject.empty().put("foo", 10.0); - DataArray array = DataArray.empty().add(object); - - Assertions.assertEquals(10.0, DataPath.getDouble(array, "[0].foo")); - Assertions.assertEquals(20.0, DataPath.getDouble(array, "[1]?.foo", 20.0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> DataPath.getDouble(array, "[1].foo")); - } - - @Test - void testArrayInObject() - { - DataArray array = DataArray.empty().add("hello"); - DataObject object = DataObject.empty().put("foo", array); - - Assertions.assertEquals("hello", DataPath.getString(object, "foo[0]")); - Assertions.assertEquals("world", DataPath.getString(object, "foo[1]?", "world")); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> DataPath.getString(object, "foo[1]")); - } - - @Test - void testArrayInArray() - { - DataArray array = DataArray.empty().add(DataArray.empty().add("10")); - - Assertions.assertEquals(10, DataPath.getUnsignedInt(array, "[0][0]")); - Assertions.assertEquals(20, DataPath.getUnsignedInt(array, "[0][1]?", 20)); - Assertions.assertEquals(20, DataPath.getUnsignedInt(array, "[1]?[0]", 20)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> DataPath.getUnsignedInt(array, "[0][1]")); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> DataPath.getUnsignedInt(array, "[1][0]")); - Assertions.assertThrows(ParsingException.class, () -> DataPath.getUnsignedInt(array, "[0][1]?")); - Assertions.assertThrows(ParsingException.class, () -> DataPath.getUnsignedInt(array, "[1]?[0]")); - } - - @Test - void testComplex() - { - DataObject object = DataObject.empty() - .put("array", DataArray.empty() - .add(DataObject.empty() - .put("foo", DataObject.empty() - .put("bar", "hello")))); - - Assertions.assertEquals("hello", DataPath.getString(object, "array[0].foo.bar")); - Assertions.assertEquals("world", DataPath.getString(object, "array[0].wrong?.bar", "world")); - Assertions.assertThrows(ParsingException.class, () -> DataPath.getString(object, "array[0].wrong?.bar")); - } -} diff --git a/src/test/java/HelpersTest.java b/src/test/java/HelpersTest.java deleted file mode 100644 index f5fed4bca5..0000000000 --- a/src/test/java/HelpersTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import net.dv8tion.jda.internal.utils.Helpers; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.List; - -public class HelpersTest -{ - @Test - public void testIsEmpty() - { - Assertions.assertTrue(Helpers.isEmpty(null)); - Assertions.assertTrue(Helpers.isEmpty("")); - Assertions.assertFalse(Helpers.isEmpty("null")); - Assertions.assertFalse(Helpers.isEmpty("testing with spaces")); - } - - @Test - public void testContainsWhitespace() - { - Assertions.assertTrue(Helpers.containsWhitespace(" ")); - Assertions.assertTrue(Helpers.containsWhitespace("testing with spaces")); - Assertions.assertFalse(Helpers.containsWhitespace(null)); - Assertions.assertFalse(Helpers.containsWhitespace("")); - Assertions.assertFalse(Helpers.containsWhitespace("null")); - } - - @Test - public void testIsBlank() - { - Assertions.assertTrue(Helpers.isBlank(" ")); - Assertions.assertTrue(Helpers.isBlank(null)); - Assertions.assertTrue(Helpers.isBlank("")); - Assertions.assertFalse(Helpers.isBlank("testing with spaces")); - Assertions.assertFalse(Helpers.isBlank("null")); - } - - @Test - public void testCountMatches() - { - Assertions.assertEquals(3, Helpers.countMatches("Hello World", 'l')); - Assertions.assertEquals(1, Helpers.countMatches("Hello World", ' ')); - Assertions.assertEquals(0, Helpers.countMatches("Hello World", '_')); - Assertions.assertEquals(0, Helpers.countMatches("", '!')); - Assertions.assertEquals(0, Helpers.countMatches(null, '?')); - } - - @Test - public void testTruncate() - { - Assertions.assertEquals("Hello", Helpers.truncate("Hello World", 5)); - Assertions.assertEquals("Hello", Helpers.truncate("Hello", 5)); - Assertions.assertEquals("Hello", Helpers.truncate("Hello", 10)); - Assertions.assertEquals("", Helpers.truncate("", 10)); - Assertions.assertEquals("", Helpers.truncate("Test", 0)); - Assertions.assertNull(Helpers.truncate(null, 10)); - } - - @Test - public void testRightPad() - { - Assertions.assertEquals("Hello ", Helpers.rightPad("Hello", 9)); - Assertions.assertEquals("Hello World", Helpers.rightPad("Hello World", 9)); - Assertions.assertEquals("Hello", Helpers.rightPad("Hello", 5)); - } - - @Test - public void testLeftPad() - { - Assertions.assertEquals(" Hello", Helpers.leftPad("Hello", 9)); - Assertions.assertEquals("Hello World", Helpers.leftPad("Hello World", 9)); - Assertions.assertEquals("Hello", Helpers.leftPad("Hello", 5)); - } - - @Test - public void testIsNumeric() - { - Assertions.assertTrue(Helpers.isNumeric("10")); - Assertions.assertTrue(Helpers.isNumeric("1")); - Assertions.assertTrue(Helpers.isNumeric("0")); - Assertions.assertTrue(Helpers.isNumeric(String.valueOf(Long.MAX_VALUE))); - Assertions.assertFalse(Helpers.isNumeric(null)); - Assertions.assertFalse(Helpers.isNumeric("")); - Assertions.assertFalse(Helpers.isNumeric("Test")); - Assertions.assertFalse(Helpers.isNumeric("1.0")); - Assertions.assertFalse(Helpers.isNumeric("1e10")); - } - - @Test - public void testDeepEquals() - { - List a = Arrays.asList("A", "B", "C"); - List b = Arrays.asList("B", "A", "C"); - List c = Arrays.asList("A", "B"); - List d = Arrays.asList("A", "B", "C"); - - Assertions.assertTrue(Helpers.deepEquals(a, a)); - Assertions.assertTrue(Helpers.deepEquals(a, d)); - Assertions.assertTrue(Helpers.deepEqualsUnordered(a, b)); - Assertions.assertFalse(Helpers.deepEquals(a, b)); - Assertions.assertFalse(Helpers.deepEquals(a, c)); - Assertions.assertFalse(Helpers.deepEqualsUnordered(b, c)); - } -} diff --git a/src/test/java/JsonTest.java b/src/test/java/JsonTest.java deleted file mode 100644 index f147dc3cfd..0000000000 --- a/src/test/java/JsonTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import net.dv8tion.jda.api.utils.data.DataObject; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class JsonTest -{ - private static final String json = "{\"int\":10,\"long\":100,\"boolean\":true,\"string\":\"test\"}"; - - @Test - public void testParse() - { - DataObject object = DataObject.fromJson(json); - Assertions.assertEquals(10, object.getInt("int", 0)); - Assertions.assertEquals(100, object.getLong("long", 0)); - Assertions.assertEquals(true, object.getBoolean("boolean", false)); - Assertions.assertEquals("test", object.getString("string", null)); - } - - @Test - public void testJsonToString() - { - DataObject object = DataObject.fromJson(json); - String result = object.toString(); - DataObject symmetric = DataObject.fromJson(result); - Assertions.assertEquals(object.toMap(), symmetric.toMap()); // lucky that this works here :) - } -} diff --git a/src/test/java/LocalizationTest.java b/src/test/java/LocalizationTest.java deleted file mode 100644 index 7708d56d9d..0000000000 --- a/src/test/java/LocalizationTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import net.dv8tion.jda.api.interactions.DiscordLocale; -import net.dv8tion.jda.api.interactions.commands.Command; -import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.*; -import net.dv8tion.jda.api.interactions.commands.localization.LocalizationFunction; -import net.dv8tion.jda.api.interactions.commands.localization.ResourceBundleLocalizationFunction; -import net.dv8tion.jda.api.utils.data.DataArray; -import net.dv8tion.jda.api.utils.data.DataObject; -import net.dv8tion.jda.api.utils.data.DataPath; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class LocalizationTest -{ - private static SlashCommandData slashCommandData; - private static DataObject data; - - @BeforeAll - public static void setup() - { - final LocalizationFunction localizationFunction = ResourceBundleLocalizationFunction - .fromBundles("MyCommands", DiscordLocale.FRENCH) - .build(); - - slashCommandData = Commands.slash("ban", "Bans someone").addSubcommandGroups( - new SubcommandGroupData("user", "Bans a member").addSubcommands( - new SubcommandData("perm", "Bans an user permanently").addOptions( - new OptionData(OptionType.STRING, "user", "The user to ban"), - new OptionData(OptionType.INTEGER, "del_days", "The amount of days to delete messages") - .addChoices( - new Command.Choice("1 Day", "1"), - new Command.Choice("7 Days", "7"), - new Command.Choice("14 Days", "14") - ) - ), - new SubcommandData("temp", "Bans an user temporarily").addOptions( - new OptionData(OptionType.STRING, "user", "The user to ban"), - new OptionData(OptionType.INTEGER, "del_days", "The amount of days to delete messages") - .addChoices( - new Command.Choice("1 Day", "1"), - new Command.Choice("7 Days", "7"), - new Command.Choice("14 Days", "14") - ) - ) - ) - ).setLocalizationFunction(localizationFunction); - - data = slashCommandData.toData(); - } - - @Test - public void commandLocalization() - { - assertEquals("ban", DataPath.getString(data, "name_localizations.fr")); - assertEquals("Bannis un utilisateur", DataPath.getString(data, "description_localizations.fr")); - } - - @Test - public void subcommandLocalization() - { - assertEquals("utilisateur", navigateOptions("user").getObject("name_localizations").getString("fr")); - assertEquals("Bannis un utilisateur", navigateOptions("user").getObject("description_localizations").getString("fr")); - } - - @Test - public void subcommandGroupLocalization() - { - assertEquals("permanent", navigateOptions("user", "perm").getObject("name_localizations").getString("fr")); - assertEquals("Bannis un utilisateur pour toujours", navigateOptions("user", "perm").getObject("description_localizations").getString("fr")); - } - - @Test - public void optionLocalization() - { - assertEquals("utilisateur", navigateOptions("user", "perm", "user").getObject("name_localizations").getString("fr")); - assertEquals("L'utilisateur à bannir", navigateOptions("user", "perm", "user").getObject("description_localizations").getString("fr")); - - assertEquals("nb_jours", navigateOptions("user", "perm", "del_days").getObject("name_localizations").getString("fr")); - assertEquals("Nombre de jours de messages à supprimer", navigateOptions("user", "perm", "del_days").getObject("description_localizations").getString("fr")); - } - - @Test - public void choiceLocalization() - { - assertEquals("1 jour", navigateChoice("1 Day", "user", "perm", "del_days").getObject("name_localizations").getString("fr")); - assertEquals("7 jours", navigateChoice("7 Days", "user", "perm", "del_days").getObject("name_localizations").getString("fr")); - assertEquals("14 jours", navigateChoice("14 Days", "user", "perm", "del_days").getObject("name_localizations").getString("fr")); - } - - @Test - public void reconstructData() - { - final DataObject data = slashCommandData.toData(); - final DataObject reconstitutedData = CommandData.fromData(data).toData(); - assertEquals(data.toMap(), reconstitutedData.toMap()); - } - - private DataObject navigateOptions(String... names) - { - DataObject o = data; - for (String name : names) - { - o = o.getArray("options").stream(DataArray::getObject) - .filter(s -> s.getString("name").equals(name)) - .findAny() - .orElseThrow(() -> new IllegalArgumentException("Could not find an option with path: " + Arrays.toString(names))); - } - return o; - } - - private DataObject navigateChoice(String choiceName, String... names) - { - return navigateOptions(names) - .getArray("choices") - .stream(DataArray::getObject) - .filter(s -> s.getString("name").equals(choiceName)) - .findAny() - .orElseThrow(() -> new IllegalArgumentException("Could not find choice '" + choiceName + "' with path: " + Arrays.toString(names))); - } -} diff --git a/src/test/java/MarkdownTest.java b/src/test/java/MarkdownTest.java deleted file mode 100644 index 384934491f..0000000000 --- a/src/test/java/MarkdownTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import net.dv8tion.jda.api.utils.MarkdownSanitizer; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class MarkdownTest -{ - private MarkdownSanitizer markdown; - - @BeforeEach - public void setup() - { - markdown = new MarkdownSanitizer().withStrategy(MarkdownSanitizer.SanitizationStrategy.REMOVE); - } - - @Test - public void testComplex() - { - Assertions.assertEquals("ABCDEF", markdown.compute("**A_B||C~~D__E`F`__~~||_**")); - } - - @Test - public void testTrivial() - { - Assertions.assertEquals("", markdown.compute("")); - Assertions.assertEquals("Hello World ~~~~", markdown.compute("Hello World ~~~~")); - Assertions.assertEquals("Hello World ~", markdown.compute("Hello World ~~~~~")); - } - - @Test - public void testBold() - { - Assertions.assertEquals("Hello", markdown.compute("**Hello**")); - Assertions.assertEquals("**Hello", markdown.compute("**Hello")); - Assertions.assertEquals("\\**Hello**", markdown.compute("\\**Hello**")); - } - - @Test - public void testItalics() - { - Assertions.assertEquals("Hello", markdown.compute("*Hello*")); - Assertions.assertEquals("Hello", markdown.compute("_Hello_")); - - Assertions.assertEquals("*Hello", markdown.compute("*Hello")); - Assertions.assertEquals("_Hello", markdown.compute("_Hello")); - - Assertions.assertEquals("\\*Hello*", markdown.compute("\\*Hello*")); - Assertions.assertEquals("\\_Hello_", markdown.compute("\\_Hello_")); - } - - @Test - public void testBoldItalics() - { - Assertions.assertEquals("Hello", markdown.compute("***Hello***")); - Assertions.assertEquals("***Hello", markdown.compute("***Hello")); - Assertions.assertEquals("\\***Hello***", markdown.compute("\\***Hello***")); - } - - @Test - public void testUnderline() - { - Assertions.assertEquals("Hello", markdown.compute("__Hello__")); - Assertions.assertEquals("__Hello", markdown.compute("__Hello")); - Assertions.assertEquals("\\__Hello__", markdown.compute("\\__Hello__")); - } - - @Test - public void testStrike() - { - Assertions.assertEquals("Hello", markdown.compute("~~Hello~~")); - Assertions.assertEquals("~~Hello", markdown.compute("~~Hello")); - Assertions.assertEquals("\\~~Hello~~", markdown.compute("\\~~Hello~~")); - } - - @Test - public void testSpoiler() - { - Assertions.assertEquals("Hello", markdown.compute("||Hello||")); - Assertions.assertEquals("||Hello", markdown.compute("||Hello")); - Assertions.assertEquals("\\||Hello||", markdown.compute("\\||Hello||")); - } - - @Test - public void testMono() - { - Assertions.assertEquals("Hello", markdown.compute("`Hello`")); - Assertions.assertEquals("`Hello", markdown.compute("`Hello")); - Assertions.assertEquals("\\`Hello`", markdown.compute("\\`Hello`")); - - Assertions.assertEquals("Hello **World**", markdown.compute("`Hello **World**`")); - Assertions.assertEquals("`Hello World", markdown.compute("`Hello **World**")); - Assertions.assertEquals("\\`Hello World`", markdown.compute("\\`Hello **World**`")); - } - - @Test - public void testMonoTwo() - { - Assertions.assertEquals("Hello", markdown.compute("``Hello``")); - Assertions.assertEquals("``Hello", markdown.compute("``Hello")); - Assertions.assertEquals("\\``Hello``", markdown.compute("\\``Hello``")); - - Assertions.assertEquals("Hello **World**", markdown.compute("``Hello **World**``")); - Assertions.assertEquals("``Hello World", markdown.compute("``Hello **World**")); - Assertions.assertEquals("\\``Hello World``", markdown.compute("\\``Hello **World**``")); - - Assertions.assertEquals("Hello `to` World", markdown.compute("``Hello `to` World``")); - Assertions.assertEquals("``Hello to World", markdown.compute("``Hello `to` World")); - Assertions.assertEquals("\\``Hello to World``", markdown.compute("\\``Hello `to` World``")); - } - - @Test - public void testBlock() - { - Assertions.assertEquals("Hello", markdown.compute("```Hello```")); - Assertions.assertEquals("```Hello", markdown.compute("```Hello")); - Assertions.assertEquals("\\```Hello```", markdown.compute("\\```Hello```")); - - Assertions.assertEquals("Hello **World**", markdown.compute("```Hello **World**```")); - Assertions.assertEquals("```Hello World", markdown.compute("```Hello **World**")); - Assertions.assertEquals("\\```Hello World```", markdown.compute("\\```Hello **World**```")); - - Assertions.assertEquals("Hello `to` World", markdown.compute("```Hello `to` World```")); - Assertions.assertEquals("```Hello to World", markdown.compute("```Hello `to` World")); - Assertions.assertEquals("\\```Hello to World```", markdown.compute("\\```Hello `to` World```")); - - Assertions.assertEquals("Test", markdown.compute("```java\nTest```")); - } - - @Test - public void testQuote() - { - Assertions.assertEquals("Hello > World", markdown.compute("> Hello > World")); - Assertions.assertEquals("Hello\nWorld", markdown.compute("> Hello\n> World")); - Assertions.assertEquals("Hello\nWorld", markdown.compute(">>> Hello\nWorld")); - Assertions.assertEquals("Hello\nWorld", markdown.compute(">>>\nHello\nWorld")); - Assertions.assertEquals("Hello > World", markdown.compute(">>>\nHello > World")); - Assertions.assertEquals("Hello\n World", markdown.compute("Hello\n > World")); - } -} - -class IgnoreMarkdownTest -{ - private MarkdownSanitizer markdown; - - @BeforeEach - public void setup() - { - markdown = new MarkdownSanitizer().withIgnored(0xFFFFFFFF); - } - - @Test - public void testComplex() - { - Assertions.assertEquals("**A_B||C~~D__E`F`__~~||_**", markdown.compute("**A_B||C~~D__E`F`__~~||_**")); - } - - @Test - public void testBold() - { - Assertions.assertEquals("**Hello**", markdown.compute("**Hello**")); - Assertions.assertEquals("**Hello", markdown.compute("**Hello")); - } - - @Test - public void testItalics() - { - Assertions.assertEquals("*Hello*", markdown.compute("*Hello*")); - Assertions.assertEquals("_Hello_", markdown.compute("_Hello_")); - - Assertions.assertEquals("*Hello", markdown.compute("*Hello")); - Assertions.assertEquals("_Hello", markdown.compute("_Hello")); - } - - @Test - public void testBoldItalics() - { - Assertions.assertEquals("***Hello***", markdown.compute("***Hello***")); - Assertions.assertEquals("***Hello", markdown.compute("***Hello")); - Assertions.assertEquals("\\***Hello***", markdown.compute("\\***Hello***")); - } - - @Test - public void testUnderline() - { - Assertions.assertEquals("__Hello__", markdown.compute("__Hello__")); - Assertions.assertEquals("__Hello", markdown.compute("__Hello")); - } - - @Test - public void testStrike() - { - Assertions.assertEquals("~~Hello~~", markdown.compute("~~Hello~~")); - Assertions.assertEquals("~~Hello", markdown.compute("~~Hello")); - } - - @Test - public void testSpoiler() - { - Assertions.assertEquals("||Hello||", markdown.compute("||Hello||")); - Assertions.assertEquals("||Hello", markdown.compute("||Hello")); - } - - @Test - public void testMono() - { - Assertions.assertEquals("`Hello`", markdown.compute("`Hello`")); - Assertions.assertEquals("`Hello", markdown.compute("`Hello")); - - Assertions.assertEquals("`Hello **World**`", markdown.compute("`Hello **World**`")); - Assertions.assertEquals("`Hello **World**", markdown.compute("`Hello **World**")); - } - - @Test - public void testMonoTwo() - { - Assertions.assertEquals("``Hello``", markdown.compute("``Hello``")); - Assertions.assertEquals("``Hello", markdown.compute("``Hello")); - - Assertions.assertEquals("``Hello **World**``", markdown.compute("``Hello **World**``")); - Assertions.assertEquals("``Hello **World**", markdown.compute("``Hello **World**")); - - Assertions.assertEquals("``Hello `to` World``", markdown.compute("``Hello `to` World``")); - Assertions.assertEquals("``Hello `to` World", markdown.compute("``Hello `to` World")); - } - - @Test - public void testBlock() - { - Assertions.assertEquals("```Hello```", markdown.compute("```Hello```")); - Assertions.assertEquals("```Hello", markdown.compute("```Hello")); - - Assertions.assertEquals("```Hello **World**```", markdown.compute("```Hello **World**```")); - Assertions.assertEquals("```Hello **World**", markdown.compute("```Hello **World**")); - - Assertions.assertEquals("```Hello `to` World```", markdown.compute("```Hello `to` World```")); - Assertions.assertEquals("```Hello `to` World", markdown.compute("```Hello `to` World")); - - Assertions.assertEquals("```java\nTest```", markdown.compute("```java\nTest```")); - } - - @Test - public void testQuote() - { - Assertions.assertEquals("> Hello > World", markdown.compute("> Hello > World")); - Assertions.assertEquals("> Hello\n> World", markdown.compute("> Hello\n> World")); - Assertions.assertEquals(">>> Hello\nWorld", markdown.compute(">>> Hello\nWorld")); - Assertions.assertEquals(">>>\nHello\nWorld", markdown.compute(">>>\nHello\nWorld")); - Assertions.assertEquals(">>>\nHello > World", markdown.compute(">>>\nHello > World")); - Assertions.assertEquals("Hello\n > World", markdown.compute("Hello\n > World")); - } -} - -class EscapeMarkdownTest -{ - private MarkdownSanitizer markdown; - - @BeforeEach - public void setup() - { - markdown = new MarkdownSanitizer().withStrategy(MarkdownSanitizer.SanitizationStrategy.ESCAPE); - } - - @Test - public void testComplex() - { - Assertions.assertEquals("\\*\\*A\\_B\\||C\\~~D\\_\\_E\\`F\\`\\_\\_\\~~\\||\\_\\*\\*", markdown.compute("**A_B||C~~D__E`F`__~~||_**")); - } - - @Test - public void testBold() - { - Assertions.assertEquals("\\*\\*Hello\\*\\*", markdown.compute("**Hello**")); - Assertions.assertEquals("**Hello", markdown.compute("**Hello")); - Assertions.assertEquals("\\**Hello**", markdown.compute("\\**Hello**")); - } - - @Test - public void testItalics() - { - Assertions.assertEquals("\\*Hello\\*", markdown.compute("*Hello*")); - Assertions.assertEquals("\\_Hello\\_", markdown.compute("_Hello_")); - - Assertions.assertEquals("*Hello", markdown.compute("*Hello")); - Assertions.assertEquals("_Hello", markdown.compute("_Hello")); - - Assertions.assertEquals("\\*Hello*", markdown.compute("\\*Hello*")); - Assertions.assertEquals("\\_Hello_", markdown.compute("\\_Hello_")); - } - - @Test - public void testBoldItalics() - { - Assertions.assertEquals("\\*\\*\\*Hello\\*\\*\\*", markdown.compute("***Hello***")); - Assertions.assertEquals("***Hello", markdown.compute("***Hello")); - Assertions.assertEquals("\\***Hello***", markdown.compute("\\***Hello***")); - } - - @Test - public void testUnderline() - { - Assertions.assertEquals("\\_\\_Hello\\_\\_", markdown.compute("__Hello__")); - Assertions.assertEquals("__Hello", markdown.compute("__Hello")); - Assertions.assertEquals("\\__Hello__", markdown.compute("\\__Hello__")); - } - - @Test - public void testStrike() - { - Assertions.assertEquals("\\~~Hello\\~~", markdown.compute("~~Hello~~")); - Assertions.assertEquals("~~Hello", markdown.compute("~~Hello")); - Assertions.assertEquals("\\~~Hello~~", markdown.compute("\\~~Hello~~")); - } - - @Test - public void testSpoiler() - { - Assertions.assertEquals("\\||Hello\\||", markdown.compute("||Hello||")); - Assertions.assertEquals("||Hello", markdown.compute("||Hello")); - Assertions.assertEquals("\\||Hello||", markdown.compute("\\||Hello||")); - } - - @Test - public void testMono() - { - Assertions.assertEquals("\\`Hello\\`", markdown.compute("`Hello`")); - Assertions.assertEquals("`Hello", markdown.compute("`Hello")); - Assertions.assertEquals("\\`Hello`", markdown.compute("\\`Hello`")); - - Assertions.assertEquals("\\`Hello **World**\\`", markdown.compute("`Hello **World**`")); - Assertions.assertEquals("`Hello \\*\\*World\\*\\*", markdown.compute("`Hello **World**")); - Assertions.assertEquals("\\`Hello \\*\\*World\\*\\*`", markdown.compute("\\`Hello **World**`")); - - } - - @Test - public void testMonoTwo() - { - Assertions.assertEquals("\\``Hello\\``", markdown.compute("``Hello``")); - Assertions.assertEquals("``Hello", markdown.compute("``Hello")); - Assertions.assertEquals("\\``Hello``", markdown.compute("\\``Hello``")); - - Assertions.assertEquals("\\``Hello **World**\\``", markdown.compute("``Hello **World**``")); - Assertions.assertEquals("``Hello \\*\\*World\\*\\*", markdown.compute("``Hello **World**")); - Assertions.assertEquals("\\``Hello \\*\\*World\\*\\*``", markdown.compute("\\``Hello **World**``")); - - Assertions.assertEquals("\\``Hello `to` World\\``", markdown.compute("``Hello `to` World``")); - Assertions.assertEquals("``Hello \\`to\\` World", markdown.compute("``Hello `to` World")); - Assertions.assertEquals("\\``Hello \\`to\\` World", markdown.compute("\\``Hello `to` World")); - } - - @Test - public void testBlock() - { - Assertions.assertEquals("\\```Hello\\```", markdown.compute("```Hello```")); - Assertions.assertEquals("```Hello", markdown.compute("```Hello")); - Assertions.assertEquals("\\```Hello", markdown.compute("\\```Hello")); - - Assertions.assertEquals("\\```Hello **World**\\```", markdown.compute("```Hello **World**```")); - Assertions.assertEquals("```Hello \\*\\*World\\*\\*", markdown.compute("```Hello **World**")); - Assertions.assertEquals("\\```Hello \\*\\*World\\*\\*", markdown.compute("\\```Hello **World**")); - - Assertions.assertEquals("\\```Hello `to` World\\```", markdown.compute("```Hello `to` World```")); - Assertions.assertEquals("```Hello \\`to\\` World", markdown.compute("```Hello `to` World")); - Assertions.assertEquals("\\```Hello \\`to\\` World", markdown.compute("\\```Hello `to` World")); - - Assertions.assertEquals("\\```java\nTest\\```", markdown.compute("```java\nTest```")); - } - - @Test - public void testQuote() - { - Assertions.assertEquals("\\> Hello > World", markdown.compute("> Hello > World")); - Assertions.assertEquals("\\> Hello\n\\> World", markdown.compute("> Hello\n> World")); - Assertions.assertEquals("\\>>> Hello\nWorld", markdown.compute(">>> Hello\nWorld")); - Assertions.assertEquals("\\>>>\nHello\nWorld", markdown.compute(">>>\nHello\nWorld")); - Assertions.assertEquals("\\>>>\nHello > World", markdown.compute(">>>\nHello > World")); - Assertions.assertEquals("\\> \\_Hello \n\\> World\\_", markdown.compute("> _Hello \n> World_")); - Assertions.assertEquals("Hello\n \\> World", markdown.compute("Hello\n > World")); - } -} - -class EscapeMarkdownAllTest -{ - @Test - public void testAsterisk() - { - Assertions.assertEquals("Hello\\*World", MarkdownSanitizer.escape("Hello*World", true)); - Assertions.assertEquals("Hello\\*\\*World", MarkdownSanitizer.escape("Hello**World", true)); - Assertions.assertEquals("Hello\\*\\*\\*World", MarkdownSanitizer.escape("Hello***World", true)); - - Assertions.assertEquals("Hello\\*World", MarkdownSanitizer.escape("Hello\\*World", true)); - Assertions.assertEquals("Hello\\*\\*World", MarkdownSanitizer.escape("Hello\\*\\*World", true)); - Assertions.assertEquals("Hello\\*\\*\\*World", MarkdownSanitizer.escape("Hello\\*\\*\\*World", true)); - } - - @Test - public void testUnderscore() - { - Assertions.assertEquals("Hello\\_World", MarkdownSanitizer.escape("Hello_World", true)); - Assertions.assertEquals("Hello\\_\\_World", MarkdownSanitizer.escape("Hello__World", true)); - Assertions.assertEquals("Hello\\_\\_\\_World", MarkdownSanitizer.escape("Hello___World", true)); - - Assertions.assertEquals("Hello\\_World", MarkdownSanitizer.escape("Hello\\_World", true)); - Assertions.assertEquals("Hello\\_\\_World", MarkdownSanitizer.escape("Hello\\_\\_World", true)); - Assertions.assertEquals("Hello\\_\\_\\_World", MarkdownSanitizer.escape("Hello\\_\\_\\_World", true)); - } - - @Test - public void testCodeBlock() - { - Assertions.assertEquals("Hello\\`World", MarkdownSanitizer.escape("Hello`World", true)); - Assertions.assertEquals("Hello\\`\\`World", MarkdownSanitizer.escape("Hello``World", true)); - Assertions.assertEquals("Hello\\`\\`\\`World", MarkdownSanitizer.escape("Hello```World", true)); - - Assertions.assertEquals("Hello\\`World", MarkdownSanitizer.escape("Hello\\`World", true)); - Assertions.assertEquals("Hello\\`\\`World", MarkdownSanitizer.escape("Hello\\`\\`World", true)); - Assertions.assertEquals("Hello\\`\\`\\`World", MarkdownSanitizer.escape("Hello\\`\\`\\`World", true)); - } - - @Test - public void testSpoiler() - { - Assertions.assertEquals("Hello\\|\\|World", MarkdownSanitizer.escape("Hello||World", true)); - Assertions.assertEquals("Hello|World", MarkdownSanitizer.escape("Hello|World", true)); - - Assertions.assertEquals("Hello\\|\\|World", MarkdownSanitizer.escape("Hello\\|\\|World", true)); - Assertions.assertEquals("Hello\\|World", MarkdownSanitizer.escape("Hello\\|World", true)); - } - - @Test - public void testStrike() - { - Assertions.assertEquals("Hello\\~\\~World", MarkdownSanitizer.escape("Hello~~World", true)); - Assertions.assertEquals("Hello\\~\\~World", MarkdownSanitizer.escape("Hello\\~\\~World", true)); - } - - @Test - public void testQuote() - { - Assertions.assertEquals("\\> Hello World", MarkdownSanitizer.escape("> Hello World", true)); - Assertions.assertEquals(">Hello World", MarkdownSanitizer.escape(">Hello World", true)); - Assertions.assertEquals("\\>\\>\\> Hello World", MarkdownSanitizer.escape(">>> Hello World", true)); - Assertions.assertEquals(">>>Hello World", MarkdownSanitizer.escape(">>>Hello World", true)); - Assertions.assertEquals("\\>\\>\\> Hello > World\n\\> Hello >>> World\n<@12345> > Hello\n \\> Hello world", MarkdownSanitizer.escape(">>> Hello > World\n> Hello >>> World\n<@12345> > Hello\n > Hello world", true)); - - Assertions.assertEquals("\\> Hello World", MarkdownSanitizer.escape("\\> Hello World", true)); - Assertions.assertEquals("\\>\\>\\> Hello World", MarkdownSanitizer.escape("\\>\\>\\> Hello World", true)); - Assertions.assertEquals("Hello > World", MarkdownSanitizer.escape("Hello > World")); - Assertions.assertEquals("Hello\n \\> World", MarkdownSanitizer.escape("Hello\n > World")); - Assertions.assertEquals("Hello\n\\> World", MarkdownSanitizer.escape("Hello\n> World")); - } -} diff --git a/src/test/java/MarkdownUtilTest.java b/src/test/java/MarkdownUtilTest.java deleted file mode 100644 index 2501e4f2bb..0000000000 --- a/src/test/java/MarkdownUtilTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static net.dv8tion.jda.api.utils.MarkdownUtil.*; - -public class MarkdownUtilTest -{ - @Test - public void testBold() - { - Assertions.assertEquals("**Hello World**", bold("Hello World")); - Assertions.assertEquals("**Hello \\*\\*Test\\*\\* World**", bold("Hello **Test** World")); - Assertions.assertEquals("**Hello *Test* World**", bold("Hello *Test* World")); - } - - @Test - public void testItalics() - { - Assertions.assertEquals("_Hello World_", italics("Hello World")); - Assertions.assertEquals("_Hello \\_Test\\_ World_", italics("Hello _Test_ World")); - Assertions.assertEquals("_Hello __Test__ World_", italics("Hello __Test__ World")); - } - - @Test - public void testUnderline() - { - Assertions.assertEquals("__Hello World__", underline("Hello World")); - Assertions.assertEquals("__Hello \\_\\_Test\\_\\_ World__", underline("Hello __Test__ World")); - Assertions.assertEquals("__Hello _Test_ World__", underline("Hello _Test_ World")); - } - - @Test - public void testMonospace() - { - Assertions.assertEquals("`Hello World`", monospace("Hello World")); - Assertions.assertEquals("`Hello \\`Test\\` World`", monospace("Hello `Test` World")); - Assertions.assertEquals("`Hello ``Test`` World`", monospace("Hello ``Test`` World")); - } - - @Test - public void testCodeblock() - { - Assertions.assertEquals("```java\nHello World```", codeblock("java", "Hello World")); - Assertions.assertEquals("```java\nHello \\```java\nTest\\``` World```", codeblock("java", "Hello ```java\nTest``` World")); - Assertions.assertEquals("```java\nHello `Test` World```", codeblock("java", "Hello `Test` World")); - - Assertions.assertEquals("```Hello World```", codeblock("Hello World")); - Assertions.assertEquals("```Hello \\```java\nTest\\``` World```", codeblock("Hello ```java\nTest``` World")); - Assertions.assertEquals("```Hello `Test` World```", codeblock("Hello `Test` World")); - } - - @Test - public void testSpoiler() - { - Assertions.assertEquals("||Hello World||", spoiler("Hello World")); - Assertions.assertEquals("||Hello \\||Test\\|| World||", spoiler("Hello ||Test|| World")); - Assertions.assertEquals("||Hello |Test| World||", spoiler("Hello |Test| World")); - } - - @Test - public void testStrike() - { - Assertions.assertEquals("~~Hello World~~", strike("Hello World")); - Assertions.assertEquals("~~Hello \\~~Test\\~~ World~~", strike("Hello ~~Test~~ World")); - Assertions.assertEquals("~~Hello ~Test~ World~~", strike("Hello ~Test~ World")); - } - - @Test - public void testQuote() - { - Assertions.assertEquals("> Hello World", quote("Hello World")); - Assertions.assertEquals("> Hello \n> \\> Test World", quote("Hello \n> Test World")); - Assertions.assertEquals("> Hello > Test World", quote("Hello > Test World")); - } - - @Test - public void testQuoteBlock() - { - Assertions.assertEquals(">>> Hello World", quoteBlock("Hello World")); - Assertions.assertEquals(">>> Hello \n>>> Test World", quoteBlock("Hello \n>>> Test World")); - } - - @Test - public void testMaskedLink() - { - Assertions.assertEquals("[Hello](World)", maskedLink("Hello", "World")); - Assertions.assertEquals("[Hello](World%29)", maskedLink("Hello", "World)")); - Assertions.assertEquals("[Hello\\]](World%29)", maskedLink("Hello]", "World)")); - } -} diff --git a/src/test/java/net/dv8tion/jda/entities/MessageSerializationTest.java b/src/test/java/net/dv8tion/jda/entities/MessageSerializationTest.java deleted file mode 100644 index d605fe5fa5..0000000000 --- a/src/test/java/net/dv8tion/jda/entities/MessageSerializationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.dv8tion.jda.entities; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.EmbedType; -import net.dv8tion.jda.api.entities.MessageEmbed; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class MessageSerializationTest -{ - @Test - void testEmbedSerialization() - { - EmbedBuilder builder = new EmbedBuilder(); - builder.setDescription("Description Text"); - builder.setTitle("Title Text", "https://example.com/title"); - builder.setAuthor("Author Text", "https://example.com/author", "https://example.com/author_icon"); - builder.setFooter("Footer Text", "https://example.com/footer_icon"); - builder.setImage("https://example.com/image"); - builder.setThumbnail("https://example.com/thumbnail"); - builder.addField("Field 1", "Field 1 Text", true); - builder.addField("Field 2", "Field 2 Text", false); - builder.addField("Field 3", "Field 3 Text", true); - - MessageEmbed embed = builder.build(); - - MessageEmbed dataEmbed = EmbedBuilder.fromData(embed.toData()).build(); - - Assertions.assertEquals(embed.getType(), dataEmbed.getType()); - Assertions.assertEquals(EmbedType.RICH, embed.getType()); - - Assertions.assertEquals(embed.getDescription(), dataEmbed.getDescription()); - Assertions.assertEquals(embed.getTitle(), dataEmbed.getTitle()); - Assertions.assertEquals(embed.getUrl(), dataEmbed.getUrl()); - Assertions.assertEquals(embed.getAuthor(), dataEmbed.getAuthor()); - Assertions.assertEquals(embed.getFooter(), dataEmbed.getFooter()); - Assertions.assertEquals(embed.getImage(), dataEmbed.getImage()); - Assertions.assertEquals(embed.getThumbnail(), dataEmbed.getThumbnail()); - Assertions.assertEquals(embed.getFields(), dataEmbed.getFields()); - - Assertions.assertEquals(embed, dataEmbed); - - Assertions.assertEquals("Description Text", dataEmbed.getDescription()); - Assertions.assertEquals("Title Text", dataEmbed.getTitle()); - Assertions.assertEquals("https://example.com/title", dataEmbed.getUrl()); - Assertions.assertEquals("Author Text", dataEmbed.getAuthor().getName()); - Assertions.assertEquals("https://example.com/author", dataEmbed.getAuthor().getUrl()); - Assertions.assertEquals("https://example.com/author_icon", dataEmbed.getAuthor().getIconUrl()); - Assertions.assertEquals("Footer Text", dataEmbed.getFooter().getText()); - Assertions.assertEquals("https://example.com/footer_icon", dataEmbed.getFooter().getIconUrl()); - Assertions.assertEquals("https://example.com/image", dataEmbed.getImage().getUrl()); - Assertions.assertEquals("https://example.com/thumbnail", dataEmbed.getThumbnail().getUrl()); - Assertions.assertEquals(3, dataEmbed.getFields().size()); - Assertions.assertEquals("Field 1", dataEmbed.getFields().get(0).getName()); - Assertions.assertEquals("Field 1 Text", dataEmbed.getFields().get(0).getValue()); - Assertions.assertTrue(dataEmbed.getFields().get(0).isInline()); - Assertions.assertEquals("Field 2", dataEmbed.getFields().get(1).getName()); - Assertions.assertEquals("Field 2 Text", dataEmbed.getFields().get(1).getValue()); - Assertions.assertFalse(dataEmbed.getFields().get(1).isInline()); - Assertions.assertEquals("Field 3", dataEmbed.getFields().get(2).getName()); - Assertions.assertEquals("Field 3 Text", dataEmbed.getFields().get(2).getValue()); - Assertions.assertTrue(dataEmbed.getFields().get(2).isInline()); - } -} diff --git a/src/test/java/net/dv8tion/jda/entitystring/EntityStringTest.java b/src/test/java/net/dv8tion/jda/entitystring/EntityStringTest.java deleted file mode 100644 index 2ac411cda1..0000000000 --- a/src/test/java/net/dv8tion/jda/entitystring/EntityStringTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.dv8tion.jda.entitystring; - -import net.dv8tion.jda.api.entities.channel.ChannelType; -import net.dv8tion.jda.internal.utils.EntityString; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class EntityStringTest -{ - @Test - @Order(1) - public void testSimple() - { - assertEquals("AnEntity", new EntityString(new AnEntity()).toString()); - assertEquals("AnEntity:AName", new EntityString(new AnEntity()).setName("AName").toString()); - } - - @Test - @Order(2) - public void testClassNameAsString() - { - assertEquals("NotAnEntity", new EntityString("NotAnEntity").toString()); - assertEquals("NotAnEntity:AName", new EntityString("NotAnEntity").setName("AName").toString()); - } - - @Test - @Order(3) - public void testType() - { - assertEquals("AnEntity[AType]", new EntityString(new AnEntity()).setType("AType").toString()); - assertEquals("AnEntity[AType]:AName", new EntityString(new AnEntity()).setType("AType").setName("AName").toString()); - assertEquals("AnEntity[NEWS]:AName", new EntityString(new AnEntity()).setType(ChannelType.NEWS).setName("AName").toString()); - } - - @Test - @Order(4) - public void testMetadata() - { - assertEquals("AnEntity(Metadata1)", new EntityString(new AnEntity()).addMetadata(null, "Metadata1").toString()); - assertEquals("AnEntity(MetaKey=Metadata1)", new EntityString(new AnEntity()).addMetadata("MetaKey", "Metadata1").toString()); - assertEquals("AnEntity(MetaKey=42)", new EntityString(new AnEntity()).addMetadata("MetaKey", 42).toString()); - assertEquals("AnEntity(MetaKey1=Metadata1, MetaKey2=Metadata2)", new EntityString(new AnEntity()) - .addMetadata("MetaKey1", "Metadata1") - .addMetadata("MetaKey2", "Metadata2") - .toString()); - } - - @Test - @Order(5) - public void testAll() - { - assertEquals("AnEntity:AName(Metadata1)", new EntityString(new AnEntity()) - .setName("AName") - .addMetadata(null, "Metadata1") - .toString()); - assertEquals("AnEntity:AName(MetaKey=Metadata1)", new EntityString(new AnEntity()) - .setName("AName") - .addMetadata("MetaKey", "Metadata1") - .toString()); - assertEquals("AnEntity:AName(MetaKey=42)", new EntityString(new AnEntity()) - .setName("AName") - .addMetadata("MetaKey", 42) - .toString()); - assertEquals("AnEntity:AName(MetaKey1=Metadata1, MetaKey2=Metadata2)", new EntityString(new AnEntity()) - .setName("AName") - .addMetadata("MetaKey1", "Metadata1") - .addMetadata("MetaKey2", "Metadata2") - .toString()); - - assertEquals("AnEntity[Type]:AName(Metadata1)", new EntityString(new AnEntity()) - .setName("AName") - .setType("Type") - .addMetadata(null, "Metadata1") - .toString()); - assertEquals("AnEntity[Type]:AName(MetaKey=Metadata1)", new EntityString(new AnEntity()) - .setName("AName") - .setType("Type") - .addMetadata("MetaKey", "Metadata1") - .toString()); - assertEquals("AnEntity[Type]:AName(MetaKey=42)", new EntityString(new AnEntity()) - .setName("AName") - .setType("Type") - .addMetadata("MetaKey", 42) - .toString()); - assertEquals("AnEntity[Type]:AName(MetaKey1=Metadata1, MetaKey2=Metadata2)", new EntityString(new AnEntity()) - .setName("AName") - .setType("Type") - .addMetadata("MetaKey1", "Metadata1") - .addMetadata("MetaKey2", "Metadata2") - .toString()); - } - - @Test - @Order(6) - public void testSimpleSnowflake() - { - assertEquals("ASnowflake(id=42)", new EntityString(new ASnowflake()).toString()); - assertEquals("ASnowflake:AName(id=42)", new EntityString(new ASnowflake()).setName("AName").toString()); - } - - @Test - @Order(7) - public void testTypeSnowflake() - { - assertEquals("ASnowflake[AType](id=42)", new EntityString(new ASnowflake()).setType("AType").toString()); - assertEquals("ASnowflake[AType]:AName(id=42)", new EntityString(new ASnowflake()).setType("AType").setName("AName").toString()); - assertEquals("ASnowflake[NEWS]:AName(id=42)", new EntityString(new ASnowflake()).setType(ChannelType.NEWS).setName("AName").toString()); - } - - @Test - @Order(8) - public void testMetadataSnowflake() - { - assertEquals("ASnowflake(id=42, Metadata1)", new EntityString(new ASnowflake()).addMetadata(null, "Metadata1").toString()); - assertEquals("ASnowflake(id=42, MetaKey=Metadata1)", new EntityString(new ASnowflake()).addMetadata("MetaKey", "Metadata1").toString()); - assertEquals("ASnowflake(id=42, MetaKey=42)", new EntityString(new ASnowflake()).addMetadata("MetaKey", 42).toString()); - assertEquals("ASnowflake(id=42, MetaKey1=Metadata1, MetaKey2=Metadata2)", new EntityString(new ASnowflake()) - .addMetadata("MetaKey1", "Metadata1") - .addMetadata("MetaKey2", "Metadata2") - .toString()); - } - - @Test - @Order(9) - public void testAllSnowflake() - { - assertEquals("ASnowflake:AName(id=42, Metadata1)", new EntityString(new ASnowflake()) - .setName("AName") - .addMetadata(null, "Metadata1") - .toString()); - assertEquals("ASnowflake:AName(id=42, MetaKey=Metadata1)", new EntityString(new ASnowflake()) - .setName("AName") - .addMetadata("MetaKey", "Metadata1") - .toString()); - assertEquals("ASnowflake:AName(id=42, MetaKey=42)", new EntityString(new ASnowflake()) - .setName("AName") - .addMetadata("MetaKey", 42) - .toString()); - assertEquals("ASnowflake:AName(id=42, MetaKey1=Metadata1, MetaKey2=Metadata2)", new EntityString(new ASnowflake()) - .setName("AName") - .addMetadata("MetaKey1", "Metadata1") - .addMetadata("MetaKey2", "Metadata2") - .toString()); - - assertEquals("ASnowflake[Type]:AName(id=42, Metadata1)", new EntityString(new ASnowflake()) - .setName("AName") - .setType("Type") - .addMetadata(null, "Metadata1") - .toString()); - assertEquals("ASnowflake[Type]:AName(id=42, MetaKey=Metadata1)", new EntityString(new ASnowflake()) - .setName("AName") - .setType("Type") - .addMetadata("MetaKey", "Metadata1") - .toString()); - assertEquals("ASnowflake[Type]:AName(id=42, MetaKey=42)", new EntityString(new ASnowflake()) - .setName("AName") - .setType("Type") - .addMetadata("MetaKey", 42) - .toString()); - assertEquals("ASnowflake[Type]:AName(id=42, MetaKey1=Metadata1, MetaKey2=Metadata2)", new EntityString(new ASnowflake()) - .setName("AName") - .setType("Type") - .addMetadata("MetaKey1", "Metadata1") - .addMetadata("MetaKey2", "Metadata2") - .toString()); - } -} diff --git a/src/test/java/net/dv8tion/jda/test/IntegrationTest.java b/src/test/java/net/dv8tion/jda/test/IntegrationTest.java new file mode 100644 index 0000000000..6138ebfd4d --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/IntegrationTest.java @@ -0,0 +1,82 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test; + +import net.dv8tion.jda.api.requests.Method; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.internal.JDAImpl; +import net.dv8tion.jda.internal.requests.Requester; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.Mock; + +import javax.annotation.Nonnull; +import java.util.concurrent.ScheduledExecutorService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.assertArg; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.openMocks; + +public class IntegrationTest +{ + @Mock + protected JDAImpl jda; + @Mock + protected Requester requester; + @Mock + protected ScheduledExecutorService scheduledExecutorService; + + private AutoCloseable closeable; + + @BeforeEach + protected final void setup() + { + closeable = openMocks(this); + when(jda.getRequester()).thenReturn(requester); + } + + @AfterEach + protected final void teardown() throws Exception + { + closeable.close(); + } + + @Nonnull + protected DataObject normalizeRequestBody(@Nonnull DataObject body) + { + return body; + } + + protected void assertNextRequestEquals(Method method, String compiledRoute, DataObject expectedBody) + { + doNothing().when(requester).request(assertArg(request -> { + assertThat(request.getRoute().getMethod()).isEqualTo(method); + assertThat(request.getRoute().getCompiledRoute()).isEqualTo(compiledRoute); + + assertThat(request.getRawBody()) + .isNotNull() + .isInstanceOf(DataObject.class); + DataObject body = normalizeRequestBody((DataObject) request.getRawBody()); + + assertThat(body) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(expectedBody); + })); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/PrettyRepresentation.java b/src/test/java/net/dv8tion/jda/test/PrettyRepresentation.java new file mode 100644 index 0000000000..5080ac4815 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/PrettyRepresentation.java @@ -0,0 +1,34 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test; + +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import org.assertj.core.presentation.StandardRepresentation; + +public class PrettyRepresentation extends StandardRepresentation +{ + @Override + protected String fallbackToStringOf(Object object) + { + if (object instanceof DataObject) + return ((DataObject) object).toPrettyString(); + else if (object instanceof DataArray) + return ((DataArray) object).toPrettyString(); + return object.toString(); + } +} diff --git a/src/test/java/net/dv8tion/jda/ChannelConsistencyTest.java b/src/test/java/net/dv8tion/jda/test/compliance/ChannelConsistencyComplianceTest.java similarity index 72% rename from src/test/java/net/dv8tion/jda/ChannelConsistencyTest.java rename to src/test/java/net/dv8tion/jda/test/compliance/ChannelConsistencyComplianceTest.java index dac29156fa..f2bab54427 100644 --- a/src/test/java/net/dv8tion/jda/ChannelConsistencyTest.java +++ b/src/test/java/net/dv8tion/jda/test/compliance/ChannelConsistencyComplianceTest.java @@ -14,13 +14,12 @@ * limitations under the License. */ -package net.dv8tion.jda; +package net.dv8tion.jda.test.compliance; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.entities.channel.attribute.IGuildChannelContainer; import net.dv8tion.jda.api.entities.channel.concrete.Category; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; @@ -30,7 +29,10 @@ import java.util.Set; import java.util.stream.Collectors; -public class ChannelConsistencyTest +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +public class ChannelConsistencyComplianceTest { private static Set getMethodNames(Class clazz) { @@ -39,11 +41,11 @@ private static Set getMethodNames(Class clazz) private static String getChannelName(ChannelType type) { - return type.name().substring(0, 1) + type.name().substring(1).toLowerCase(Locale.ROOT); + return type.name().charAt(0) + type.name().substring(1).toLowerCase(Locale.ROOT); } @Test - public void checkCreateChannelMethods() + void checkCreateChannelMethods() { Set guildMethods = getMethodNames(Guild.class); @@ -57,7 +59,7 @@ public void checkCreateChannelMethods() { String channelName = getChannelName(type); String methodName = "create" + channelName + "Channel"; - Assertions.assertTrue(guildMethods.contains(methodName), "Missing method Guild#" + methodName); + assertThat(guildMethods).contains(methodName); } Set categoryMethods = getMethodNames(Category.class); @@ -66,12 +68,12 @@ public void checkCreateChannelMethods() { String channelName = getChannelName(type); String methodName = "create" + channelName + "Channel"; - Assertions.assertTrue(categoryMethods.contains(methodName), "Missing method Category#" + methodName); + assertThat(categoryMethods).contains(methodName); } } @Test - public void checkCacheAccessMethods() + void checkCacheAccessMethods() { Set jdaMethods = getMethodNames(IGuildChannelContainer.class); Set categoryMethods = getMethodNames(Category.class); @@ -87,22 +89,22 @@ public void checkCacheAccessMethods() String channelName = getChannelName(type); String methodName = "get" + channelName + "ChannelCache"; - Assertions.assertTrue(jdaMethods.contains(methodName), "Missing method IGuildChannelContainer#" + methodName); + assertThat(jdaMethods).contains(methodName); methodName = "get" + channelName + "ChannelsByName"; - Assertions.assertTrue(jdaMethods.contains(methodName), "Missing method IGuildChannelContainer#" + methodName); + assertThat(jdaMethods).contains(methodName); methodName = "get" + channelName + "ChannelById"; - Assertions.assertTrue(jdaMethods.contains(methodName), "Missing method IGuildChannelContainer#" + methodName); + assertThat(jdaMethods).contains(methodName); methodName = "get" + channelName + "Channels"; - Assertions.assertTrue(jdaMethods.contains(methodName), "Missing method IGuildChannelContainer#" + methodName); - Assertions.assertTrue(categoryMethods.contains(methodName), "Missing method Category#" + methodName); + assertThat(jdaMethods).contains(methodName); + assertThat(categoryMethods).contains(methodName); } } @Test - public void checkManagerExists() + void checkManagerExists() { EnumSet editable = EnumSet.complementOf(EnumSet.of( ChannelType.PRIVATE, ChannelType.GROUP, ChannelType.CATEGORY, @@ -114,9 +116,9 @@ public void checkManagerExists() { String channelName = getChannelName(type); - Assertions.assertDoesNotThrow(() -> { - Class.forName("net.dv8tion.jda.api.managers.channel.concrete." + channelName + "ChannelManager"); - }, "Missing manager interface for ChannelType." + type); + assertThatCode(() -> + Class.forName("net.dv8tion.jda.api.managers.channel.concrete." + channelName + "ChannelManager") + ).as("Missing manager interface for ChannelType." + type).doesNotThrowAnyException(); } } } diff --git a/src/test/java/net/dv8tion/jda/EventConsistencyTest.java b/src/test/java/net/dv8tion/jda/test/compliance/EventConsistencyComplianceTest.java similarity index 80% rename from src/test/java/net/dv8tion/jda/EventConsistencyTest.java rename to src/test/java/net/dv8tion/jda/test/compliance/EventConsistencyComplianceTest.java index 73831791de..8b246c19b7 100644 --- a/src/test/java/net/dv8tion/jda/EventConsistencyTest.java +++ b/src/test/java/net/dv8tion/jda/test/compliance/EventConsistencyComplianceTest.java @@ -14,14 +14,13 @@ * limitations under the License. */ -package net.dv8tion.jda; +package net.dv8tion.jda.test.compliance; import net.dv8tion.jda.api.events.Event; import net.dv8tion.jda.api.events.GenericEvent; import net.dv8tion.jda.api.events.UpdateEvent; import net.dv8tion.jda.api.events.self.SelfUpdateDiscriminatorEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.reflections.Reflections; @@ -31,7 +30,10 @@ import java.util.HashSet; import java.util.Set; -public class EventConsistencyTest +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +public class EventConsistencyComplianceTest { static Set> eventTypes; static Set> excludedTypes; @@ -61,7 +63,9 @@ void testListenerAdapter() continue; String name = type.getSimpleName(); String methodName = "on" + name.substring(0, name.length() - "Event".length()); - Assertions.assertDoesNotThrow(() -> adapter.getDeclaredMethod(methodName, type), "Method for event " + type + " is missing!"); + assertThatCode(() -> adapter.getDeclaredMethod(methodName, type)) + .as("Method for event " + type + " is missing!") + .doesNotThrowAnyException(); found.add(methodName); } @@ -69,7 +73,9 @@ void testListenerAdapter() { if (!method.isAccessible() || method.getAnnotation(Deprecated.class) != null) continue; - Assertions.assertTrue(found.contains(method.getName()), "Dangling method found in ListenerAdapter " + method.getName()); + assertThat(found.contains(method.getName())) + .as("Dangling method found in ListenerAdapter " + method.getName()) + .isTrue(); } } } diff --git a/src/test/java/net/dv8tion/jda/test/data/DataPathTest.java b/src/test/java/net/dv8tion/jda/test/data/DataPathTest.java new file mode 100644 index 0000000000..39a22b3cc2 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/data/DataPathTest.java @@ -0,0 +1,117 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.data; + +import net.dv8tion.jda.api.exceptions.ParsingException; +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.api.utils.data.DataPath; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.*; + +public class DataPathTest +{ + @Test + void testSimple() + { + DataObject object = DataObject.empty() + .put("foo", "10"); // string to also test parsing + + assertThat(DataPath.getInt(object, "foo")).isEqualTo(10); + + DataArray array = DataArray.empty().add("20"); + assertThat(DataPath.getInt(array, "[0]")).isEqualTo(20); + } + + @Test + void testSimpleMissing() + { + DataObject object = DataObject.empty(); + + assertThat(DataPath.getLong(object, "foo?", 0)).isEqualTo(0L); + assertThatThrownBy(() -> DataPath.getLong(object, "foo")) + .hasMessage("Unable to resolve value with key foo to type long: null") + .isInstanceOf(ParsingException.class); + + DataArray array = DataArray.empty(); + + assertThat(DataPath.getBoolean(array, "[0]?", true)).isTrue(); + assertThatThrownBy(() -> DataPath.getObject(array, "[0]")) + .hasMessage("Could not resolve value of type Object at path \"[0]\"") + .isInstanceOf(ParsingException.class); + } + + @Test + void testObjectInArray() + { + DataObject object = DataObject.empty().put("foo", 10.0); + DataArray array = DataArray.empty().add(object); + + assertThat(DataPath.getDouble(array, "[0].foo")).isEqualTo(10.0); + assertThat(DataPath.getDouble(array, "[1]?.foo", 20.0)).isEqualTo(20.0); + + assertThatIndexOutOfBoundsException() + .isThrownBy(() -> DataPath.getDouble(array, "[1].foo")); + } + + @Test + void testArrayInObject() + { + DataArray array = DataArray.empty().add("hello"); + DataObject object = DataObject.empty().put("foo", array); + + assertThat(DataPath.getString(object, "foo[0]")).isEqualTo("hello"); + assertThat(DataPath.getString(object, "foo[1]?", "world")).isEqualTo("world"); + assertThatIndexOutOfBoundsException() + .isThrownBy(() -> DataPath.getString(object, "foo[1]")); + } + + @Test + void testArrayInArray() + { + DataArray array = DataArray.empty().add(DataArray.empty().add("10")); + + assertThat(DataPath.getUnsignedInt(array, "[0][0]")).isEqualTo(10); + assertThat(DataPath.getUnsignedInt(array, "[0][1]?", 20)).isEqualTo(20); + assertThat(DataPath.getUnsignedInt(array, "[1]?[0]", 20)).isEqualTo(20); + assertThatIndexOutOfBoundsException().isThrownBy(() -> DataPath.getUnsignedInt(array, "[0][1]")); + assertThatIndexOutOfBoundsException().isThrownBy(() -> DataPath.getUnsignedInt(array, "[1][0]")); + assertThatThrownBy(() -> DataPath.getUnsignedInt(array, "[0][1]?")) + .hasMessage("Could not resolve value of type unsigned int at path \"[0][1]?\"") + .isInstanceOf(ParsingException.class); + assertThatThrownBy(() -> DataPath.getUnsignedInt(array, "[1]?[0]")) + .hasMessage("Could not resolve value of type unsigned int at path \"[1]?[0]\"") + .isInstanceOf(ParsingException.class); + } + + @Test + void testComplex() + { + DataObject object = DataObject.empty() + .put("array", DataArray.empty() + .add(DataObject.empty() + .put("foo", DataObject.empty() + .put("bar", "hello")))); + + assertThat(DataPath.getString(object, "array[0].foo.bar")).isEqualTo("hello"); + assertThat(DataPath.getString(object, "array[0].wrong?.bar", "world")).isEqualTo("world"); + assertThatThrownBy(() -> DataPath.getString(object, "array[0].wrong?.bar")) + .hasMessage("Could not resolve value of type String at path \"array[0].wrong?.bar\"") + .isInstanceOf(ParsingException.class); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/data/JsonTest.java b/src/test/java/net/dv8tion/jda/test/data/JsonTest.java new file mode 100644 index 0000000000..581e4be5d6 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/data/JsonTest.java @@ -0,0 +1,353 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.data; + +import net.dv8tion.jda.api.exceptions.ParsingException; +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.internal.utils.Helpers; +import net.dv8tion.jda.test.PrettyRepresentation; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class JsonTest +{ + private static final String TEST_TIME_STRING = "2024-01-01T12:34:56.789Z"; + private static final OffsetDateTime TEST_TIME = OffsetDateTime.parse(TEST_TIME_STRING); + private static final String testJson = jsonOf( + kv("int", 10), + kv("long", 100), + kv("boolean", true), + kv("string", "test"), + kv("double", 4.2), + kv("time", TEST_TIME_STRING) + ); + private static final String testJsonArray = Stream + .of(10, 100L, true, "\"test\"", 4.2, 5.2f) + .map(String::valueOf) + .collect(Collectors.joining(",\n", "[", "]")); + + private static final byte[] simpleEtfArray = {-125, 108, 0, 0, 0, 6, 97, 10, 97, 100, 100, 0, 4, 116, 114, 117, 101, 109, 0, 0, 0, 4, 116, 101, 115, 116, 70, 64, 16, -52, -52, -52, -52, -52, -51, 70, 64, 20, -52, -52, -52, -52, -52, -51, 106}; + private static final byte[] complexEtfArray = {-125, 108, 0, 0, 0, 6, 109, 0, 0, 0, 3, 111, 110, 101, 97, 2, 70, 64, 11, -103, -103, -103, -103, -103, -102, 97, 7, 116, 0, 0, 0, 2, 109, 0, 0, 0, 5, 102, 105, 114, 115, 116, 109, 0, 0, 0, 5, 101, 105, 103, 104, 116, 109, 0, 0, 0, 6, 115, 101, 99, 111, 110, 100, 106, 108, 0, 0, 0, 2, 109, 0, 0, 0, 4, 110, 105, 110, 101, 116, 0, 0, 0, 1, 109, 0, 0, 0, 3, 107, 101, 121, 109, 0, 0, 0, 3, 116, 101, 110, 106, 106}; + + @Nested + class DataObjectTest + { + @Test + void testParse() + { + DataObject object = DataObject.fromJson(testJson); + assertThat(object.getInt("int")).isEqualTo(10); + assertThat(object.getLong("long")).isEqualTo(100); + assertThat(object.getDouble("double")).isEqualTo(4.2); + assertThat(object.getBoolean("boolean")).isTrue(); + assertThat(object.getString("string")).isEqualTo("test"); + assertThat(object.getOffsetDateTime("time")).isEqualTo(TEST_TIME); + } + + @Test + void testCoerce() + { + DataObject data = DataObject.empty() + .put("stringified_int", "42") + .put("stringified_boolean", "true") + .put("stringified_long", "86699011792191488") + .put("stringified_datetime", TEST_TIME_STRING) + .put("stringified_double", "123.456"); + + assertThat(data.toMap()).containsOnly( + entry("stringified_int", "42"), + entry("stringified_boolean", "true"), + entry("stringified_long", "86699011792191488"), + entry("stringified_datetime", TEST_TIME_STRING), + entry("stringified_double", "123.456") + ); + + assertThat(data.getInt("stringified_int")).isEqualTo(42); + assertThat(data.getBoolean("stringified_boolean")).isTrue(); + assertThat(data.getLong("stringified_long")).isEqualTo(86699011792191488L); + assertThat(data.getUnsignedLong("stringified_long")).isEqualTo(86699011792191488L); + assertThat(data.getDouble("stringified_double")).isEqualTo(123.456); + assertThat(data.getString("stringified_datetime")).isEqualTo(TEST_TIME_STRING); + } + + @Test + void testFallback() + { + DataObject data = DataObject.fromJson(jsonOf()); + + assertThat(data).isEqualTo(DataObject.empty()); + assertThat(data).hasToString("{}"); + + assertThat(data.isNull("key")).isTrue(); + assertThat(data.hasKey("key")).isFalse(); + + assertThat(data.getDouble("key", 5.3)).isEqualTo(5.3); + assertThat(data.getInt("key", 4)).isEqualTo(4); + assertThat(data.getUnsignedInt("key", 7)).isEqualTo(7); + assertThat(data.getLong("key", 123L)).isEqualTo(123); + assertThat(data.getUnsignedLong("key", 321L)).isEqualTo(321L); + assertThat(data.getBoolean("key")).isFalse(); + assertThat(data.getBoolean("key", true)).isTrue(); + assertThat(data.getOffsetDateTime("key", TEST_TIME)).isEqualTo(TEST_TIME); + assertThat(data.opt("key")).isEmpty(); + assertThat(data.optObject("key")).isEmpty(); + assertThat(data.optArray("key")).isEmpty(); + } + + @Test + void testJsonToString() + { + DataObject object = DataObject.fromJson(testJson); + String result = object.toString(); + DataObject symmetric = DataObject.fromJson(result); + + assertThat(symmetric.toMap()).isNotSameAs(object.toMap()); + assertThat(symmetric.toMap()).isEqualTo(object.toMap()); + assertThat(symmetric.toMap()).hasSize(6); + assertThat(symmetric.toMap()).containsOnly( + entry("int", 10), + entry("long", 100), + entry("boolean", true), + entry("string", "test"), + entry("double", 4.2), + entry("time", TEST_TIME_STRING) + ); + } + + @Test + void testFactories() + { + DataObject reference = DataObject.fromJson(testJson); + + assertThat(DataObject.fromJson(testJson.getBytes(StandardCharsets.UTF_8))) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(reference); + assertThat(DataObject.fromJson(new StringReader(testJson))) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(reference); + assertThat(DataObject.fromJson(new ByteArrayInputStream(testJson.getBytes(StandardCharsets.UTF_8)))) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(reference); + } + } + + @Nested + class DataArrayTest + { + @Test + void testParse() + { + DataArray object = DataArray.fromJson(testJsonArray); + assertThat(object.getInt(0)).isEqualTo(10); + assertThat(object.getLong(1)).isEqualTo(100); + assertThat(object.getBoolean(2)).isTrue(); + assertThat(object.getString(3)).isEqualTo("test"); + assertThat(object.getDouble(4)).isEqualTo(4.2); + assertThat(object.getDouble(5)).isEqualTo(5.2); + } + + @Test + void testCoerce() + { + DataArray array = DataArray.empty() + .add("42") + .add("true") + .add("86699011792191488") + .add(TEST_TIME_STRING) + .add("123.456"); + + assertThat(array.toList()).containsExactly( + "42", "true", "86699011792191488", TEST_TIME_STRING, "123.456" + ); + + assertThat(array.getInt(0)).isEqualTo(42); + assertThat(array.getBoolean(1)).isTrue(); + assertThat(array.getLong(2)).isEqualTo(86699011792191488L); + assertThat(array.getUnsignedLong(2)).isEqualTo(86699011792191488L); + assertThat(array.getString(3)).isEqualTo(TEST_TIME_STRING); + assertThat(array.getDouble(4)).isEqualTo(123.456); + } + + @Test + void testFallback() + { + DataArray data = DataArray.fromJson("[]"); + + assertThat(data).isEqualTo(DataArray.empty()); + assertThat(data).hasToString("[]"); + + assertThat(data.isNull(0)).isTrue(); + assertThat(data.length()).isEqualTo(0); + assertThat(data.isEmpty()).isTrue(); + + assertThat(data.getDouble(0, 5.3)).isEqualTo(5.3); + assertThat(data.getInt(0, 4)).isEqualTo(4); + assertThat(data.getUnsignedInt(0, 7)).isEqualTo(7); + assertThat(data.getLong(0, 123L)).isEqualTo(123); + assertThat(data.getUnsignedLong(0, 321L)).isEqualTo(321L); + assertThat(data.getBoolean(0)).isFalse(); + assertThat(data.getBoolean(0, true)).isTrue(); + assertThat(data.getOffsetDateTime(0, TEST_TIME)).isEqualTo(TEST_TIME); + } + + @Test + void testJsonToString() + { + DataArray object = DataArray.fromJson(testJsonArray); + String result = object.toString(); + DataArray symmetric = DataArray.fromJson(result); + + assertThat(symmetric.toList()).isNotSameAs(object.toList()); + assertThat(symmetric.toList()).isEqualTo(object.toList()); + assertThat(symmetric.toList()).hasSize(6); + assertThat(symmetric.toList()).containsExactly( + 10, 100, true, "test", 4.2, 5.2 + ); + } + + @Test + void testStream() + { + DataArray intArray = IntStream.range(0, 3).boxed().collect(Helpers.toDataArray()); + assertThat(intArray.stream(DataArray::getInt)) + .containsExactly(0, 1, 2); + assertThat(intArray.stream(DataArray::getLong)) + .containsExactly(0L, 1L, 2L); + + DataArray doubleArray = DoubleStream.of(0.1, 0.5, 1.2, 4.2).boxed().collect(Helpers.toDataArray()); + assertThat(doubleArray.stream(DataArray::getDouble)) + .containsExactly(0.1, 0.5, 1.2, 4.2); + + DataArray stringArray = DataArray.empty().add("foo").add("bar"); + assertThat(stringArray.stream(DataArray::getString)) + .containsExactly("foo", "bar"); + + DataArray polyTypedArray = DataArray.empty().add(1).add(2.3).add("four"); + assertThatThrownBy(() -> polyTypedArray.stream(DataArray::getInt).toArray()) + .isInstanceOf(NumberFormatException.class); + assertThatThrownBy(() -> polyTypedArray.stream(DataArray::getDouble).toArray()) + .isInstanceOf(NumberFormatException.class); + assertThatThrownBy(() -> polyTypedArray.stream(DataArray::getObject).toArray()) + .isInstanceOf(ParsingException.class) + .hasMessage("Cannot parse value for index 0 into type Map: 1 instance of Integer"); + assertThat(polyTypedArray.stream(DataArray::getString)) + .containsExactly("1", "2.3", "four"); + + DataArray objectArray = DataArray.empty() + .add(DataObject.empty().put("foo", 1)) + .add(DataObject.empty().put("foo", 2)); + assertThat(objectArray.stream(DataArray::getObject).map(obj -> obj.getInt("foo"))) + .containsExactly(1, 2); + + objectArray.add(DataArray.empty()); + assertThatThrownBy(() -> + objectArray.stream(DataArray::getObject).map(obj -> obj.getInt("foo")).toArray() + ) + .isInstanceOf(ParsingException.class) + .hasMessage("Cannot parse value for index 2 into type Map: [] instance of ArrayList"); + } + + @Test + void testFactories() + { + assertThat(DataArray.fromJson(new StringReader(testJsonArray))) + .withRepresentation(new PrettyRepresentation()) + .containsExactly(10, 100, true, "test", 4.2, 5.2); + assertThat(DataArray.fromJson(new ByteArrayInputStream(testJsonArray.getBytes(StandardCharsets.UTF_8)))) + .withRepresentation(new PrettyRepresentation()) + .containsExactly(10, 100, true, "test", 4.2, 5.2); + assertThat(DataArray.fromJson(testJsonArray)) + .withRepresentation(new PrettyRepresentation()) + .containsExactly(10, 100, true, "test", 4.2, 5.2); + + List inputList = Arrays.asList(10, 100L, true, "test", 4.2, 5.2f); + DataArray array = DataArray.fromCollection(inputList); + assertThat(array) + .withRepresentation(new PrettyRepresentation()) + .as("Do not lose types from input collections") + .containsExactly(10, 100L, true, "test", 4.2, 5.2f); + assertThat(array.toList()).isNotSameAs(inputList); + assertThat(array.toList()).isEqualTo(inputList); + assertThat(array.add("foo").toList()).isNotEqualTo(inputList); + + assertThat(DataArray.fromETF(simpleEtfArray)) + .withRepresentation(new PrettyRepresentation()) + .containsExactly(10, 100, true, "test", 4.2, 5.2); + assertThat(DataArray.fromETF(simpleEtfArray).toETF()) + .isEqualTo(simpleEtfArray); + } + + @Test + void testExTerm() + { + DataArray array = DataArray.empty() + .add("one") + .add(2) + .add(3.45) + .add(7L) + .add(DataObject.empty() + .put("first", "eight") + .put("second", DataArray.empty())) + .add(DataArray.empty() + .add("nine") + .add(DataObject.empty() + .put("key", "ten"))); + + assertThat(array).hasSize(6); + assertThat(array.toETF()).isEqualTo(complexEtfArray); + assertThat(DataArray.fromETF(complexEtfArray).toETF()) + .isEqualTo(complexEtfArray); + assertThat(DataArray.fromETF(complexEtfArray).toPrettyString()) + .isEqualToIgnoringWhitespace(array.toPrettyString()); + } + } + + private static Map.Entry entry(K key, V value) + { + return new AbstractMap.SimpleEntry<>(key, value); + } + + private static String kv(String key, Object value) + { + return String.format(Locale.ROOT, "\"%s\": %s", key, value); + } + + private static String kv(String key, String value) + { + return String.format(Locale.ROOT, "\"%s\": \"%s\"", key, value); + } + + private static String jsonOf(String... keyValueMapping) + { + return Stream.of(keyValueMapping) + .collect(Collectors.joining(",\n", "{", "}")); + } +} diff --git a/src/test/java/net/dv8tion/jda/entities/ActivityTest.java b/src/test/java/net/dv8tion/jda/test/entities/ActivityTest.java similarity index 69% rename from src/test/java/net/dv8tion/jda/entities/ActivityTest.java rename to src/test/java/net/dv8tion/jda/test/entities/ActivityTest.java index d6150f9217..96565c900d 100644 --- a/src/test/java/net/dv8tion/jda/entities/ActivityTest.java +++ b/src/test/java/net/dv8tion/jda/test/entities/ActivityTest.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package net.dv8tion.jda.entities; +package net.dv8tion.jda.test.entities; import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.RichPresence; @@ -22,11 +22,12 @@ import net.dv8tion.jda.api.utils.data.DataObject; import net.dv8tion.jda.internal.entities.EntityBuilder; import net.dv8tion.jda.internal.managers.PresenceImpl; +import net.dv8tion.jda.test.PrettyRepresentation; import org.junit.jupiter.api.Test; import java.util.Arrays; -import static org.junit.jupiter.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; public class ActivityTest { @@ -43,8 +44,15 @@ private static DataObject formatActivity(int type, String name, String state) return json; } + private static void assertEquals(DataObject expected, DataObject actual) + { + assertThat(actual) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(expected); + } + @Test - public void activitySerializationTest() + void activitySerializationTest() { assertEquals( formatActivity(0, "playing test", null), @@ -102,7 +110,7 @@ public void activitySerializationTest() } @Test - public void activityBasicDeserializationTest() + void activityBasicDeserializationTest() { Activity activity = EntityBuilder.createActivity( DataObject.empty() @@ -110,15 +118,15 @@ public void activityBasicDeserializationTest() .put("name", "Games") ); - assertFalse(activity.isRich()); - assertEquals(Activity.ActivityType.PLAYING, activity.getType()); - assertEquals("Games", activity.getName());; - assertNull(activity.getState()); - assertNull(activity.getUrl()); + assertThat(activity.isRich()).isFalse(); + assertThat(activity.getType()).isEqualTo(Activity.ActivityType.PLAYING); + assertThat(activity.getName()).isEqualTo("Games"); + assertThat(activity.getState()).isNull(); + assertThat(activity.getUrl()).isNull(); } @Test - public void activityRichDeserializationTest() + void activityRichDeserializationTest() { Activity activity = EntityBuilder.createActivity( DataObject.empty() @@ -127,11 +135,11 @@ public void activityRichDeserializationTest() .put("state", "Active") ); - assertFalse(activity.isRich(), "isRich()"); - assertEquals(Activity.ActivityType.PLAYING, activity.getType()); - assertEquals("Games", activity.getName());; - assertEquals("Active", activity.getState()); - assertNull(activity.getUrl(), "url"); + assertThat(activity.isRich()).isFalse(); + assertThat(activity.getType()).isEqualTo(Activity.ActivityType.PLAYING); + assertThat(activity.getName()).isEqualTo("Games");; + assertThat(activity.getState()).isEqualTo("Active"); + assertThat(activity.getUrl()).isNull(); activity = EntityBuilder.createActivity( DataObject.empty() @@ -155,30 +163,31 @@ public void activityRichDeserializationTest() ); RichPresence rich = activity.asRichPresence(); - assertEquals(activity, rich); + assertThat(rich).isNotNull(); + assertThat(rich).isEqualTo(activity); - assertEquals(Activity.ActivityType.PLAYING, rich.getType()); - assertEquals("The Best Game Ever", rich.getName()); - assertEquals("In a Group", rich.getState()); + assertThat(rich.getType()).isEqualTo(Activity.ActivityType.PLAYING); + assertThat(rich.getName()).isEqualTo("The Best Game Ever"); + assertThat(rich.getState()).isEqualTo("In a Group"); - assertNotNull(rich.getParty(), "party"); - assertEquals("1234", rich.getParty().getId()); - assertEquals(3, rich.getParty().getSize()); - assertEquals(6, rich.getParty().getMax()); + assertThat(rich.getParty()).isNotNull(); + assertThat(rich.getParty().getId()).isEqualTo("1234"); + assertThat(rich.getParty().getSize()).isEqualTo(3); + assertThat(rich.getParty().getMax()).isEqualTo(6); - assertNotNull(rich.getTimestamps()); - assertEquals(1507665886, rich.getTimestamps().getStart()); - assertEquals(1507666000, rich.getTimestamps().getEnd()); + assertThat(rich.getTimestamps()).isNotNull(); + assertThat(rich.getTimestamps().getStart()).isEqualTo(1507665886); + assertThat(rich.getTimestamps().getEnd()).isEqualTo(1507666000); - assertNotNull(rich.getLargeImage(), "assets.large_image"); - assertEquals("canary-large", rich.getLargeImage().getKey()); - assertNull(rich.getLargeImage().getText(), "assets.large_text"); + assertThat(rich.getLargeImage()).isNotNull(); + assertThat(rich.getLargeImage().getKey()).isEqualTo("canary-large"); + assertThat(rich.getLargeImage().getText()).isNull(); - assertNotNull(rich.getSmallImage(), "assets.small_image"); - assertEquals("ptb-large", rich.getSmallImage().getKey()); - assertEquals("Small icon", rich.getSmallImage().getText()); + assertThat(rich.getSmallImage()).isNotNull(); + assertThat(rich.getSmallImage().getKey()).isEqualTo("ptb-large"); + assertThat(rich.getSmallImage().getText()).isEqualTo("Small icon"); - assertEquals("4b2fdce12f639de8bfa7e3591b71a0d679d7c93f", rich.getSessionId()); - assertEquals("e7eb30d2ee025ed05c71ea495f770b76454ee4e0", rich.getSyncId()); + assertThat(rich.getSessionId()).isEqualTo("4b2fdce12f639de8bfa7e3591b71a0d679d7c93f"); + assertThat(rich.getSyncId()).isEqualTo("e7eb30d2ee025ed05c71ea495f770b76454ee4e0"); } } diff --git a/src/test/java/net/dv8tion/jda/test/entities/MessageSerializationTest.java b/src/test/java/net/dv8tion/jda/test/entities/MessageSerializationTest.java new file mode 100644 index 0000000000..8d4bb8ec33 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/entities/MessageSerializationTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.entities; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.test.PrettyRepresentation; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MessageSerializationTest +{ + + private static final String DESCRIPTION_TEXT = "Description Text"; + private static final String TITLE_TEXT = "Title Text"; + private static final String TITLE_URL = "https://example.com/title"; + private static final String AUTHOR_TEXT = "Author Text"; + private static final String AUTHOR_URL = "https://example.com/author"; + private static final String AUTHOR_ICON = "https://example.com/author_icon"; + private static final String FOOTER_TEXT = "Footer Text"; + private static final String FOOTER_ICON = "https://example.com/footer_icon"; + private static final String IMAGE_URL = "https://example.com/image"; + private static final String THUMBNAIL_URL = "https://example.com/thumbnail"; + private static final String FIELD_1_NAME = "Field 1"; + private static final String FIELD_1_TEXT = "Field 1 Text"; + private static final String FIELD_2_NAME = "Field 2"; + private static final String FIELD_2_TEXT = "Field 2 Text"; + private static final String FIELD_3_NAME = "Field 3"; + private static final String FIELD_3_TEXT = "Field 3 Text"; + + @Test + void testEmbedSerialization() + { + MessageEmbed embed = getTestEmbed(); + + MessageEmbed dataEmbed = EmbedBuilder.fromData(embed.toData()).build(); + + assertThat(dataEmbed).isNotSameAs(embed); + assertThat(dataEmbed).isEqualTo(embed); + + assertThat(dataEmbed.toData()) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty() + .put("title", TITLE_TEXT) + .put("url", TITLE_URL) + .put("description", DESCRIPTION_TEXT) + .put("image", DataObject.empty() + .put("url", IMAGE_URL)) + .put("thumbnail", DataObject.empty() + .put("url", THUMBNAIL_URL)) + .put("footer", DataObject.empty() + .put("icon_url", FOOTER_ICON) + .put("text", FOOTER_TEXT)) + .put("author", DataObject.empty() + .put("icon_url", AUTHOR_ICON) + .put("name", AUTHOR_TEXT) + .put("url", AUTHOR_URL)) + .put("fields", DataArray.empty() + .add(DataObject.empty() + .put("inline", true) + .put("name", FIELD_1_NAME) + .put("value", FIELD_1_TEXT)) + .add(DataObject.empty() + .put("inline", false) + .put("name", FIELD_2_NAME) + .put("value", FIELD_2_TEXT)) + .add(DataObject.empty() + .put("inline", true) + .put("name", FIELD_3_NAME) + .put("value", FIELD_3_TEXT)))); + } + + @NotNull + private static MessageEmbed getTestEmbed() + { + return new EmbedBuilder() + .setDescription(DESCRIPTION_TEXT) + .setTitle(TITLE_TEXT, TITLE_URL) + .setAuthor(AUTHOR_TEXT, AUTHOR_URL, AUTHOR_ICON) + .setFooter(FOOTER_TEXT, FOOTER_ICON) + .setImage(IMAGE_URL) + .setThumbnail(THUMBNAIL_URL) + .addField(FIELD_1_NAME, FIELD_1_TEXT, true) + .addField(FIELD_2_NAME, FIELD_2_TEXT, false) + .addField(FIELD_3_NAME, FIELD_3_TEXT, true) + .build(); + } +} diff --git a/src/test/java/net/dv8tion/jda/entities/channel/ChannelCacheViewTest.java b/src/test/java/net/dv8tion/jda/test/entities/channel/ChannelCacheViewTest.java similarity index 83% rename from src/test/java/net/dv8tion/jda/entities/channel/ChannelCacheViewTest.java rename to src/test/java/net/dv8tion/jda/test/entities/channel/ChannelCacheViewTest.java index 70b4bd4eac..9391e395b1 100644 --- a/src/test/java/net/dv8tion/jda/entities/channel/ChannelCacheViewTest.java +++ b/src/test/java/net/dv8tion/jda/test/entities/channel/ChannelCacheViewTest.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package net.dv8tion.jda.entities.channel; +package net.dv8tion.jda.test.entities.channel; import net.dv8tion.jda.api.entities.channel.Channel; import net.dv8tion.jda.api.entities.channel.ChannelType; @@ -40,7 +40,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; class ChannelCacheViewTest @@ -182,10 +182,10 @@ void testSortedStream() { SortedChannelCacheView cache = getMockedGuildCache(); String output = toListString(cache.stream()); - assertEquals(VALID_SORT_ORDER, output); + assertThat(output).isEqualTo(VALID_SORT_ORDER); output = toListString(cache.parallelStream()); - assertEquals(VALID_SORT_ORDER, output); + assertThat(output).isEqualTo(VALID_SORT_ORDER); } @Test @@ -193,13 +193,13 @@ void testUnsortedStream() { SortedChannelCacheView cache = getMockedGuildCache(); String output = toListString(cache.streamUnordered()); - assertNotEquals(VALID_SORT_ORDER, output); + assertThat(output).isNotEqualTo(VALID_SORT_ORDER); output = toListString(cache.parallelStreamUnordered()); - assertNotEquals(VALID_SORT_ORDER, output); + assertThat(output).isNotEqualTo(VALID_SORT_ORDER); output = cache.applyStream(ChannelCacheViewTest::toListString); - assertNotEquals(VALID_SORT_ORDER, output); + assertThat(output).isNotEqualTo(VALID_SORT_ORDER); } @Test @@ -208,15 +208,16 @@ void testAsListWorks() SortedChannelCacheView cache = getMockedGuildCache(); String output = toListString(cache.asList().stream()); - assertEquals(VALID_SORT_ORDER, output); + assertThat(output).isEqualTo(VALID_SORT_ORDER); SortedChannelCacheView voiceView = cache.ofType(VoiceChannel.class); List fromOfType = voiceView.asList(); List voiceChannelFilter = cache.applyStream(stream -> stream.filter(VoiceChannel.class::isInstance).collect(Collectors.toList())); - assertEquals(voiceView.size(), voiceChannelFilter.size()); - assertTrue(fromOfType.containsAll(voiceChannelFilter), "The filtered CacheView must contain all of VoiceChannel"); - assertTrue(voiceChannelFilter.containsAll(fromOfType), "The filtered CacheView must contain exactly all of VoiceChannel"); + assertThat(voiceChannelFilter) + .hasSameSizeAs(voiceView); + assertThat(voiceChannelFilter) + .hasSameElementsAs(fromOfType); } @Test @@ -225,15 +226,16 @@ void testAsSetWorks() SortedChannelCacheView cache = getMockedGuildCache(); String output = toListString(cache.asSet().stream()); - assertEquals(VALID_SORT_ORDER, output); + assertThat(output).isEqualTo(VALID_SORT_ORDER); SortedChannelCacheView voiceView = cache.ofType(VoiceChannel.class); Set fromOfType = voiceView.asSet(); Set voiceChannelFilter = cache.applyStream(stream -> stream.filter(VoiceChannel.class::isInstance).collect(Collectors.toSet())); - assertEquals(voiceView.size(), voiceChannelFilter.size()); - assertTrue(fromOfType.containsAll(voiceChannelFilter), "The filtered CacheView must contain all of VoiceChannel"); - assertTrue(voiceChannelFilter.containsAll(fromOfType), "The filtered CacheView must contain exactly all of VoiceChannel"); + assertThat(voiceChannelFilter) + .hasSize((int) voiceView.size()); + assertThat(voiceChannelFilter) + .hasSameElementsAs(fromOfType); } @Test @@ -242,12 +244,12 @@ void testSizeWorks() SortedChannelCacheView cache = getMockedGuildCache(); NavigableSet asSet = cache.asSet(); - assertEquals(asSet.size(), cache.size()); + assertThat(cache).hasSameSizeAs(asSet); SortedChannelCacheView ofTypeMessage = cache.ofType(GuildMessageChannel.class); Set filterMessageType = asSet.stream().filter(GuildMessageChannel.class::isInstance).collect(Collectors.toSet()); - assertEquals(filterMessageType.size(), ofTypeMessage.size()); + assertThat(ofTypeMessage).hasSameSizeAs(filterMessageType); } @Test @@ -255,16 +257,22 @@ void testEmptyWorks() { SortedChannelCacheView empty = new SortedChannelCacheViewImpl<>(GuildChannel.class); - assertTrue(empty.isEmpty(), "New cache must be empty"); + assertThat(empty).isEmpty(); SortedChannelCacheViewImpl filled = getMockedGuildCache(); - assertFalse(filled.ofType(GuildMessageChannel.class).isEmpty(), "Filtered cache must not be empty before remove"); + assertThat(filled.ofType(GuildMessageChannel.class)) + .as("Filtered cache must not be empty before remove") + .isNotEmpty(); filled.removeIf(GuildMessageChannel.class, (c) -> true); - assertFalse(filled.isEmpty(), "Filled cache must not be empty"); - assertTrue(filled.ofType(GuildMessageChannel.class).isEmpty(), "Filtered cache must be empty"); + assertThat(filled) + .as("Filled cache must not be empty") + .isNotEmpty(); + assertThat(filled.ofType(GuildMessageChannel.class)) + .as("Filtered cache must be empty") + .isEmpty(); } @Test @@ -276,17 +284,21 @@ void testRemoveWorks() GuildChannel textWithoutParent = getByName.get().get(0); - assertSame(textWithoutParent, cache.remove(textWithoutParent), "Remove returns instance"); - assertTrue(getByName.get().isEmpty(), "Channel should be removed"); + assertThat(textWithoutParent) + .as("Remove returns instance") + .isSameAs(cache.remove(textWithoutParent)); + assertThat(getByName.get()) + .as("Channel should be removed") + .isEmpty(); List messageChannels = getOfType.get(); - assertFalse(messageChannels.isEmpty(), "Message channels should not be removed"); + assertThat(messageChannels).isNotEmpty(); cache.removeIf(GuildChannel.class, GuildMessageChannel.class::isInstance); messageChannels = getOfType.get(); - assertTrue(messageChannels.isEmpty(), "Message channels should be removed"); + assertThat(messageChannels).isEmpty(); } } diff --git a/src/test/java/net/dv8tion/jda/entitystring/ASnowflake.java b/src/test/java/net/dv8tion/jda/test/entitystring/ASnowflake.java similarity index 95% rename from src/test/java/net/dv8tion/jda/entitystring/ASnowflake.java rename to src/test/java/net/dv8tion/jda/test/entitystring/ASnowflake.java index 4370e113c0..c290926ac0 100644 --- a/src/test/java/net/dv8tion/jda/entitystring/ASnowflake.java +++ b/src/test/java/net/dv8tion/jda/test/entitystring/ASnowflake.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package net.dv8tion.jda.entitystring; +package net.dv8tion.jda.test.entitystring; import net.dv8tion.jda.api.entities.ISnowflake; diff --git a/src/test/java/net/dv8tion/jda/entitystring/AnEntity.java b/src/test/java/net/dv8tion/jda/test/entitystring/AnEntity.java similarity index 94% rename from src/test/java/net/dv8tion/jda/entitystring/AnEntity.java rename to src/test/java/net/dv8tion/jda/test/entitystring/AnEntity.java index e3aac7407a..c581091f09 100644 --- a/src/test/java/net/dv8tion/jda/entitystring/AnEntity.java +++ b/src/test/java/net/dv8tion/jda/test/entitystring/AnEntity.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package net.dv8tion.jda.entitystring; +package net.dv8tion.jda.test.entitystring; public class AnEntity { diff --git a/src/test/java/net/dv8tion/jda/test/entitystring/EntityStringTest.java b/src/test/java/net/dv8tion/jda/test/entitystring/EntityStringTest.java new file mode 100644 index 0000000000..cde9d3edaa --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/entitystring/EntityStringTest.java @@ -0,0 +1,206 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.entitystring; + +import net.dv8tion.jda.api.entities.channel.ChannelType; +import net.dv8tion.jda.internal.utils.EntityString; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class EntityStringTest +{ + @Test + @Order(1) + void testSimple() + { + assertThat(new EntityString(new AnEntity())) + .hasToString("AnEntity"); + assertThat(new EntityString(new AnEntity()).setName("AName")) + .hasToString("AnEntity:AName"); + } + + @Test + @Order(2) + void testClassNameAsString() + { + assertThat(new EntityString("NotAnEntity")) + .hasToString("NotAnEntity"); + assertThat(new EntityString("NotAnEntity").setName("AName")) + .hasToString("NotAnEntity:AName"); + } + + @Test + @Order(3) + void testType() + { + assertThat(new EntityString(new AnEntity()).setType("AType")) + .hasToString("AnEntity[AType]"); + assertThat(new EntityString(new AnEntity()).setType("AType").setName("AName")) + .hasToString("AnEntity[AType]:AName"); + assertThat(new EntityString(new AnEntity()).setType(ChannelType.NEWS).setName("AName")) + .hasToString("AnEntity[NEWS]:AName"); + } + + @Test + @Order(4) + void testMetadata() + { + assertThat(new EntityString(new AnEntity()).addMetadata(null, "Metadata1")) + .hasToString("AnEntity(Metadata1)"); + assertThat(new EntityString(new AnEntity()).addMetadata("MetaKey", "Metadata1")) + .hasToString("AnEntity(MetaKey=Metadata1)"); + assertThat(new EntityString(new AnEntity()).addMetadata("MetaKey", 42)) + .hasToString("AnEntity(MetaKey=42)"); + assertThat(new EntityString(new AnEntity()) + .addMetadata("MetaKey1", "Metadata1") + .addMetadata("MetaKey2", "Metadata2")) + .hasToString("AnEntity(MetaKey1=Metadata1, MetaKey2=Metadata2)"); + } + + @Test + @Order(5) + void testAll() + { + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .addMetadata(null, "Metadata1")) + .hasToString("AnEntity:AName(Metadata1)"); + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .addMetadata("MetaKey", "Metadata1")) + .hasToString("AnEntity:AName(MetaKey=Metadata1)"); + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .addMetadata("MetaKey", 42)) + .hasToString("AnEntity:AName(MetaKey=42)"); + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .addMetadata("MetaKey1", "Metadata1") + .addMetadata("MetaKey2", "Metadata2")) + .hasToString("AnEntity:AName(MetaKey1=Metadata1, MetaKey2=Metadata2)"); + + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .setType("Type") + .addMetadata(null, "Metadata1")) + .hasToString("AnEntity[Type]:AName(Metadata1)"); + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .setType("Type") + .addMetadata("MetaKey", "Metadata1")) + .hasToString("AnEntity[Type]:AName(MetaKey=Metadata1)"); + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .setType("Type") + .addMetadata("MetaKey", 42)) + .hasToString("AnEntity[Type]:AName(MetaKey=42)"); + assertThat(new EntityString(new AnEntity()) + .setName("AName") + .setType("Type") + .addMetadata("MetaKey1", "Metadata1") + .addMetadata("MetaKey2", "Metadata2")) + .hasToString("AnEntity[Type]:AName(MetaKey1=Metadata1, MetaKey2=Metadata2)"); + } + + @Test + @Order(6) + void testSimpleSnowflake() + { + assertThat(new EntityString(new ASnowflake())) + .hasToString("ASnowflake(id=42)"); + assertThat(new EntityString(new ASnowflake()).setName("AName")) + .hasToString("ASnowflake:AName(id=42)"); + } + + @Test + @Order(7) + void testTypeSnowflake() + { + assertThat(new EntityString(new ASnowflake()).setType("AType")) + .hasToString("ASnowflake[AType](id=42)"); + assertThat(new EntityString(new ASnowflake()).setType("AType").setName("AName")) + .hasToString("ASnowflake[AType]:AName(id=42)"); + assertThat(new EntityString(new ASnowflake()).setType(ChannelType.NEWS).setName("AName")) + .hasToString("ASnowflake[NEWS]:AName(id=42)"); + } + + @Test + @Order(8) + void testMetadataSnowflake() + { + assertThat(new EntityString(new ASnowflake()).addMetadata(null, "Metadata1")) + .hasToString("ASnowflake(id=42, Metadata1)"); + assertThat(new EntityString(new ASnowflake()).addMetadata("MetaKey", "Metadata1")) + .hasToString("ASnowflake(id=42, MetaKey=Metadata1)"); + assertThat(new EntityString(new ASnowflake()).addMetadata("MetaKey", 42)) + .hasToString("ASnowflake(id=42, MetaKey=42)"); + assertThat(new EntityString(new ASnowflake()) + .addMetadata("MetaKey1", "Metadata1") + .addMetadata("MetaKey2", "Metadata2")) + .hasToString("ASnowflake(id=42, MetaKey1=Metadata1, MetaKey2=Metadata2)"); + } + + @Test + @Order(9) + void testAllSnowflake() + { + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .addMetadata(null, "Metadata1")) + .hasToString("ASnowflake:AName(id=42, Metadata1)"); + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .addMetadata("MetaKey", "Metadata1")) + .hasToString("ASnowflake:AName(id=42, MetaKey=Metadata1)"); + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .addMetadata("MetaKey", 42)) + .hasToString("ASnowflake:AName(id=42, MetaKey=42)"); + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .addMetadata("MetaKey1", "Metadata1") + .addMetadata("MetaKey2", "Metadata2")) + .hasToString("ASnowflake:AName(id=42, MetaKey1=Metadata1, MetaKey2=Metadata2)"); + + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .setType("Type") + .addMetadata(null, "Metadata1")) + .hasToString("ASnowflake[Type]:AName(id=42, Metadata1)"); + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .setType("Type") + .addMetadata("MetaKey", "Metadata1")) + .hasToString("ASnowflake[Type]:AName(id=42, MetaKey=Metadata1)"); + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .setType("Type") + .addMetadata("MetaKey", 42)) + .hasToString("ASnowflake[Type]:AName(id=42, MetaKey=42)"); + assertThat(new EntityString(new ASnowflake()) + .setName("AName") + .setType("Type") + .addMetadata("MetaKey1", "Metadata1") + .addMetadata("MetaKey2", "Metadata2")) + .hasToString("ASnowflake[Type]:AName(id=42, MetaKey1=Metadata1, MetaKey2=Metadata2)"); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/interactions/CommandDataTest.java b/src/test/java/net/dv8tion/jda/test/interactions/CommandDataTest.java new file mode 100644 index 0000000000..1dae4f186c --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/interactions/CommandDataTest.java @@ -0,0 +1,238 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.interactions; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData; +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import net.dv8tion.jda.test.PrettyRepresentation; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +public class CommandDataTest +{ + private static DataObject defaultCommand() + { + return DataObject.empty() + .put("type", 1) + .put("dm_permission", true) + .put("name_localizations", DataObject.empty()) + .put("description_localizations", DataObject.empty()) + .put("nsfw", false) + .put("default_member_permissions", null) + .put("options", DataArray.empty()); + } + + private static DataObject defaultOption(OptionType type, String name, String description) + { + return DataObject.empty() + .put("type", type.getKey()) + .put("name", name) + .put("description", description) + .put("required", false) + .put("autocomplete", false) + .put("name_localizations", DataObject.empty()) + .put("description_localizations", DataObject.empty()); + } + + @Test + void testNormal() + { + CommandData command = new CommandDataImpl("ban", "Ban a user from this server") + .setGuildOnly(true) + .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS)) + .addOption(OptionType.USER, "user", "The user to ban", true) // required before non-required + .addOption(OptionType.STRING, "reason", "The ban reason") // test that default is false + .addOption(OptionType.INTEGER, "days", "The duration of the ban", false); // test with explicit false + + DataObject data = command.toData(); + + assertThat(data) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(defaultCommand() + .put("type", 1) + .put("name", "ban") + .put("description", "Ban a user from this server") + .put("dm_permission", false) + .put("default_member_permissions", "4") + .put("options", DataArray.empty() + .add(defaultOption(OptionType.USER, "user", "The user to ban").put("required", true)) + .add(defaultOption(OptionType.STRING, "reason", "The ban reason")) + .add(defaultOption(OptionType.INTEGER, "days", "The duration of the ban")))); + } + + @Test + void testDefaultMemberPermissions() + { + CommandData command = new CommandDataImpl("ban", "Ban a user from this server") + .setDefaultPermissions(DefaultMemberPermissions.DISABLED); + + assertThat(command.toData().get("default_member_permissions")).isEqualTo("0"); + + command.setDefaultPermissions(DefaultMemberPermissions.ENABLED); + + assertThat(command.toData().opt("default_member_permissions")).isEmpty(); + } + + @Test + void testSubcommand() + { + CommandDataImpl command = new CommandDataImpl("mod", "Moderation commands") + .addSubcommands(new SubcommandData("ban", "Ban a user from this server") + .addOption(OptionType.USER, "user", "The user to ban", true) // required before non-required + .addOption(OptionType.STRING, "reason", "The ban reason") // test that default is false + .addOption(OptionType.INTEGER, "days", "The duration of the ban", false)); // test with explicit false + + assertThat(command.toData()) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(defaultCommand() + .put("name", "mod") + .put("description", "Moderation commands") + .put("options", DataArray.empty() + .add(defaultOption(OptionType.SUB_COMMAND, "ban", "Ban a user from this server") + .remove("autocomplete") + .remove("required") + .put("options", DataArray.empty() + .add(defaultOption(OptionType.USER, "user", "The user to ban").put("required", true)) + .add(defaultOption(OptionType.STRING, "reason", "The ban reason")) + .add(defaultOption(OptionType.INTEGER, "days", "The duration of the ban")))))); + } + + @Test + void testSubcommandGroup() + { + CommandDataImpl command = new CommandDataImpl("mod", "Moderation commands") + .addSubcommandGroups(new SubcommandGroupData("ban", "Ban or unban a user from this server") + .addSubcommands(new SubcommandData("add", "Ban a user from this server") + .addOption(OptionType.USER, "user", "The user to ban", true) // required before non-required + .addOption(OptionType.STRING, "reason", "The ban reason") // test that default is false + .addOption(OptionType.INTEGER, "days", "The duration of the ban", false))); // test with explicit false + + assertThat(command.toData()) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(defaultCommand() + .put("name", "mod") + .put("description", "Moderation commands") + .put("options", DataArray.empty() + .add(defaultOption(OptionType.SUB_COMMAND_GROUP, "ban", "Ban or unban a user from this server") + .remove("autocomplete") + .remove("required") + .put("options", DataArray.empty() + .add(defaultOption(OptionType.SUB_COMMAND, "add", "Ban a user from this server") + .remove("autocomplete") + .remove("required") + .put("options", DataArray.empty() + .add(defaultOption(OptionType.USER, "user", "The user to ban").put("required", true)) + .add(defaultOption(OptionType.STRING, "reason", "The ban reason")) + .add(defaultOption(OptionType.INTEGER, "days", "The duration of the ban")))))))); + } + + @Test + void testRequiredThrows() + { + CommandDataImpl command = new CommandDataImpl("ban", "Simple ban command"); + command.addOption(OptionType.STRING, "opt", "desc"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> command.addOption(OptionType.STRING, "other", "desc", true)) + .withMessage("Cannot add required options after non-required options!"); + + SubcommandData subcommand = new SubcommandData("sub", "Simple subcommand"); + subcommand.addOption(OptionType.STRING, "opt", "desc"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> subcommand.addOption(OptionType.STRING, "other", "desc", true)) + .withMessage("Cannot add required options after non-required options!"); + } + + @Test + void testNameChecks() + { + assertThatIllegalArgumentException() + .isThrownBy(() -> new CommandDataImpl("invalid name", "Valid description")) + .withMessage("Name must match regex ^[\\w-]+$. Provided: \"invalid name\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new CommandDataImpl("invalidName", "Valid description")) + .withMessage("Name must be lowercase only! Provided: \"invalidName\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new CommandDataImpl("valid_name", "")) + .withMessage("Description may not be empty"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubcommandData("invalid name", "Valid description")) + .withMessage("Name must match regex ^[\\w-]+$. Provided: \"invalid name\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubcommandData("invalidName", "Valid description")) + .withMessage("Name must be lowercase only! Provided: \"invalidName\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubcommandData("valid_name", "")) + .withMessage("Description may not be empty"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubcommandGroupData("invalid name", "Valid description")) + .withMessage("Name must match regex ^[\\w-]+$. Provided: \"invalid name\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubcommandGroupData("invalidName", "Valid description")) + .withMessage("Name must be lowercase only! Provided: \"invalidName\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SubcommandGroupData("valid_name", "")) + .withMessage("Description may not be empty"); + } + + @Test + void testChoices() + { + OptionData stringOption = new OptionData(OptionType.STRING, "choice", "Option with choices!"); + assertThatIllegalArgumentException() + .isThrownBy(() -> stringOption.addChoice("invalid name", 0)) + .withMessage("Cannot add long choice for OptionType.STRING"); + assertThatIllegalArgumentException() + .isThrownBy(() -> stringOption.addChoice("invalidName", 0.0)) + .withMessage("Cannot add double choice for OptionType.STRING"); + assertThatIllegalArgumentException() + .isThrownBy(() -> stringOption.addChoice("valid_name", "")) + .withMessage("Value may not be empty"); + + OptionData intOption = new OptionData(OptionType.INTEGER, "choice", "Option with choices!"); + List choices = new ArrayList<>(); + for (int i = 0; i < 25; i++) + { + intOption.addChoice("choice_" + i, i); + choices.add(new Command.Choice("choice_" + i, i)); + } + assertThatIllegalArgumentException() + .isThrownBy(() -> intOption.addChoice("name", 100)) + .withMessage("Cannot have more than 25 choices for an option!"); + assertThat(intOption.getChoices()) + .hasSize(25); + assertThat(intOption.getChoices()) + .isEqualTo(choices); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/interactions/LocalizationTest.java b/src/test/java/net/dv8tion/jda/test/interactions/LocalizationTest.java new file mode 100644 index 0000000000..3f9c09cf9f --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/interactions/LocalizationTest.java @@ -0,0 +1,209 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.interactions; + +import net.dv8tion.jda.api.interactions.DiscordLocale; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.*; +import net.dv8tion.jda.api.interactions.commands.localization.LocalizationFunction; +import net.dv8tion.jda.api.interactions.commands.localization.ResourceBundleLocalizationFunction; +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.test.PrettyRepresentation; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class LocalizationTest +{ + private static SlashCommandData slashCommandData; + private static DataObject data; + + @BeforeAll + static void setup() + { + LocalizationFunction localizationFunction = ResourceBundleLocalizationFunction + .fromBundles("MyCommands", DiscordLocale.FRENCH) + .build(); + + slashCommandData = Commands.slash("ban", "Bans someone").addSubcommandGroups( + new SubcommandGroupData("user", "Bans a member").addSubcommands( + new SubcommandData("perm", "Bans a user permanently").addOptions( + new OptionData(OptionType.STRING, "user", "The user to ban"), + new OptionData(OptionType.INTEGER, "del_days", "The amount of days to delete messages") + .addChoices( + new Command.Choice("1 Day", "1"), + new Command.Choice("7 Days", "7"), + new Command.Choice("14 Days", "14") + ) + ), + new SubcommandData("temp", "Bans a user temporarily").addOptions( + new OptionData(OptionType.STRING, "user", "The user to ban"), + new OptionData(OptionType.INTEGER, "del_days", "The amount of days to delete messages") + .addChoices( + new Command.Choice("1 Day", "1"), + new Command.Choice("7 Days", "7"), + new Command.Choice("14 Days", "14") + ) + ) + ) + ).setLocalizationFunction(localizationFunction); + + data = slashCommandData.toData(); + } + + @Test + void commandLocalization() + { + assertThat(data.getString("name")).isEqualTo("ban"); + assertThat(data.getString("description")).isEqualTo("Bans someone"); + + assertThat(data.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "ban")); + assertThat(data.getObject("description_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "Bannis un utilisateur")); + } + + @Test + void subcommandLocalization() + { + DataObject subcommandGroup = getOption(data, "user"); + + assertThat(subcommandGroup.getString("name")).isEqualTo("user"); + assertThat(subcommandGroup.getString("description")).isEqualTo("Bans a member"); + + assertThat(subcommandGroup.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "utilisateur")); + assertThat(subcommandGroup.getObject("description_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "Bannis un utilisateur")); + } + + @Test + void subcommandGroupLocalization() + { + DataObject subcommandGroup = getOption(data, "user"); + DataObject subcommand = getOption(subcommandGroup, "perm"); + + assertThat(subcommand.getString("name")).isEqualTo("perm"); + assertThat(subcommand.getString("description")).isEqualTo("Bans a user permanently"); + + assertThat(subcommand.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "permanent")); + assertThat(subcommand.getObject("description_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "Bannis un utilisateur pour toujours")); + } + + @Test + void optionLocalization() + { + DataObject subcommandGroup = getOption(data, "user"); + DataObject subcommand = getOption(subcommandGroup, "perm"); + DataObject userOption = getOption(subcommand, "user"); + DataObject delDaysOption = getOption(subcommand, "del_days"); + + assertThat(userOption.getString("name")).isEqualTo("user"); + assertThat(userOption.getString("description")).isEqualTo("The user to ban"); + + assertThat(delDaysOption.getString("name")).isEqualTo("del_days"); + assertThat(delDaysOption.getString("description")).isEqualTo("The amount of days to delete messages"); + + assertThat(userOption.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "utilisateur")); + assertThat(userOption.getObject("description_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "L'utilisateur à bannir")); + + assertThat(delDaysOption.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "nb_jours")); + assertThat(delDaysOption.getObject("description_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "Nombre de jours de messages à supprimer")); + } + + @Test + void choiceLocalization() + { + DataObject subcommandGroup = getOption(data, "user"); + DataObject subcommand = getOption(subcommandGroup, "perm"); + DataObject delDaysOption = getOption(subcommand, "del_days"); + + DataObject days1 = getChoice(delDaysOption, "1 Day"); + assertThat(days1.getString("name")).isEqualTo("1 Day"); + assertThat(days1.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "1 jour")); + + DataObject days7 = getChoice(delDaysOption, "7 Days"); + assertThat(days7.getString("name")).isEqualTo("7 Days"); + assertThat(days7.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "7 jours")); + + DataObject days14 = getChoice(delDaysOption, "14 Days"); + assertThat(days14.getString("name")).isEqualTo("14 Days"); + assertThat(days14.getObject("name_localizations")) + .withRepresentation(new PrettyRepresentation()) + .isEqualTo(DataObject.empty().put("fr", "14 jours")); + } + + @Test + void reconstructData() + { + final DataObject data = slashCommandData.toData(); + final DataObject reconstitutedData = CommandData.fromData(data).toData(); + assertThat(reconstitutedData.toMap()).isEqualTo(data.toMap()); + } + + private static DataObject getOption(DataObject root, String name) + { + Stream options = root.getArray("options") + .stream(DataArray::getObject) + .filter(option -> option.getString("name").equals(name)); + return assertExactlyOne(options); + } + + private static DataObject getChoice(DataObject root, String name) + { + Stream choices = root.getArray("choices") + .stream(DataArray::getObject) + .filter(choice -> choice.getString("name").equals(name)); + return assertExactlyOne(choices); + } + + private static T assertExactlyOne(Stream stream) + { + List results = stream.collect(Collectors.toList()); + assertThat(results) + .withRepresentation(new PrettyRepresentation()) + .hasSize(1); + return results.get(0); + } +} diff --git a/src/test/java/net/dv8tion/jda/interactions/SelectMenuTests.java b/src/test/java/net/dv8tion/jda/test/interactions/SelectMenuTests.java similarity index 56% rename from src/test/java/net/dv8tion/jda/interactions/SelectMenuTests.java rename to src/test/java/net/dv8tion/jda/test/interactions/SelectMenuTests.java index 670c7dd30b..e356ce7b95 100644 --- a/src/test/java/net/dv8tion/jda/interactions/SelectMenuTests.java +++ b/src/test/java/net/dv8tion/jda/test/interactions/SelectMenuTests.java @@ -14,22 +14,22 @@ * limitations under the License. */ -package net.dv8tion.jda.interactions; +package net.dv8tion.jda.test.interactions; import net.dv8tion.jda.api.interactions.components.selections.EntitySelectMenu; import net.dv8tion.jda.api.interactions.components.selections.EntitySelectMenu.Builder; import net.dv8tion.jda.api.interactions.components.selections.EntitySelectMenu.DefaultValue; import net.dv8tion.jda.api.interactions.components.selections.EntitySelectMenu.SelectTarget; import net.dv8tion.jda.api.utils.data.DataObject; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; public class SelectMenuTests { @Test - public void testEntitySelectDefaultValueValid() + void testEntitySelectDefaultValueValid() { Builder builder = EntitySelectMenu.create("customid", SelectTarget.ROLE); builder.setDefaultValues(DefaultValue.role("1234")); @@ -37,9 +37,9 @@ public void testEntitySelectDefaultValueValid() EntitySelectMenu menu = builder.build(); DataObject value = menu.toData().getArray("default_values").getObject(0); - Assertions.assertEquals(Arrays.asList(DefaultValue.role("1234")), menu.getDefaultValues()); - Assertions.assertEquals("role", value.getString("type")); - Assertions.assertEquals("1234", value.getString("id")); + assertThat(menu.getDefaultValues()).containsExactly(DefaultValue.role("1234")); + assertThat(value.getString("type")).isEqualTo("role"); + assertThat(value.getString("id")).isEqualTo("1234"); builder = EntitySelectMenu.create("customid", SelectTarget.USER); builder.setDefaultValues(DefaultValue.user("1234")); @@ -47,9 +47,9 @@ public void testEntitySelectDefaultValueValid() menu = builder.build(); value = menu.toData().getArray("default_values").getObject(0); - Assertions.assertEquals(Arrays.asList(DefaultValue.user("1234")), menu.getDefaultValues()); - Assertions.assertEquals("user", value.getString("type")); - Assertions.assertEquals("1234", value.getString("id")); + assertThat(menu.getDefaultValues()).containsExactly(DefaultValue.user("1234")); + assertThat(value.getString("type")).isEqualTo("user"); + assertThat(value.getString("id")).isEqualTo("1234"); builder = EntitySelectMenu.create("customid", SelectTarget.CHANNEL); builder.setDefaultValues(DefaultValue.channel("1234")); @@ -57,41 +57,41 @@ public void testEntitySelectDefaultValueValid() menu = builder.build(); value = menu.toData().getArray("default_values").getObject(0); - Assertions.assertEquals(Arrays.asList(DefaultValue.channel("1234")), menu.getDefaultValues()); - Assertions.assertEquals("channel", value.getString("type")); - Assertions.assertEquals("1234", value.getString("id")); + assertThat(menu.getDefaultValues()).containsExactly(DefaultValue.channel("1234")); + assertThat(value.getString("type")).isEqualTo("channel"); + assertThat(value.getString("id")).isEqualTo("1234"); } @Test - public void testEntitySelectDefaultValueInvalid() + void testEntitySelectDefaultValueInvalid() { - Assertions.assertThrows(IllegalArgumentException.class, () -> { + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.ROLE); builder.setDefaultValues(DefaultValue.user("1234")); - }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { + }).withMessage("The select menu supports types SelectTarget.ROLE, but provided default value has type SelectTarget.USER!"); + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.ROLE); builder.setDefaultValues(DefaultValue.channel("1234")); - }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { + }).withMessage("The select menu supports types SelectTarget.ROLE, but provided default value has type SelectTarget.CHANNEL!"); + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.ROLE, SelectTarget.USER); builder.setDefaultValues(DefaultValue.channel("1234")); - }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { + }).withMessage("The select menu supports types SelectTarget.ROLE and SelectTarget.USER, but provided default value has type SelectTarget.CHANNEL!"); + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.USER); builder.setDefaultValues(DefaultValue.channel("1234")); - }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { + }).withMessage("The select menu supports types SelectTarget.USER, but provided default value has type SelectTarget.CHANNEL!"); + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.USER); builder.setDefaultValues(DefaultValue.role("1234")); - }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { + }).withMessage("The select menu supports types SelectTarget.USER, but provided default value has type SelectTarget.ROLE!"); + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.CHANNEL); builder.setDefaultValues(DefaultValue.user("1234")); - }); - Assertions.assertThrows(IllegalArgumentException.class, () -> { + }).withMessage("The select menu supports types SelectTarget.CHANNEL, but provided default value has type SelectTarget.USER!"); + assertThatIllegalArgumentException().isThrownBy(() -> { Builder builder = EntitySelectMenu.create("customid", SelectTarget.CHANNEL); builder.setDefaultValues(DefaultValue.role("1234")); - }); + }).withMessage("The select menu supports types SelectTarget.CHANNEL, but provided default value has type SelectTarget.ROLE!"); } } diff --git a/src/test/java/net/dv8tion/jda/test/restaction/MessageCreateActionTest.java b/src/test/java/net/dv8tion/jda/test/restaction/MessageCreateActionTest.java new file mode 100644 index 0000000000..c7afa5cd0a --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/restaction/MessageCreateActionTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.restaction; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; +import net.dv8tion.jda.api.utils.data.DataArray; +import net.dv8tion.jda.api.utils.data.DataObject; +import net.dv8tion.jda.internal.requests.restaction.MessageCreateActionImpl; +import net.dv8tion.jda.test.IntegrationTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +import javax.annotation.Nonnull; + +import static net.dv8tion.jda.api.requests.Method.POST; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class MessageCreateActionTest extends IntegrationTest +{ + private static final String FIXED_CHANNEL_ID = "1234567890"; + private static final String FIXED_NONCE = "123456"; + private static final String ENDPOINT_URL = "channels/" + FIXED_CHANNEL_ID + "/messages"; + + @Mock + protected MessageChannel channel; + + private static DataObject defaultMessageRequest() + { + return DataObject.empty() + .put("allowed_mentions", DataObject.empty() + .put("parse", DataArray.empty() + .add("users") + .add("roles") + .add("everyone")) + .put("replied_user", true)) + .put("components", DataArray.empty()) + .put("content", "") + .put("embeds", DataArray.empty()) + .put("enforce_nonce", true) + .put("flags", 0) + .put("nonce", FIXED_NONCE) + .put("tts", false); + } + + @BeforeEach + void setupChannel() + { + when(channel.getId()).thenReturn(FIXED_CHANNEL_ID); + when(channel.getJDA()).thenReturn(jda); + } + + @Test + void testEmpty() + { + assertThatIllegalStateException().isThrownBy(() -> + new MessageCreateActionImpl(channel) + .queue() + ).withMessage("Cannot build empty messages! Must provide at least one of: content, embed, file, or stickers"); + } + + @Test + void testContentOnly() + { + assertNextRequestEquals(POST, ENDPOINT_URL, defaultMessageRequest() + .put("content", "test content")); + + new MessageCreateActionImpl(channel) + .setContent("test content") + .queue(); + + verify(requester, times(1)).request(any()); + } + + @Test + void testEmbedOnly() + { + assertNextRequestEquals(POST, ENDPOINT_URL, defaultMessageRequest() + .put("embeds", DataArray.empty() + .add(DataObject.empty().put("description", "test description")))); + + new MessageCreateActionImpl(channel) + .setEmbeds(new EmbedBuilder() + .setDescription("test description") + .build()) + .queue(); + + verify(requester, times(1)).request(any()); + } + + @Nonnull + protected DataObject normalizeRequestBody(@Nonnull DataObject body) + { + return body.put("nonce", FIXED_NONCE); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/restaction/RestActionTest.java b/src/test/java/net/dv8tion/jda/test/restaction/RestActionTest.java new file mode 100644 index 0000000000..72f226075c --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/restaction/RestActionTest.java @@ -0,0 +1,115 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.restaction; + +import net.dv8tion.jda.internal.requests.CompletedRestAction; +import net.dv8tion.jda.test.IntegrationTest; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.concurrent.CancellationException; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class RestActionTest extends IntegrationTest +{ + @Test + void testMapOperator() + { + assertThat( + new CompletedRestAction<>(jda, "12345") + .map(Integer::parseInt) + .complete() + ).isEqualTo(12345); + } + + @Test + void testFlatMapOperator() + { + assertThat( + new CompletedRestAction<>(jda, "12345") + .flatMap(value -> new CompletedRestAction<>(jda, Integer.parseInt(value))) + .complete() + ).isEqualTo(12345); + + assertThat( + new CompletedRestAction<>(jda, "12345") + .flatMap( + value -> value.startsWith("123"), + value -> new CompletedRestAction<>(jda, Integer.parseInt(value))) + .complete() + ).isEqualTo(12345); + + assertThatThrownBy(() -> + new CompletedRestAction<>(jda, "12345") + .flatMap( + value -> value.startsWith("wrong"), + value -> new CompletedRestAction<>(jda, Integer.parseInt(value))) + .complete() + ).isInstanceOf(CancellationException.class).hasMessage("FlatMap condition failed"); + + assertThat( + new CompletedRestAction<>(jda, "12345") + .flatMap( + value -> value.startsWith("wrong"), + value -> new CompletedRestAction<>(jda, Integer.parseInt(value))) + .submit() + ) + .failsWithin(Duration.ZERO) + .withThrowableThat() + .havingRootCause() + .isInstanceOf(CancellationException.class); + } + + @Test + void testDelayOperator() + { + when(scheduledExecutorService.schedule(any(Runnable.class), anyLong(), any())) + .thenReturn(null); + + new CompletedRestAction<>(jda, "12345") + .delay(Duration.ofSeconds(2), scheduledExecutorService) + .queue(); + + new CompletedRestAction<>(jda, "12345") + .delay(3, TimeUnit.SECONDS, scheduledExecutorService) + .queue(); + + verify(scheduledExecutorService, times(1)) + .schedule(any(Runnable.class), eq(2000L), eq(TimeUnit.MILLISECONDS)); + + verify(scheduledExecutorService, times(1)) + .schedule(any(Runnable.class), eq(3L), eq(TimeUnit.SECONDS)); + } + + @Test + void testQueueAfter() + { + when(scheduledExecutorService.schedule(any(Runnable.class), anyLong(), any())) + .thenReturn(null); + + new CompletedRestAction<>(jda, "12345") + .queueAfter(2, TimeUnit.SECONDS, scheduledExecutorService); + + verify(scheduledExecutorService, times(1)) + .schedule(any(Runnable.class), eq(2L), eq(TimeUnit.SECONDS)); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/util/HelpersTest.java b/src/test/java/net/dv8tion/jda/test/util/HelpersTest.java new file mode 100644 index 0000000000..de13a47581 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/util/HelpersTest.java @@ -0,0 +1,124 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.util; + +import net.dv8tion.jda.internal.utils.Helpers; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class HelpersTest +{ + @Test + void testIsEmpty() + { + assertThat(Helpers.isEmpty(null)).isTrue(); + assertThat(Helpers.isEmpty("")).isTrue(); + assertThat(Helpers.isEmpty("null")).isFalse(); + assertThat(Helpers.isEmpty("testing with spaces")).isFalse(); + } + + @Test + void testContainsWhitespace() + { + assertThat(Helpers.containsWhitespace(" ")).isTrue(); + assertThat(Helpers.containsWhitespace("testing with spaces")).isTrue(); + assertThat(Helpers.containsWhitespace(null)).isFalse(); + assertThat(Helpers.containsWhitespace("")).isFalse(); + assertThat(Helpers.containsWhitespace("null")).isFalse(); + } + + @Test + void testIsBlank() + { + assertThat(Helpers.isBlank(" ")).isTrue(); + assertThat(Helpers.isBlank(null)).isTrue(); + assertThat(Helpers.isBlank("")).isTrue(); + assertThat(Helpers.isBlank("testing with spaces")).isFalse(); + assertThat(Helpers.isBlank("null")).isFalse(); + } + + @Test + void testCountMatches() + { + assertThat(Helpers.countMatches("Hello World", 'l')).isEqualTo(3); + assertThat(Helpers.countMatches("Hello World", ' ')).isEqualTo(1); + assertThat(Helpers.countMatches("Hello World", '_')).isEqualTo(0); + assertThat(Helpers.countMatches("", '!')).isEqualTo(0); + assertThat(Helpers.countMatches(null, '?')).isEqualTo(0); + } + + @Test + void testTruncate() + { + assertThat(Helpers.truncate("Hello World", 5)).isEqualTo("Hello"); + assertThat(Helpers.truncate("Hello", 5)).isEqualTo("Hello"); + assertThat(Helpers.truncate("Hello", 10)).isEqualTo("Hello"); + assertThat(Helpers.truncate("", 10)).isEqualTo(""); + assertThat(Helpers.truncate("Test", 0)).isEqualTo(""); + assertThat(Helpers.truncate(null, 10)).isNull(); + } + + @Test + void testRightPad() + { + assertThat(Helpers.rightPad("Hello", 9)).isEqualTo("Hello "); + assertThat(Helpers.rightPad("Hello World", 9)).isEqualTo("Hello World"); + assertThat(Helpers.rightPad("Hello", 5)).isEqualTo("Hello"); + } + + @Test + void testLeftPad() + { + assertThat(Helpers.leftPad("Hello", 9)).isEqualTo(" Hello"); + assertThat(Helpers.leftPad("Hello World", 9)).isEqualTo("Hello World"); + assertThat(Helpers.leftPad("Hello", 5)).isEqualTo("Hello"); + } + + @Test + void testIsNumeric() + { + assertThat(Helpers.isNumeric("10")).isTrue(); + assertThat(Helpers.isNumeric("1")).isTrue(); + assertThat(Helpers.isNumeric("0")).isTrue(); + assertThat(Helpers.isNumeric(String.valueOf(Long.MAX_VALUE))).isTrue(); + assertThat(Helpers.isNumeric(null)).isFalse(); + assertThat(Helpers.isNumeric("")).isFalse(); + assertThat(Helpers.isNumeric("Test")).isFalse(); + assertThat(Helpers.isNumeric("1.0")).isFalse(); + assertThat(Helpers.isNumeric("1e10")).isFalse(); + } + + @Test + void testDeepEquals() + { + List a = Arrays.asList("A", "B", "C"); + List b = Arrays.asList("B", "A", "C"); + List c = Arrays.asList("A", "B"); + List d = Arrays.asList("A", "B", "C"); + + assertThat(Helpers.deepEquals(a, a)).isTrue(); + assertThat(Helpers.deepEquals(a, d)).isTrue(); + assertThat(Helpers.deepEqualsUnordered(a, b)).isTrue(); + assertThat(Helpers.deepEquals(a, b)).isFalse(); + assertThat(Helpers.deepEquals(a, c)).isFalse(); + assertThat(Helpers.deepEqualsUnordered(b, c)).isFalse(); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/util/MarkdownTest.java b/src/test/java/net/dv8tion/jda/test/util/MarkdownTest.java new file mode 100644 index 0000000000..12388cdc68 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/util/MarkdownTest.java @@ -0,0 +1,471 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.util; + +import net.dv8tion.jda.api.utils.MarkdownSanitizer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class MarkdownTest +{ + private MarkdownSanitizer markdown; + + @BeforeEach + void setup() + { + markdown = new MarkdownSanitizer().withStrategy(MarkdownSanitizer.SanitizationStrategy.REMOVE); + } + + @Test + void testComplex() + { + assertThat(markdown.compute("**A_B||C~~D__E`F`__~~||_**")).isEqualTo("ABCDEF"); + } + + @Test + void testTrivial() + { + assertThat(markdown.compute("")).isEqualTo(""); + assertThat(markdown.compute("Hello World ~~~~")).isEqualTo("Hello World ~~~~"); + assertThat(markdown.compute("Hello World ~~~~~")).isEqualTo("Hello World ~"); + } + + @Test + void testBold() + { + assertThat(markdown.compute("**Hello**")).isEqualTo("Hello"); + assertThat(markdown.compute("**Hello")).isEqualTo("**Hello"); + assertThat(markdown.compute("\\**Hello**")).isEqualTo("\\**Hello**"); + } + + @Test + void testItalics() + { + assertThat(markdown.compute("*Hello*")).isEqualTo("Hello"); + assertThat(markdown.compute("_Hello_")).isEqualTo("Hello"); + + assertThat(markdown.compute("*Hello")).isEqualTo("*Hello"); + assertThat(markdown.compute("_Hello")).isEqualTo("_Hello"); + + assertThat(markdown.compute("\\*Hello*")).isEqualTo("\\*Hello*"); + assertThat(markdown.compute("\\_Hello_")).isEqualTo("\\_Hello_"); + } + + @Test + void testBoldItalics() + { + assertThat(markdown.compute("***Hello***")).isEqualTo("Hello"); + assertThat(markdown.compute("***Hello")).isEqualTo("***Hello"); + assertThat(markdown.compute("\\***Hello***")).isEqualTo("\\***Hello***"); + } + + @Test + void testUnderline() + { + assertThat(markdown.compute("__Hello__")).isEqualTo("Hello"); + assertThat(markdown.compute("__Hello")).isEqualTo("__Hello"); + assertThat(markdown.compute("\\__Hello__")).isEqualTo("\\__Hello__"); + } + + @Test + void testStrike() + { + assertThat(markdown.compute("~~Hello~~")).isEqualTo("Hello"); + assertThat(markdown.compute("~~Hello")).isEqualTo("~~Hello"); + assertThat(markdown.compute("\\~~Hello~~")).isEqualTo("\\~~Hello~~"); + } + + @Test + void testSpoiler() + { + assertThat(markdown.compute("||Hello||")).isEqualTo("Hello"); + assertThat(markdown.compute("||Hello")).isEqualTo("||Hello"); + assertThat(markdown.compute("\\||Hello||")).isEqualTo("\\||Hello||"); + } + + @Test + void testMono() + { + assertThat(markdown.compute("`Hello`")).isEqualTo("Hello"); + assertThat(markdown.compute("`Hello")).isEqualTo("`Hello"); + assertThat(markdown.compute("\\`Hello`")).isEqualTo("\\`Hello`"); + + assertThat(markdown.compute("`Hello **World**`")).isEqualTo("Hello **World**"); + assertThat(markdown.compute("`Hello **World**")).isEqualTo("`Hello World"); + assertThat(markdown.compute("\\`Hello **World**`")).isEqualTo("\\`Hello World`"); + } + + @Test + void testMonoTwo() + { + assertThat(markdown.compute("``Hello``")).isEqualTo("Hello"); + assertThat(markdown.compute("``Hello")).isEqualTo("``Hello"); + assertThat(markdown.compute("\\``Hello``")).isEqualTo("\\``Hello``"); + + assertThat(markdown.compute("``Hello **World**``")).isEqualTo("Hello **World**"); + assertThat(markdown.compute("``Hello **World**")).isEqualTo("``Hello World"); + assertThat(markdown.compute("\\``Hello **World**``")).isEqualTo("\\``Hello World``"); + + assertThat(markdown.compute("``Hello `to` World``")).isEqualTo("Hello `to` World"); + assertThat(markdown.compute("``Hello `to` World")).isEqualTo("``Hello to World"); + assertThat(markdown.compute("\\``Hello `to` World``")).isEqualTo("\\``Hello to World``"); + } + + @Test + void testBlock() + { + assertThat(markdown.compute("```Hello```")).isEqualTo("Hello"); + assertThat(markdown.compute("```Hello")).isEqualTo("```Hello"); + assertThat(markdown.compute("\\```Hello```")).isEqualTo("\\```Hello```"); + + assertThat(markdown.compute("```Hello **World**```")).isEqualTo("Hello **World**"); + assertThat(markdown.compute("```Hello **World**")).isEqualTo("```Hello World"); + assertThat(markdown.compute("\\```Hello **World**```")).isEqualTo("\\```Hello World```"); + + assertThat(markdown.compute("```Hello `to` World```")).isEqualTo("Hello `to` World"); + assertThat(markdown.compute("```Hello `to` World")).isEqualTo("```Hello to World"); + assertThat(markdown.compute("\\```Hello `to` World```")).isEqualTo("\\```Hello to World```"); + + assertThat(markdown.compute("```java\nTest```")).isEqualTo("Test"); + } + + @Test + void testQuote() + { + assertThat(markdown.compute("> Hello > World")).isEqualTo("Hello > World"); + assertThat(markdown.compute("> Hello\n> World")).isEqualTo("Hello\nWorld"); + assertThat(markdown.compute(">>> Hello\nWorld")).isEqualTo("Hello\nWorld"); + assertThat(markdown.compute(">>>\nHello\nWorld")).isEqualTo("Hello\nWorld"); + assertThat(markdown.compute(">>>\nHello > World")).isEqualTo("Hello > World"); + assertThat(markdown.compute("Hello\n > World")).isEqualTo("Hello\n World"); + } +} + +class IgnoreMarkdownTest +{ + private MarkdownSanitizer markdown; + + @BeforeEach + void setup() + { + markdown = new MarkdownSanitizer().withIgnored(0xFFFFFFFF); + } + + @Test + void testComplex() + { + assertThat(markdown.compute("**A_B||C~~D__E`F`__~~||_**")).isEqualTo("**A_B||C~~D__E`F`__~~||_**"); + } + + @Test + void testBold() + { + assertThat(markdown.compute("**Hello**")).isEqualTo("**Hello**"); + assertThat(markdown.compute("**Hello")).isEqualTo("**Hello"); + } + + @Test + void testItalics() + { + assertThat(markdown.compute("*Hello*")).isEqualTo("*Hello*"); + assertThat(markdown.compute("_Hello_")).isEqualTo("_Hello_"); + + assertThat(markdown.compute("*Hello")).isEqualTo("*Hello"); + assertThat(markdown.compute("_Hello")).isEqualTo("_Hello"); + } + + @Test + void testBoldItalics() + { + assertThat(markdown.compute("***Hello***")).isEqualTo("***Hello***"); + assertThat(markdown.compute("***Hello")).isEqualTo("***Hello"); + assertThat(markdown.compute("\\***Hello***")).isEqualTo("\\***Hello***"); + } + + @Test + void testUnderline() + { + assertThat(markdown.compute("__Hello__")).isEqualTo("__Hello__"); + assertThat(markdown.compute("__Hello")).isEqualTo("__Hello"); + } + + @Test + void testStrike() + { + assertThat(markdown.compute("~~Hello~~")).isEqualTo("~~Hello~~"); + assertThat(markdown.compute("~~Hello")).isEqualTo("~~Hello"); + } + + @Test + void testSpoiler() + { + assertThat(markdown.compute("||Hello||")).isEqualTo("||Hello||"); + assertThat(markdown.compute("||Hello")).isEqualTo("||Hello"); + } + + @Test + void testMono() + { + assertThat(markdown.compute("`Hello`")).isEqualTo("`Hello`"); + assertThat(markdown.compute("`Hello")).isEqualTo("`Hello"); + + assertThat(markdown.compute("`Hello **World**`")).isEqualTo("`Hello **World**`"); + assertThat(markdown.compute("`Hello **World**")).isEqualTo("`Hello **World**"); + } + + @Test + void testMonoTwo() + { + assertThat(markdown.compute("``Hello``")).isEqualTo("``Hello``"); + assertThat(markdown.compute("``Hello")).isEqualTo("``Hello"); + + assertThat(markdown.compute("``Hello **World**``")).isEqualTo("``Hello **World**``"); + assertThat(markdown.compute("``Hello **World**")).isEqualTo("``Hello **World**"); + + assertThat(markdown.compute("``Hello `to` World``")).isEqualTo("``Hello `to` World``"); + assertThat(markdown.compute("``Hello `to` World")).isEqualTo("``Hello `to` World"); + } + + @Test + void testBlock() + { + assertThat(markdown.compute("```Hello```")).isEqualTo("```Hello```"); + assertThat(markdown.compute("```Hello")).isEqualTo("```Hello"); + + assertThat(markdown.compute("```Hello **World**```")).isEqualTo("```Hello **World**```"); + assertThat(markdown.compute("```Hello **World**")).isEqualTo("```Hello **World**"); + + assertThat(markdown.compute("```Hello `to` World```")).isEqualTo("```Hello `to` World```"); + assertThat(markdown.compute("```Hello `to` World")).isEqualTo("```Hello `to` World"); + + assertThat(markdown.compute("```java\nTest```")).isEqualTo("```java\nTest```"); + } + + @Test + void testQuote() + { + assertThat(markdown.compute("> Hello > World")).isEqualTo("> Hello > World"); + assertThat(markdown.compute("> Hello\n> World")).isEqualTo("> Hello\n> World"); + assertThat(markdown.compute(">>> Hello\nWorld")).isEqualTo(">>> Hello\nWorld"); + assertThat(markdown.compute(">>>\nHello\nWorld")).isEqualTo(">>>\nHello\nWorld"); + assertThat(markdown.compute(">>>\nHello > World")).isEqualTo(">>>\nHello > World"); + assertThat(markdown.compute("Hello\n > World")).isEqualTo("Hello\n > World"); + } +} + +class EscapeMarkdownTest +{ + private MarkdownSanitizer markdown; + + @BeforeEach + void setup() + { + markdown = new MarkdownSanitizer().withStrategy(MarkdownSanitizer.SanitizationStrategy.ESCAPE); + } + + @Test + void testComplex() + { + assertThat(markdown.compute("**A_B||C~~D__E`F`__~~||_**")).isEqualTo("\\*\\*A\\_B\\||C\\~~D\\_\\_E\\`F\\`\\_\\_\\~~\\||\\_\\*\\*"); + } + + @Test + void testBold() + { + assertThat(markdown.compute("**Hello**")).isEqualTo("\\*\\*Hello\\*\\*"); + assertThat(markdown.compute("**Hello")).isEqualTo("**Hello"); + assertThat(markdown.compute("\\**Hello**")).isEqualTo("\\**Hello**"); + } + + @Test + void testItalics() + { + assertThat(markdown.compute("*Hello*")).isEqualTo("\\*Hello\\*"); + assertThat(markdown.compute("_Hello_")).isEqualTo("\\_Hello\\_"); + + assertThat(markdown.compute("*Hello")).isEqualTo("*Hello"); + assertThat(markdown.compute("_Hello")).isEqualTo("_Hello"); + + assertThat(markdown.compute("\\*Hello*")).isEqualTo("\\*Hello*"); + assertThat(markdown.compute("\\_Hello_")).isEqualTo("\\_Hello_"); + } + + @Test + void testBoldItalics() + { + assertThat(markdown.compute("***Hello***")).isEqualTo("\\*\\*\\*Hello\\*\\*\\*"); + assertThat(markdown.compute("***Hello")).isEqualTo("***Hello"); + assertThat(markdown.compute("\\***Hello***")).isEqualTo("\\***Hello***"); + } + + @Test + void testUnderline() + { + assertThat(markdown.compute("__Hello__")).isEqualTo("\\_\\_Hello\\_\\_"); + assertThat(markdown.compute("__Hello")).isEqualTo("__Hello"); + assertThat(markdown.compute("\\__Hello__")).isEqualTo("\\__Hello__"); + } + + @Test + void testStrike() + { + assertThat(markdown.compute("~~Hello~~")).isEqualTo("\\~~Hello\\~~"); + assertThat(markdown.compute("~~Hello")).isEqualTo("~~Hello"); + assertThat(markdown.compute("\\~~Hello~~")).isEqualTo("\\~~Hello~~"); + } + + @Test + void testSpoiler() + { + assertThat(markdown.compute("||Hello||")).isEqualTo("\\||Hello\\||"); + assertThat(markdown.compute("||Hello")).isEqualTo("||Hello"); + assertThat(markdown.compute("\\||Hello||")).isEqualTo("\\||Hello||"); + } + + @Test + void testMono() + { + assertThat(markdown.compute("`Hello`")).isEqualTo("\\`Hello\\`"); + assertThat(markdown.compute("`Hello")).isEqualTo("`Hello"); + assertThat(markdown.compute("\\`Hello`")).isEqualTo("\\`Hello`"); + + assertThat(markdown.compute("`Hello **World**`")).isEqualTo("\\`Hello **World**\\`"); + assertThat(markdown.compute("`Hello **World**")).isEqualTo("`Hello \\*\\*World\\*\\*"); + assertThat(markdown.compute("\\`Hello **World**`")).isEqualTo("\\`Hello \\*\\*World\\*\\*`"); + + } + + @Test + void testMonoTwo() + { + assertThat(markdown.compute("``Hello``")).isEqualTo("\\``Hello\\``"); + assertThat(markdown.compute("``Hello")).isEqualTo("``Hello"); + assertThat(markdown.compute("\\``Hello``")).isEqualTo("\\``Hello``"); + + assertThat(markdown.compute("``Hello **World**``")).isEqualTo("\\``Hello **World**\\``"); + assertThat(markdown.compute("``Hello **World**")).isEqualTo("``Hello \\*\\*World\\*\\*"); + assertThat(markdown.compute("\\``Hello **World**``")).isEqualTo("\\``Hello \\*\\*World\\*\\*``"); + + assertThat(markdown.compute("``Hello `to` World``")).isEqualTo("\\``Hello `to` World\\``"); + assertThat(markdown.compute("``Hello `to` World")).isEqualTo("``Hello \\`to\\` World"); + assertThat(markdown.compute("\\``Hello `to` World")).isEqualTo("\\``Hello \\`to\\` World"); + } + + @Test + void testBlock() + { + assertThat(markdown.compute("```Hello```")).isEqualTo("\\```Hello\\```"); + assertThat(markdown.compute("```Hello")).isEqualTo("```Hello"); + assertThat(markdown.compute("\\```Hello")).isEqualTo("\\```Hello"); + + assertThat(markdown.compute("```Hello **World**```")).isEqualTo("\\```Hello **World**\\```"); + assertThat(markdown.compute("```Hello **World**")).isEqualTo("```Hello \\*\\*World\\*\\*"); + assertThat(markdown.compute("\\```Hello **World**")).isEqualTo("\\```Hello \\*\\*World\\*\\*"); + + assertThat(markdown.compute("```Hello `to` World```")).isEqualTo("\\```Hello `to` World\\```"); + assertThat(markdown.compute("```Hello `to` World")).isEqualTo("```Hello \\`to\\` World"); + assertThat(markdown.compute("\\```Hello `to` World")).isEqualTo("\\```Hello \\`to\\` World"); + + assertThat(markdown.compute("```java\nTest```")).isEqualTo("\\```java\nTest\\```"); + } + + @Test + void testQuote() + { + assertThat(markdown.compute("> Hello > World")).isEqualTo("\\> Hello > World"); + assertThat(markdown.compute("> Hello\n> World")).isEqualTo("\\> Hello\n\\> World"); + assertThat(markdown.compute(">>> Hello\nWorld")).isEqualTo("\\>>> Hello\nWorld"); + assertThat(markdown.compute(">>>\nHello\nWorld")).isEqualTo("\\>>>\nHello\nWorld"); + assertThat(markdown.compute(">>>\nHello > World")).isEqualTo("\\>>>\nHello > World"); + assertThat(markdown.compute("> _Hello \n> World_")).isEqualTo("\\> \\_Hello \n\\> World\\_"); + assertThat(markdown.compute("Hello\n > World")).isEqualTo("Hello\n \\> World"); + } +} + +class EscapeMarkdownAllTest +{ + @Test + void testAsterisk() + { + assertThat(MarkdownSanitizer.escape("Hello*World", true)).isEqualTo("Hello\\*World"); + assertThat(MarkdownSanitizer.escape("Hello**World", true)).isEqualTo("Hello\\*\\*World"); + assertThat(MarkdownSanitizer.escape("Hello***World", true)).isEqualTo("Hello\\*\\*\\*World"); + + assertThat(MarkdownSanitizer.escape("Hello\\*World", true)).isEqualTo("Hello\\*World"); + assertThat(MarkdownSanitizer.escape("Hello\\*\\*World", true)).isEqualTo("Hello\\*\\*World"); + assertThat(MarkdownSanitizer.escape("Hello\\*\\*\\*World", true)).isEqualTo("Hello\\*\\*\\*World"); + } + + @Test + void testUnderscore() + { + assertThat(MarkdownSanitizer.escape("Hello_World", true)).isEqualTo("Hello\\_World"); + assertThat(MarkdownSanitizer.escape("Hello__World", true)).isEqualTo("Hello\\_\\_World"); + assertThat(MarkdownSanitizer.escape("Hello___World", true)).isEqualTo("Hello\\_\\_\\_World"); + + assertThat(MarkdownSanitizer.escape("Hello\\_World", true)).isEqualTo("Hello\\_World"); + assertThat(MarkdownSanitizer.escape("Hello\\_\\_World", true)).isEqualTo("Hello\\_\\_World"); + assertThat(MarkdownSanitizer.escape("Hello\\_\\_\\_World", true)).isEqualTo("Hello\\_\\_\\_World"); + } + + @Test + void testCodeBlock() + { + assertThat(MarkdownSanitizer.escape("Hello`World", true)).isEqualTo("Hello\\`World"); + assertThat(MarkdownSanitizer.escape("Hello``World", true)).isEqualTo("Hello\\`\\`World"); + assertThat(MarkdownSanitizer.escape("Hello```World", true)).isEqualTo("Hello\\`\\`\\`World"); + + assertThat(MarkdownSanitizer.escape("Hello\\`World", true)).isEqualTo("Hello\\`World"); + assertThat(MarkdownSanitizer.escape("Hello\\`\\`World", true)).isEqualTo("Hello\\`\\`World"); + assertThat(MarkdownSanitizer.escape("Hello\\`\\`\\`World", true)).isEqualTo("Hello\\`\\`\\`World"); + } + + @Test + void testSpoiler() + { + assertThat(MarkdownSanitizer.escape("Hello||World", true)).isEqualTo("Hello\\|\\|World"); + assertThat(MarkdownSanitizer.escape("Hello|World", true)).isEqualTo("Hello|World"); + + assertThat(MarkdownSanitizer.escape("Hello\\|\\|World", true)).isEqualTo("Hello\\|\\|World"); + assertThat(MarkdownSanitizer.escape("Hello\\|World", true)).isEqualTo("Hello\\|World"); + } + + @Test + void testStrike() + { + assertThat(MarkdownSanitizer.escape("Hello~~World", true)).isEqualTo("Hello\\~\\~World"); + assertThat(MarkdownSanitizer.escape("Hello\\~\\~World", true)).isEqualTo("Hello\\~\\~World"); + } + + @Test + void testQuote() + { + assertThat(MarkdownSanitizer.escape("> Hello World", true)).isEqualTo("\\> Hello World"); + assertThat(MarkdownSanitizer.escape(">Hello World", true)).isEqualTo(">Hello World"); + assertThat(MarkdownSanitizer.escape(">>> Hello World", true)).isEqualTo("\\>\\>\\> Hello World"); + assertThat(MarkdownSanitizer.escape(">>>Hello World", true)).isEqualTo(">>>Hello World"); + assertThat(MarkdownSanitizer.escape(">>> Hello > World\n> Hello >>> World\n<@12345> > Hello\n > Hello world", true)).isEqualTo("\\>\\>\\> Hello > World\n\\> Hello >>> World\n<@12345> > Hello\n \\> Hello world"); + + assertThat(MarkdownSanitizer.escape("\\> Hello World", true)).isEqualTo("\\> Hello World"); + assertThat(MarkdownSanitizer.escape("\\>\\>\\> Hello World", true)).isEqualTo("\\>\\>\\> Hello World"); + assertThat(MarkdownSanitizer.escape("Hello > World")).isEqualTo("Hello > World"); + assertThat(MarkdownSanitizer.escape("Hello\n > World")).isEqualTo("Hello\n \\> World"); + assertThat(MarkdownSanitizer.escape("Hello\n> World")).isEqualTo("Hello\n\\> World"); + } +} diff --git a/src/test/java/net/dv8tion/jda/test/util/MarkdownUtilTest.java b/src/test/java/net/dv8tion/jda/test/util/MarkdownUtilTest.java new file mode 100644 index 0000000000..c9143bcf24 --- /dev/null +++ b/src/test/java/net/dv8tion/jda/test/util/MarkdownUtilTest.java @@ -0,0 +1,108 @@ +/* + * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.dv8tion.jda.test.util; + +import org.junit.jupiter.api.Test; + +import static net.dv8tion.jda.api.utils.MarkdownUtil.*; +import static org.assertj.core.api.Assertions.assertThat; + +public class MarkdownUtilTest +{ + @Test + void testBold() + { + assertThat(bold("Hello World")).isEqualTo("**Hello World**"); + assertThat(bold("Hello **Test** World")).isEqualTo("**Hello \\*\\*Test\\*\\* World**"); + assertThat(bold("Hello *Test* World")).isEqualTo("**Hello *Test* World**"); + } + + @Test + void testItalics() + { + assertThat(italics("Hello World")).isEqualTo("_Hello World_"); + assertThat(italics("Hello _Test_ World")).isEqualTo("_Hello \\_Test\\_ World_"); + assertThat(italics("Hello __Test__ World")).isEqualTo("_Hello __Test__ World_"); + } + + @Test + void testUnderline() + { + assertThat(underline("Hello World")).isEqualTo("__Hello World__"); + assertThat(underline("Hello __Test__ World")).isEqualTo("__Hello \\_\\_Test\\_\\_ World__"); + assertThat(underline("Hello _Test_ World")).isEqualTo("__Hello _Test_ World__"); + } + + @Test + void testMonospace() + { + assertThat(monospace("Hello World")).isEqualTo("`Hello World`"); + assertThat(monospace("Hello `Test` World")).isEqualTo("`Hello \\`Test\\` World`"); + assertThat(monospace("Hello ``Test`` World")).isEqualTo("`Hello ``Test`` World`"); + } + + @Test + void testCodeblock() + { + assertThat(codeblock("java", "Hello World")).isEqualTo("```java\nHello World```"); + assertThat(codeblock("java", "Hello ```java\nTest``` World")).isEqualTo("```java\nHello \\```java\nTest\\``` World```"); + assertThat(codeblock("java", "Hello `Test` World")).isEqualTo("```java\nHello `Test` World```"); + + assertThat(codeblock("Hello World")).isEqualTo("```Hello World```"); + assertThat(codeblock("Hello ```java\nTest``` World")).isEqualTo("```Hello \\```java\nTest\\``` World```"); + assertThat(codeblock("Hello `Test` World")).isEqualTo("```Hello `Test` World```"); + } + + @Test + void testSpoiler() + { + assertThat(spoiler("Hello World")).isEqualTo("||Hello World||"); + assertThat(spoiler("Hello ||Test|| World")).isEqualTo("||Hello \\||Test\\|| World||"); + assertThat(spoiler("Hello |Test| World")).isEqualTo("||Hello |Test| World||"); + } + + @Test + void testStrike() + { + assertThat(strike("Hello World")).isEqualTo("~~Hello World~~"); + assertThat(strike("Hello ~~Test~~ World")).isEqualTo("~~Hello \\~~Test\\~~ World~~"); + assertThat(strike("Hello ~Test~ World")).isEqualTo("~~Hello ~Test~ World~~"); + } + + @Test + void testQuote() + { + assertThat(quote("Hello World")).isEqualTo("> Hello World"); + assertThat(quote("Hello \n> Test World")).isEqualTo("> Hello \n> \\> Test World"); + assertThat(quote("Hello > Test World")).isEqualTo("> Hello > Test World"); + } + + @Test + void testQuoteBlock() + { + assertThat(quoteBlock("Hello World")).isEqualTo(">>> Hello World"); + assertThat(quoteBlock("Hello \n>>> Test World")).isEqualTo(">>> Hello \n>>> Test World"); + } + + @Test + void testMaskedLink() + { + assertThat(maskedLink("Hello", "World")).isEqualTo("[Hello](World)"); + assertThat(maskedLink("Hello", "World)")).isEqualTo("[Hello](World%29)"); + assertThat(maskedLink("Hello]", "World)")).isEqualTo("[Hello\\]](World%29)"); + } +}