Implement first unit tests

This commit is contained in:
Christian Koop 2021-10-30 14:53:05 +02:00
parent afb53ba3a0
commit b4d1f4fc60
No known key found for this signature in database
GPG Key ID: 89A8181384E010A3
9 changed files with 733 additions and 1 deletions

View File

@ -3,8 +3,13 @@ package com.songoda.core.utils;
import org.bukkit.Location;
public class LocationUtils {
/**
* Compares the block coordinates of two locations <strong>ignoring the world</strong>
*/
public static boolean isLocationMatching(Location location1, Location location2) {
return location1.getBlockX() == location2.getBlockX() && location1.getBlockY() == location2.getBlockY() && location1.getBlockZ() == location2.getBlockZ();
return location1.getBlockX() == location2.getBlockX() &&
location1.getBlockY() == location2.getBlockY() &&
location1.getBlockZ() == location2.getBlockZ();
}
public static boolean isInArea(Location l, Location pos1, Location pos2) {

View File

@ -0,0 +1,127 @@
package com.songoda.core.input;
import be.seeseemelk.mockbukkit.MockBukkit;
import be.seeseemelk.mockbukkit.MockPlugin;
import be.seeseemelk.mockbukkit.ServerMock;
import be.seeseemelk.mockbukkit.entity.PlayerMock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Disabled("BukkitMock seems to cause some troubles here, skipping for now")
class ChatPromptTest {
private final String inputMsg = "&eInput-Message";
private ServerMock server;
private MockPlugin plugin;
private PlayerMock player;
@BeforeEach
void setUp() {
this.server = MockBukkit.mock();
this.plugin = MockBukkit.createMockPlugin();
this.player = this.server.addPlayer();
}
@AfterEach
void tearDown() {
MockBukkit.unmock();
}
@Test
void showPrompt() throws InterruptedException {
List<String> chatInputs = new ArrayList<>(1);
ChatPrompt.showPrompt(this.plugin, this.player, event -> {
assertEquals(this.player, event.getPlayer());
chatInputs.add(event.getMessage());
});
this.player.chat(this.inputMsg);
Thread.sleep(1000);
// this.server.getScheduler().waitAsyncTasksFinished() // does not wait for async events
String playerReceivedMsg = this.player.nextMessage();
assertNotNull(playerReceivedMsg);
assertTrue(playerReceivedMsg.endsWith(this.inputMsg));
assertEquals(1, chatInputs.size());
assertEquals(this.inputMsg, chatInputs.get(0));
}
/* FIXME: Something is still running in the background and prevents the test from finishing */
@Disabled("Scheduling mock seems bugged, skipping for now")
@Test
void showPromptWithTimeout() {
AtomicBoolean calledOnClose = new AtomicBoolean(false);
ChatPrompt.showPrompt(this.plugin, this.player, event -> {
})
.setOnClose(() -> calledOnClose.set(true))
.setTimeOut(this.player, 40);
this.server.getScheduler().performTicks(40);
String playerReceivedMsg = this.player.nextMessage();
assertNotNull(playerReceivedMsg);
assertTrue(playerReceivedMsg.contains("timed out"));
this.server.getScheduler().performOneTick();
assertTrue(calledOnClose.get());
}
@Test
void cancelPrompt() {
AtomicBoolean calledOnCancel = new AtomicBoolean(false);
AtomicBoolean calledHandler = new AtomicBoolean(false);
ChatPrompt prompt = ChatPrompt.showPrompt(plugin, player, (event) -> calledHandler.set(true));
prompt.setOnCancel(() -> calledOnCancel.set(true));
this.server.dispatchCommand(player, "cancel");
// this.player.chat("/cancel");
// Thread.sleep(1000);
// this.server.getScheduler().waitAsyncTasksFinished() // does not wait for async events
System.out.println(this.player.nextMessage());
// assertTrue(player.nextMessage().endsWith("/cancel"));
assertTrue(calledOnCancel.get());
assertFalse(calledHandler.get());
}
@Test
void isRegistered() {
assertFalse(ChatPrompt.isRegistered(this.player));
ChatPrompt.showPrompt(this.plugin, this.player, (event) -> {
});
assertTrue(ChatPrompt.isRegistered(this.player));
}
@Test
void unregister() {
assertFalse(ChatPrompt.unregister(this.player));
ChatPrompt.showPrompt(this.plugin, this.player, (event) -> {
});
assertTrue(ChatPrompt.unregister(this.player));
assertFalse(ChatPrompt.unregister(this.player));
}
}

View File

@ -0,0 +1,60 @@
package com.songoda.core.math;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MathUtilsTest {
private final String warningMessage = "MathTest";
private final String warningMessageExpectedStart = "[" + warningMessage + "] ";
@Test
void eval() {
assertEquals(10.5 + 4, MathUtils.eval("10.5 + 4"));
assertEquals(10.5 - 5, MathUtils.eval("10.5 - 5"));
assertEquals(10 * 4, MathUtils.eval("10 * 4"));
assertEquals(10.5 / .5, MathUtils.eval("10.5 / .5"));
assertEquals(20 - +4, MathUtils.eval("20 - +4"));
assertEquals(Math.pow(10, 2), MathUtils.eval("10^2"));
assertEquals(Math.pow(-10, 2), MathUtils.eval("(-10)^2"));
assertEquals(-Math.pow(10, 2), MathUtils.eval("-10^2"));
assertEquals(Math.sqrt(49), MathUtils.eval("sqrt(49)"));
assertEquals(Math.sin(Math.toRadians(90)), MathUtils.eval("sin(90)"));
assertEquals(Math.cos(Math.toRadians(90)), MathUtils.eval("cos(90)"));
assertEquals(Math.tan(Math.toRadians(89650)), MathUtils.eval("tan(89650)"));
assertEquals(Integer.MAX_VALUE + (long) Integer.MAX_VALUE,
MathUtils.eval(Integer.MAX_VALUE + "+" + Integer.MAX_VALUE));
}
@Test
void evalWithCommaAsDecimalSeparator() {
Exception ex = assertThrowsExactly(RuntimeException.class, () -> MathUtils.eval("1,0", warningMessage));
assertTrue(ex.getMessage().startsWith(warningMessageExpectedStart),
() -> "'" + ex.getMessage() + "' does not start with '" + warningMessageExpectedStart + "'");
assertTrue(ex.getMessage().contains("Unexpected: "));
}
@Test
void evalWithUnsupportedSyntax() {
Exception ex = assertThrowsExactly(RuntimeException.class, () -> MathUtils.eval("!2", warningMessage));
assertTrue(ex.getMessage().startsWith(warningMessageExpectedStart),
() -> "'" + ex.getMessage() + "' does not start with '" + warningMessageExpectedStart + "'");
assertTrue(ex.getMessage().contains("Unexpected: "));
}
@Test
void evalWithUnsupportedFunction() {
Exception ex = assertThrowsExactly(RuntimeException.class, () -> MathUtils.eval("acos(90)", warningMessage));
assertTrue(ex.getMessage().startsWith(warningMessageExpectedStart),
() -> "'" + ex.getMessage() + "' does not start with '" + warningMessageExpectedStart + "'");
assertTrue(ex.getMessage().contains("Unknown function: "));
}
}

View File

@ -0,0 +1,29 @@
package com.songoda.core.utils;
import be.seeseemelk.mockbukkit.WorldMock;
import org.bukkit.Location;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LocationUtilsTest {
@Test
void isLocationMatching() {
assertTrue(LocationUtils.isLocationMatching(
new Location(null, 10, 20, 30),
new Location(new WorldMock(), 10.25, 20.5, 30.75)
));
assertFalse(LocationUtils.isLocationMatching(
new Location(null, 10, 20, 30),
new Location(new WorldMock(), -10.25, 20.5, 30.75)
));
}
@Disabled("Test not yet implemented")
@Test
void isInArea() {
}
}

View File

@ -0,0 +1,64 @@
package com.songoda.core.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class NumberUtilsTest {
@Test
void formatEconomy() {
assertEquals("$1,999.99", NumberUtils.formatEconomy('$', 1999.99));
}
@Test
void formatNumber() {
assertEquals("1,999.99", NumberUtils.formatNumber(1999.99));
assertEquals("1,999,999.99", NumberUtils.formatNumber(1999999.99));
}
@Test
void formatWithSuffix() {
assertEquals("100", NumberUtils.formatWithSuffix(100));
assertEquals("150,5M", NumberUtils.formatWithSuffix(150_500_000));
assertEquals("150,5M", NumberUtils.formatWithSuffix(150_500_999));
assertEquals("151,0M", NumberUtils.formatWithSuffix(150_999_999));
assertEquals("150,5G", NumberUtils.formatWithSuffix(150_500_000_000L));
assertEquals("150,5T", NumberUtils.formatWithSuffix(150_500_000_000_000L));
assertEquals("150,5P", NumberUtils.formatWithSuffix(150_500_000_000_000_000L));
assertEquals("1,5E", NumberUtils.formatWithSuffix(150_500_000_000_000_000_0L));
assertEquals("9,2E", NumberUtils.formatWithSuffix(Long.MAX_VALUE));
assertEquals(String.valueOf(Long.MIN_VALUE), NumberUtils.formatWithSuffix(Long.MIN_VALUE));
}
@Test
void isInt() {
assertFalse(NumberUtils.isInt(null));
assertFalse(NumberUtils.isInt(""));
assertTrue(NumberUtils.isInt("100"));
assertTrue(NumberUtils.isInt("-100"));
assertTrue(NumberUtils.isInt("+100"));
assertFalse(NumberUtils.isInt("100.0"));
assertFalse(NumberUtils.isInt("Int"));
}
@Test
void isNumeric() {
assertFalse(NumberUtils.isNumeric(null));
assertFalse(NumberUtils.isNumeric(""));
assertTrue(NumberUtils.isNumeric("100"));
assertTrue(NumberUtils.isNumeric("100.0"));
assertTrue(NumberUtils.isNumeric("-100.0"));
assertTrue(NumberUtils.isNumeric("+100.0"));
assertFalse(NumberUtils.isNumeric("Numeric"));
}
}

View File

@ -0,0 +1,230 @@
package com.songoda.core.utils;
import be.seeseemelk.mockbukkit.MockBukkit;
import be.seeseemelk.mockbukkit.ServerMock;
import be.seeseemelk.mockbukkit.entity.PlayerMock;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PlayerUtilsTest {
private ServerMock server;
@BeforeEach
void setUp() {
this.server = MockBukkit.mock();
}
@AfterEach
void tearDown() {
MockBukkit.unmock();
this.server = null;
}
@Test
void sendMessages() {
String[] messages = new String[] {"First message", "Second message"};
PlayerMock player = this.server.addPlayer();
PlayerUtils.sendMessages(player, messages);
PlayerUtils.sendMessages(player, Arrays.asList(messages));
for (int i = 0; i < 2; ++i) {
assertEquals(messages[0], player.nextMessage());
assertEquals(messages[1], player.nextMessage());
}
assertNull(player.nextMessage());
}
@Disabled("Player#hidePlayer can currently not be mocked")
@Test
void getVisiblePlayerNames() {
PlayerMock player = this.server.addPlayer("BasePlayer");
PlayerMock visiblePlayer = this.server.addPlayer("VisiblePlayer");
PlayerMock hiddenPlayer = this.server.addPlayer("HiddenPlayer");
player.hidePlayer(MockBukkit.createMockPlugin(), hiddenPlayer);
List<String> result = PlayerUtils.getVisiblePlayerNames(player, null);
assertTrue(result.contains(visiblePlayer.getName()));
assertFalse(result.contains(hiddenPlayer.getName()));
assertFalse(result.contains(player.getName()));
assertEquals(0, PlayerUtils.getVisiblePlayerNames(player, "_").size());
}
@Disabled("Player#hidePlayer can currently not be mocked")
@Test
void getVisiblePlayerDisplayNames() {
PlayerMock player = this.server.addPlayer("BasePlayer");
PlayerMock visiblePlayer = this.server.addPlayer("VisiblePlayer");
PlayerMock hiddenPlayer = this.server.addPlayer("HiddenPlayer");
player.setDisplayName("Base");
visiblePlayer.setDisplayName("Visible");
hiddenPlayer.setDisplayName("Hidden");
player.hidePlayer(MockBukkit.createMockPlugin(), hiddenPlayer);
List<String> result = PlayerUtils.getVisiblePlayerDisplayNames(player, null);
assertTrue(result.contains(visiblePlayer.getDisplayName()));
assertFalse(result.contains(hiddenPlayer.getDisplayName()));
assertFalse(result.contains(player.getDisplayName()));
assertEquals(0, PlayerUtils.getVisiblePlayerDisplayNames(player, "_").size());
}
@Disabled("Player#hidePlayer can currently not be mocked")
@Test
void getVisiblePlayers() {
PlayerMock player = this.server.addPlayer("BasePlayer");
PlayerMock visiblePlayer = this.server.addPlayer("VisiblePlayer");
PlayerMock hiddenPlayer = this.server.addPlayer("HiddenPlayer");
player.hidePlayer(MockBukkit.createMockPlugin(), hiddenPlayer);
List<Player> result = PlayerUtils.getVisiblePlayers(player, null);
assertTrue(result.contains(visiblePlayer));
assertFalse(result.contains(hiddenPlayer));
assertFalse(result.contains(player));
assertEquals(0, PlayerUtils.getVisiblePlayers(player, "_").size());
}
@Test
void getAllPlayers() {
PlayerMock basePlayer = this.server.addPlayer("BasePlayer");
this.server.addPlayer("Player_1");
this.server.addPlayer("Player_2");
this.server.addPlayer("Player3");
List<String> result = PlayerUtils.getAllPlayers(basePlayer, "");
assertEquals(3, result.size());
assertFalse(result.contains(basePlayer.getName()));
assertTrue(PlayerUtils.getAllPlayers(basePlayer, "_").isEmpty());
assertEquals(0, PlayerUtils.getAllPlayers(basePlayer, "Player_").size());
}
@Test
void getAllPlayersDisplay() {
PlayerMock basePlayer = this.server.addPlayer("BasePlayer");
this.server.addPlayer("Player_1");
this.server.addPlayer("Player_2");
this.server.addPlayer("Player3");
List<String> result = PlayerUtils.getAllPlayersDisplay(basePlayer, "");
assertEquals(3, result.size());
assertFalse(result.contains(basePlayer.getDisplayName()));
assertEquals(2, PlayerUtils.getAllPlayersDisplay(basePlayer, "Player_").size());
assertEquals(0, PlayerUtils.getAllPlayersDisplay(basePlayer, "_").size());
}
@Test
void findPlayer() {
Player p3 = this.server.addPlayer("Player");
Player p1 = this.server.addPlayer("Player_1");
Player p2 = this.server.addPlayer("_Player_2");
p1.setDisplayName("p1");
p2.setDisplayName("p2");
p3.setDisplayName("p3");
assertEquals(p1, PlayerUtils.findPlayer("Player_"));
assertEquals(p2, PlayerUtils.findPlayer("_Play"));
assertEquals(p3, PlayerUtils.findPlayer("Player"));
assertEquals(p3, PlayerUtils.findPlayer("p"));
assertEquals(p1, PlayerUtils.findPlayer("p1"));
assertEquals(p2, PlayerUtils.findPlayer("p2"));
assertEquals(p3, PlayerUtils.findPlayer("p3"));
}
@Test
void getRandomPlayer() {
assertNull(PlayerUtils.getRandomPlayer());
for (int i = 0; i < 10; ++i) {
this.server.addPlayer(String.valueOf(i));
}
Set<Player> returnedPlayers = new HashSet<>();
for (int i = 0; i < 50; ++i) {
if (returnedPlayers.size() >= 5) {
break;
}
returnedPlayers.add(PlayerUtils.getRandomPlayer());
}
assertTrue(returnedPlayers.size() >= 5);
}
@Test
void giveItem() {
Player player = this.server.addPlayer();
PlayerUtils.giveItem(player, new ItemStack(Material.STONE));
assertTrue(player.getInventory().contains(Material.STONE, 1));
PlayerUtils.giveItem(player, new ItemStack(Material.GRASS_BLOCK), new ItemStack(Material.GRASS_BLOCK));
assertTrue(player.getInventory().contains(Material.GRASS_BLOCK, 2));
PlayerUtils.giveItem(player, Arrays.asList(new ItemStack(Material.WHEAT_SEEDS), new ItemStack(Material.WHEAT_SEEDS)));
assertTrue(player.getInventory().contains(Material.WHEAT_SEEDS, 2));
}
@Test
void giveItemOnFullInventory() {
PlayerMock player = this.server.addPlayer();
fillInventory(player);
int entityCount = this.server.getEntities().size();
PlayerUtils.giveItem(player, new ItemStack(Material.STONE));
assertEquals(entityCount + 1, this.server.getEntities().size());
entityCount = this.server.getEntities().size();
PlayerUtils.giveItem(player, new ItemStack(Material.GRASS_BLOCK), new ItemStack(Material.GRASS_BLOCK));
assertEquals(entityCount + 2, this.server.getEntities().size());
entityCount = this.server.getEntities().size();
PlayerUtils.giveItem(player, Arrays.asList(new ItemStack(Material.WHEAT_SEEDS), new ItemStack(Material.WHEAT_SEEDS), new ItemStack(Material.WHEAT_SEEDS)));
assertEquals(entityCount + 3, this.server.getEntities().size());
}
@Disabled("Test is incomplete")
@Test
void getNumberFromPermission() {
Player player = this.server.addPlayer();
assertEquals(-1, PlayerUtils.getNumberFromPermission(player, "example.plugin.feature", -1));
}
private void fillInventory(Player player) {
ItemStack[] contents = new ItemStack[player.getInventory().getContents().length];
for (int i = 0; i < contents.length; ++i) {
contents[i] = new ItemStack(Material.BARRIER);
}
player.getInventory().setContents(contents);
}
}

View File

@ -0,0 +1,40 @@
package com.songoda.core.utils;
import org.bukkit.block.BlockFace;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RotationUtilsTest {
@Test
void faceToYaw() {
assertEquals(180, RotationUtils.faceToYaw(BlockFace.NORTH));
assertEquals(-90, RotationUtils.faceToYaw(BlockFace.EAST));
assertEquals(0, RotationUtils.faceToYaw(BlockFace.SOUTH));
assertEquals(90, RotationUtils.faceToYaw(BlockFace.WEST));
assertEquals(0, RotationUtils.faceToYaw(BlockFace.UP));
assertEquals(0, RotationUtils.faceToYaw(BlockFace.DOWN));
}
@Test
void yawToFace() {
assertEquals(BlockFace.NORTH, RotationUtils.yawToFace(180 - 25));
assertEquals(BlockFace.NORTH, RotationUtils.yawToFace(180));
assertEquals(BlockFace.NORTH, RotationUtils.yawToFace(180 + 25));
assertEquals(BlockFace.EAST, RotationUtils.yawToFace(-90 - 25));
assertEquals(BlockFace.EAST, RotationUtils.yawToFace(-90));
assertEquals(BlockFace.EAST, RotationUtils.yawToFace(-90 + 25));
assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(-25));
assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(0));
assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(25));
assertEquals(BlockFace.WEST, RotationUtils.yawToFace(90 - 25));
assertEquals(BlockFace.WEST, RotationUtils.yawToFace(90));
assertEquals(BlockFace.WEST, RotationUtils.yawToFace(90 + 25));
assertEquals(BlockFace.SOUTH, RotationUtils.yawToFace(Float.MAX_VALUE));
}
}

