Compare commits

..

6 Commits

Author SHA1 Message Date
ec963ef691 new event TabCompleteRequestEvent and deprecate TabCompleteEvent 2023-09-22 00:19:41 +02:00
317844dd80 Add CommandsDeclareEvent to declare commands with brigadier API 2023-09-22 00:19:33 +02:00
e47394e10d Server branding now includes the backend server name 2023-09-21 23:55:32 +02:00
3ba71310b8 Multi-session with same Minecraft account with specific permission
Players with permission bungeecord.multiple_connect can have multiple connections with the same Minecraft account.
The UUID and player name is altered to avoid collision with other player:
UUID : xxxxxxxx-xxxx-VIxx-xxxx-xxxxxxxxxxxx
- The UUID version (V above) is now the provided version + 8 (for online player, it is 4, so it becomes C).
- The I digit will follow the index of the duplicated player : first duplicated player is 1, second one is 2.
- The name of the player will be the real player name, followed by the character "." (dot) followed by the duplication index.

Bedrock accounts connected using the Floodgate plugin will not be able to connect multiple times due to the risk of xUID collision.
2023-09-21 23:55:32 +02:00
fe2baa08b5 Change projet configuration and POM for Pandacube 2023-09-21 23:55:32 +02:00
fb1c808d0e Remove modules and startup delay
We don’t need them for Pandacube
2023-09-21 23:55:29 +02:00
26 changed files with 419 additions and 463 deletions

View File

@ -1,13 +1,12 @@
package net.md_5.bungee.api; package net.md_5.bungee.api;
import static org.junit.jupiter.api.Assertions.*;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.Collection; import java.util.Collection;
import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ServerConnectEvent; import net.md_5.bungee.api.event.ServerConnectEvent;
import org.junit.jupiter.api.Test; import org.junit.Test;
public class ServerConnectRequestTest public class ServerConnectRequestTest
{ {
@ -79,15 +78,15 @@ public class ServerConnectRequestTest
} }
}; };
@Test @Test(expected = NullPointerException.class)
public void testNullTarget() public void testNullTarget()
{ {
assertThrows( NullPointerException.class, () -> ServerConnectRequest.builder().target( null ).reason( ServerConnectEvent.Reason.JOIN_PROXY ).build() ); ServerConnectRequest.builder().target( null ).reason( ServerConnectEvent.Reason.JOIN_PROXY ).build();
} }
@Test @Test(expected = NullPointerException.class)
public void testNullReason() public void testNullReason()
{ {
assertThrows( NullPointerException.class, () -> ServerConnectRequest.builder().target( DUMMY_INFO ).reason( null ).build() ); ServerConnectRequest.builder().target( DUMMY_INFO ).reason( null ).build();
} }
} }

View File