View File

@ -0,0 +1,129 @@
package com.songoda.core.utils;
import org.bukkit.ChatColor;
import org.junit.jupiter.api.Test;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class TextUtilsTest {
@Test
void formatText() {
final String testString = "hello&6 world &r:)";
final String testStringResult = "hello" + ChatColor.COLOR_CHAR + "6 world " + ChatColor.COLOR_CHAR + "r:)";
assertEquals("", TextUtils.formatText((String) null));
assertEquals("", TextUtils.formatText(""));
assertEquals(testStringResult, TextUtils.formatText(testString));
assertEquals(Arrays.asList(testStringResult.split(" ")), TextUtils.formatText(testString.split(" ")));
assertEquals(Arrays.asList(testStringResult.split(" ")), TextUtils.formatText(Arrays.asList(testString.split(" "))));
}
@Test
void formatTextCapitalize() {
assertEquals("Hello§6§l world §r:)", TextUtils.formatText("hello&6&l world &r:)", true));
// assertEquals("§2Hello§6§l world §r:)", TextUtils.formatText("&2hello&6&l world &r:)", true)); // FIXME: https://github.com/songoda/SongodaCore/issues/26
}
@Test
void wrap() {
assertEquals(Arrays.asList("Lorem ipsum dolor sit amet,", " consectetuer adipiscing elit.",
" Aenean commodo ligula eget", " dolor. Aenean massa. Cum",
" sociis natoque penatibus", " et magnis dis parturient",
" montes, nascetur ridiculus", " mus."),
TextUtils.wrap("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor." +
" Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus."));
assertEquals(Collections.singletonList("§6Hello world!"), TextUtils.wrap("6", "Hello world!"));
}
@Test
void convertToInvisibleLoreString() {
assertEquals("", TextUtils.convertToInvisibleLoreString(null));
assertEquals("", TextUtils.convertToInvisibleLoreString(""));
assertEquals("§;§§§;§6§;§H§;§e§;§l§;§l§;§o§;§ §;§w§;§o§;§r§;§l§;§d", TextUtils.convertToInvisibleLoreString("§6Hello world"));
assertEquals("§;§&§;§6§;§H§;§e§;§l§;§l§;§o§;§ §;§w§;§o§;§r§;§l§;§d", TextUtils.convertToInvisibleLoreString("&6Hello world"));
}
@Test
void convertToInvisibleString() {
assertEquals("", TextUtils.convertToInvisibleString(null));
assertEquals("", TextUtils.convertToInvisibleString(""));
assertEquals("§§§6§H§e§l§l§o§ §w§o§r§l§d", TextUtils.convertToInvisibleString("§6Hello world"));
assertEquals("§&§6§H§e§l§l§o§;§w§o§r§l§d", TextUtils.convertToInvisibleString("&6Hello;world"));
}
@Test
void convertFromInvisibleString() {
assertEquals("", TextUtils.convertFromInvisibleString(null));
assertEquals("", TextUtils.convertFromInvisibleString(""));
assertEquals("§;§§§;§6§;§H§;§e§;§l§;§l§;§o§;§ §;§w§;§o§;§r§;§l§;§d", TextUtils.convertToInvisibleLoreString("§6Hello world"));
assertEquals("6Helloworld", TextUtils.convertFromInvisibleString("§§§6§H§e§l§l§o§;§w§o§r§l§d"));
assertEquals("&6Hello world", TextUtils.convertFromInvisibleString("§&§6§H§e§l§l§o§ §w§o§r§l§d"));
}
@Test
void detectCharset() throws IOException {
byte[] asciiString = "Hello world!\n".getBytes(StandardCharsets.US_ASCII);
byte[] utf8String = "\uD83D\uDE43 Hello world!\n".getBytes(StandardCharsets.UTF_8);
byte[] loremIpsum = ("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n" +
"\n" +
"Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n" +
"\n" +
"In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.\n" +
"\n" +
"Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum.\n" +
"\n" +
"Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.\n" +
"\n" +
"Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,").getBytes(StandardCharsets.UTF_8);
byte[] utf16LeBom = new byte[] {(byte) 0xFF, (byte) 0xFE, 'a', 'b', 'c'};
byte[] utf16BeBom = new byte[] {(byte) 0xFE, (byte) 0xFF, 'a', 'b', 'c'};
byte[] utf8Bom = new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 'a', 'b', 'c'};
assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(asciiString, asciiString.length, null));
assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(utf8String, utf8String.length, null));
assertEquals(StandardCharsets.UTF_16LE, TextUtils.detectCharset(utf16LeBom, utf16LeBom.length, null));
assertEquals(StandardCharsets.UTF_16BE, TextUtils.detectCharset(utf16BeBom, utf16BeBom.length, null));
assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(utf8Bom, utf8Bom.length, null));
Path tmpFilePath = Files.createTempFile(null, null);
File tmpFile = tmpFilePath.toFile();
tmpFile.deleteOnExit();
try (OutputStream writer = new FileOutputStream(tmpFile)) {
for (int i = 0; i < 5; ++i) {
writer.write(loremIpsum);
}
writer.flush();
}
assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(tmpFile, null));
Files.deleteIfExists(tmpFilePath);
assertNull(TextUtils.detectCharset(tmpFile, null));
try (BufferedInputStream tmpIn = new BufferedInputStream(new ByteArrayInputStream(loremIpsum))) {
assertEquals(StandardCharsets.UTF_8, TextUtils.detectCharset(tmpIn, null));
}
}
}

View File

@ -0,0 +1,48 @@
package com.songoda.core.utils;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TimeUtilsTest {
@Test
void makeReadable() {
assertEquals("", TimeUtils.makeReadable(null));
assertEquals("20m", TimeUtils.makeReadable(TimeUnit.MINUTES.toMillis(20)));
assertEquals("20m 10s", TimeUtils.makeReadable(
TimeUnit.MINUTES.toMillis(20) + TimeUnit.SECONDS.toMillis(10)));
assertEquals("10d 2h 32m 12s", TimeUtils.makeReadable(
TimeUnit.DAYS.toMillis(10) +
TimeUnit.HOURS.toMillis(2) +
TimeUnit.MINUTES.toMillis(32) +
TimeUnit.SECONDS.toMillis(12) +
100
));
}
@Test
void parseTime() {
assertEquals(TimeUnit.MINUTES.toMillis(20), TimeUtils.parseTime("20m"));
assertEquals(TimeUnit.MINUTES.toMillis(20) + TimeUnit.SECONDS.toMillis(10), TimeUtils.parseTime("20m 10s"));
assertEquals(TimeUnit.DAYS.toMillis(10) +
TimeUnit.HOURS.toMillis(2) +
TimeUnit.MINUTES.toMillis(32) +
TimeUnit.SECONDS.toMillis(12),
TimeUtils.parseTime("10d 2h 32m 12s"));
assertEquals(TimeUnit.MINUTES.toMillis(100) +
TimeUnit.SECONDS.toMillis(100),
TimeUtils.parseTime("100m 100s"));
assertEquals(TimeUnit.MINUTES.toMillis(100) +
TimeUnit.SECONDS.toMillis(100),
TimeUtils.parseTime("100m100s"));
assertEquals(0, TimeUtils.parseTime("10?"));
assertEquals(0, TimeUtils.parseTime("10xX"));
}
}