@ -1,38 +1,63 @@
package net.md_5.bungee.util; package net.md_5.bungee.util;
import static org.junit.jupiter.api.Assertions.*;
import io.netty.channel.unix.DomainSocketAddress; import io.netty.channel.unix.DomainSocketAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.stream.Stream; import java.util.Arrays;
import java.util.Collection;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import net.md_5.bungee.Util; import net.md_5.bungee.Util;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.Assert;
import org.junit.jupiter.params.provider.Arguments; import org.junit.Test;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RequiredArgsConstructor @RequiredArgsConstructor
@RunWith(Parameterized.class)
public class AddressParseTest public class AddressParseTest
{ {
public static Stream<Arguments> data() @Parameters
public static Collection<Object[]> data()
{ {
return Stream.of( return Arrays.asList( new Object[][]
Arguments.of( "127.0.0.1", "127.0.0.1", Util.DEFAULT_PORT ), {
Arguments.of( "127.0.0.1:1337", "127.0.0.1", 1337 ), {
Arguments.of( "[::1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT ), "127.0.0.1", "127.0.0.1", Util.DEFAULT_PORT
Arguments.of( "[0:0:0:0::1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT ), },
Arguments.of( "[0:0:0:0:0:0:0:1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT ), {
Arguments.of( "[::1]:1337", "0:0:0:0:0:0:0:1", 1337 ), "127.0.0.1:1337", "127.0.0.1", 1337
Arguments.of( "[0:0:0:0::1]:1337", "0:0:0:0:0:0:0:1", 1337 ), },
Arguments.of( "[0:0:0:0:0:0:0:1]:1337", "0:0:0:0:0:0:0:1", 1337 ), {
Arguments.of( "unix:///var/run/bungee.sock", "/var/run/bungee.sock", -1 ) "[::1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT
); },
{
"[0:0:0:0::1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT
},
{
"[0:0:0:0:0:0:0:1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT
},
{
"[::1]:1337", "0:0:0:0:0:0:0:1", 1337
},
{
"[0:0:0:0::1]:1337", "0:0:0:0:0:0:0:1", 1337
},
{
"[0:0:0:0:0:0:0:1]:1337", "0:0:0:0:0:0:0:1", 1337
},
{
"unix:///var/run/bungee.sock", "/var/run/bungee.sock", -1
}
} );
} }
private final String line;
private final String host;
private final int port;
@ParameterizedTest @Test
@MethodSource("data") public void test()
public void test(String line, String host, int port)
{ {
SocketAddress parsed = Util.getAddr( line ); SocketAddress parsed = Util.getAddr( line );
@ -40,14 +65,14 @@ public class AddressParseTest
{ {
InetSocketAddress tcp = (InetSocketAddress) parsed; InetSocketAddress tcp = (InetSocketAddress) parsed;
assertEquals( host, tcp.getHostString() ); Assert.assertEquals( host, tcp.getHostString() );
assertEquals( port, tcp.getPort() ); Assert.assertEquals( port, tcp.getPort() );
} else if ( parsed instanceof DomainSocketAddress ) } else if ( parsed instanceof DomainSocketAddress )
{ {
DomainSocketAddress unix = (DomainSocketAddress) parsed; DomainSocketAddress unix = (DomainSocketAddress) parsed;
assertEquals( host, unix.path() ); Assert.assertEquals( host, unix.path() );
assertEquals( -1, port ); Assert.assertEquals( -1, port );
} else } else
{ {
throw new AssertionError( "Unknown socket " + parsed ); throw new AssertionError( "Unknown socket " + parsed );

View File

@ -1,7 +1,7 @@
package net.md_5.bungee.util; package net.md_5.bungee.util;
import static org.junit.jupiter.api.Assertions.*; import org.junit.Assert;
import org.junit.jupiter.api.Test; import org.junit.Test;
public class CaseInsensitiveTest public class CaseInsensitiveTest
{ {
@ -13,12 +13,12 @@ public class CaseInsensitiveTest
CaseInsensitiveMap<Object> map = new CaseInsensitiveMap<>(); CaseInsensitiveMap<Object> map = new CaseInsensitiveMap<>();
map.put( "FOO", obj ); map.put( "FOO", obj );
assertTrue( map.contains( "foo" ) ); // Assert that contains is case insensitive Assert.assertTrue( map.contains( "foo" ) ); // Assert that contains is case insensitive
assertTrue( map.entrySet().iterator().next().getKey().equals( "FOO" ) ); // Assert that case is preserved Assert.assertTrue( map.entrySet().iterator().next().getKey().equals( "FOO" ) ); // Assert that case is preserved
// Assert that remove is case insensitive // Assert that remove is case insensitive
map.remove( "FoO" ); map.remove( "FoO" );
assertFalse( map.contains( "foo" ) ); Assert.assertFalse( map.contains( "foo" ) );
} }
@Test @Test
@ -27,8 +27,8 @@ public class CaseInsensitiveTest
CaseInsensitiveSet set = new CaseInsensitiveSet(); CaseInsensitiveSet set = new CaseInsensitiveSet();
set.add( "FOO" ); set.add( "FOO" );
assertTrue( set.contains( "foo" ) ); // Assert that contains is case insensitive Assert.assertTrue( set.contains( "foo" ) ); // Assert that contains is case insensitive
set.remove( "FoO" ); set.remove( "FoO" );
assertFalse( set.contains( "foo" ) ); // Assert that remove is case insensitive Assert.assertFalse( set.contains( "foo" ) ); // Assert that remove is case insensitive
} }
} }

View File

@ -1,9 +1,9 @@
package net.md_5.bungee.util; package net.md_5.bungee.util;
import static org.junit.jupiter.api.Assertions.*;
import java.util.UUID; import java.util.UUID;
import net.md_5.bungee.Util; import net.md_5.bungee.Util;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class UUIDTest public class UUIDTest
{ {
@ -13,7 +13,7 @@ public class UUIDTest
{ {
UUID uuid = UUID.fromString( "af74a02d-19cb-445b-b07f-6866a861f783" ); UUID uuid = UUID.fromString( "af74a02d-19cb-445b-b07f-6866a861f783" );
UUID uuid1 = Util.getUUID( "af74a02d19cb445bb07f6866a861f783" ); UUID uuid1 = Util.getUUID( "af74a02d19cb445bb07f6866a861f783" );
assertEquals( uuid, uuid1 ); Assert.assertEquals( uuid, uuid1 );
} }
@Test @Test
@ -23,7 +23,7 @@ public class UUIDTest
{ {
UUID expected = UUID.randomUUID(); UUID expected = UUID.randomUUID();
UUID actual = Util.getUUID( expected.toString().replace( "-", "" ) ); UUID actual = Util.getUUID( expected.toString().replace( "-", "" ) );
assertEquals( expected, actual, "Could not parse UUID " + expected ); Assert.assertEquals( "Could not parse UUID " + expected, expected, actual );
} }
} }
} }

View File

@ -1,6 +1,5 @@
package net.md_5.bungee.api.chat; package net.md_5.bungee.api.chat;
import static org.junit.jupiter.api.Assertions.*;
import java.awt.Color; import java.awt.Color;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -11,7 +10,8 @@ import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.hover.content.Item; import net.md_5.bungee.api.chat.hover.content.Item;
import net.md_5.bungee.api.chat.hover.content.Text; import net.md_5.bungee.api.chat.hover.content.Text;
import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.chat.ComponentSerializer;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class ComponentsTest public class ComponentsTest
{ {
@ -20,14 +20,14 @@ public class ComponentsTest
{ {
String json = ComponentSerializer.toString( components ); String json = ComponentSerializer.toString( components );
BaseComponent[] parsed = ComponentSerializer.parse( json ); BaseComponent[] parsed = ComponentSerializer.parse( json );
assertEquals( TextComponent.toLegacyText( parsed ), TextComponent.toLegacyText( components ) ); Assert.assertEquals( TextComponent.toLegacyText( parsed ), TextComponent.toLegacyText( components ) );
} }
public static void testDissembleReassemble(BaseComponent component) public static void testDissembleReassemble(BaseComponent component)
{ {
String json = ComponentSerializer.toString( component ); String json = ComponentSerializer.toString( component );
BaseComponent[] parsed = ComponentSerializer.parse( json ); BaseComponent[] parsed = ComponentSerializer.parse( json );
assertEquals( TextComponent.toLegacyText( parsed ), TextComponent.toLegacyText( component ) ); Assert.assertEquals( TextComponent.toLegacyText( parsed ), TextComponent.toLegacyText( component ) );
} }
public static void testAssembleDissemble(String json, boolean modern) public static void testAssembleDissemble(String json, boolean modern)
@ -35,11 +35,11 @@ public class ComponentsTest
if ( modern ) if ( modern )
{ {
BaseComponent deserialized = ComponentSerializer.deserialize( json ); BaseComponent deserialized = ComponentSerializer.deserialize( json );
assertEquals( json, ComponentSerializer.toString( deserialized ) ); Assert.assertEquals( json, ComponentSerializer.toString( deserialized ) );
} else } else
{ {
BaseComponent[] parsed = ComponentSerializer.parse( json ); BaseComponent[] parsed = ComponentSerializer.parse( json );
assertEquals( json, ComponentSerializer.toString( parsed ) ); Assert.assertEquals( json, ComponentSerializer.toString( parsed ) );
} }
} }
@ -69,7 +69,7 @@ public class ComponentsTest
json = "{\"extra\":[{\"text\":\"[\"},{\"extra\":[{\"translate\":\"block.minecraft.dirt\"}],\"text\":\"\"},{\"text\":\"]\"}],\"hoverEvent\":{\"action\":\"show_item\",\"value\":[" + hoverVal + "]},\"text\":\"\"}"; json = "{\"extra\":[{\"text\":\"[\"},{\"extra\":[{\"translate\":\"block.minecraft.dirt\"}],\"text\":\"\"},{\"text\":\"]\"}],\"hoverEvent\":{\"action\":\"show_item\",\"value\":[" + hoverVal + "]},\"text\":\"\"}";
components = ComponentSerializer.parse( json ); components = ComponentSerializer.parse( json );
Text contentText = ( (Text) components[0].getHoverEvent().getContents().get( 0 ) ); Text contentText = ( (Text) components[0].getHoverEvent().getContents().get( 0 ) );
assertEquals( hoverVal, ComponentSerializer.toString( (BaseComponent[]) contentText.getValue() ) ); Assert.assertEquals( hoverVal, ComponentSerializer.toString( (BaseComponent[]) contentText.getValue() ) );
testDissembleReassemble( components ); testDissembleReassemble( components );
////////// //////////
TextComponent component1 = new TextComponent( "HoverableText" ); TextComponent component1 = new TextComponent( "HoverableText" );
@ -80,10 +80,10 @@ public class ComponentsTest
json = ComponentSerializer.toString( component1 ); json = ComponentSerializer.toString( component1 );
components = ComponentSerializer.parse( json ); components = ComponentSerializer.parse( json );
Item parsedContentItem = ( (Item) components[0].getHoverEvent().getContents().get( 0 ) ); Item parsedContentItem = ( (Item) components[0].getHoverEvent().getContents().get( 0 ) );
assertEquals( contentItem, parsedContentItem ); Assert.assertEquals( contentItem, parsedContentItem );
assertEquals( contentItem.getCount(), parsedContentItem.getCount() ); Assert.assertEquals( contentItem.getCount(), parsedContentItem.getCount() );
assertEquals( contentItem.getId(), parsedContentItem.getId() ); Assert.assertEquals( contentItem.getId(), parsedContentItem.getId() );
assertEquals( nbt, parsedContentItem.getTag().getNbt() ); Assert.assertEquals( nbt, parsedContentItem.getTag().getNbt() );
} }
@Test @Test
@ -91,8 +91,8 @@ public class ComponentsTest
{ {
this.testEmptyComponentBuilder( this.testEmptyComponentBuilder(
ComponentBuilder::create, ComponentBuilder::create,
(components) -> assertEquals( components.length, 0 ), (components) -> Assert.assertEquals( components.length, 0 ),
(components, size) -> assertEquals( size, components.length ) (components, size) -> Assert.assertEquals( size, components.length )
); );
} }
@ -101,8 +101,8 @@ public class ComponentsTest
{ {
this.testEmptyComponentBuilder( this.testEmptyComponentBuilder(
ComponentBuilder::build, ComponentBuilder::build,
(component) -> assertNull( component.getExtra() ), (component) -> Assert.assertNull( component.getExtra() ),
(component, size) -> assertEquals( component.getExtra().size(), size ) (component, size) -> Assert.assertEquals( component.getExtra().size(), size )
); );
} }
@ -125,23 +125,23 @@ public class ComponentsTest
public void testDummyRetaining() public void testDummyRetaining()
{ {
ComponentBuilder builder = new ComponentBuilder(); ComponentBuilder builder = new ComponentBuilder();
assertNotNull( builder.getCurrentComponent() ); Assert.assertNotNull( builder.getCurrentComponent() );
builder.color( ChatColor.GREEN ); builder.color( ChatColor.GREEN );
builder.append( "test ", ComponentBuilder.FormatRetention.ALL ); builder.append( "test ", ComponentBuilder.FormatRetention.ALL );
assertEquals( builder.getCurrentComponent().getColor(), ChatColor.GREEN ); Assert.assertEquals( builder.getCurrentComponent().getColor(), ChatColor.GREEN );
} }
@Test @Test(expected = IndexOutOfBoundsException.class)
public void testComponentGettingExceptions() public void testComponentGettingExceptions()
{ {
ComponentBuilder builder = new ComponentBuilder(); ComponentBuilder builder = new ComponentBuilder();
assertThrows( IndexOutOfBoundsException.class, () -> builder.getComponent( -1 ) ); builder.getComponent( -1 );
assertThrows( IndexOutOfBoundsException.class, () -> builder.getComponent( 0 ) ); builder.getComponent( 0 );
assertThrows( IndexOutOfBoundsException.class, () -> builder.getComponent( 1 ) ); builder.getComponent( 1 );
BaseComponent component = new TextComponent( "Hello" ); BaseComponent component = new TextComponent( "Hello" );
builder.append( component ); builder.append( component );
assertEquals( builder.getComponent( 0 ), component ); Assert.assertEquals( builder.getComponent( 0 ), component );
assertThrows( IndexOutOfBoundsException.class, () -> builder.getComponent( 1 ) ); builder.getComponent( 1 );
} }
@Test @Test
@ -150,33 +150,33 @@ public class ComponentsTest
ComponentBuilder builder = new ComponentBuilder(); ComponentBuilder builder = new ComponentBuilder();
TextComponent apple = new TextComponent( "apple" ); TextComponent apple = new TextComponent( "apple" );
builder.append( apple ); builder.append( apple );
assertEquals( builder.getCurrentComponent(), apple ); Assert.assertEquals( builder.getCurrentComponent(), apple );
assertEquals( builder.getComponent( 0 ), apple ); Assert.assertEquals( builder.getComponent( 0 ), apple );
TextComponent mango = new TextComponent( "mango" ); TextComponent mango = new TextComponent( "mango" );
TextComponent orange = new TextComponent( "orange" ); TextComponent orange = new TextComponent( "orange" );
builder.append( mango ); builder.append( mango );
builder.append( orange ); builder.append( orange );
builder.removeComponent( 1 ); // Removing mango builder.removeComponent( 1 ); // Removing mango
assertEquals( builder.getComponent( 0 ), apple ); Assert.assertEquals( builder.getComponent( 0 ), apple );
assertEquals( builder.getComponent( 1 ), orange ); Assert.assertEquals( builder.getComponent( 1 ), orange );
} }
@Test @Test
public void testToLegacyFromLegacy() public void testToLegacyFromLegacy()
{ {
String text = "§a§lHello §f§kworld§7!"; String text = "§a§lHello §f§kworld§7!";
assertEquals( text, TextComponent.toLegacyText( TextComponent.fromLegacyText( text ) ) ); Assert.assertEquals( text, TextComponent.toLegacyText( TextComponent.fromLegacyText( text ) ) );
} }
@Test @Test(expected = IndexOutOfBoundsException.class)
public void testComponentBuilderCursorInvalidPos() public void testComponentBuilderCursorInvalidPos()
{ {
ComponentBuilder builder = new ComponentBuilder(); ComponentBuilder builder = new ComponentBuilder();
builder.append( new TextComponent( "Apple, " ) ); builder.append( new TextComponent( "Apple, " ) );
builder.append( new TextComponent( "Orange, " ) ); builder.append( new TextComponent( "Orange, " ) );
assertThrows( IndexOutOfBoundsException.class, () -> builder.setCursor( -1 ) ); builder.setCursor( -1 );
assertThrows( IndexOutOfBoundsException.class, () -> builder.setCursor( 2 ) ); builder.setCursor( 2 );
} }
@Test @Test
@ -184,24 +184,24 @@ public class ComponentsTest
{ {
TextComponent t1, t2, t3; TextComponent t1, t2, t3;
ComponentBuilder builder = new ComponentBuilder(); ComponentBuilder builder = new ComponentBuilder();
assertEquals( builder.getCursor(), -1 ); Assert.assertEquals( builder.getCursor(), -1 );
builder.append( t1 = new TextComponent( "Apple, " ) ); builder.append( t1 = new TextComponent( "Apple, " ) );
assertEquals( builder.getCursor(), 0 ); Assert.assertEquals( builder.getCursor(), 0 );
builder.append( t2 = new TextComponent( "Orange, " ) ); builder.append( t2 = new TextComponent( "Orange, " ) );
builder.append( t3 = new TextComponent( "Mango, " ) ); builder.append( t3 = new TextComponent( "Mango, " ) );
assertEquals( builder.getCursor(), 2 ); Assert.assertEquals( builder.getCursor(), 2 );
builder.setCursor( 0 ); builder.setCursor( 0 );
assertEquals( builder.getCurrentComponent(), t1 ); Assert.assertEquals( builder.getCurrentComponent(), t1 );
// Test that appending new components updates the position to the new list size // Test that appending new components updates the position to the new list size
// after having previously set it to 0 (first component) // after having previously set it to 0 (first component)
builder.append( new TextComponent( "and Grapefruit" ) ); builder.append( new TextComponent( "and Grapefruit" ) );
assertEquals( builder.getCursor(), 3 ); Assert.assertEquals( builder.getCursor(), 3 );
builder.setCursor( 0 ); builder.setCursor( 0 );
builder.resetCursor(); builder.resetCursor();
assertEquals( builder.getCursor(), 3 ); Assert.assertEquals( builder.getCursor(), 3 );
} }
@Test @Test
@ -210,7 +210,7 @@ public class ComponentsTest
String text = "§a§lHello §r§kworld§7!"; String text = "§a§lHello §r§kworld§7!";
BaseComponent[] components = TextComponent.fromLegacyText( text ); BaseComponent[] components = TextComponent.fromLegacyText( text );
BaseComponent[] builderComponents = new ComponentBuilder().append( components ).create(); BaseComponent[] builderComponents = new ComponentBuilder().append( components ).create();
assertArrayEquals( components, builderComponents ); Assert.assertArrayEquals( components, builderComponents );
} }
/* /*
@ -232,7 +232,7 @@ public class ComponentsTest
component.setHoverEvent( event ); component.setHoverEvent( event );
String serialised = ComponentSerializer.toString( component ); String serialised = ComponentSerializer.toString( component );
BaseComponent[] deserialised = ComponentSerializer.parse( serialised ); BaseComponent[] deserialised = ComponentSerializer.parse( serialised );
assertEquals( TextComponent.toLegacyText( deserialised ), TextComponent.toLegacyText( component ) ); Assert.assertEquals( TextComponent.toLegacyText( deserialised ), TextComponent.toLegacyText( component ) );
} }
*/ */
@ -247,9 +247,9 @@ public class ComponentsTest
); );
TextComponent component = new TextComponent( "test" ); TextComponent component = new TextComponent( "test" );
component.setHoverEvent( hoverEvent ); component.setHoverEvent( hoverEvent );
assertEquals( component.getHoverEvent().getContents().size(), 1 ); Assert.assertEquals( component.getHoverEvent().getContents().size(), 1 );
assertTrue( component.getHoverEvent().getContents().get( 0 ) instanceof Text ); Assert.assertTrue( component.getHoverEvent().getContents().get( 0 ) instanceof Text );
assertEquals( ( (Text) component.getHoverEvent().getContents().get( 0 ) ).getValue(), advancement ); Assert.assertEquals( ( (Text) component.getHoverEvent().getContents().get( 0 ) ).getValue(), advancement );
} }
@Test @Test
@ -274,11 +274,11 @@ public class ComponentsTest
TextComponent component = new TextComponent( "Sample text" ); TextComponent component = new TextComponent( "Sample text" );
component.setHoverEvent( hoverEvent ); component.setHoverEvent( hoverEvent );
assertEquals( hoverEvent.getContents().size(), 1 ); Assert.assertEquals( hoverEvent.getContents().size(), 1 );
assertTrue( hoverEvent.isLegacy() ); Assert.assertTrue( hoverEvent.isLegacy() );
String serialized = ComponentSerializer.toString( component ); String serialized = ComponentSerializer.toString( component );
BaseComponent[] deserialized = ComponentSerializer.parse( serialized ); BaseComponent[] deserialized = ComponentSerializer.parse( serialized );
assertEquals( component.getHoverEvent(), deserialized[0].getHoverEvent() ); Assert.assertEquals( component.getHoverEvent(), deserialized[0].getHoverEvent() );
} }
@Test @Test
@ -303,12 +303,12 @@ public class ComponentsTest
{ {
TextComponent component = new TextComponent( "Sample text" ); TextComponent component = new TextComponent( "Sample text" );
component.setHoverEvent( hoverEvent ); component.setHoverEvent( hoverEvent );
assertEquals( hoverEvent.getContents().size(), 2 ); Assert.assertEquals( hoverEvent.getContents().size(), 2 );
assertFalse( hoverEvent.isLegacy() ); Assert.assertFalse( hoverEvent.isLegacy() );
String serialized = ComponentSerializer.toString( component ); String serialized = ComponentSerializer.toString( component );
T deserialized = deserializer.apply( serialized ); T deserialized = deserializer.apply( serialized );
assertEquals( component.getHoverEvent(), hoverEventGetter.apply( deserialized ) ); Assert.assertEquals( component.getHoverEvent(), hoverEventGetter.apply( deserialized ) );
// Test single content: // Test single content:
String json = "{\"italic\":true,\"color\":\"gray\",\"translate\":\"chat.type.admin\",\"with\":[{\"text\":\"@\"}" String json = "{\"italic\":true,\"color\":\"gray\",\"translate\":\"chat.type.admin\",\"with\":[{\"text\":\"@\"}"
@ -345,10 +345,10 @@ public class ComponentsTest
TextComponent second = new TextComponent( " world" ); TextComponent second = new TextComponent( " world" );
second.copyFormatting( first, ComponentBuilder.FormatRetention.ALL, true ); second.copyFormatting( first, ComponentBuilder.FormatRetention.ALL, true );
assertEquals( first.isBold(), second.isBold() ); Assert.assertEquals( first.isBold(), second.isBold() );
assertEquals( first.getColor(), second.getColor() ); Assert.assertEquals( first.getColor(), second.getColor() );
assertEquals( first.getClickEvent(), second.getClickEvent() ); Assert.assertEquals( first.getClickEvent(), second.getClickEvent() );
assertEquals( first.getHoverEvent(), second.getHoverEvent() ); Assert.assertEquals( first.getHoverEvent(), second.getHoverEvent() );
} }
@Test @Test
@ -368,7 +368,7 @@ public class ComponentsTest
ComponentBuilder builder = new ComponentBuilder( "Hello " ).color( ChatColor.RED ).append( "world" ).color( ChatColor.DARK_RED ); ComponentBuilder builder = new ComponentBuilder( "Hello " ).color( ChatColor.RED ).append( "world" ).color( ChatColor.DARK_RED );
ComponentBuilder cloned = new ComponentBuilder( builder ); ComponentBuilder cloned = new ComponentBuilder( builder );
assertEquals( legacyTextFunction.apply( builder ), legacyTextFunction.apply( cloned ) ); Assert.assertEquals( legacyTextFunction.apply( builder ), legacyTextFunction.apply( cloned ) );
} }
@Test @Test
@ -403,10 +403,10 @@ public class ComponentsTest
ScoreComponent scoreComponent = new ScoreComponent( "myscore", "myobjective" ); ScoreComponent scoreComponent = new ScoreComponent( "myscore", "myobjective" );
builder.append( scoreComponent ); // non array based BaseComponent append builder.append( scoreComponent ); // non array based BaseComponent append
T component = componentBuilder.apply( builder ); T component = componentBuilder.apply( builder );
assertEquals( "Hello ", extraGetter.apply( component, 0 ).toPlainText() ); Assert.assertEquals( "Hello ", extraGetter.apply( component, 0 ).toPlainText() );
assertEquals( textComponent.toPlainText(), extraGetter.apply( component, 1 ).toPlainText() ); Assert.assertEquals( textComponent.toPlainText(), extraGetter.apply( component, 1 ).toPlainText() );
assertEquals( translatableComponent.toPlainText(), extraGetter.apply( component, 2 ).toPlainText() ); Assert.assertEquals( translatableComponent.toPlainText(), extraGetter.apply( component, 2 ).toPlainText() );
assertEquals( scoreComponent.toPlainText(), extraGetter.apply( component, 3 ).toPlainText() ); Assert.assertEquals( scoreComponent.toPlainText(), extraGetter.apply( component, 3 ).toPlainText() );
} }
@Test @Test
@ -416,7 +416,7 @@ public class ComponentsTest
String text = ComponentSerializer.toString( component ); String text = ComponentSerializer.toString( component );
BaseComponent[] reparsed = ComponentSerializer.parse( text ); BaseComponent[] reparsed = ComponentSerializer.parse( text );
assertArrayEquals( component, reparsed ); Assert.assertArrayEquals( component, reparsed );
} }
@Test @Test
@ -456,10 +456,10 @@ public class ComponentsTest
T component = componentBuilder.apply( builder ); T component = componentBuilder.apply( builder );
assertEquals( extraGetter.apply( component, 1 ).getHoverEvent(), hoverEvent ); Assert.assertEquals( extraGetter.apply( component, 1 ).getHoverEvent(), hoverEvent );
assertEquals( extraGetter.apply( component, 1 ).getClickEvent(), clickEvent ); Assert.assertEquals( extraGetter.apply( component, 1 ).getClickEvent(), clickEvent );
assertEquals( "Hello world!", toPlainTextFunction.apply( component ) ); Assert.assertEquals( "Hello world!", toPlainTextFunction.apply( component ) );
assertEquals( expectedLegacyText, toLegacyTextFunction.apply( component ) ); Assert.assertEquals( expectedLegacyText, toLegacyTextFunction.apply( component ) );
} }
@Test @Test
@ -492,8 +492,8 @@ public class ComponentsTest
T component = componentBuilder.apply( builder ); T component = componentBuilder.apply( builder );
assertEquals( "Hello world!", toPlainTextFunction.apply( component ) ); Assert.assertEquals( "Hello world!", toPlainTextFunction.apply( component ) );
assertEquals( expectedLegacyString, toLegacyTextFunction.apply( component ) ); Assert.assertEquals( expectedLegacyString, toLegacyTextFunction.apply( component ) );
} }
@Test @Test
@ -502,8 +502,8 @@ public class ComponentsTest
TextComponent textComponent = new TextComponent( "Hello world" ); TextComponent textComponent = new TextComponent( "Hello world" );
textComponent.setColor( ChatColor.RED ); textComponent.setColor( ChatColor.RED );
assertEquals( "Hello world", textComponent.toPlainText() ); Assert.assertEquals( "Hello world", textComponent.toPlainText() );
assertEquals( ChatColor.RED + "Hello world", textComponent.toLegacyText() ); Assert.assertEquals( ChatColor.RED + "Hello world", textComponent.toLegacyText() );
} }
@Test @Test
@ -511,25 +511,25 @@ public class ComponentsTest
{ {
BaseComponent[] test1 = TextComponent.fromLegacyText( ChatColor.AQUA + "Aqua " + ChatColor.RED + ChatColor.BOLD + "RedBold" ); BaseComponent[] test1 = TextComponent.fromLegacyText( ChatColor.AQUA + "Aqua " + ChatColor.RED + ChatColor.BOLD + "RedBold" );
assertEquals( "Aqua RedBold", BaseComponent.toPlainText( test1 ) ); Assert.assertEquals( "Aqua RedBold", BaseComponent.toPlainText( test1 ) );
assertEquals( ChatColor.AQUA + "Aqua " + ChatColor.RED + ChatColor.BOLD + "RedBold", BaseComponent.toLegacyText( test1 ) ); Assert.assertEquals( ChatColor.AQUA + "Aqua " + ChatColor.RED + ChatColor.BOLD + "RedBold", BaseComponent.toLegacyText( test1 ) );
BaseComponent[] test2 = TextComponent.fromLegacyText( "Text http://spigotmc.org " + ChatColor.GREEN + "google.com/test" ); BaseComponent[] test2 = TextComponent.fromLegacyText( "Text http://spigotmc.org " + ChatColor.GREEN + "google.com/test" );
assertEquals( "Text http://spigotmc.org google.com/test", BaseComponent.toPlainText( test2 ) ); Assert.assertEquals( "Text http://spigotmc.org google.com/test", BaseComponent.toPlainText( test2 ) );
//The extra ChatColor instances are sometimes inserted when not needed but it doesn't change the result //The extra ChatColor instances are sometimes inserted when not needed but it doesn't change the result
assertEquals( ChatColor.WHITE + "Text " + ChatColor.WHITE + "http://spigotmc.org" + ChatColor.WHITE Assert.assertEquals( ChatColor.WHITE + "Text " + ChatColor.WHITE + "http://spigotmc.org" + ChatColor.WHITE
+ " " + ChatColor.GREEN + "google.com/test" + ChatColor.GREEN, BaseComponent.toLegacyText( test2 ) ); + " " + ChatColor.GREEN + "google.com/test" + ChatColor.GREEN, BaseComponent.toLegacyText( test2 ) );
ClickEvent url1 = test2[1].getClickEvent(); ClickEvent url1 = test2[1].getClickEvent();
assertNotNull( url1 ); Assert.assertNotNull( url1 );
assertTrue( url1.getAction() == ClickEvent.Action.OPEN_URL ); Assert.assertTrue( url1.getAction() == ClickEvent.Action.OPEN_URL );
assertEquals( "http://spigotmc.org", url1.getValue() ); Assert.assertEquals( "http://spigotmc.org", url1.getValue() );
ClickEvent url2 = test2[3].getClickEvent(); ClickEvent url2 = test2[3].getClickEvent();
assertNotNull( url2 ); Assert.assertNotNull( url2 );
assertTrue( url2.getAction() == ClickEvent.Action.OPEN_URL ); Assert.assertTrue( url2.getAction() == ClickEvent.Action.OPEN_URL );
assertEquals( "http://google.com/test", url2.getValue() ); Assert.assertEquals( "http://google.com/test", url2.getValue() );
} }
@Test @Test
@ -541,18 +541,18 @@ public class ComponentsTest
item, "5", item, "5",
"thinkofdeath" ); "thinkofdeath" );
assertEquals( "Given Golden Sword * 5 to thinkofdeath", translatableComponent.toPlainText() ); Assert.assertEquals( "Given Golden Sword * 5 to thinkofdeath", translatableComponent.toPlainText() );
assertEquals( ChatColor.WHITE + "Given " + ChatColor.AQUA + "Golden Sword" + ChatColor.WHITE Assert.assertEquals( ChatColor.WHITE + "Given " + ChatColor.AQUA + "Golden Sword" + ChatColor.WHITE
+ " * " + ChatColor.WHITE + "5" + ChatColor.WHITE + " to " + ChatColor.WHITE + "thinkofdeath", + " * " + ChatColor.WHITE + "5" + ChatColor.WHITE + " to " + ChatColor.WHITE + "thinkofdeath",
translatableComponent.toLegacyText() ); translatableComponent.toLegacyText() );
TranslatableComponent positional = new TranslatableComponent( "book.pageIndicator", "5", "50" ); TranslatableComponent positional = new TranslatableComponent( "book.pageIndicator", "5", "50" );
assertEquals( "Page 5 of 50", positional.toPlainText() ); Assert.assertEquals( "Page 5 of 50", positional.toPlainText() );
assertEquals( ChatColor.WHITE + "Page " + ChatColor.WHITE + "5" + ChatColor.WHITE + " of " + ChatColor.WHITE + "50", positional.toLegacyText() ); Assert.assertEquals( ChatColor.WHITE + "Page " + ChatColor.WHITE + "5" + ChatColor.WHITE + " of " + ChatColor.WHITE + "50", positional.toLegacyText() );
TranslatableComponent one_four_two = new TranslatableComponent( "filled_map.buried_treasure" ); TranslatableComponent one_four_two = new TranslatableComponent( "filled_map.buried_treasure" );
assertEquals( "Buried Treasure Map", one_four_two.toPlainText() ); Assert.assertEquals( "Buried Treasure Map", one_four_two.toPlainText() );
} }
@Test @Test
@ -586,8 +586,8 @@ public class ComponentsTest
append( "World" ).bold( true ).color( ChatColor.BLUE ). append( "World" ).bold( true ).color( ChatColor.BLUE ).
append( "!" ).color( ChatColor.YELLOW ) ); append( "!" ).color( ChatColor.YELLOW ) );
assertEquals( "Hello World!", toPlainTextFunction.apply( component ) ); Assert.assertEquals( "Hello World!", toPlainTextFunction.apply( component ) );
assertEquals( expectedLegacyString, toLegacyTextFunction.apply( component ) ); Assert.assertEquals( expectedLegacyString, toLegacyTextFunction.apply( component ) );
} }
@Test @Test
@ -613,8 +613,8 @@ public class ComponentsTest
T component = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED ) T component = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED )
.append( "World" ).reset() ); .append( "World" ).reset() );
assertEquals( ChatColor.RED, extraGetter.apply( component, 0 ).getColor() ); Assert.assertEquals( ChatColor.RED, extraGetter.apply( component, 0 ).getColor() );
assertEquals( ChatColor.WHITE, extraGetter.apply( component, 1 ).getColor() ); Assert.assertEquals( ChatColor.WHITE, extraGetter.apply( component, 1 ).getColor() );
} }
@Test @Test
@ -640,41 +640,41 @@ public class ComponentsTest
T noneRetention = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED ) T noneRetention = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED )
.append( "World", ComponentBuilder.FormatRetention.NONE ) ); .append( "World", ComponentBuilder.FormatRetention.NONE ) );
assertEquals( ChatColor.RED, extraGetter.apply( noneRetention, 0 ).getColor() ); Assert.assertEquals( ChatColor.RED, extraGetter.apply( noneRetention, 0 ).getColor() );
assertEquals( ChatColor.WHITE, extraGetter.apply( noneRetention, 1 ).getColor() ); Assert.assertEquals( ChatColor.WHITE, extraGetter.apply( noneRetention, 1 ).getColor() );
HoverEvent testEvent = new HoverEvent( HoverEvent.Action.SHOW_TEXT, new Text( new ComponentBuilder( "test" ).build() ) ); HoverEvent testEvent = new HoverEvent( HoverEvent.Action.SHOW_TEXT, new Text( new ComponentBuilder( "test" ).build() ) );
T formattingRetention = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED ) T formattingRetention = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED )
.event( testEvent ).append( "World", ComponentBuilder.FormatRetention.FORMATTING ) ); .event( testEvent ).append( "World", ComponentBuilder.FormatRetention.FORMATTING ) );
assertEquals( ChatColor.RED, extraGetter.apply( formattingRetention, 0 ).getColor() ); Assert.assertEquals( ChatColor.RED, extraGetter.apply( formattingRetention, 0 ).getColor() );
assertEquals( testEvent, extraGetter.apply( formattingRetention, 0 ).getHoverEvent() ); Assert.assertEquals( testEvent, extraGetter.apply( formattingRetention, 0 ).getHoverEvent() );
assertEquals( ChatColor.RED, extraGetter.apply( formattingRetention, 1 ).getColor() ); Assert.assertEquals( ChatColor.RED, extraGetter.apply( formattingRetention, 1 ).getColor() );
assertNull( extraGetter.apply( formattingRetention, 1 ).getHoverEvent() ); Assert.assertNull( extraGetter.apply( formattingRetention, 1 ).getHoverEvent() );
ClickEvent testClickEvent = new ClickEvent( ClickEvent.Action.OPEN_URL, "http://www.example.com" ); ClickEvent testClickEvent = new ClickEvent( ClickEvent.Action.OPEN_URL, "http://www.example.com" );
T eventRetention = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED ) T eventRetention = componentBuilder.apply( new ComponentBuilder( "Hello " ).color( ChatColor.RED )
.event( testEvent ).event( testClickEvent ).append( "World", ComponentBuilder.FormatRetention.EVENTS ) ); .event( testEvent ).event( testClickEvent ).append( "World", ComponentBuilder.FormatRetention.EVENTS ) );
assertEquals( ChatColor.RED, extraGetter.apply( eventRetention, 0 ).getColor() ); Assert.assertEquals( ChatColor.RED, extraGetter.apply( eventRetention, 0 ).getColor() );
assertEquals( testEvent, extraGetter.apply( eventRetention, 0 ).getHoverEvent() ); Assert.assertEquals( testEvent, extraGetter.apply( eventRetention, 0 ).getHoverEvent() );
assertEquals( testClickEvent, extraGetter.apply( eventRetention, 0 ).getClickEvent() ); Assert.assertEquals( testClickEvent, extraGetter.apply( eventRetention, 0 ).getClickEvent() );
assertEquals( ChatColor.WHITE, extraGetter.apply( eventRetention, 1 ).getColor() ); Assert.assertEquals( ChatColor.WHITE, extraGetter.apply( eventRetention, 1 ).getColor() );
assertEquals( testEvent, extraGetter.apply( eventRetention, 1 ).getHoverEvent() ); Assert.assertEquals( testEvent, extraGetter.apply( eventRetention, 1 ).getHoverEvent() );
assertEquals( testClickEvent, extraGetter.apply( eventRetention, 1 ).getClickEvent() ); Assert.assertEquals( testClickEvent, extraGetter.apply( eventRetention, 1 ).getClickEvent() );
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testLoopSimple() public void testLoopSimple()
{ {
TextComponent component = new TextComponent( "Testing" ); TextComponent component = new TextComponent( "Testing" );
component.addExtra( component ); component.addExtra( component );
assertThrows( IllegalArgumentException.class, () -> ComponentSerializer.toString( component ) ); ComponentSerializer.toString( component );
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testLoopComplex() public void testLoopComplex()
{ {
TextComponent a = new TextComponent( "A" ); TextComponent a = new TextComponent( "A" );
@ -685,7 +685,7 @@ public class ComponentsTest
a.addExtra( b ); a.addExtra( b );
b.addExtra( c ); b.addExtra( c );
c.addExtra( a ); c.addExtra( a );
assertThrows( IllegalArgumentException.class, () -> ComponentSerializer.toString( a ) ); ComponentSerializer.toString( a );
} }
@Test @Test
@ -699,7 +699,7 @@ public class ComponentsTest
ComponentSerializer.toString( a ); ComponentSerializer.toString( a );
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testRepeatedError() public void testRepeatedError()
{ {
TextComponent a = new TextComponent( "A" ); TextComponent a = new TextComponent( "A" );
@ -711,7 +711,7 @@ public class ComponentsTest
a.addExtra( c ); a.addExtra( c );
c.addExtra( a ); c.addExtra( a );
a.addExtra( b ); a.addExtra( b );
assertThrows( IllegalArgumentException.class, () -> ComponentSerializer.toString( a ) ); ComponentSerializer.toString( a );
} }
@Test @Test
@ -736,7 +736,7 @@ public class ComponentsTest
String emptyLegacyText = fromAndToLegacyText( "" ); String emptyLegacyText = fromAndToLegacyText( "" );
// all invalid color codes and the trailing '§' should be ignored // all invalid color codes and the trailing '§' should be ignored
assertEquals( emptyLegacyText, invalidColorCodesLegacyText ); Assert.assertEquals( emptyLegacyText, invalidColorCodesLegacyText );
} }
@Test @Test
@ -745,12 +745,12 @@ public class ComponentsTest
String text = "§a"; String text = "§a";
BaseComponent[] converted = TextComponent.fromLegacyText( text ); BaseComponent[] converted = TextComponent.fromLegacyText( text );
assertEquals( ChatColor.GREEN, converted[0].getColor() ); Assert.assertEquals( ChatColor.GREEN, converted[0].getColor() );
String roundtripLegacyText = BaseComponent.toLegacyText( converted ); String roundtripLegacyText = BaseComponent.toLegacyText( converted );
// color code should not be lost during conversion // color code should not be lost during conversion
assertEquals( text, roundtripLegacyText ); Assert.assertEquals( text, roundtripLegacyText );
} }
@Test @Test
@ -762,7 +762,7 @@ public class ComponentsTest
TextComponent second = new TextComponent( "Hello, " ); TextComponent second = new TextComponent( "Hello, " );
second.addExtra( new TextComponent( "World!" ) ); second.addExtra( new TextComponent( "World!" ) );
assertEquals( first, second ); Assert.assertEquals( first, second );
} }
@Test @Test
@ -774,7 +774,7 @@ public class ComponentsTest
TextComponent second = new TextComponent( "Hello, " ); TextComponent second = new TextComponent( "Hello, " );
second.addExtra( new TextComponent( "World!" ) ); second.addExtra( new TextComponent( "World!" ) );
assertNotEquals( first, second ); Assert.assertNotEquals( first, second );
} }
@Test @Test
@ -785,7 +785,7 @@ public class ComponentsTest
BaseComponent[] reColored = TextComponent.fromLegacyText( legacy ); BaseComponent[] reColored = TextComponent.fromLegacyText( legacy );
assertArrayEquals( hexColored, reColored ); Assert.assertArrayEquals( hexColored, reColored );
} }
@Test @Test
@ -817,18 +817,18 @@ public class ComponentsTest
String expected = "{\"extra\":[{\"underlined\":true,\"color\":\"dark_red\",\"text\":\"44444\"},{\"color\":" String expected = "{\"extra\":[{\"underlined\":true,\"color\":\"dark_red\",\"text\":\"44444\"},{\"color\":"
+ "\"white\",\"text\":\"dd\"},{\"bold\":true,\"color\":\"gold\",\"text\":\"6666\"}],\"text\":\"\"}"; + "\"white\",\"text\":\"dd\"},{\"bold\":true,\"color\":\"gold\",\"text\":\"6666\"}],\"text\":\"\"}";
assertEquals( expected, ComponentSerializer.toString( a ) ); Assert.assertEquals( expected, ComponentSerializer.toString( a ) );
builder.append( a ); builder.append( a );
String test1 = componentSerializer.apply( componentBuilder.apply( builder ) ); String test1 = componentSerializer.apply( componentBuilder.apply( builder ) );
assertEquals( expected, test1 ); Assert.assertEquals( expected, test1 );
BaseComponent[] b = TextComponent.fromLegacyText( "§rrrrr" ); BaseComponent[] b = TextComponent.fromLegacyText( "§rrrrr" );
builder.append( b ); builder.append( b );
String test2 = componentSerializer.apply( componentBuilder.apply( builder ) ); String test2 = componentSerializer.apply( componentBuilder.apply( builder ) );
assertEquals( Assert.assertEquals(
"{\"extra\":[{\"underlined\":true,\"color\":\"dark_red\",\"text\":\"44444\"}," "{\"extra\":[{\"underlined\":true,\"color\":\"dark_red\",\"text\":\"44444\"},"
+ "{\"color\":\"white\",\"text\":\"dd\"},{\"bold\":true,\"color\":\"gold\",\"text\":\"6666\"}," + "{\"color\":\"white\",\"text\":\"dd\"},{\"bold\":true,\"color\":\"gold\",\"text\":\"6666\"},"
+ "{\"color\":\"white\",\"text\":\"rrrr\"}],\"text\":\"\"}", + "{\"color\":\"white\",\"text\":\"rrrr\"}],\"text\":\"\"}",

View File

@ -1,8 +1,8 @@
package net.md_5.bungee.api.chat; package net.md_5.bungee.api.chat;
import static org.junit.jupiter.api.Assertions.*;
import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.chat.ComponentSerializer;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class TranslatableComponentTest public class TranslatableComponentTest
{ {
@ -11,8 +11,8 @@ public class TranslatableComponentTest
public void testMissingPlaceholdersAdded() public void testMissingPlaceholdersAdded()
{ {
TranslatableComponent testComponent = new TranslatableComponent( "Test string with %s placeholders: %s", 2, "aoeu" ); TranslatableComponent testComponent = new TranslatableComponent( "Test string with %s placeholders: %s", 2, "aoeu" );
assertEquals( "Test string with 2 placeholders: aoeu", testComponent.toPlainText() ); Assert.assertEquals( "Test string with 2 placeholders: aoeu", testComponent.toPlainText() );
assertEquals( "§fTest string with §f2§f placeholders: §faoeu", testComponent.toLegacyText() ); Assert.assertEquals( "§fTest string with §f2§f placeholders: §faoeu", testComponent.toLegacyText() );
} }
@Test @Test
@ -22,7 +22,7 @@ public class TranslatableComponentTest
String jsonString = ComponentSerializer.toString( testComponent ); String jsonString = ComponentSerializer.toString( testComponent );
BaseComponent[] baseComponents = ComponentSerializer.parse( jsonString ); BaseComponent[] baseComponents = ComponentSerializer.parse( jsonString );
assertEquals( "Test string with a placeholder", TextComponent.toPlainText( baseComponents ) ); Assert.assertEquals( "Test string with a placeholder", TextComponent.toPlainText( baseComponents ) );
assertEquals( "§fTest string with §fa§f placeholder", TextComponent.toLegacyText( baseComponents ) ); Assert.assertEquals( "§fTest string with §fa§f placeholder", TextComponent.toLegacyText( baseComponents ) );
} }
} }

View File

@ -36,6 +36,7 @@
<module name="SuppressWarningsHolder"/> <module name="SuppressWarningsHolder"/>
<!-- See http://checkstyle.sourceforge.net/config_imports.html --> <!-- See http://checkstyle.sourceforge.net/config_imports.html -->
<module name="AvoidStarImport"/>
<module name="ImportOrder"> <module name="ImportOrder">
<property name="option" value="above"/> <property name="option" value="above"/>
<property name="ordered" value="true"/> <property name="ordered" value="true"/>

View File

@ -1,138 +1,148 @@
package net.md_5.bungee.config; package net.md_5.bungee.config;
import static org.junit.jupiter.api.Assertions.*;
import java.io.StringReader; import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.junit.jupiter.params.ParameterizedTest; import org.junit.Assert;
import org.junit.jupiter.params.provider.Arguments; import org.junit.Test;
import org.junit.jupiter.params.provider.MethodSource; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RequiredArgsConstructor @RequiredArgsConstructor
@RunWith(Parameterized.class)
public class CompoundConfigurationTest public class CompoundConfigurationTest
{ {
public static Stream<Arguments> data() @Parameters(name = "{0}")
public static Iterable<Object[]> data()
{ {
return Stream.of( // CHECKSTYLE:OFF
Arguments.of( return Arrays.asList( new Object[][]
// provider {
YamlConfiguration.class, {
// testDocument // provider
"" YamlConfiguration.class,
+ "receipt: Oz-Ware Purchase Invoice\n" // testDocument
+ "date: 2012-08-06\n" ""
+ "customer:\n" + "receipt: Oz-Ware Purchase Invoice\n"
+ " given: Dorothy\n" + "date: 2012-08-06\n"
+ " family: Gale\n" + "customer:\n"
+ "\n" + " given: Dorothy\n"
+ "items:\n" + " family: Gale\n"
+ " - part_no: A4786\n" + "\n"
+ " descrip: Water Bucket (Filled)\n" + "items:\n"
+ " price: 1.47\n" + " - part_no: A4786\n"
+ " quantity: 4\n" + " descrip: Water Bucket (Filled)\n"
+ "\n" + " price: 1.47\n"
+ " - part_no: E1628\n" + " quantity: 4\n"
+ " descrip: High Heeled \"Ruby\" Slippers\n" + "\n"
+ " size: 8\n" + " - part_no: E1628\n"
+ " price: 100.27\n" + " descrip: High Heeled \"Ruby\" Slippers\n"
+ " quantity: 1\n" + " size: 8\n"
+ "\n" + " price: 100.27\n"
+ "bill-to: &id001\n" + " quantity: 1\n"
+ " street: |\n" + "\n"
+ " 123 Tornado Alley\n" + "bill-to: &id001\n"
+ " Suite 16\n" + " street: |\n"
+ " city: East Centerville\n" + " 123 Tornado Alley\n"
+ " state: KS\n" + " Suite 16\n"
+ "\n" + " city: East Centerville\n"
+ "ship-to: *id001\n" + " state: KS\n"
+ "\n" + "\n"
+ "specialDelivery: >\n" + "ship-to: *id001\n"
+ " Follow the Yellow Brick\n" + "\n"
+ " Road to the Emerald City.\n" + "specialDelivery: >\n"
+ " Pay no attention to the\n" + " Follow the Yellow Brick\n"
+ " man behind the curtain.", + " Road to the Emerald City.\n"
// numberTest + " Pay no attention to the\n"
"" + " man behind the curtain.",
+ "someKey:\n" // numberTest
+ " 1: 1\n" ""
+ " 2: 2\n" + "someKey:\n"
+ " 3: 3\n" + " 1: 1\n"
+ " 4: 4", + " 2: 2\n"
// nullTest + " 3: 3\n"
"" + " 4: 4",
+ "null:\n" // nullTest
+ " null: object\n" ""
+ " object: null\n" + "null:\n"
), + " null: object\n"
Arguments.of( + " object: null\n"
// provider },
JsonConfiguration.class, {
// testDocument // provider
"" JsonConfiguration.class,
+ "{\n" // testDocument
+ " \"customer\": {\n" ""
+ " \"given\": \"Dorothy\", \n" + "{\n"
+ " \"family\": \"Gale\"\n" + " \"customer\": {\n"
+ " }, \n" + " \"given\": \"Dorothy\", \n"
+ " \"ship-to\": {\n" + " \"family\": \"Gale\"\n"
+ " \"city\": \"East Centerville\", \n" + " }, \n"
+ " \"state\": \"KS\", \n" + " \"ship-to\": {\n"
+ " \"street\": \"123 Tornado Alley\\nSuite 16\\n\"\n" + " \"city\": \"East Centerville\", \n"
+ " }, \n" + " \"state\": \"KS\", \n"
+ " \"bill-to\": {\n" + " \"street\": \"123 Tornado Alley\\nSuite 16\\n\"\n"
+ " \"city\": \"East Centerville\", \n" + " }, \n"
+ " \"state\": \"KS\", \n" + " \"bill-to\": {\n"
+ " \"street\": \"123 Tornado Alley\\nSuite 16\\n\"\n" + " \"city\": \"East Centerville\", \n"
+ " }, \n" + " \"state\": \"KS\", \n"
+ " \"date\": \"2012-08-06\", \n" + " \"street\": \"123 Tornado Alley\\nSuite 16\\n\"\n"
+ " \"items\": [\n" + " }, \n"
+ " {\n" + " \"date\": \"2012-08-06\", \n"
+ " \"part_no\": \"A4786\", \n" + " \"items\": [\n"
+ " \"price\": 1.47, \n" + " {\n"
+ " \"descrip\": \"Water Bucket (Filled)\", \n" + " \"part_no\": \"A4786\", \n"
+ " \"quantity\": 4\n" + " \"price\": 1.47, \n"
+ " }, \n" + " \"descrip\": \"Water Bucket (Filled)\", \n"
+ " {\n" + " \"quantity\": 4\n"
+ " \"part_no\": \"E1628\", \n" + " }, \n"
+ " \"descrip\": \"High Heeled \\\"Ruby\\\" Slippers\", \n" + " {\n"
+ " \"price\": 100.27, \n" + " \"part_no\": \"E1628\", \n"
+ " \"quantity\": 1, \n" + " \"descrip\": \"High Heeled \\\"Ruby\\\" Slippers\", \n"
+ " \"size\": 8\n" + " \"price\": 100.27, \n"
+ " }\n" + " \"quantity\": 1, \n"
+ " ], \n" + " \"size\": 8\n"
+ " \"receipt\": \"Oz-Ware Purchase Invoice\", \n" + " }\n"
+ " \"specialDelivery\": \"Follow the Yellow Brick Road to the Emerald City. Pay no attention to the man behind the curtain.\"\n" + " ], \n"
+ "}", + " \"receipt\": \"Oz-Ware Purchase Invoice\", \n"
// numberTest + " \"specialDelivery\": \"Follow the Yellow Brick Road to the Emerald City. Pay no attention to the man behind the curtain.\"\n"
"" + "}",
+ "{\n" // numberTest
+ " \"someKey\": {\n" ""
+ " \"1\": 1, \n" + "{\n"
+ " \"2\": 2, \n" + " \"someKey\": {\n"
+ " \"3\": 3, \n" + " \"1\": 1, \n"
+ " \"4\": 4\n" + " \"2\": 2, \n"
+ " }\n" + " \"3\": 3, \n"
+ "}", + " \"4\": 4\n"
// nullTest + " }\n"
"" + "}",
+ "{\n" // nullTest
+ " \"null\": {\n" ""
+ " \"null\": \"object\", \n" + "{\n"
+ " \"object\": null\n" + " \"null\": {\n"
+ " }\n" + " \"null\": \"object\", \n"
+ "}" + " \"object\": null\n"
) + " }\n"
); + "}"
}
} );
// CHECKSTYLE:ON
} }
//
private final Class<? extends ConfigurationProvider> provider;
private final String testDocument;
private final String numberTest;
private final String nullTest;
@ParameterizedTest @Test
@MethodSource("data") public void testConfig() throws Exception
public void testConfig(Class<? extends ConfigurationProvider> provider, String testDocument, String numberTest, String nullTest) throws Exception
{ {
Configuration conf = ConfigurationProvider.getProvider( provider ).load( testDocument ); Configuration conf = ConfigurationProvider.getProvider( provider ).load( testDocument );
testSection( conf ); testSection( conf );
@ -141,7 +151,7 @@ public class CompoundConfigurationTest
ConfigurationProvider.getProvider( provider ).save( conf, sw ); ConfigurationProvider.getProvider( provider ).save( conf, sw );
// Check nulls were saved, see #1094 // Check nulls were saved, see #1094
assertFalse( sw.toString().contains( "null" ), "Config contains null" ); Assert.assertFalse( "Config contains null", sw.toString().contains( "null" ) );
conf = ConfigurationProvider.getProvider( provider ).load( new StringReader( sw.toString() ) ); conf = ConfigurationProvider.getProvider( provider ).load( new StringReader( sw.toString() ) );
conf.set( "receipt", "Oz-Ware Purchase Invoice" ); // Add it back conf.set( "receipt", "Oz-Ware Purchase Invoice" ); // Add it back
@ -150,38 +160,37 @@ public class CompoundConfigurationTest
private void testSection(Configuration conf) private void testSection(Configuration conf)
{ {
assertEquals( "Oz-Ware Purchase Invoice", conf.getString( "receipt" ), "receipt" ); Assert.assertEquals( "receipt", "Oz-Ware Purchase Invoice", conf.getString( "receipt" ) );
// assertEquals( "2012-08-06", conf.get( "date" ).toString(), "date" ); // Assert.assertEquals( "date", "2012-08-06", conf.get( "date" ).toString() );
Configuration customer = conf.getSection( "customer" ); Configuration customer = conf.getSection( "customer" );
assertEquals( "Dorothy", customer.getString( "given" ), "customer.given" ); Assert.assertEquals( "customer.given", "Dorothy", customer.getString( "given" ) );
assertEquals( "Dorothy", conf.getString( "customer.given" ), "customer.given" ); Assert.assertEquals( "customer.given", "Dorothy", conf.getString( "customer.given" ) );
List items = conf.getList( "items" ); List items = conf.getList( "items" );
Map item = (Map) items.get( 0 ); Map item = (Map) items.get( 0 );
assertEquals( "A4786", item.get( "part_no" ), "items[0].part_no" ); Assert.assertEquals( "items[0].part_no", "A4786", item.get( "part_no" ) );
conf.set( "receipt", null ); conf.set( "receipt", null );
assertEquals( null, conf.get( "receipt" ) ); Assert.assertEquals( null, conf.get( "receipt" ) );
assertEquals( "foo", conf.get( "receipt", "foo" ) ); Assert.assertEquals( "foo", conf.get( "receipt", "foo" ) );
Configuration newSection = conf.getSection( "new.section" ); Configuration newSection = conf.getSection( "new.section" );
newSection.set( "value", "foo" ); newSection.set( "value", "foo" );
assertEquals( "foo", conf.get( "new.section.value" ) ); Assert.assertEquals( "foo", conf.get( "new.section.value" ) );
conf.set( "other.new.section", "bar" ); conf.set( "other.new.section", "bar" );
assertEquals( "bar", conf.get( "other.new.section" ) ); Assert.assertEquals( "bar", conf.get( "other.new.section" ) );
assertTrue( conf.contains( "customer.given" ) ); Assert.assertTrue( conf.contains( "customer.given" ) );
assertTrue( customer.contains( "given" ) ); Assert.assertTrue( customer.contains( "given" ) );
assertFalse( conf.contains( "customer.foo" ) ); Assert.assertFalse( conf.contains( "customer.foo" ) );
assertFalse( customer.contains( "foo" ) ); Assert.assertFalse( customer.contains( "foo" ) );
} }
@ParameterizedTest @Test
@MethodSource("data") public void testNumberedKeys()
public void testNumberedKeys(Class<? extends ConfigurationProvider> provider, String testDocument, String numberTest, String nullTest)
{ {
Configuration conf = ConfigurationProvider.getProvider( provider ).load( numberTest ); Configuration conf = ConfigurationProvider.getProvider( provider ).load( numberTest );
@ -192,31 +201,29 @@ public class CompoundConfigurationTest
} }
} }
@ParameterizedTest @Test
@MethodSource("data") public void testNull()
public void testNull(Class<? extends ConfigurationProvider> provider, String testDocument, String numberTest, String nullTest)
{ {
Configuration conf = ConfigurationProvider.getProvider( provider ).load( nullTest ); Configuration conf = ConfigurationProvider.getProvider( provider ).load( nullTest );
assertEquals( "object", conf.get( "null.null" ) ); Assert.assertEquals( "object", conf.get( "null.null" ) );
assertEquals( "object", conf.getSection( "null" ).get( "null" ) ); Assert.assertEquals( "object", conf.getSection( "null" ).get( "null" ) );
assertEquals( null, conf.get( "null.object" ) ); Assert.assertEquals( null, conf.get( "null.object" ) );
assertEquals( "", conf.getString( "null.object" ) ); Assert.assertEquals( "", conf.getString( "null.object" ) );
} }
@ParameterizedTest @Test
@MethodSource("data") public void testMapAddition()
public void testMapAddition(Class<? extends ConfigurationProvider> provider, String testDocument, String numberTest, String nullTest)
{ {
Configuration conf = ConfigurationProvider.getProvider( provider ).load( testDocument ); Configuration conf = ConfigurationProvider.getProvider( provider ).load( testDocument );
conf.set( "addition", Collections.singletonMap( "foo", "bar" ) ); conf.set( "addition", Collections.singletonMap( "foo", "bar" ) );
// Order matters // Order matters
assertEquals( "bar", conf.getSection( "addition" ).getString( "foo" ) ); Assert.assertEquals( "bar", conf.getSection( "addition" ).getString( "foo" ) );
assertEquals( "bar", conf.getString( "addition.foo" ) ); Assert.assertEquals( "bar", conf.getString( "addition.foo" ) );
assertTrue( conf.get( "addition" ) instanceof Configuration ); Assert.assertTrue( conf.get( "addition" ) instanceof Configuration );
} }
} }

View File

@ -1,7 +1,7 @@
package net.md_5.bungee.config; package net.md_5.bungee.config;
import static org.junit.jupiter.api.Assertions.*; import org.junit.Assert;
import org.junit.jupiter.api.Test; import org.junit.Test;
public class DefaultConfigurationTest public class DefaultConfigurationTest
{ {
@ -16,8 +16,8 @@ public class DefaultConfigurationTest
Configuration actualConfig = new Configuration( defaultConfig ); Configuration actualConfig = new Configuration( defaultConfig );
assertEquals( 10, actualConfig.getInt( "setting" ) ); Assert.assertEquals( 10, actualConfig.getInt( "setting" ) );
assertEquals( 11, actualConfig.getInt( "nested.setting" ) ); Assert.assertEquals( 11, actualConfig.getInt( "nested.setting" ) );
assertEquals( 12, actualConfig.getInt( "double.nested.setting" ) ); Assert.assertEquals( 12, actualConfig.getInt( "double.nested.setting" ) );
} }
} }

View File

@ -1,8 +1,8 @@
package net.md_5.bungee.event; package net.md_5.bungee.event;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class EventBusTest public class EventBusTest
{ {
@ -15,14 +15,14 @@ public class EventBusTest
{ {
bus.register( this ); bus.register( this );
bus.post( new FirstEvent() ); bus.post( new FirstEvent() );
assertEquals( 0, latch.getCount() ); Assert.assertEquals( 0, latch.getCount() );
} }
@EventHandler @EventHandler
public void firstListener(FirstEvent event) public void firstListener(FirstEvent event)
{ {
bus.post( new SecondEvent() ); bus.post( new SecondEvent() );
assertEquals( 1, latch.getCount() ); Assert.assertEquals( 1, latch.getCount() );
latch.countDown(); latch.countDown();
} }

View File

@ -1,8 +1,8 @@
package net.md_5.bungee.event; package net.md_5.bungee.event;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class EventPriorityTest public class EventPriorityTest
{ {
@ -16,41 +16,41 @@ public class EventPriorityTest
bus.register( this ); bus.register( this );
bus.register( new EventPriorityListenerPartner() ); bus.register( new EventPriorityListenerPartner() );
bus.post( new PriorityTestEvent() ); bus.post( new PriorityTestEvent() );
assertEquals( 0, latch.getCount() ); Assert.assertEquals( 0, latch.getCount() );
} }
@EventHandler(priority = Byte.MIN_VALUE) @EventHandler(priority = Byte.MIN_VALUE)
public void onMinPriority(PriorityTestEvent event) public void onMinPriority(PriorityTestEvent event)
{ {
assertEquals( 7, latch.getCount() ); Assert.assertEquals( 7, latch.getCount() );
latch.countDown(); latch.countDown();
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onLowestPriority(PriorityTestEvent event) public void onLowestPriority(PriorityTestEvent event)
{ {
assertEquals( 6, latch.getCount() ); Assert.assertEquals( 6, latch.getCount() );
latch.countDown(); latch.countDown();
} }
@EventHandler @EventHandler
public void onNormalPriority(PriorityTestEvent event) public void onNormalPriority(PriorityTestEvent event)
{ {
assertEquals( 4, latch.getCount() ); Assert.assertEquals( 4, latch.getCount() );
latch.countDown(); latch.countDown();
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onHighestPriority(PriorityTestEvent event) public void onHighestPriority(PriorityTestEvent event)
{ {
assertEquals( 2, latch.getCount() ); Assert.assertEquals( 2, latch.getCount() );
latch.countDown(); latch.countDown();
} }
@EventHandler(priority = Byte.MAX_VALUE) @EventHandler(priority = Byte.MAX_VALUE)
public void onMaxPriority(PriorityTestEvent event) public void onMaxPriority(PriorityTestEvent event)
{ {
assertEquals( 1, latch.getCount() ); Assert.assertEquals( 1, latch.getCount() );
latch.countDown(); latch.countDown();
} }
@ -64,14 +64,14 @@ public class EventPriorityTest
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onHighPriority(PriorityTestEvent event) public void onHighPriority(PriorityTestEvent event)
{ {
assertEquals( 3, latch.getCount() ); Assert.assertEquals( 3, latch.getCount() );
latch.countDown(); latch.countDown();
} }
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void onLowPriority(PriorityTestEvent event) public void onLowPriority(PriorityTestEvent event)
{ {
assertEquals( 5, latch.getCount() ); Assert.assertEquals( 5, latch.getCount() );
latch.countDown(); latch.countDown();
} }
} }

View File

@ -1,8 +1,8 @@
package net.md_5.bungee.event; package net.md_5.bungee.event;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class SubclassTest extends EventBusTest public class SubclassTest extends EventBusTest
{ {
@ -14,13 +14,13 @@ public class SubclassTest extends EventBusTest
public void testNestedEvents() public void testNestedEvents()
{ {
super.testNestedEvents(); super.testNestedEvents();
assertEquals( 0, latch.getCount() ); Assert.assertEquals( 0, latch.getCount() );
} }
@EventHandler @EventHandler
protected void extraListener(FirstEvent event) protected void extraListener(FirstEvent event)
{ {
assertEquals( 1, latch.getCount() ); Assert.assertEquals( 1, latch.getCount() );
latch.countDown(); latch.countDown();
} }
} }

View File

@ -1,7 +1,7 @@
package net.md_5.bungee.event; package net.md_5.bungee.event;
import static org.junit.jupiter.api.Assertions.fail; import org.junit.Assert;
import org.junit.jupiter.api.Test; import org.junit.Test;
public class UnregisteringListenerTest public class UnregisteringListenerTest
{ {
@ -19,7 +19,7 @@ public class UnregisteringListenerTest
@EventHandler @EventHandler
public void onEvent(TestEvent evt) public void onEvent(TestEvent evt)
{ {
fail( "Event listener wasn't unregistered" ); Assert.fail( "Event listener wasn't unregistered" );
} }
public static class TestEvent public static class TestEvent

View File

@ -1,6 +1,5 @@
package net.md_5.bungee; package net.md_5.bungee;
import static org.junit.jupiter.api.Assertions.*;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import java.util.Random; import java.util.Random;
@ -10,11 +9,12 @@ import net.md_5.bungee.jni.NativeCode;
import net.md_5.bungee.jni.cipher.BungeeCipher; import net.md_5.bungee.jni.cipher.BungeeCipher;
import net.md_5.bungee.jni.cipher.JavaCipher; import net.md_5.bungee.jni.cipher.JavaCipher;
import net.md_5.bungee.jni.cipher.NativeCipher; import net.md_5.bungee.jni.cipher.NativeCipher;
import org.junit.jupiter.api.MethodOrderer; import org.junit.Assert;
import org.junit.jupiter.api.Test; import org.junit.FixMethodOrder;
import org.junit.jupiter.api.TestMethodOrder; import org.junit.Test;
import org.junit.runners.MethodSorters;
@TestMethodOrder(MethodOrderer.MethodName.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NativeCipherTest public class NativeCipherTest
{ {
@ -34,7 +34,7 @@ public class NativeCipherTest
if ( NativeCode.isSupported() ) if ( NativeCode.isSupported() )
{ {
boolean loaded = factory.load(); boolean loaded = factory.load();
assertTrue( loaded, "Native cipher failed to load!" ); Assert.assertTrue( "Native cipher failed to load!", loaded );
NativeCipher cipher = new NativeCipher(); NativeCipher cipher = new NativeCipher();
System.out.println( "Testing native cipher..." ); System.out.println( "Testing native cipher..." );
@ -48,7 +48,7 @@ public class NativeCipherTest
if ( NativeCode.isSupported() ) if ( NativeCode.isSupported() )
{ {
boolean loaded = factory.load(); boolean loaded = factory.load();
assertTrue( loaded, "Native cipher failed to load!" ); Assert.assertTrue( "Native cipher failed to load!", loaded );
NativeCipher cipher = new NativeCipher(); NativeCipher cipher = new NativeCipher();
@ -98,7 +98,7 @@ public class NativeCipherTest
// Encrypt // Encrypt
cipher.init( true, secret ); cipher.init( true, secret );
cipher.cipher( nativePlain, out ); cipher.cipher( nativePlain, out );
assertEquals( nativeCiphered, out ); Assert.assertEquals( nativeCiphered, out );
out.clear(); out.clear();
@ -106,7 +106,7 @@ public class NativeCipherTest
cipher.init( false, secret ); cipher.init( false, secret );
cipher.cipher( nativeCiphered, out ); cipher.cipher( nativeCiphered, out );
nativePlain.resetReaderIndex(); nativePlain.resetReaderIndex();
assertEquals( nativePlain, out ); Assert.assertEquals( nativePlain, out );
System.out.println( "This cipher works correctly!" ); System.out.println( "This cipher works correctly!" );
} }

View File

@ -1,6 +1,5 @@
package net.md_5.bungee; package net.md_5.bungee;
import static org.junit.jupiter.api.Assertions.*;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import java.util.Arrays; import java.util.Arrays;
@ -10,7 +9,8 @@ import net.md_5.bungee.jni.NativeCode;
import net.md_5.bungee.jni.zlib.BungeeZlib; import net.md_5.bungee.jni.zlib.BungeeZlib;
import net.md_5.bungee.jni.zlib.JavaZlib; import net.md_5.bungee.jni.zlib.JavaZlib;
import net.md_5.bungee.jni.zlib.NativeZlib; import net.md_5.bungee.jni.zlib.NativeZlib;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class NativeZlibTest public class NativeZlibTest
{ {
@ -22,7 +22,7 @@ public class NativeZlibTest
{ {
if ( NativeCode.isSupported() ) if ( NativeCode.isSupported() )
{ {
assertTrue( factory.load(), "Native code failed to load!" ); Assert.assertTrue( "Native code failed to load!", factory.load() );
test( factory.newInstance() ); test( factory.newInstance() );
} }
test( new JavaZlib() ); test( new JavaZlib() );
@ -64,6 +64,6 @@ public class NativeZlibTest
long elapsed = System.currentTimeMillis() - start; long elapsed = System.currentTimeMillis() - start;
System.out.println( "Took: " + elapsed + "ms" ); System.out.println( "Took: " + elapsed + "ms" );
assertTrue( Arrays.equals( dataBuf, check ), "Results do not match" ); Assert.assertTrue( "Results do not match", Arrays.equals( dataBuf, check ) );
} }
} }

View File

@ -90,9 +90,9 @@
</dependencyManagement> </dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>junit</groupId>
<artifactId>junit-jupiter</artifactId> <artifactId>junit</artifactId>
<version>5.10.0</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -15,7 +15,6 @@ public class MinecraftEncoder extends MessageToByteEncoder<DefinedPacket>
@Setter @Setter
private Protocol protocol; private Protocol protocol;
private boolean server; private boolean server;
@Getter
@Setter @Setter
private int protocolVersion; private int protocolVersion;

View File

@ -658,8 +658,8 @@ public enum Protocol
/*========================================================================*/ /*========================================================================*/
public static final int MAX_PACKET_ID = 0xFF; public static final int MAX_PACKET_ID = 0xFF;
/*========================================================================*/ /*========================================================================*/
public final DirectionData TO_SERVER = new DirectionData( this, ProtocolConstants.Direction.TO_SERVER ); final DirectionData TO_SERVER = new DirectionData( this, ProtocolConstants.Direction.TO_SERVER );
public final DirectionData TO_CLIENT = new DirectionData( this, ProtocolConstants.Direction.TO_CLIENT ); final DirectionData TO_CLIENT = new DirectionData( this, ProtocolConstants.Direction.TO_CLIENT );
public static void main(String[] args) public static void main(String[] args)
{ {
@ -719,7 +719,7 @@ public enum Protocol
return new ProtocolMapping( protocol, id ); return new ProtocolMapping( protocol, id );
} }
public static final class DirectionData static final class DirectionData
{ {
private final TIntObjectMap<ProtocolData> protocols = new TIntObjectHashMap<>(); private final TIntObjectMap<ProtocolData> protocols = new TIntObjectHashMap<>();
@ -802,17 +802,6 @@ public enum Protocol
} }
} }
public boolean hasPacket(Class<? extends DefinedPacket> packet, int version)
{
ProtocolData protocolData = getProtocolData( version );
if ( protocolData == null )
{
throw new BadPacketException( "Unsupported protocol version" );
}
return protocolData.packetMap.containsKey( packet );
}
final int getId(Class<? extends DefinedPacket> packet, int version) final int getId(Class<? extends DefinedPacket> packet, int version)
{ {

View File

@ -1,7 +1,7 @@
package net.md_5.bungee.protocol.packet; package net.md_5.bungee.protocol.packet;
import static org.junit.jupiter.api.Assertions.*; import org.junit.Assert;
import org.junit.jupiter.api.Test; import org.junit.Test;
public class PluginMessageTest public class PluginMessageTest
{ {
@ -9,9 +9,9 @@ public class PluginMessageTest
@Test @Test
public void testModerniseChannel() public void testModerniseChannel()
{ {
assertEquals( "bungeecord:main", PluginMessage.MODERNISE.apply( "BungeeCord" ) ); Assert.assertEquals( "bungeecord:main", PluginMessage.MODERNISE.apply( "BungeeCord" ) );
assertEquals( "BungeeCord", PluginMessage.MODERNISE.apply( "bungeecord:main" ) ); Assert.assertEquals( "BungeeCord", PluginMessage.MODERNISE.apply( "bungeecord:main" ) );
assertEquals( "legacy:foo", PluginMessage.MODERNISE.apply( "FoO" ) ); Assert.assertEquals( "legacy:foo", PluginMessage.MODERNISE.apply( "FoO" ) );
assertEquals( "foo:bar", PluginMessage.MODERNISE.apply( "foo:bar" ) ); Assert.assertEquals( "foo:bar", PluginMessage.MODERNISE.apply( "foo:bar" ) );
} }
} }

View File

@ -5,7 +5,6 @@ import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import lombok.Data; import lombok.Data;
import lombok.Getter; import lombok.Getter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -14,7 +13,6 @@ import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.connection.Server; import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.netty.ChannelWrapper; import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.DefinedPacket;
import net.md_5.bungee.protocol.Protocol;
import net.md_5.bungee.protocol.packet.PluginMessage; import net.md_5.bungee.protocol.packet.PluginMessage;
@RequiredArgsConstructor @RequiredArgsConstructor
@ -32,7 +30,6 @@ public class ServerConnection implements Server
private final boolean forgeServer = false; private final boolean forgeServer = false;
@Getter @Getter
private final Queue<KeepAliveData> keepAlives = new ArrayDeque<>(); private final Queue<KeepAliveData> keepAlives = new ArrayDeque<>();
private final Queue<DefinedPacket> packetQueue = new ConcurrentLinkedQueue<>();
private final Unsafe unsafe = new Unsafe() private final Unsafe unsafe = new Unsafe()
{ {
@ -43,31 +40,10 @@ public class ServerConnection implements Server
} }
}; };
public void sendPacketQueued(DefinedPacket packet)
{
Protocol encodeProtocol = ch.getEncodeProtocol();
if ( !encodeProtocol.TO_SERVER.hasPacket( packet.getClass(), ch.getEncodeVersion() ) )
{
packetQueue.add( packet );
} else
{
unsafe().sendPacket( packet );
}
}
public void sendQueuedPackets()
{
DefinedPacket packet;
while ( ( packet = packetQueue.poll() ) != null )
{
unsafe().sendPacket( packet );
}
}
@Override @Override
public void sendData(String channel, byte[] data) public void sendData(String channel, byte[] data)
{ {
sendPacketQueued( new PluginMessage( channel, data, forgeServer ) ); unsafe().sendPacket( new PluginMessage( channel, data, forgeServer ) );
} }
@Override @Override

View File

@ -20,7 +20,6 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Queue; import java.util.Queue;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level; import java.util.logging.Level;
import lombok.Getter; import lombok.Getter;
import lombok.NonNull; import lombok.NonNull;
@ -143,7 +142,6 @@ public final class UserConnection implements ProxiedPlayer
@Setter @Setter
private ForgeServerHandler forgeServerHandler; private ForgeServerHandler forgeServerHandler;
/*========================================================================*/ /*========================================================================*/
private final Queue<DefinedPacket> packetQueue = new ConcurrentLinkedQueue<>();
private final Unsafe unsafe = new Unsafe() private final Unsafe unsafe = new Unsafe()
{ {
@Override @Override
@ -179,27 +177,6 @@ public final class UserConnection implements ProxiedPlayer
ch.write( packet ); ch.write( packet );
} }
public void sendPacketQueued(DefinedPacket packet)
{
Protocol encodeProtocol = ch.getEncodeProtocol();
if ( !encodeProtocol.TO_CLIENT.hasPacket( packet.getClass(), getPendingConnection().getVersion() ) )
{
packetQueue.add( packet );
} else
{
unsafe().sendPacket( packet );
}
}
public void sendQueuedPackets()
{
DefinedPacket packet;
while ( ( packet = packetQueue.poll() ) != null )
{
unsafe().sendPacket( packet );
}
}
@Deprecated @Deprecated
public boolean isActive() public boolean isActive()
{ {
@ -512,10 +489,10 @@ public final class UserConnection implements ProxiedPlayer
position = ChatMessageType.SYSTEM; position = ChatMessageType.SYSTEM;
} }
sendPacketQueued( new SystemChat( message, position.ordinal() ) ); unsafe().sendPacket( new SystemChat( message, position.ordinal() ) );
} else } else
{ {
sendPacketQueued( new Chat( message, (byte) position.ordinal(), sender ) ); unsafe().sendPacket( new Chat( message, (byte) position.ordinal(), sender ) );
} }
} }
@ -536,7 +513,7 @@ public final class UserConnection implements ProxiedPlayer
net.md_5.bungee.protocol.packet.Title title = new net.md_5.bungee.protocol.packet.Title(); net.md_5.bungee.protocol.packet.Title title = new net.md_5.bungee.protocol.packet.Title();
title.setAction( net.md_5.bungee.protocol.packet.Title.Action.ACTIONBAR ); title.setAction( net.md_5.bungee.protocol.packet.Title.Action.ACTIONBAR );
title.setText( ComponentSerializer.toString( message ) ); title.setText( ComponentSerializer.toString( message ) );
sendPacketQueued( title ); unsafe.sendPacket( title );
} }
} else } else
{ {
@ -547,7 +524,7 @@ public final class UserConnection implements ProxiedPlayer
@Override @Override
public void sendData(String channel, byte[] data) public void sendData(String channel, byte[] data)
{ {
sendPacketQueued( new PluginMessage( channel, data, forgeClientHandler.isForgeUser() ) ); unsafe().sendPacket( new PluginMessage( channel, data, forgeClientHandler.isForgeUser() ) );
} }
@Override @Override
@ -723,7 +700,7 @@ public final class UserConnection implements ProxiedPlayer
header = ChatComponentTransformer.getInstance().transform( this, true, header )[0]; header = ChatComponentTransformer.getInstance().transform( this, true, header )[0];
footer = ChatComponentTransformer.getInstance().transform( this, true, footer )[0]; footer = ChatComponentTransformer.getInstance().transform( this, true, footer )[0];
sendPacketQueued( new PlayerListHeaderFooter( unsafe().sendPacket( new PlayerListHeaderFooter(
ComponentSerializer.toString( header ), ComponentSerializer.toString( header ),
ComponentSerializer.toString( footer ) ComponentSerializer.toString( footer )
) ); ) );
@ -735,7 +712,7 @@ public final class UserConnection implements ProxiedPlayer
header = ChatComponentTransformer.getInstance().transform( this, true, header ); header = ChatComponentTransformer.getInstance().transform( this, true, header );
footer = ChatComponentTransformer.getInstance().transform( this, true, footer ); footer = ChatComponentTransformer.getInstance().transform( this, true, footer );
sendPacketQueued( new PlayerListHeaderFooter( unsafe().sendPacket( new PlayerListHeaderFooter(
ComponentSerializer.toString( header ), ComponentSerializer.toString( header ),
ComponentSerializer.toString( footer ) ComponentSerializer.toString( footer )
) ); ) );

View File

@ -31,7 +31,6 @@ import net.md_5.bungee.protocol.packet.Chat;
import net.md_5.bungee.protocol.packet.ClientChat; import net.md_5.bungee.protocol.packet.ClientChat;
import net.md_5.bungee.protocol.packet.ClientCommand; import net.md_5.bungee.protocol.packet.ClientCommand;
import net.md_5.bungee.protocol.packet.ClientSettings; import net.md_5.bungee.protocol.packet.ClientSettings;
import net.md_5.bungee.protocol.packet.FinishConfiguration;
import net.md_5.bungee.protocol.packet.KeepAlive; import net.md_5.bungee.protocol.packet.KeepAlive;
import net.md_5.bungee.protocol.packet.LoginAcknowledged; import net.md_5.bungee.protocol.packet.LoginAcknowledged;
import net.md_5.bungee.protocol.packet.PlayerListItem; import net.md_5.bungee.protocol.packet.PlayerListItem;
@ -341,21 +340,10 @@ public class UpstreamBridge extends PacketHandler
ch.setDecodeProtocol( Protocol.CONFIGURATION ); ch.setDecodeProtocol( Protocol.CONFIGURATION );
ch.write( new LoginAcknowledged() ); ch.write( new LoginAcknowledged() );
ch.setEncodeProtocol( Protocol.CONFIGURATION ); ch.setEncodeProtocol( Protocol.CONFIGURATION );
con.getServer().sendQueuedPackets();
throw CancelSendSignal.INSTANCE; throw CancelSendSignal.INSTANCE;
} }
} }
@Override
public void handle(FinishConfiguration finishConfiguration) throws Exception
{
con.sendQueuedPackets();
super.handle( finishConfiguration );
}
@Override @Override
public String toString() public String toString()
{ {

View File

@ -69,11 +69,6 @@ public class ChannelWrapper
ch.pipeline().get( MinecraftEncoder.class ).setProtocolVersion( protocol ); ch.pipeline().get( MinecraftEncoder.class ).setProtocolVersion( protocol );
} }
public int getEncodeVersion()
{
return ch.pipeline().get( MinecraftEncoder.class ).getProtocolVersion();
}
public void write(Object packet) public void write(Object packet)
{ {
if ( !closed ) if ( !closed )

View File

@ -1,12 +1,12 @@
package net.md_5.bungee; package net.md_5.bungee;
import static org.junit.jupiter.api.Assertions.*;
import com.google.common.base.Ticker; import com.google.common.base.Ticker;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class ThrottleTest public class ThrottleTest
{ {
@ -38,18 +38,18 @@ public class ThrottleTest
address = new InetSocketAddress( InetAddress.getByName( null ), 0 ); address = new InetSocketAddress( InetAddress.getByName( null ), 0 );
} }
assertFalse( throttle.throttle( address ), "Address should not be throttled" ); // 1 Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); // 1
assertFalse( throttle.throttle( address ), "Address should not be throttled" ); // 2 Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); // 2
assertFalse( throttle.throttle( address ), "Address should not be throttled" ); // 3 Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); // 3
assertTrue( throttle.throttle( address ), "Address should be throttled" ); // The 3rd one must be throttled, but also increased the count to 4 Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); // The 3rd one must be throttled, but also increased the count to 4
throttle.unthrottle( address ); // We are back at 3, next attempt will make it 4 and throttle throttle.unthrottle( address ); // We are back at 3, next attempt will make it 4 and throttle
throttle.unthrottle( address ); // Now we are at 2, will not be throttled throttle.unthrottle( address ); // Now we are at 2, will not be throttled
assertFalse( throttle.throttle( address ), "Address should not be throttled" ); // 3 Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); // 3
assertTrue( throttle.throttle( address ), "Address should be throttled" ); // 4 Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); // 4
// Now test expiration // Now test expiration
ticker.value += TimeUnit.MILLISECONDS.toNanos( 50 ); ticker.value += TimeUnit.MILLISECONDS.toNanos( 50 );
assertFalse( throttle.throttle( address ), "Address should not be throttled" ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
} }
} }

View File

@ -1,13 +1,13 @@
package net.md_5.bungee.scheduler; package net.md_5.bungee.scheduler;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import net.md_5.bungee.api.plugin.DummyPlugin; import net.md_5.bungee.api.plugin.DummyPlugin;
import net.md_5.bungee.api.scheduler.ScheduledTask; import net.md_5.bungee.api.scheduler.ScheduledTask;
import net.md_5.bungee.api.scheduler.TaskScheduler; import net.md_5.bungee.api.scheduler.TaskScheduler;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class SchedulerTest public class SchedulerTest
{ {
@ -31,7 +31,7 @@ public class SchedulerTest
latch.await( 5, TimeUnit.SECONDS ); latch.await( 5, TimeUnit.SECONDS );
assertEquals( 0, latch.getCount() ); Assert.assertEquals( 0, latch.getCount() );
} }
@Test @Test
@ -43,17 +43,17 @@ public class SchedulerTest
ScheduledTask task = setup( scheduler, b ); ScheduledTask task = setup( scheduler, b );
scheduler.cancel( task.getId() ); scheduler.cancel( task.getId() );
Thread.sleep( 250 ); Thread.sleep( 250 );
assertFalse( b.get() ); Assert.assertFalse( b.get() );
task = setup( scheduler, b ); task = setup( scheduler, b );
scheduler.cancel( task ); scheduler.cancel( task );
Thread.sleep( 250 ); Thread.sleep( 250 );
assertFalse( b.get() ); Assert.assertFalse( b.get() );
task = setup( scheduler, b ); task = setup( scheduler, b );
scheduler.cancel( task.getOwner() ); scheduler.cancel( task.getOwner() );
Thread.sleep( 250 ); Thread.sleep( 250 );
assertFalse( b.get() ); Assert.assertFalse( b.get() );
} }
@Test @Test
@ -64,11 +64,11 @@ public class SchedulerTest
setup( scheduler, b ); setup( scheduler, b );
Thread.sleep( 250 ); Thread.sleep( 250 );
assertTrue( b.get() ); Assert.assertTrue( b.get() );
b.set( false ); b.set( false );
Thread.sleep( 250 ); Thread.sleep( 250 );
assertTrue( b.get() ); Assert.assertTrue( b.get() );
} }
private ScheduledTask setup(TaskScheduler scheduler, final AtomicBoolean hasRun) private ScheduledTask setup(TaskScheduler scheduler, final AtomicBoolean hasRun)

View File

@ -1,8 +1,8 @@
package net.md_5.bungee.util; package net.md_5.bungee.util;
import static org.junit.jupiter.api.Assertions.*;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import org.junit.jupiter.api.Test; import org.junit.Assert;
import org.junit.Test;
public class AddressUtilTest public class AddressUtilTest
{ {
@ -11,9 +11,9 @@ public class AddressUtilTest
public void testScope() public void testScope()
{ {
InetSocketAddress addr = new InetSocketAddress( "0:0:0:0:0:0:0:1%0", 25577 ); InetSocketAddress addr = new InetSocketAddress( "0:0:0:0:0:0:0:1%0", 25577 );
assertEquals( "0:0:0:0:0:0:0:1", AddressUtil.sanitizeAddress( addr ) ); Assert.assertEquals( "0:0:0:0:0:0:0:1", AddressUtil.sanitizeAddress( addr ) );
InetSocketAddress addr2 = new InetSocketAddress( "0:0:0:0:0:0:0:1", 25577 ); InetSocketAddress addr2 = new InetSocketAddress( "0:0:0:0:0:0:0:1", 25577 );
assertEquals( "0:0:0:0:0:0:0:1", AddressUtil.sanitizeAddress( addr2 ) ); Assert.assertEquals( "0:0:0:0:0:0:0:1", AddressUtil.sanitizeAddress( addr2 ) );
} }
} }