diff options
author | Jiayu Liu <Jimexist@users.noreply.github.com> | 2022-05-06 03:30:52 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-05-05 15:30:52 -0400 |
commit | 0c9c9df7637154029a88ca6923e1fc2c0a9fd188 (patch) | |
tree | 02f4af68bb31c171fa6e1d0ce6b1db77f3edccaf /lib/java/src | |
parent | ada086529730b13eedb74a975db5167f405d18af (diff) | |
download | thrift-0c9c9df7637154029a88ca6923e1fc2c0a9fd188.tar.gz |
THRIFT-5560: use JUnit 5 for all Java lib tests (#2574)
Diffstat (limited to 'lib/java/src')
67 files changed, 2193 insertions, 2059 deletions
diff --git a/lib/java/src/test/java/org/apache/thrift/Fixtures.java b/lib/java/src/test/java/org/apache/thrift/Fixtures.java index 61f40a590..a8b051866 100644 --- a/lib/java/src/test/java/org/apache/thrift/Fixtures.java +++ b/lib/java/src/test/java/org/apache/thrift/Fixtures.java @@ -33,15 +33,44 @@ import thrift.test.Nesting; import thrift.test.OneOfEach; public class Fixtures { - public static final OneOfEach oneOfEach; - public static final Nesting nesting; - public static final HolyMoley holyMoley; - public static final CompactProtoTestStruct compactProtoTestStruct; + + public static OneOfEach getOneOfEach() { + return oneOfEach.deepCopy(); + } + + public static Nesting getNesting() { + return nesting.deepCopy(); + } + + public static HolyMoley getHolyMoley() { + return holyMoley.deepCopy(); + } + + public static CompactProtoTestStruct getCompactProtoTestStruct() { + return compactProtoTestStruct.deepCopy(); + } + + public static byte[] getPersistentBytesOneOfEach() { + return persistentBytesOneOfEach.clone(); + } + + public static byte[] getPersistentBytesHolyMoley() { + return persistentBytesHolyMoley.clone(); + } + + public static byte[] getPersistentBytesNesting() { + return persistentBytesNesting.clone(); + } + + private static final OneOfEach oneOfEach; + private static final Nesting nesting; + private static final HolyMoley holyMoley; + private static final CompactProtoTestStruct compactProtoTestStruct; // These byte arrays are serialized versions of the above structs. // They were serialized in binary protocol using thrift 0.6.x and are used to // test backwards compatibility with respect to the standard scheme. - public static final byte[] persistentBytesOneOfEach = new byte[] { (byte) 0x02, (byte) 0x00, + private static final byte[] persistentBytesOneOfEach = new byte[] { (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x03, (byte) 0xD6, (byte) 0x06, (byte) 0x00, (byte) 0x04, (byte) 0x69, (byte) 0x78, @@ -81,7 +110,7 @@ public class Fixtures { (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00 }; - public static final byte[] persistentBytesNesting = new byte[] { (byte) 0x0C, (byte) 0x00, + private static final byte[] persistentBytesNesting = new byte[] { (byte) 0x0C, (byte) 0x00, (byte) 0x01, (byte) 0x08, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x7A, (byte) 0x69, (byte) 0x0B, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x13, @@ -129,7 +158,7 @@ public class Fixtures { (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00 }; - public static final byte[] persistentBytesHolyMoley = new byte[] { (byte) 0x0F, (byte) 0x00, + private static final byte[] persistentBytesHolyMoley = new byte[] { (byte) 0x0F, (byte) 0x00, (byte) 0x01, (byte) 0x0C, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x02, (byte) 0x00, (byte) 0x01, (byte) 0x01, (byte) 0x02, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x03, @@ -278,33 +307,33 @@ public class Fixtures { nesting = new Nesting(bonk, oneOfEach); holyMoley = new HolyMoley(); - List<OneOfEach> big = new ArrayList<OneOfEach>(); + List<OneOfEach> big = new ArrayList<>(); big.add(new OneOfEach(oneOfEach)); big.add(nesting.my_ooe); holyMoley.setBig(big); holyMoley.getBig().get(0).setA_bite((byte) 0x22); holyMoley.getBig().get(0).setA_bite((byte) 0x23); - holyMoley.setContain(new HashSet<List<String>>()); - ArrayList<String> stage1 = new ArrayList<String>(2); + holyMoley.setContain(new HashSet<>()); + ArrayList<String> stage1 = new ArrayList<>(2); stage1.add("and a one"); stage1.add("and a two"); holyMoley.getContain().add(stage1); - stage1 = new ArrayList<String>(3); + stage1 = new ArrayList<>(3); stage1.add("then a one, two"); stage1.add("three!"); stage1.add("FOUR!!"); holyMoley.getContain().add(stage1); - stage1 = new ArrayList<String>(0); + stage1 = new ArrayList<>(0); holyMoley.getContain().add(stage1); - ArrayList<Bonk> stage2 = new ArrayList<Bonk>(); - holyMoley.setBonks(new HashMap<String, List<Bonk>>()); + ArrayList<Bonk> stage2 = new ArrayList<>(); + holyMoley.setBonks(new HashMap<>()); // one empty holyMoley.getBonks().put("zero", stage2); // one with two - stage2 = new ArrayList<Bonk>(); + stage2 = new ArrayList<>(); Bonk b = new Bonk(); b.setType(1); b.setMessage("Wait."); @@ -316,7 +345,7 @@ public class Fixtures { holyMoley.getBonks().put("two", stage2); // one with three - stage2 = new ArrayList<Bonk>(); + stage2 = new ArrayList<>(); b = new Bonk(); b.setType(3); b.setMessage("quoth"); diff --git a/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java b/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java index acafaef10..8fd9a97c9 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java +++ b/lib/java/src/test/java/org/apache/thrift/TestDeepCopy.java @@ -1,11 +1,14 @@ package org.apache.thrift; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; import thrift.test.DeepCopyBar; import thrift.test.DeepCopyFoo; -public class TestDeepCopy extends TestCase { +import static org.junit.jupiter.api.Assertions.assertNotSame; +public class TestDeepCopy { + + @Test public void testDeepCopy() throws Exception { final DeepCopyFoo foo = new DeepCopyFoo(); diff --git a/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java b/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java index 683246ba6..b7b291396 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java +++ b/lib/java/src/test/java/org/apache/thrift/TestEnumContainers.java @@ -19,7 +19,7 @@ package org.apache.thrift; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; import thrift.test.enumcontainers.EnumContainersTestConstants; import thrift.test.enumcontainers.GodBean; import thrift.test.enumcontainers.GreekGodGoddess; @@ -29,8 +29,14 @@ import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; -public class TestEnumContainers extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +public class TestEnumContainers { + + @Test public void testEnumContainers() throws Exception { final GodBean b1 = new GodBean(); b1.addToGoddess(GreekGodGoddess.HERA); @@ -51,11 +57,11 @@ public class TestEnumContainers extends TestCase { deserializer.deserialize(b3, bytes); } - assertTrue(b1.getGoddess() != b2.getGoddess()); - assertTrue(b1.getPower() != b2.getPower()); + assertNotSame(b1.getGoddess(), b2.getGoddess()); + assertNotSame(b1.getPower(), b2.getPower()); - assertTrue(b1.getGoddess() != b3.getGoddess()); - assertTrue(b1.getPower() != b3.getPower()); + assertNotSame(b1.getGoddess(), b3.getGoddess()); + assertNotSame(b1.getPower(), b3.getPower()); for (GodBean each : new GodBean[]{b1, b2, b3}) { assertTrue(each.getGoddess().contains(GreekGodGoddess.HERA)); @@ -71,6 +77,7 @@ public class TestEnumContainers extends TestCase { } } + @Test public void testEnumConstants() { assertEquals("lightning bolt", EnumContainersTestConstants.ATTRIBUTES.get(GreekGodGoddess.ZEUS)); assertTrue(EnumContainersTestConstants.ATTRIBUTES instanceof EnumMap); diff --git a/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java b/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java index fc9889890..45662045d 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java +++ b/lib/java/src/test/java/org/apache/thrift/TestFullCamel.java @@ -19,20 +19,19 @@ package org.apache.thrift; -import java.util.HashSet; - -import junit.framework.TestCase; - import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TType; - +import org.junit.jupiter.api.Test; import thrift.test.fullcamel.OneOfEachZZ; import thrift.test.fullcamel.UnderscoreSrv; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + // Sanity check for the code generated by 'fullcamel'. // -public class TestFullCamel extends TestCase { +public class TestFullCamel { + @Test public void testCamelCaseSyntax() throws Exception { TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); @@ -42,10 +41,11 @@ public class TestFullCamel extends TestCase { obj.setImFalse(true); byte[] serBytes = binarySerializer.serialize(obj); binaryDeserializer.deserialize(obj, serBytes); - assertTrue( obj.getABite() == (byte) 0xae ); - assertTrue( obj.isImFalse() == true ); + assertEquals((byte) 0xae, obj.getABite()); + assertTrue(obj.isImFalse()); } + @Test public void testCamelCaseRpcMethods() throws Exception { final UnderscoreSrv.Iface srv = new UnderscoreSrv.Iface() { @Override diff --git a/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java b/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java index 85e7966bf..7b00cca2a 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java +++ b/lib/java/src/test/java/org/apache/thrift/TestMultiplexedProcessor.java @@ -19,40 +19,41 @@ package org.apache.thrift; +import org.apache.thrift.protocol.TMessage; +import org.apache.thrift.protocol.TMessageType; +import org.apache.thrift.protocol.TProtocol; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.junit.Before; -import org.junit.Test; - public class TestMultiplexedProcessor { private TMultiplexedProcessor mp; private TProtocol iprot; private TProtocol oprot; - @Before + @BeforeEach public void setUp() throws Exception { mp = new TMultiplexedProcessor(); iprot = mock(TProtocol.class); oprot = mock(TProtocol.class); } - @Test(expected = TException.class) + @Test public void testWrongMessageType() throws TException { when (iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.REPLY, 42)); - mp.process(iprot, oprot); + assertThrows(TException.class, ()->mp.process(iprot, oprot)); } - @Test(expected = TException.class) + @Test public void testNoSuchService() throws TException { when(iprot.readMessageBegin()).thenReturn(new TMessage("service:func", TMessageType.CALL, 42)); - mp.process(iprot, oprot); + assertThrows(TException.class, ()->mp.process(iprot, oprot)); } static class StubProcessor implements TProcessor { diff --git a/lib/java/src/test/java/org/apache/thrift/TestOptionType.java b/lib/java/src/test/java/org/apache/thrift/TestOptionType.java index ddde9d35f..6365203af 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestOptionType.java +++ b/lib/java/src/test/java/org/apache/thrift/TestOptionType.java @@ -19,10 +19,16 @@ package org.apache.thrift; -import junit.framework.TestCase; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; // Tests and documents behavior for the "Option<T>" type -public class TestOptionType extends TestCase { +public class TestOptionType { + @Test public void testSome() { String name = "Chuck Norris"; Option<String> option = Option.fromNullable(name); @@ -34,6 +40,7 @@ public class TestOptionType extends TestCase { assertEquals(option.get(),"Chuck Norris"); } + @Test public void testNone() throws Exception { String name = null; Option<String> option = Option.fromNullable(name); @@ -43,23 +50,18 @@ public class TestOptionType extends TestCase { assertEquals("None", option.toString()); assertEquals(option.or("default value"), "default value"); // Expect exception - try { - Object value = option.get(); - fail("Expected IllegalStateException, got no exception"); - } catch (IllegalStateException ex) { - - } catch(Exception ex) { - fail("Expected IllegalStateException, got some other exception: "+ex.toString()); - } + assertThrows(IllegalStateException.class, option::get); } + @Test public void testMakeSome() throws Exception { Option<String> some = Option.some("wee"); - assertTrue(some instanceof Option.Some); + assertTrue(some.isDefined()); } + @Test public void testMakeNone() throws Exception { Option<Integer> none = Option.none(); - assertTrue(none instanceof Option.None); + assertFalse(none.isDefined()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestOptionals.java b/lib/java/src/test/java/org/apache/thrift/TestOptionals.java index b34e06dd3..38322eeee 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestOptionals.java +++ b/lib/java/src/test/java/org/apache/thrift/TestOptionals.java @@ -19,70 +19,78 @@ package org.apache.thrift; -import junit.framework.TestCase; - -import thrift.test.Opt4; +import org.junit.jupiter.api.Test; import thrift.test.Opt30; +import thrift.test.Opt4; import thrift.test.Opt64; import thrift.test.Opt80; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + // Exercises the isSet methods using structs from ManyOptionals.thrift -public class TestOptionals extends TestCase { +public class TestOptionals { + @Test public void testEncodingUtils() throws Exception { assertEquals((short)0x8, EncodingUtils.setBit((short)0, 3, true)); assertEquals((short)0, EncodingUtils.setBit((short)0x8, 3, false)); - assertEquals(true, EncodingUtils.testBit((short)0x8, 3)); - assertEquals(false, EncodingUtils.testBit((short)0x8, 4)); + assertTrue(EncodingUtils.testBit((short) 0x8, 3)); + assertFalse(EncodingUtils.testBit((short) 0x8, 4)); assertEquals(Short.MIN_VALUE, EncodingUtils.setBit((short)0, 15, true)); assertEquals((short)0, EncodingUtils.setBit(Short.MIN_VALUE, 15, false)); - assertEquals(true, EncodingUtils.testBit(Short.MIN_VALUE, 15)); - assertEquals(false, EncodingUtils.testBit(Short.MIN_VALUE, 14)); + assertTrue(EncodingUtils.testBit(Short.MIN_VALUE, 15)); + assertFalse(EncodingUtils.testBit(Short.MIN_VALUE, 14)); } + @Test public void testOpt4() throws Exception { Opt4 x = new Opt4(); - assertEquals(false, x.isSetDef1()); + assertFalse(x.isSetDef1()); x.setDef1(3); - assertEquals(true, x.isSetDef1()); - assertEquals(false, x.isSetDef2()); + assertTrue(x.isSetDef1()); + assertFalse(x.isSetDef2()); Opt4 copy = new Opt4(x); - assertEquals(true, copy.isSetDef1()); + assertTrue(copy.isSetDef1()); copy.unsetDef1(); - assertEquals(false, copy.isSetDef1()); - assertEquals(true, x.isSetDef1()); + assertFalse(copy.isSetDef1()); + assertTrue(x.isSetDef1()); } + @Test public void testOpt30() throws Exception { Opt30 x = new Opt30(); - assertEquals(false, x.isSetDef1()); + assertFalse(x.isSetDef1()); x.setDef1(3); - assertEquals(true, x.isSetDef1()); - assertEquals(false, x.isSetDef2()); + assertTrue(x.isSetDef1()); + assertFalse(x.isSetDef2()); } + @Test public void testOpt64() throws Exception { Opt64 x = new Opt64(); - assertEquals(false, x.isSetDef1()); + assertFalse(x.isSetDef1()); x.setDef1(3); - assertEquals(true, x.isSetDef1()); - assertEquals(false, x.isSetDef2()); + assertTrue(x.isSetDef1()); + assertFalse(x.isSetDef2()); x.setDef64(22); - assertEquals(true, x.isSetDef64()); - assertEquals(false, x.isSetDef63()); + assertTrue(x.isSetDef64()); + assertFalse(x.isSetDef63()); } + @Test public void testOpt80() throws Exception { Opt80 x = new Opt80(); - assertEquals(false, x.isSetDef1()); + assertFalse(x.isSetDef1()); x.setDef1(3); - assertEquals(true, x.isSetDef1()); - assertEquals(false, x.isSetDef2()); + assertTrue(x.isSetDef1()); + assertFalse(x.isSetDef2()); Opt80 copy = new Opt80(x); copy.unsetDef1(); - assertEquals(false, copy.isSetDef1()); - assertEquals(true, x.isSetDef1()); + assertFalse(copy.isSetDef1()); + assertTrue(x.isSetDef1()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java b/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java index 93dacedda..2f3cf3bad 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java +++ b/lib/java/src/test/java/org/apache/thrift/TestOptionalsWithJdk8.java @@ -19,12 +19,18 @@ package org.apache.thrift; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; import thrift.test.optiontypejdk8.Person; +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; + // Tests and documents behavior for the JDK8 "Option<T>" type -public class TestOptionalsWithJdk8 extends TestCase { +public class TestOptionalsWithJdk8 { + @Test public void testConstruction() { Person person = new Person(1L, "name"); assertFalse(person.getAge().isPresent()); @@ -42,6 +48,7 @@ public class TestOptionalsWithJdk8 extends TestCase { assertEquals(Integer.valueOf(0), person.getPetsSize().orElse(0)); } + @Test public void testEmpty() { Person person = new Person(); person.setPhone("phone"); diff --git a/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java b/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java index d691fe356..b38f39c8f 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java +++ b/lib/java/src/test/java/org/apache/thrift/TestRenderedDoubleConstants.java @@ -19,38 +19,41 @@ package org.apache.thrift; -import java.util.List; -import junit.framework.TestCase; -import static org.junit.Assert.*; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import thrift.test.DoubleConstantsTestConstants; -public class TestRenderedDoubleConstants extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestRenderedDoubleConstants { private static final double EPSILON = 0.0000001; private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST = - "failed to verify a double constant generated by Thrift (expected = %f, got = %f)"; + "failed to verify a double constant generated by Thrift (expected = %f, got = %f)"; private static final String ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST = - "failed to verify a list item by Thrift (expected = %f, got = %f)"; + "failed to verify a list item by Thrift (expected = %f, got = %f)"; private static final String ASSERTION_MESSAGE_FOR_TYPE_CHECKS = - "the rendered variable with name %s is not of double type"; + "the rendered variable with name %s is not of double type"; // to make sure lists containing doubles are generated correctly + @Test public void testRenderedDoubleList() throws Exception { final double[] EXPECTED_LIST = - {1d,-100d,100d,9223372036854775807d,-9223372036854775807d,3.14159265359,1000000.1,-1000000.1,1.7e+308, - -1.7e+308,9223372036854775816.43,-9223372036854775816.43}; + {1d, -100d, 100d, 9223372036854775807d, -9223372036854775807d, 3.14159265359, 1000000.1, -1000000.1, 1.7e+308, + -1.7e+308, 9223372036854775816.43, -9223372036854775816.43}; assertEquals(EXPECTED_LIST.length, DoubleConstantsTestConstants.DOUBLE_LIST_TEST.size()); for (int i = 0; i < EXPECTED_LIST.length; ++i) { assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST, EXPECTED_LIST[i], - DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i)), - EXPECTED_LIST[i], DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i), EPSILON); + DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i), EPSILON, String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_LIST_TEST, + EXPECTED_LIST[i], + DoubleConstantsTestConstants.DOUBLE_LIST_TEST.get(i))); } } // to make sure the variables inside Thrift files are generated correctly + @Test public void testRenderedDoubleConstants() throws Exception { final double EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT = 1.0; final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT = -100.0; @@ -64,116 +67,115 @@ public class TestRenderedDoubleConstants extends TestCase { final double EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE = -1.7e+308; final double EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE = -9223372036854775816.43; assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST, EPSILON, String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_SMALL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); assertEquals( - String.format( - ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST), - EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON); + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST, EPSILON, + String.format( + ASSERTION_MESSAGE_FOR_RENDERED_DOUBLE_CONSTANTS_TEST, + EXPECTED_DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE, + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_INT_CONSTANT_TEST")); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_INT_CONSTANT_TEST")); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGEST_INT_CONSTANT_TEST")); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALLEST_INT_CONSTANT_TEST")); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_DOUBLE_WITH_MANY_DECIMALS_TEST")); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_FRACTIONAL_DOUBLE_TEST")); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_FRACTIONAL_DOUBLE_TEST")); //assertTrue( // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST"), // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_DOUBLE_TEST)); assertTrue( - String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST"), - Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST)); + Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST), + String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_LARGE_FRACTIONAL_DOUBLE_TEST")); //assertTrue( // String.format(ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST"), // Double.class.isInstance(DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_SMALL_DOUBLE_TEST)); assertTrue( - String.format( - ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST"), - Double.class.isInstance( - DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST)); + Double.class.isInstance( + DoubleConstantsTestConstants.DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST), + String.format( + ASSERTION_MESSAGE_FOR_TYPE_CHECKS, "DOUBLE_ASSIGNED_TO_NEGATIVE_BUT_LARGE_FRACTIONAL_DOUBLE_TEST")); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestReuse.java b/lib/java/src/test/java/org/apache/thrift/TestReuse.java index 2482d3925..56dc1d4ed 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestReuse.java +++ b/lib/java/src/test/java/org/apache/thrift/TestReuse.java @@ -19,25 +19,29 @@ package org.apache.thrift; -import java.util.HashSet; - import org.apache.thrift.protocol.TBinaryProtocol; - +import org.junit.jupiter.api.Test; import thrift.test.Reuse; +import java.util.HashSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + // Tests reusing objects for deserialization. // public class TestReuse extends TestStruct { + @Test public void testReuseObject() throws Exception { TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); Reuse ru1 = new Reuse(); - HashSet<String> hs1 = new HashSet<String>(); + HashSet<String> hs1 = new HashSet<>(); byte[] serBytes; - String st1 = new String("string1"); - String st2 = new String("string2"); + String st1 = "string1"; + String st2 = "string2"; ru1.setVal1(11); ru1.setVal2(hs1); @@ -50,8 +54,8 @@ public class TestReuse extends TestStruct { binaryDeserializer.deserialize(ru1, serBytes); - assertTrue( ru1.getVal2() == hs1 ); - assertTrue( hs1.size() == 2 ); + assertSame(hs1, ru1.getVal2()); + assertEquals(2, hs1.size()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestStruct.java b/lib/java/src/test/java/org/apache/thrift/TestStruct.java index 3379ed120..84b00b4fb 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestStruct.java +++ b/lib/java/src/test/java/org/apache/thrift/TestStruct.java @@ -18,16 +18,6 @@ */ package org.apache.thrift; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - import org.apache.thrift.meta_data.FieldMetaData; import org.apache.thrift.meta_data.ListMetaData; import org.apache.thrift.meta_data.MapMetaData; @@ -35,7 +25,7 @@ import org.apache.thrift.meta_data.SetMetaData; import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TType; - +import org.junit.jupiter.api.Test; import thrift.test.Bonk; import thrift.test.CrazyNesting; import thrift.test.HolyMoley; @@ -48,12 +38,29 @@ import thrift.test.StructA; import thrift.test.StructB; import thrift.test.Xtruct; -public class TestStruct extends TestCase { +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestStruct { + @Test public void testIdentity() throws Exception { TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); - OneOfEach ooe = Fixtures.oneOfEach; + OneOfEach ooe = Fixtures.getOneOfEach(); Nesting n = new Nesting(); n.my_ooe = ooe; @@ -66,9 +73,9 @@ public class TestStruct extends TestCase { "\u043e\u0261\u0433\u0430\u03c1\u210e\u0020"+ "\u0391\u0074\u0074\u03b1\u217d\u03ba\u01c3"+ "\u203c"; - n.my_bonk = Fixtures.nesting.my_bonk; + n.my_bonk = Fixtures.getNesting().my_bonk; - HolyMoley hm = Fixtures.holyMoley; + HolyMoley hm = Fixtures.getHolyMoley(); OneOfEach ooe2 = new OneOfEach(); binaryDeserializer.deserialize( @@ -96,11 +103,12 @@ public class TestStruct extends TestCase { assertEquals(hm.hashCode(), hm2.hashCode()); } + @Test public void testDeepCopy() throws Exception { TSerializer binarySerializer = new TSerializer(new TBinaryProtocol.Factory()); TDeserializer binaryDeserializer = new TDeserializer(new TBinaryProtocol.Factory()); - HolyMoley hm = Fixtures.holyMoley; + HolyMoley hm = Fixtures.getHolyMoley(); byte[] binaryCopy = binarySerializer.serialize(hm); HolyMoley hmCopy = new HolyMoley(); @@ -121,6 +129,7 @@ public class TestStruct extends TestCase { assertFalse(hm.equals(hmCopy2)); } + @Test public void testCompareTo() throws Exception { Bonk bonk1 = new Bonk(); Bonk bonk2 = new Bonk(); @@ -150,6 +159,7 @@ public class TestStruct extends TestCase { assertEquals(0, bonk1.compareTo(bonk2)); } + @Test public void testCompareToWithDataStructures() { Insanity insanity1 = new Insanity(); Insanity insanity2 = new Insanity(); @@ -162,7 +172,7 @@ public class TestStruct extends TestCase { expectGreaterThan(insanity1, insanity2); // insanity1.map = {2:1}, insanity2.map = null - insanity1.getUserMap().put(Numberz.TWO, 1l); + insanity1.getUserMap().put(Numberz.TWO, 1L); expectGreaterThan(insanity1, insanity2); // insanity1.map = {2:1}, insanity2.map = {} @@ -170,34 +180,35 @@ public class TestStruct extends TestCase { expectGreaterThan(insanity1, insanity2); // insanity1.map = {2:1}, insanity2.map = {2:2} - insanity2.getUserMap().put(Numberz.TWO, 2l); + insanity2.getUserMap().put(Numberz.TWO, 2L); expectLessThan(insanity1, insanity2); // insanity1.map = {2:1, 3:5}, insanity2.map = {2:2} - insanity1.getUserMap().put(Numberz.THREE, 5l); + insanity1.getUserMap().put(Numberz.THREE, 5L); expectGreaterThan(insanity1, insanity2); // insanity1.map = {2:1, 3:5}, insanity2.map = {2:1, 4:5} - insanity2.getUserMap().put(Numberz.TWO, 1l); - insanity2.getUserMap().put(Numberz.FIVE, 5l); + insanity2.getUserMap().put(Numberz.TWO, 1L); + insanity2.getUserMap().put(Numberz.FIVE, 5L); expectLessThan(insanity1, insanity2); } private void expectLessThan(Insanity insanity1, Insanity insanity2) { int compareTo = insanity1.compareTo(insanity2); - assertTrue(insanity1 + " should be less than " + insanity2 + ", but is: " + compareTo, compareTo < 0); + assertTrue(compareTo < 0, insanity1 + " should be less than " + insanity2 + ", but is: " + compareTo); } private void expectGreaterThan(Insanity insanity1, Insanity insanity2) { int compareTo = insanity1.compareTo(insanity2); - assertTrue(insanity1 + " should be greater than " + insanity2 + ", but is: " + compareTo, compareTo > 0); + assertTrue(compareTo > 0, insanity1 + " should be greater than " + insanity2 + ", but is: " + compareTo); } private void expectEquals(Insanity insanity1, Insanity insanity2) { int compareTo = insanity1.compareTo(insanity2); - assertEquals(insanity1 + " should be equal to " + insanity2 + ", but is: " + compareTo, 0, compareTo); + assertEquals(0, compareTo, insanity1 + " should be equal to " + insanity2 + ", but is: " + compareTo); } + @Test public void testMetaData() throws Exception { Map<CrazyNesting._Fields, FieldMetaData> mdMap = CrazyNesting.metaDataMap; @@ -251,6 +262,7 @@ public class TestStruct extends TestCase { assertFalse(vmd.keyMetaData.isTypedef()); } + @Test public void testToString() throws Exception { JavaTestHelper object = new JavaTestHelper(); object.req_int = 0; @@ -277,7 +289,7 @@ public class TestStruct extends TestCase { "97 6A 95 6C 93 6E 91 70 8F 72 8D 74 8B 76 89 78 87 7A 85 7C 83 "+ "7E 81)", object.toString()); - + object.req_bin = ByteBuffer.wrap(new byte[] { 0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20, -21, 22, -23, 24, -25, 26, -27, 28, -29, @@ -304,18 +316,13 @@ public class TestStruct extends TestCase { object.req_bin = ByteBuffer.wrap(new byte[] {}); object.setOpt_binIsSet(true); - assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:)", + assertEquals("JavaTestHelper(req_int:0, req_obj:, req_bin:)", object.toString()); } - private static void assertArrayEquals(byte[] expected, byte[] actual) { - if (!java.util.Arrays.equals(expected, actual)) { - fail("Expected byte array did not match actual."); - } - } - + @Test public void testBytesBufferFeatures() throws Exception { - + final String testString = "testBytesBufferFeatures"; final JavaTestHelper o = new JavaTestHelper(); @@ -344,11 +351,12 @@ public class TestStruct extends TestCase { assertArrayEquals(testString.getBytes(), o.getReq_bin()); } + @Test public void testJavaSerializable() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); - - OneOfEach ooe = Fixtures.oneOfEach; + + OneOfEach ooe = Fixtures.getOneOfEach(); // Serialize ooe the Java way... oos.writeObject(ooe); @@ -362,35 +370,21 @@ public class TestStruct extends TestCase { assertEquals(ooe, ooe2); } + @Test public void testSubStructValidation() throws Exception { StructA valid = new StructA("valid"); StructA invalid = new StructA(); StructB b = new StructB(); - try { - b.validate(); - fail(); - } catch (TException e) { - // expected - } + assertThrows(TException.class, b::validate); b = new StructB().setAb(valid); b.validate(); b = new StructB().setAb(invalid); - try { - b.validate(); - fail(); - } catch (TException e) { - // expected - } + assertThrows(TException.class, b::validate); b = new StructB().setAb(valid).setAa(invalid); - try { - b.validate(); - fail(); - } catch (TException e) { - // expected - } + assertThrows(TException.class, b::validate); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java b/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java index 8b0855525..b877afa3b 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTBaseHelper.java @@ -18,6 +18,8 @@ */ package org.apache.thrift; +import org.junit.jupiter.api.Test; + import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; @@ -26,18 +28,25 @@ import java.util.List; import java.util.Map; import java.util.Set; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + + -public class TestTBaseHelper extends TestCase { +public class TestTBaseHelper { + @Test public void testByteArrayComparison() { assertTrue(TBaseHelper.compareTo(new byte[]{'a','b'}, new byte[]{'a','c'}) < 0); } + @Test public void testSets() { - Set<String> a = new HashSet<String>(); - Set<String> b = new HashSet<String>(); + Set<String> a = new HashSet<>(); + Set<String> b = new HashSet<>(); - assertTrue(TBaseHelper.compareTo(a, b) == 0); + assertEquals(0, TBaseHelper.compareTo(a, b)); a.add("test"); @@ -45,7 +54,7 @@ public class TestTBaseHelper extends TestCase { b.add("test"); - assertTrue(TBaseHelper.compareTo(a, b) == 0); + assertEquals(0, TBaseHelper.compareTo(a, b)); b.add("aardvark"); @@ -56,40 +65,43 @@ public class TestTBaseHelper extends TestCase { assertTrue(TBaseHelper.compareTo(a, b) > 0); } + @Test public void testNestedStructures() { - Set<List<String>> a = new HashSet<List<String>>(); - Set<List<String>> b = new HashSet<List<String>>(); + Set<List<String>> a = new HashSet<>(); + Set<List<String>> b = new HashSet<>(); - a.add(Arrays.asList(new String[] {"a","b"})); - b.add(Arrays.asList(new String[] {"a","b", "c"})); - a.add(Arrays.asList(new String[] {"a","b"})); - b.add(Arrays.asList(new String[] {"a","b", "c"})); + a.add(Arrays.asList("a","b")); + b.add(Arrays.asList("a","b", "c")); + a.add(Arrays.asList("a","b")); + b.add(Arrays.asList("a","b", "c")); assertTrue(TBaseHelper.compareTo(a, b) < 0); } + @Test public void testMapsInSets() { - Set<Map<String, Long>> a = new HashSet<Map<String, Long>>(); - Set<Map<String, Long>> b = new HashSet<Map<String, Long>>(); + Set<Map<String, Long>> a = new HashSet<>(); + Set<Map<String, Long>> b = new HashSet<>(); - assertTrue(TBaseHelper.compareTo(a, b) == 0); + assertEquals(0, TBaseHelper.compareTo(a, b)); - Map<String, Long> innerA = new HashMap<String, Long>(); - Map<String, Long> innerB = new HashMap<String, Long>(); + Map<String, Long> innerA = new HashMap<>(); + Map<String, Long> innerB = new HashMap<>(); a.add(innerA); b.add(innerB); - innerA.put("a", 1l); - innerB.put("a", 2l); + innerA.put("a", 1L); + innerB.put("a", 2L); assertTrue(TBaseHelper.compareTo(a, b) < 0); } + @Test public void testByteArraysInMaps() { - Map<byte[], Long> a = new HashMap<byte[], Long>(); - Map<byte[], Long> b = new HashMap<byte[], Long>(); + Map<byte[], Long> a = new HashMap<>(); + Map<byte[], Long> b = new HashMap<>(); - assertTrue(TBaseHelper.compareTo(a, b) == 0); + assertEquals(0, TBaseHelper.compareTo(a, b)); a.put(new byte[]{'a','b'}, 1000L); b.put(new byte[]{'a','b'}, 1000L); @@ -98,38 +110,42 @@ public class TestTBaseHelper extends TestCase { assertTrue(TBaseHelper.compareTo(a, b) > 0); } + @Test public void testMapsWithNulls() { - Map<String, String> a = new HashMap<String, String>(); - Map<String, String> b = new HashMap<String, String>(); + Map<String, String> a = new HashMap<>(); + Map<String, String> b = new HashMap<>(); a.put("a", null); a.put("b", null); b.put("a", null); b.put("b", null); - assertTrue(TBaseHelper.compareTo(a, b) == 0); + assertEquals(0, TBaseHelper.compareTo(a, b)); } + @Test public void testMapKeyComparison() { - Map<String, String> a = new HashMap<String, String>(); - Map<String, String> b = new HashMap<String, String>(); + Map<String, String> a = new HashMap<>(); + Map<String, String> b = new HashMap<>(); a.put("a", "a"); b.put("b", "a"); assertTrue(TBaseHelper.compareTo(a, b) < 0); } + @Test public void testMapValueComparison() { - Map<String, String> a = new HashMap<String, String>(); - Map<String, String> b = new HashMap<String, String>(); + Map<String, String> a = new HashMap<>(); + Map<String, String> b = new HashMap<>(); a.put("a", "b"); b.put("a", "a"); assertTrue(TBaseHelper.compareTo(a, b) > 0); } + @Test public void testByteArraysInSets() { - Set<byte[]> a = new HashSet<byte[]>(); - Set<byte[]> b = new HashSet<byte[]>(); + Set<byte[]> a = new HashSet<>(); + Set<byte[]> b = new HashSet<>(); if (TBaseHelper.compareTo(a, b) != 0) throw new RuntimeException("Set compare failed:" + a + " vs. " + b); @@ -141,20 +157,23 @@ public class TestTBaseHelper extends TestCase { assertTrue(TBaseHelper.compareTo(a, b) > 0); } + @Test public void testByteBufferToByteArray() throws Exception { byte[] b1 = {10,9,8,7,6,5,4,3,2,1,0}; byte[] b2 = TBaseHelper.byteBufferToByteArray(ByteBuffer.wrap(b1)); - assertEquals("b1 and b2 should be the exact same array (identity) due to fast path", b1, b2); + assertEquals(b1, b2, "b1 and b2 should be the exact same array (identity) due to fast path"); byte[] b3 = TBaseHelper.byteBufferToByteArray(ByteBuffer.wrap(b1, 1, 3)); assertEquals(3, b3.length); assertEquals(ByteBuffer.wrap(b1, 1, 3), ByteBuffer.wrap(b3)); } + @Test public void testRightSize() throws Exception { assertNull(TBaseHelper.rightSize(null)); } + @Test public void testByteBufferToString() { byte[] array = new byte[]{1, 2, 3}; ByteBuffer bb = ByteBuffer.wrap(array, 1, 2); @@ -172,6 +191,7 @@ public class TestTBaseHelper extends TestCase { assertEquals("02 03", sb.toString()); } + @Test public void testCopyBinaryWithByteBuffer() throws Exception { byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; ByteBuffer b = ByteBuffer.wrap(bytes); @@ -198,6 +218,7 @@ public class TestTBaseHelper extends TestCase { assertNull(TBaseHelper.copyBinary((ByteBuffer)null)); } + @Test public void testCopyBinaryWithByteArray() throws Exception { byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; byte[] copy = TBaseHelper.copyBinary(bytes); diff --git a/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java b/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java index a4a353d6c..c3b588e61 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTDeserializer.java @@ -18,34 +18,35 @@ */ package org.apache.thrift; -import java.nio.ByteBuffer; - -import junit.framework.TestCase; - import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TJSONProtocol; import org.apache.thrift.protocol.TProtocolFactory; - +import org.junit.jupiter.api.Test; import thrift.test.Backwards; import thrift.test.OneOfEach; import thrift.test.PrimitiveThenStruct; import thrift.test.StructWithAUnion; import thrift.test.TestUnion; -public class TestTDeserializer extends TestCase { +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestTDeserializer { private static final TProtocolFactory[] PROTOCOLS = new TProtocolFactory[] { - new TBinaryProtocol.Factory(), - new TCompactProtocol.Factory(), + new TBinaryProtocol.Factory(), + new TCompactProtocol.Factory(), new TJSONProtocol.Factory() }; + @Test public void testPartialDeserialize() throws Exception { //Root:StructWithAUnion // 1:Union // 1.3:OneOfEach - OneOfEach level3OneOfEach = Fixtures.oneOfEach; + OneOfEach level3OneOfEach = Fixtures.getOneOfEach(); TestUnion level2TestUnion = new TestUnion(TestUnion._Fields.STRUCT_FIELD, level3OneOfEach); StructWithAUnion level1SWU = new StructWithAUnion(level2TestUnion); @@ -108,15 +109,15 @@ public class TestTDeserializer extends TestCase { } } - public static void testPartialDeserialize(TProtocolFactory protocolFactory, TBase input, TBase output, TBase expected, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { + private void testPartialDeserialize(TProtocolFactory protocolFactory, TBase input, TBase output, TBase expected, TFieldIdEnum fieldIdPathFirst, TFieldIdEnum ... fieldIdPathRest) throws TException { byte[] record = serialize(input, protocolFactory); TDeserializer deserializer = new TDeserializer(protocolFactory); for (int i = 0; i < 2; i++) { TBase outputCopy = output.deepCopy(); deserializer.partialDeserialize(outputCopy, record, fieldIdPathFirst, fieldIdPathRest); - assertEquals("on attempt " + i + ", with " + protocolFactory.toString() - + ", expected " + expected + " but got " + outputCopy, - expected, outputCopy); + assertEquals(expected, + outputCopy, "on attempt " + i + ", with " + protocolFactory + + ", expected " + expected + " but got " + outputCopy); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java b/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java index e2cca4039..e61b1794b 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTEnumHelper.java @@ -18,24 +18,29 @@ */ package org.apache.thrift; +import org.junit.jupiter.api.Test; import thrift.test.Numberz; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class TestTEnumHelper extends TestCase { +public class TestTEnumHelper { + @Test public void testGetByValue_ValidValues() { for (Numberz n: Numberz.values()) { int value = n.getValue(); assertEquals(n, TEnumHelper.getByValue(Numberz.class, value)); - } + } } + @Test public void testGetByValue_InvalidValue() { - assertEquals(null, TEnumHelper.getByValue(Numberz.class, 0)); + assertNull(TEnumHelper.getByValue(Numberz.class, 0)); } + @Test public void testGetByValue_InvalidClass() { - assertEquals(null, TEnumHelper.getByValue(TEnum.class, 0)); + assertNull(TEnumHelper.getByValue(TEnum.class, 0)); } } diff --git a/lib/java/src/test/java/org/apache/thrift/TestTUnion.java b/lib/java/src/test/java/org/apache/thrift/TestTUnion.java index f1e6f0e1f..36e87c027 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestTUnion.java +++ b/lib/java/src/test/java/org/apache/thrift/TestTUnion.java @@ -18,6 +18,19 @@ */ package org.apache.thrift; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.protocol.TTupleProtocol; +import org.apache.thrift.transport.TMemoryBuffer; +import org.junit.jupiter.api.Test; +import thrift.test.ComparableUnion; +import thrift.test.Empty; +import thrift.test.RandomStuff; +import thrift.test.SomeEnum; +import thrift.test.StructWithAUnion; +import thrift.test.TestUnion; +import thrift.test.TestUnionMinusStringField; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; @@ -30,81 +43,63 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.protocol.TTupleProtocol; -import org.apache.thrift.transport.TMemoryBuffer; - -import thrift.test.ComparableUnion; -import thrift.test.Empty; -import thrift.test.RandomStuff; -import thrift.test.SomeEnum; -import thrift.test.StructWithAUnion; -import thrift.test.TestUnion; -import thrift.test.TestUnionMinusStringField; - -public class TestTUnion extends TestCase { +public class TestTUnion { + @Test public void testBasic() throws Exception { - TestUnion union = new TestUnion(); - - assertFalse(union.isSet()); - assertFalse(union.isSetI32_field()); - assertNull(union.getFieldValue()); - - union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); - - assertEquals(Integer.valueOf(25), union.getFieldValue()); - - assertEquals(Integer.valueOf(25), union.getFieldValue(TestUnion._Fields.I32_FIELD)); - - assertTrue(union.isSetI32_field()); - - try { - union.getFieldValue(TestUnion._Fields.STRING_FIELD); - fail("should have thrown an exception"); - } catch (IllegalArgumentException e) { - // cool! + { + TestUnion union = new TestUnion(); + assertFalse(union.isSet()); + assertFalse(union.isSetI32_field()); + assertNull(union.getFieldValue()); } - - union = new TestUnion(); - - // should not throw an exception here - union.hashCode(); - - union.setI32_field(1); - assertEquals(1, union.getI32_field()); - union.hashCode(); - - assertFalse(union.isSetString_field()); - - try { - union.getString_field(); - fail("should have thrown an exception"); - } catch (Exception e) { - // sweet + { + TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); + assertEquals(25, union.getFieldValue()); + assertEquals(25, union.getFieldValue(TestUnion._Fields.I32_FIELD)); + assertTrue(union.isSetI32_field()); + assertThrows(IllegalArgumentException.class, () -> union.getFieldValue(TestUnion._Fields.STRING_FIELD)); + } + { + TestUnion union = new TestUnion(); + // should not throw an exception here + union.hashCode(); + union.setI32_field(1); + assertEquals(1, union.getI32_field()); + union.hashCode(); + assertFalse(union.isSetString_field()); + + assertThrows(Exception.class, union::getString_field); + } + { + TestUnion union = TestUnion.i32_field(1); + assertFalse(union.equals(null)); + } + { + TestUnion union = TestUnion.enum_field(SomeEnum.ONE); + union.hashCode(); + } + { + TestUnion union = new TestUnion(); + // should not throw an exception + union.toString(); } - - union = TestUnion.i32_field(1); - - assertFalse(union.equals((TestUnion)null)); - - union = TestUnion.enum_field(SomeEnum.ONE); - union.hashCode(); - - union = new TestUnion(); - // should not throw an exception - union.toString(); } + @Test public void testCompareTo() throws Exception { ComparableUnion cu = ComparableUnion.string_field("a"); ComparableUnion cu2 = ComparableUnion.string_field("b"); - assertTrue(cu.compareTo(cu) == 0); - assertTrue(cu2.compareTo(cu2) == 0); + assertEquals(0, cu.compareTo(cu)); + assertEquals(0, cu2.compareTo(cu2)); assertTrue(cu.compareTo(cu2) < 0); assertTrue(cu2.compareTo(cu) > 0); @@ -118,10 +113,10 @@ public class TestTUnion extends TestCase { assertTrue(cu.compareTo(cu2) < 0); assertTrue(cu2.compareTo(cu) > 0); - + TestUnion union1 = new TestUnion(TestUnion._Fields.STRUCT_LIST, new ArrayList<RandomStuff>()); TestUnion union2 = new TestUnion(TestUnion._Fields.STRUCT_LIST, new ArrayList<RandomStuff>()); - assertTrue(union1.compareTo(union2) == 0); + assertEquals(0, union1.compareTo(union2)); TestUnion union3 = new TestUnion(TestUnion._Fields.I32_SET, new HashSet<Integer>()); Set<Integer> i32_set = new HashSet<Integer>(); @@ -136,6 +131,7 @@ public class TestTUnion extends TestCase { assertTrue(union5.compareTo(union6) > 0); } + @Test public void testEquality() throws Exception { TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); @@ -152,6 +148,7 @@ public class TestTUnion extends TestCase { assertFalse(union.equals(otherUnion)); } + @Test public void testSerialization() throws Exception { TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); union.setI32_set(Collections.singleton(42)); @@ -186,7 +183,8 @@ public class TestTUnion extends TestCase { swau.write(proto); new Empty().read(proto); } - + + @Test public void testTupleProtocolSerialization () throws Exception { TestUnion union = new TestUnion(TestUnion._Fields.I32_FIELD, 25); union.setI32_set(Collections.singleton(42)); @@ -222,6 +220,7 @@ public class TestTUnion extends TestCase { new Empty().read(proto); } + @Test public void testSkip() throws Exception { TestUnion tu = TestUnion.string_field("string"); byte[] tuSerialized = new TSerializer().serialize(tu); @@ -231,6 +230,7 @@ public class TestTUnion extends TestCase { assertNull(tums.getFieldValue()); } + @Test public void testDeepCopy() throws Exception { byte[] bytes = {1, 2, 3}; ByteBuffer value = ByteBuffer.wrap(bytes); @@ -239,7 +239,8 @@ public class TestTUnion extends TestCase { assertEquals(cu, copy); assertNotSame(cu.bufferForBinary_field().array(), copy.bufferForBinary_field().array()); } - + + @Test public void testToString() throws Exception { byte[] bytes = {1, 2, 3}; ByteBuffer value = ByteBuffer.wrap(bytes); @@ -248,10 +249,11 @@ public class TestTUnion extends TestCase { assertEquals(expectedString, cu.toString()); } + @Test public void testJavaSerializable() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); - + TestUnion tu = TestUnion.string_field("string"); // Serialize tu the Java way... diff --git a/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java b/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java index d1fc21368..7e7fc4b9c 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java +++ b/lib/java/src/test/java/org/apache/thrift/TestUnsafeBinaries.java @@ -19,15 +19,17 @@ package org.apache.thrift; -import java.nio.ByteBuffer; -import java.util.Arrays; - +import org.junit.jupiter.api.Test; import thrift.test.SafeBytes; import thrift.test.UnsafeBytes; +import java.nio.ByteBuffer; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + // test generating types with un-copied byte[]/ByteBuffer input/output // -public class TestUnsafeBinaries extends TestStruct { +public class TestUnsafeBinaries { private static byte[] input() { return new byte[]{1, 1}; @@ -38,6 +40,7 @@ public class TestUnsafeBinaries extends TestStruct { // // constructor doesn't copy + @Test public void testUnsafeConstructor() throws Exception { byte[] input = input(); @@ -45,30 +48,26 @@ public class TestUnsafeBinaries extends TestStruct { input[0] = 2; - assertTrue(Arrays.equals( - new byte[]{2, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); } // getter doesn't copy // note: this behavior is the same with/without the flag, but if this default ever changes, the current behavior // should be retained when using this flag + @Test public void testUnsafeGetter(){ UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); byte[] val = struct.getBytes(); val[0] = 2; - assertTrue(Arrays.equals( - new byte[]{2, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); } // setter doesn't copy + @Test public void testUnsafeSetter(){ UnsafeBytes struct = new UnsafeBytes(); @@ -77,24 +76,19 @@ public class TestUnsafeBinaries extends TestStruct { val[0] = 2; - assertTrue(Arrays.equals( - new byte[]{2, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); } // buffer doens't copy + @Test public void testUnsafeBufferFor(){ UnsafeBytes struct = new UnsafeBytes(ByteBuffer.wrap(input())); ByteBuffer val = struct.bufferForBytes(); val.array()[0] = 2; - assertTrue(Arrays.equals( - new byte[]{2, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{2, 1}, struct.getBytes()); } @@ -102,6 +96,7 @@ public class TestUnsafeBinaries extends TestStruct { // verify that the default generator does not change behavior // + @Test public void testSafeConstructor() { byte[] input = input(); @@ -109,13 +104,11 @@ public class TestUnsafeBinaries extends TestStruct { input[0] = 2; - assertTrue(Arrays.equals( - new byte[]{1, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{1, 1}, struct.getBytes()); } + @Test public void testSafeSetter() { byte[] input = input(); @@ -123,23 +116,18 @@ public class TestUnsafeBinaries extends TestStruct { input[0] = 2; - assertTrue(Arrays.equals( - new byte[]{1, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{1, 1}, struct.getBytes()); } + @Test public void testSafeBufferFor(){ SafeBytes struct = new SafeBytes(ByteBuffer.wrap(input())); ByteBuffer val = struct.bufferForBytes(); val.array()[0] = 2; - assertTrue(Arrays.equals( - new byte[]{1, 1}, - struct.getBytes()) - ); + assertArrayEquals(new byte[]{1, 1}, struct.getBytes()); } diff --git a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java index 392ca22d4..9a755d3be 100644 --- a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java +++ b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClient.java @@ -1,13 +1,16 @@ package org.apache.thrift.async; -import junit.framework.TestCase; import org.apache.thrift.TException; - +import org.junit.jupiter.api.Test; import thrift.test.Srv; import thrift.test.Srv.AsyncClient; -public class TestTAsyncClient extends TestCase { +import static org.junit.jupiter.api.Assertions.assertThrows; + + +public class TestTAsyncClient { + @Test public void testRaisesExceptionWhenUsedConcurrently() throws Exception { TAsyncClientManager mockClientManager = new TAsyncClientManager() { @Override @@ -18,11 +21,6 @@ public class TestTAsyncClient extends TestCase { Srv.AsyncClient c = new AsyncClient(null, mockClientManager, null); c.Janky(0, null); - try { - c.checkReady(); - fail("should have hit an exception"); - } catch (Exception e) { - // awesome - } + assertThrows(Exception.class, c::checkReady); } } diff --git a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java index 0a20e522b..8d12429f7 100644 --- a/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java +++ b/lib/java/src/test/java/org/apache/thrift/async/TestTAsyncClientManager.java @@ -18,20 +18,6 @@ */ package org.apache.thrift.async; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import junit.framework.TestCase; - import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.ServerTestBase; @@ -39,341 +25,373 @@ import org.apache.thrift.server.THsHaServer; import org.apache.thrift.server.THsHaServer.Args; import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TNonblockingSocket; - import org.apache.thrift.transport.TTransportException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import thrift.test.CompactProtoTestStruct; import thrift.test.ExceptionWithAMap; import thrift.test.Srv; import thrift.test.Srv.Iface; -public class TestTAsyncClientManager extends TestCase { - - private THsHaServer server_; - private Thread serverThread_; - private TAsyncClientManager clientManager_; - - public void setUp() throws Exception { - server_ = new THsHaServer(new Args(new TNonblockingServerSocket( - new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(ServerTestBase.PORT))). - processor(new Srv.Processor(new SrvHandler()))); - serverThread_ = new Thread(new Runnable() { - public void run() { - server_.serve(); - } - }); - serverThread_.start(); - clientManager_ = new TAsyncClientManager(); - Thread.sleep(500); - } - - public void tearDown() throws Exception { - server_.stop(); - clientManager_.stop(); - serverThread_.join(); - } - - public void testBasicCall() throws Exception { - Srv.AsyncClient client = getClient(); - basicCall(client); - } - - public void testBasicCallWithTimeout() throws Exception { - Srv.AsyncClient client = getClient(); - client.setTimeout(5000); - basicCall(client); - } - - private static abstract class ErrorCallTest<C extends TAsyncClient, R> { - final void runTest() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference<Exception> error = new AtomicReference<Exception>(); - C client = executeErroringCall(new AsyncMethodCallback<R>() { - @Override - public void onComplete(R response) { - latch.countDown(); - } +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; - @Override - public void onError(Exception exception) { - error.set(exception); - latch.countDown(); - } - }); - latch.await(2, TimeUnit.SECONDS); - assertTrue(client.hasError()); - Exception exception = error.get(); - assertNotNull(exception); - assertSame(exception, client.getError()); - validateError(client, exception); +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestTAsyncClientManager { + + private THsHaServer server_; + private Thread serverThread_; + private TAsyncClientManager clientManager_; + + @BeforeEach + public void setUp() throws Exception { + server_ = new THsHaServer(new Args(new TNonblockingServerSocket( + new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs().port(ServerTestBase.PORT))). + processor(new Srv.Processor(new SrvHandler()))); + serverThread_ = new Thread(new Runnable() { + public void run() { + server_.serve(); + } + }); + serverThread_.start(); + clientManager_ = new TAsyncClientManager(); + Thread.sleep(500); } - /** - * Executes a call that is expected to raise an exception. - * - * @param callback The testing callback that should be installed. - * @return The client the call was made against. - * @throws Exception if there was a problem setting up the client or making the call. - */ - abstract C executeErroringCall(AsyncMethodCallback<R> callback) throws Exception; - - /** - * Further validates the properties of the error raised in the remote call and the state of the - * client after that call. - * - * @param client The client returned from {@link #executeErroringCall(AsyncMethodCallback)}. - * @param error The exception raised by the remote call. - */ - abstract void validateError(C client, Exception error); - } - - public void testUnexpectedRemoteExceptionCall() throws Exception { - new ErrorCallTest<Srv.AsyncClient, Boolean>() { - @Override - Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { - Srv.AsyncClient client = getClient(); - client.declaredExceptionMethod(false, callback); - return client; - } - - @Override - void validateError(Srv.AsyncClient client, Exception error) { - assertFalse(client.hasTimeout()); - assertTrue(error instanceof TException); - } - }.runTest(); - } - - public void testDeclaredRemoteExceptionCall() throws Exception { - new ErrorCallTest<Srv.AsyncClient, Boolean>() { - @Override - Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { - Srv.AsyncClient client = getClient(); - client.declaredExceptionMethod(true, callback); - return client; - } - - @Override - void validateError(Srv.AsyncClient client, Exception error) { - assertFalse(client.hasTimeout()); - assertEquals(ExceptionWithAMap.class, error.getClass()); - ExceptionWithAMap exceptionWithAMap = (ExceptionWithAMap) error; - assertEquals("blah", exceptionWithAMap.getBlah()); - assertEquals(new HashMap<String, String>(), exceptionWithAMap.getMap_field()); - } - }.runTest(); - } - - public void testTimeoutCall() throws Exception { - new ErrorCallTest<Srv.AsyncClient, Integer>() { - @Override - Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Integer> callback) throws Exception { - Srv.AsyncClient client = getClient(); - client.setTimeout(100); - client.primitiveMethod(callback); - return client; - } - - @Override - void validateError(Srv.AsyncClient client, Exception error) { - assertTrue(client.hasTimeout()); - assertTrue(error instanceof TimeoutException); - } - }.runTest(); - } - - public void testVoidCall() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); - Srv.AsyncClient client = getClient(); - client.voidMethod(new FailureLessCallback<Void>() { - @Override - public void onComplete(Void response) { - returned.set(true); - latch.countDown(); - } - }); - latch.await(1, TimeUnit.SECONDS); - assertTrue(returned.get()); - } - - public void testOnewayCall() throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); - Srv.AsyncClient client = getClient(); - client.onewayMethod(new FailureLessCallback<Void>() { - @Override - public void onComplete(Void response) { - returned.set(true); - latch.countDown(); - } - }); - latch.await(1, TimeUnit.SECONDS); - assertTrue(returned.get()); - } - - public void testParallelCalls() throws Exception { - // make multiple calls with deserialization in the selector thread (repro Eric's issue) - int numThreads = 50; - int numCallsPerThread = 100; - List<JankyRunnable> runnables = new ArrayList<JankyRunnable>(); - List<Thread> threads = new ArrayList<Thread>(); - for (int i = 0; i < numThreads; i++) { - JankyRunnable runnable = new JankyRunnable(numCallsPerThread); - Thread thread = new Thread(runnable); - thread.start(); - threads.add(thread); - runnables.add(runnable); + @AfterEach + public void tearDown() throws Exception { + server_.stop(); + clientManager_.stop(); + serverThread_.join(); } - for (Thread thread : threads) { - thread.join(); + + @Test + public void testBasicCall() throws Exception { + Srv.AsyncClient client = getClient(); + basicCall(client); } - int numSuccesses = 0; - for (JankyRunnable runnable : runnables) { - numSuccesses += runnable.getNumSuccesses(); + + @Test + public void testBasicCallWithTimeout() throws Exception { + Srv.AsyncClient client = getClient(); + client.setTimeout(5000); + basicCall(client); } - assertEquals(numThreads * numCallsPerThread, numSuccesses); - } - - private Srv.AsyncClient getClient() throws IOException, TTransportException { - TNonblockingSocket clientSocket = new TNonblockingSocket(ServerTestBase.HOST, ServerTestBase.PORT); - return new Srv.AsyncClient(new TBinaryProtocol.Factory(), clientManager_, clientSocket); - } - - private void basicCall(Srv.AsyncClient client) throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); - client.Janky(1, new FailureLessCallback<Integer>() { - @Override - public void onComplete(Integer response) { - assertEquals(3, response.intValue()); - returned.set(true); - latch.countDown(); - } - - @Override - public void onError(Exception exception) { - try { - StringWriter sink = new StringWriter(); - exception.printStackTrace(new PrintWriter(sink, true)); - fail("unexpected onError with exception " + sink.toString()); - } finally { - latch.countDown(); + + private static abstract class ErrorCallTest<C extends TAsyncClient, R> { + final void runTest() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicReference<Exception> error = new AtomicReference<Exception>(); + C client = executeErroringCall(new AsyncMethodCallback<R>() { + @Override + public void onComplete(R response) { + latch.countDown(); + } + + @Override + public void onError(Exception exception) { + error.set(exception); + latch.countDown(); + } + }); + latch.await(2, TimeUnit.SECONDS); + assertTrue(client.hasError()); + Exception exception = error.get(); + assertNotNull(exception); + assertSame(exception, client.getError()); + validateError(client, exception); } - } - }); - latch.await(100, TimeUnit.SECONDS); - assertTrue(returned.get()); - } - - public class SrvHandler implements Iface { - // Use this method for a standard call testing - @Override - public int Janky(int arg) throws TException { - assertEquals(1, arg); - return 3; - } - // Using this method for timeout testing - sleeps for 1 second before returning - @Override - public int primitiveMethod() throws TException { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return 0; + /** + * Executes a call that is expected to raise an exception. + * + * @param callback The testing callback that should be installed. + * @return The client the call was made against. + * @throws Exception if there was a problem setting up the client or making the call. + */ + abstract C executeErroringCall(AsyncMethodCallback<R> callback) throws Exception; + + /** + * Further validates the properties of the error raised in the remote call and the state of the + * client after that call. + * + * @param client The client returned from {@link #executeErroringCall(AsyncMethodCallback)}. + * @param error The exception raised by the remote call. + */ + abstract void validateError(C client, Exception error); } - @Override - public void methodWithDefaultArgs(int something) throws TException { } + @Test + public void testUnexpectedRemoteExceptionCall() throws Exception { + new ErrorCallTest<Srv.AsyncClient, Boolean>() { + @Override + Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { + Srv.AsyncClient client = getClient(); + client.declaredExceptionMethod(false, callback); + return client; + } - @Override - public CompactProtoTestStruct structMethod() throws TException { - return null; + @Override + void validateError(Srv.AsyncClient client, Exception error) { + assertFalse(client.hasTimeout()); + assertTrue(error instanceof TException); + } + }.runTest(); } - @Override - public void voidMethod() throws TException { - } + @Test + public void testDeclaredRemoteExceptionCall() throws Exception { + new ErrorCallTest<Srv.AsyncClient, Boolean>() { + @Override + Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Boolean> callback) throws Exception { + Srv.AsyncClient client = getClient(); + client.declaredExceptionMethod(true, callback); + return client; + } - @Override - public void onewayMethod() throws TException { + @Override + void validateError(Srv.AsyncClient client, Exception error) { + assertFalse(client.hasTimeout()); + assertEquals(ExceptionWithAMap.class, error.getClass()); + ExceptionWithAMap exceptionWithAMap = (ExceptionWithAMap) error; + assertEquals("blah", exceptionWithAMap.getBlah()); + assertEquals(new HashMap<String, String>(), exceptionWithAMap.getMap_field()); + } + }.runTest(); } - @Override - public boolean declaredExceptionMethod(boolean shouldThrowDeclared) throws TException { - if (shouldThrowDeclared) { - throw new ExceptionWithAMap("blah", new HashMap<String, String>()); - } else { - throw new TException("Unexpected!"); - } + @Test + public void testTimeoutCall() throws Exception { + new ErrorCallTest<Srv.AsyncClient, Integer>() { + @Override + Srv.AsyncClient executeErroringCall(AsyncMethodCallback<Integer> callback) throws Exception { + Srv.AsyncClient client = getClient(); + client.setTimeout(100); + client.primitiveMethod(callback); + return client; + } + + @Override + void validateError(Srv.AsyncClient client, Exception error) { + assertTrue(client.hasTimeout()); + assertTrue(error instanceof TimeoutException); + } + }.runTest(); } - } - private static abstract class FailureLessCallback<T> implements AsyncMethodCallback<T> { - @Override - public void onError(Exception exception) { - fail(exception); + @Test + public void testVoidCall() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + Srv.AsyncClient client = getClient(); + client.voidMethod(new FailureLessCallback<Void>() { + @Override + public void onComplete(Void response) { + returned.set(true); + latch.countDown(); + } + }); + latch.await(1, TimeUnit.SECONDS); + assertTrue(returned.get()); } - } - - private static void fail(Exception exception) { - StringWriter sink = new StringWriter(); - exception.printStackTrace(new PrintWriter(sink, true)); - fail("unexpected error " + sink.toString()); - } - - private class JankyRunnable implements Runnable { - private int numCalls_; - private int numSuccesses_ = 0; - private Srv.AsyncClient client_; - - public JankyRunnable(int numCalls) throws Exception { - numCalls_ = numCalls; - client_ = getClient(); - client_.setTimeout(20000); + + @Test + public void testOnewayCall() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + Srv.AsyncClient client = getClient(); + client.onewayMethod(new FailureLessCallback<Void>() { + @Override + public void onComplete(Void response) { + returned.set(true); + latch.countDown(); + } + }); + latch.await(1, TimeUnit.SECONDS); + assertTrue(returned.get()); } - public int getNumSuccesses() { - return numSuccesses_; + @Test + public void testParallelCalls() throws Exception { + // make multiple calls with deserialization in the selector thread (repro Eric's issue) + int numThreads = 50; + int numCallsPerThread = 100; + List<JankyRunnable> runnables = new ArrayList<JankyRunnable>(); + List<Thread> threads = new ArrayList<Thread>(); + for (int i = 0; i < numThreads; i++) { + JankyRunnable runnable = new JankyRunnable(numCallsPerThread); + Thread thread = new Thread(runnable); + thread.start(); + threads.add(thread); + runnables.add(runnable); + } + for (Thread thread : threads) { + thread.join(); + } + int numSuccesses = 0; + for (JankyRunnable runnable : runnables) { + numSuccesses += runnable.getNumSuccesses(); + } + assertEquals(numThreads * numCallsPerThread, numSuccesses); } - public void run() { - for (int i = 0; i < numCalls_ && !client_.hasError(); i++) { - final int iteration = i; - try { - // connect an async client - final CountDownLatch latch = new CountDownLatch(1); - final AtomicBoolean returned = new AtomicBoolean(false); - client_.Janky(1, new AsyncMethodCallback<Integer>() { + private Srv.AsyncClient getClient() throws IOException, TTransportException { + TNonblockingSocket clientSocket = new TNonblockingSocket(ServerTestBase.HOST, ServerTestBase.PORT); + return new Srv.AsyncClient(new TBinaryProtocol.Factory(), clientManager_, clientSocket); + } + private void basicCall(Srv.AsyncClient client) throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + client.Janky(1, new FailureLessCallback<Integer>() { @Override - public void onComplete(Integer result) { - assertEquals(3, result.intValue()); - returned.set(true); - latch.countDown(); + public void onComplete(Integer response) { + assertEquals(3, response.intValue()); + returned.set(true); + latch.countDown(); } @Override public void onError(Exception exception) { - try { - StringWriter sink = new StringWriter(); - exception.printStackTrace(new PrintWriter(sink, true)); - fail("unexpected onError on iteration " + iteration + ": " + sink.toString()); - } finally { - latch.countDown(); - } + try { + StringWriter sink = new StringWriter(); + exception.printStackTrace(new PrintWriter(sink, true)); + Assertions.fail("unexpected onError with exception " + sink.toString()); + } finally { + latch.countDown(); + } + } + }); + latch.await(100, TimeUnit.SECONDS); + assertTrue(returned.get()); + } + + public static class SrvHandler implements Iface { + // Use this method for a standard call testing + @Override + public int Janky(int arg) throws TException { + assertEquals(1, arg); + return 3; + } + + // Using this method for timeout testing - sleeps for 1 second before returning + @Override + public int primitiveMethod() throws TException { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return 0; + } + + @Override + public void methodWithDefaultArgs(int something) throws TException { + } + + @Override + public CompactProtoTestStruct structMethod() throws TException { + return null; + } + + @Override + public void voidMethod() throws TException { + } + + @Override + public void onewayMethod() throws TException { + } + + @Override + public boolean declaredExceptionMethod(boolean shouldThrowDeclared) throws TException { + if (shouldThrowDeclared) { + throw new ExceptionWithAMap("blah", new HashMap<String, String>()); + } else { + throw new TException("Unexpected!"); + } + } + } + + private static abstract class FailureLessCallback<T> implements AsyncMethodCallback<T> { + @Override + public void onError(Exception exception) { + fail(exception); + } + } + + private static void fail(Exception exception) { + StringWriter sink = new StringWriter(); + exception.printStackTrace(new PrintWriter(sink, true)); + Assertions.fail("unexpected error " + sink); + } + + private class JankyRunnable implements Runnable { + private final int numCalls_; + private int numSuccesses_ = 0; + private final Srv.AsyncClient client_; + + public JankyRunnable(int numCalls) throws Exception { + numCalls_ = numCalls; + client_ = getClient(); + client_.setTimeout(20000); + } + + public int getNumSuccesses() { + return numSuccesses_; + } + + public void run() { + for (int i = 0; i < numCalls_ && !client_.hasError(); i++) { + final int iteration = i; + try { + // connect an async client + final CountDownLatch latch = new CountDownLatch(1); + final AtomicBoolean returned = new AtomicBoolean(false); + client_.Janky(1, new AsyncMethodCallback<Integer>() { + + @Override + public void onComplete(Integer result) { + assertEquals(3, result.intValue()); + returned.set(true); + latch.countDown(); + } + + @Override + public void onError(Exception exception) { + try { + StringWriter sink = new StringWriter(); + exception.printStackTrace(new PrintWriter(sink, true)); + Assertions.fail("unexpected onError on iteration " + iteration + ": " + sink.toString()); + } finally { + latch.countDown(); + } + } + }); + + boolean calledBack = latch.await(30, TimeUnit.SECONDS); + assertTrue(calledBack, "wasn't called back in time on iteration " + iteration); + assertTrue(returned.get(), "onComplete not called on iteration " + iteration); + this.numSuccesses_++; + } catch (Exception e) { + fail(e); + } } - }); - - boolean calledBack = latch.await(30, TimeUnit.SECONDS); - assertTrue("wasn't called back in time on iteration " + iteration, calledBack); - assertTrue("onComplete not called on iteration " + iteration, returned.get()); - this.numSuccesses_++; - } catch (Exception e) { - fail(e); } - } } - } } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java b/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java index 394dcc2e9..152bf4851 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/EnumCacheTest.java @@ -19,12 +19,12 @@ package org.apache.thrift.partial; -import org.apache.thrift.partial.ExceptionAsserts; - import org.apache.thrift.TEnum; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test ThriftCodec serializes and deserializes thrift objects correctly. @@ -85,10 +85,10 @@ public class EnumCacheTest { cache.get(TestEnum.class, 0); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'enumClass' must not be null", - () -> cache.get(null, 1)); + () -> cache.get(null, 1), + "'enumClass' must not be null"); } @Test diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ExceptionAsserts.java b/lib/java/src/test/java/org/apache/thrift/partial/ExceptionAsserts.java deleted file mode 100644 index 239903cf4..000000000 --- a/lib/java/src/test/java/org/apache/thrift/partial/ExceptionAsserts.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.thrift.partial; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public final class ExceptionAsserts { - private ExceptionAsserts() {} - - @FunctionalInterface - public interface CodeThatMayThrow { - void run() throws Exception; - } - - /** - * Asserts that the given code throws an exception of the given type - * and that the exception message contains the given sub-message. - * - * Usage: - * - * ExceptionAsserts.assertThrows( - * IllegalArgumentException.class, - * "'nullArg' must not be null", - * () -> Preconditions.checkNotNull(null, "nullArg")); - * - * Note: JUnit 5 has similar functionality but it will be a long time before - * we move to that framework because of significant differences and lack of - * backward compatibility for some JUnit rules. - */ - public static <E extends Exception> void assertThrows( - Class<E> expectedExceptionClass, - String partialMessage, - CodeThatMayThrow code) { - - Exception thrownException = null; - - try { - code.run(); - } catch (Exception e) { - if (expectedExceptionClass.isAssignableFrom(e.getClass())) { - - thrownException = e; - - if (partialMessage != null) { - String msg = e.getMessage(); - assertNotNull( - String.format("Exception message is null, expected to contain: '%s'", partialMessage), - msg); - assertTrue( - String.format("Exception message '%s' does not contain: '%s'", msg, partialMessage), - msg.contains(partialMessage)); - } - } else { - fail(String.format( - "Expected exception of type %s but got %s", - expectedExceptionClass.getName(), - e.getClass().getName())); - } - } - - if (thrownException == null) { - fail(String.format( - "Expected exception of type %s but got none", - expectedExceptionClass.getName())); - } - } - - public static <E extends Exception> void assertThrows( - Class<E> expectedExceptionClass, - CodeThatMayThrow code) { - assertThrows(expectedExceptionClass, null, code); - } -} diff --git a/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java b/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java index e1209d733..4498e332a 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/PartialThriftComparerTest.java @@ -19,21 +19,18 @@ package org.apache.thrift.partial; -import static org.junit.Assert.*; - import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; -import org.apache.thrift.partial.TestStruct; -import org.apache.thrift.partial.ThriftField; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; -import java.util.Collections; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class PartialThriftComparerTest { private ThriftSerDe serde; @@ -63,13 +60,9 @@ public class PartialThriftComparerTest { StringBuilder sb = new StringBuilder(); TestStruct ts2 = (TestStruct) partialBinaryDeser.partialDeserializeObject(bytesBinary); - if (!comparer.areEqual(ts1, ts2, sb)) { - fail(sb.toString()); - } + assertTrue(comparer.areEqual(ts1, ts2, sb), sb::toString); ts2 = (TestStruct) partialCompactDeser.partialDeserializeObject(bytesCompact); - if (!comparer.areEqual(ts1, ts2, sb)) { - fail(sb.toString()); - } + assertTrue(comparer.areEqual(ts1, ts2, sb), sb::toString); } } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java b/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java index 0a838e970..860f515dd 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/TFieldDataTest.java @@ -21,9 +21,9 @@ package org.apache.thrift.partial; import org.apache.thrift.protocol.TField; import org.apache.thrift.protocol.TType; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TFieldDataTest { diff --git a/lib/java/src/test/java/org/apache/thrift/TestPartialThriftDeserializer.java b/lib/java/src/test/java/org/apache/thrift/partial/TestPartialThriftDeserializer.java index c0c7b892d..722e108ad 100644 --- a/lib/java/src/test/java/org/apache/thrift/TestPartialThriftDeserializer.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/TestPartialThriftDeserializer.java @@ -1,50 +1,49 @@ /* * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file + * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file + * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.thrift.partial; -import static org.junit.Assert.*; - -import org.apache.thrift.partial.TestStruct; -import org.apache.thrift.partial.ThriftField; -import org.apache.thrift.partial.TstEnum; -import org.apache.thrift.partial.ExceptionAsserts; - -import org.apache.thrift.TBase; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; -import org.apache.thrift.TSerializer; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TestPartialThriftDeserializer { private ThriftSerDe serde = new ThriftSerDe(); @@ -59,24 +58,24 @@ public class TestPartialThriftDeserializer { @Test public void testArgChecks() throws TException { // Should not throw. - List<String> fieldNames = Arrays.asList("i32Field"); + List<String> fieldNames = Collections.singletonList("i32Field"); new TDeserializer(TestStruct.class, fieldNames, binaryProtocolFactory); // Verify it throws correctly. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'thriftClass' must not be null", - () -> new TDeserializer(null, fieldNames, binaryProtocolFactory)); + () -> new TDeserializer(null, fieldNames, binaryProtocolFactory), + "'thriftClass' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'fieldNames' must not be null", - () -> new TDeserializer(TestStruct.class, null, binaryProtocolFactory)); + () -> new TDeserializer(TestStruct.class, null, binaryProtocolFactory), + "'fieldNames' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'processor' must not be null", - () -> new TDeserializer(TestStruct.class, fieldNames, null, binaryProtocolFactory)); + () -> new TDeserializer(TestStruct.class, fieldNames, null, binaryProtocolFactory), + "'processor' must not be null"); } /** @@ -119,19 +118,15 @@ public class TestPartialThriftDeserializer { StringBuilder sb = new StringBuilder(); TestStruct ts2 = (TestStruct) partialBinaryDeserializer.partialDeserializeObject(bytesBinary); validatePartialSimpleField(ts1, ts2); - if (!comparer.areEqual(ts1, ts2, sb)) { - fail(sb.toString()); - } + assertTrue(comparer.areEqual(ts1, ts2, sb), sb::toString); ts2 = (TestStruct) partialCompactDeserializer.partialDeserializeObject(bytesCompact); validatePartialSimpleField(ts1, ts2); - if (!comparer.areEqual(ts1, ts2, sb)) { - fail(sb.toString()); - } + assertTrue(comparer.areEqual(ts1, ts2, sb), sb::toString); } private void validatePartialSimpleField(TestStruct ts1, TestStruct ts2) { - assertTrue(ts2.toString(), ts2.isSetI32Field()); + assertTrue(ts2.isSetI32Field(), ts2.toString()); assertEquals(ts1.getI32Field(), ts2.getI32Field()); assertFalse(ts2.isSetI16Field()); } @@ -211,21 +206,17 @@ public class TestPartialThriftDeserializer { TestStruct ts2 = (TestStruct) partialBinaryDeserializer.partialDeserializeObject(bytesBinary); validatePartialComplex(ts1, ts2, id, numItems); - if (!comparer.areEqual(ts1, ts2, sb)) { - fail(sb.toString()); - } + assertTrue(comparer.areEqual(ts1, ts2, sb), sb::toString); ts2 = (TestStruct) partialCompactDeserializer.partialDeserializeObject(bytesCompact); validatePartialComplex(ts1, ts2, id, numItems); - if (!comparer.areEqual(ts1, ts2, sb)) { - fail(sb.toString()); - } + assertTrue(comparer.areEqual(ts1, ts2, sb), sb::toString); } private void validatePartialComplex(TestStruct ts1, TestStruct ts2, int id, int numItems) { // Validate primitive fields. - assertTrue(ts2.toString(), ts2.isSetByteField()); + assertTrue(ts2.isSetByteField(), ts2.toString()); assertEquals(ts1.getByteField(), ts2.getByteField()); assertTrue(ts2.isSetI16Field()); @@ -378,7 +369,7 @@ public class TestPartialThriftDeserializer { for (int i = 0; i < numItems; i++) { ByteBuffer bb = ByteBuffer.wrap(testData.BYTES); - assertTrue(bb.compareTo(list.get(i)) == 0); + assertEquals(0, bb.compareTo(list.get(i))); } } diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java index a6d5655e4..115726ed0 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ThriftFieldTest.java @@ -19,17 +19,18 @@ package org.apache.thrift.partial; -import static org.junit.Assert.*; - -import org.apache.thrift.partial.ExceptionAsserts; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class ThriftFieldTest { @@ -40,29 +41,29 @@ public class ThriftFieldTest { // Should not throw. test = new ThriftField("foo"); - test = new ThriftField("foo", Arrays.asList(new ThriftField("bar"))); - testFields = ThriftField.fromNames(Arrays.asList("foo")); + test = new ThriftField("foo", Collections.singletonList(new ThriftField("bar"))); + testFields = ThriftField.fromNames(Collections.singletonList("foo")); // Verify it throws. - ExceptionAsserts.assertThrows( - IllegalArgumentException.class, - "'name' must not be null", - () -> new ThriftField(null, Collections.emptyList())); + assertThrows( + IllegalArgumentException.class, + () -> new ThriftField(null, Collections.emptyList()), + "'name' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'fields' must not be null", - () -> new ThriftField("foo", null)); + () -> new ThriftField("foo", null), + "'fields' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'fieldNames' must not be null", - () -> ThriftField.fromNames(null)); + () -> ThriftField.fromNames(null), + "'fieldNames' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'fieldNames' must have at least one element", - () -> ThriftField.fromNames(Collections.emptyList())); + () -> ThriftField.fromNames(Collections.emptyList()), + "'fieldNames' must have at least one element"); } @Test @@ -112,6 +113,7 @@ public class ThriftFieldTest { assertEquals(0, f322.fields.size()); } + @Test public void testEquality() { List<String> fieldNames = Arrays.asList( diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java index acc53c8a6..f47657245 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ThriftMetadataTest.java @@ -19,12 +19,6 @@ package org.apache.thrift.partial; -import static org.junit.Assert.*; - -import org.apache.thrift.partial.TestStruct; -import org.apache.thrift.partial.ThriftField; -import org.apache.thrift.partial.ExceptionAsserts; - import org.apache.thrift.TBase; import org.apache.thrift.meta_data.EnumMetaData; import org.apache.thrift.meta_data.FieldValueMetaData; @@ -33,11 +27,18 @@ import org.apache.thrift.meta_data.MapMetaData; import org.apache.thrift.meta_data.SetMetaData; import org.apache.thrift.meta_data.StructMetaData; import org.apache.thrift.protocol.TType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ThriftMetadataTest { private PartialThriftTestData testData = new PartialThriftTestData(); @@ -49,15 +50,15 @@ public class ThriftMetadataTest { ThriftMetadata.ThriftStruct.fromFields(TestStruct.class, testFields); // Verify it throws correctly. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'clasz' must not be null", - () -> ThriftMetadata.ThriftStruct.fromFields(null, testFields)); + () -> ThriftMetadata.ThriftStruct.fromFields(null, testFields), + "'clasz' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'fields' must not be null", - () -> ThriftMetadata.ThriftStruct.fromFields(TestStruct.class, null)); + () -> ThriftMetadata.ThriftStruct.fromFields(TestStruct.class, null), + "'fields' must not be null"); } @Test diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java index d4ab92509..a8b0dac8f 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ThriftStructProcessorTest.java @@ -19,35 +19,37 @@ package org.apache.thrift.partial; -import static org.junit.Assert.*; - -import org.apache.thrift.partial.TestStruct; -import org.apache.thrift.partial.ThriftField; -import org.apache.thrift.partial.ThriftMetadata; -import org.apache.thrift.partial.TstEnum; - import org.apache.thrift.TBase; import org.apache.thrift.TException; import org.apache.thrift.TFieldIdEnum; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class ThriftStructProcessorTest { private PartialThriftTestData testData = new PartialThriftTestData(); @Test public void testStruct() throws TException { - List<ThriftField> fields = ThriftField.fromNames(Arrays.asList("i32Field")); + List<ThriftField> fields = ThriftField.fromNames(Collections.singletonList("i32Field")); ThriftMetadata.ThriftStruct metadata = ThriftMetadata.ThriftStruct.fromFields(TestStruct.class, fields); ThriftStructProcessor processor = new ThriftStructProcessor(); @@ -299,9 +301,7 @@ public class ThriftStructProcessorTest { return field.fieldId; } } - - fail("Field not found: " + fieldName); - return null; + throw new IllegalStateException("Field not found: " + fieldName); } private Object getFieldValue(TBase struct, TFieldIdEnum fieldId) { diff --git a/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java b/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java index 9d96844f8..d2e8eaa18 100644 --- a/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java +++ b/lib/java/src/test/java/org/apache/thrift/partial/ValidateTest.java @@ -19,11 +19,7 @@ package org.apache.thrift.partial; -import org.apache.thrift.partial.ExceptionAsserts; -import org.apache.thrift.partial.TestData; - -import org.junit.Test; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Files; @@ -31,6 +27,8 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class ValidateTest { @Test public void testCheckNotNull() { @@ -41,10 +39,10 @@ public class ValidateTest { Validate.checkNotNull(nonNullArg, "nonNullArg"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'nullArg' must not be null", - () -> Validate.checkNotNull(nullArg, "nullArg")); + () -> Validate.checkNotNull(nullArg, "nullArg"), + "'nullArg' must not be null"); } @Test @@ -57,14 +55,14 @@ public class ValidateTest { Validate.checkPositiveInteger(positiveArg, "positiveArg"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'negativeArg' must be a positive integer", - () -> Validate.checkPositiveInteger(negativeArg, "negativeArg")); - ExceptionAsserts.assertThrows( + () -> Validate.checkPositiveInteger(negativeArg, "negativeArg"), + "'negativeArg' must be a positive integer"); + assertThrows( IllegalArgumentException.class, - "'zero' must be a positive integer", - () -> Validate.checkPositiveInteger(zero, "zero")); + () -> Validate.checkPositiveInteger(zero, "zero"), + "'zero' must be a positive integer"); } @Test @@ -78,10 +76,10 @@ public class ValidateTest { Validate.checkNotNegative(positiveArg, "positiveArg"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'negativeArg' must not be negative", - () -> Validate.checkNotNegative(negativeArg, "negativeArg")); + () -> Validate.checkNotNegative(negativeArg, "negativeArg"), + "'negativeArg' must not be negative"); } @Test @@ -90,10 +88,10 @@ public class ValidateTest { Validate.checkRequired(true, "arg"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg' is required", - () -> Validate.checkRequired(false, "arg")); + () -> Validate.checkRequired(false, "arg"), + "'arg' is required"); } @Test @@ -102,10 +100,10 @@ public class ValidateTest { Validate.checkValid(true, "arg"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg' is invalid", - () -> Validate.checkValid(false, "arg")); + () -> Validate.checkValid(false, "arg"), + "'arg' is invalid"); } @Test @@ -116,10 +114,10 @@ public class ValidateTest { Validate.checkValid(true, "arg", validValues); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg' is invalid. Valid values are: foo, bar", - () -> Validate.checkValid(false, "arg", validValues)); + () -> Validate.checkValid(false, "arg", validValues), + "'arg' is invalid. Valid values are: foo, bar"); } @Test @@ -132,60 +130,60 @@ public class ValidateTest { Validate.checkNotNullAndNotEmpty(TestData.nonEmptyLongArray, "array"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'string' must not be empty", - () -> Validate.checkNotNullAndNotEmpty("", "string")); + () -> Validate.checkNotNullAndNotEmpty("", "string"), + "'string' must not be empty"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must not be null", - () -> Validate.checkNotNullAndNotEmpty(TestData.nullArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.nullArray, "array"), + "'array' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must have at least one element", - () -> Validate.checkNotNullAndNotEmpty(TestData.emptyArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.emptyArray, "array"), + "'array' must have at least one element"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must not be null", - () -> Validate.checkNotNullAndNotEmpty(TestData.nullByteArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.nullByteArray, "array"), + "'array' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must have at least one element", - () -> Validate.checkNotNullAndNotEmpty(TestData.emptyByteArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.emptyByteArray, "array"), + "'array' must have at least one element"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must not be null", - () -> Validate.checkNotNullAndNotEmpty(TestData.nullShortArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.nullShortArray, "array"), + "'array' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must have at least one element", - () -> Validate.checkNotNullAndNotEmpty(TestData.emptyShortArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.emptyShortArray, "array"), + "'array' must have at least one element"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must not be null", - () -> Validate.checkNotNullAndNotEmpty(TestData.nullIntArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.nullIntArray, "array"), + "'array' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must have at least one element", - () -> Validate.checkNotNullAndNotEmpty(TestData.emptyIntArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.emptyIntArray, "array"), + "'array' must have at least one element"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must not be null", - () -> Validate.checkNotNullAndNotEmpty(TestData.nullLongArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.nullLongArray, "array"), + "'array' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'array' must have at least one element", - () -> Validate.checkNotNullAndNotEmpty(TestData.emptyLongArray, "array")); + () -> Validate.checkNotNullAndNotEmpty(TestData.emptyLongArray, "array"), + "'array' must have at least one element"); } @Test @@ -194,15 +192,15 @@ public class ValidateTest { Validate.checkNotNullAndNotEmpty(TestData.validList, "list"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'list' must not be null", - () -> Validate.checkNotNullAndNotEmpty(TestData.nullList, "list")); + () -> Validate.checkNotNullAndNotEmpty(TestData.nullList, "list"), + "'list' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'list' must have at least one element", - () -> Validate.checkNotNullAndNotEmpty(TestData.emptyList, "list")); + () -> Validate.checkNotNullAndNotEmpty(TestData.emptyList, "list"), + "'list' must have at least one element"); } @Test @@ -211,17 +209,17 @@ public class ValidateTest { Validate.checkNotNullAndNumberOfElements(Arrays.asList(1, 2, 3), 3, "arg"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg' must not be null", - () -> Validate.checkNotNullAndNumberOfElements(null, 3, "arg") + () -> Validate.checkNotNullAndNumberOfElements(null, 3, "arg"), + "'arg' must not be null" ); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "Number of elements in 'arg' must be exactly 3, 2 given.", - () -> Validate.checkNotNullAndNumberOfElements(Arrays.asList(1, 2), 3, "arg") + () -> Validate.checkNotNullAndNumberOfElements(Arrays.asList(1, 2), 3, "arg"), + "Number of elements in 'arg' must be exactly 3, 2 given." ); } @@ -231,10 +229,10 @@ public class ValidateTest { Validate.checkValuesEqual(1, "arg1", 1, "arg2"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg1' (1) must equal 'arg2' (2)", - () -> Validate.checkValuesEqual(1, "arg1", 2, "arg2")); + () -> Validate.checkValuesEqual(1, "arg1", 2, "arg2"), + "'arg1' (1) must equal 'arg2' (2)"); } @Test @@ -243,10 +241,10 @@ public class ValidateTest { Validate.checkIntegerMultiple(10, "arg1", 5, "arg2"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg1' (10) must be an integer multiple of 'arg2' (3)", - () -> Validate.checkIntegerMultiple(10, "arg1", 3, "arg2")); + () -> Validate.checkIntegerMultiple(10, "arg1", 3, "arg2"), + "'arg1' (10) must be an integer multiple of 'arg2' (3)"); } @Test @@ -255,10 +253,10 @@ public class ValidateTest { Validate.checkGreater(10, "arg1", 5, "arg2"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg1' (5) must be greater than 'arg2' (10)", - () -> Validate.checkGreater(5, "arg1", 10, "arg2")); + () -> Validate.checkGreater(5, "arg1", 10, "arg2"), + "'arg1' (5) must be greater than 'arg2' (10)"); } @Test @@ -267,10 +265,10 @@ public class ValidateTest { Validate.checkGreaterOrEqual(10, "arg1", 5, "arg2"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg1' (5) must be greater than or equal to 'arg2' (10)", - () -> Validate.checkGreaterOrEqual(5, "arg1", 10, "arg2")); + () -> Validate.checkGreaterOrEqual(5, "arg1", 10, "arg2"), + "'arg1' (5) must be greater than or equal to 'arg2' (10)"); } @Test @@ -280,15 +278,15 @@ public class ValidateTest { Validate.checkWithinRange(10.0, "arg", 5.0, 15.0); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg' (5) must be within the range [10, 20]", - () -> Validate.checkWithinRange(5, "arg", 10, 20)); + () -> Validate.checkWithinRange(5, "arg", 10, 20), + "'arg' (5) must be within the range [10, 20]"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'arg' (5.0) must be within the range [10.0, 20.0]", - () -> Validate.checkWithinRange(5.0, "arg", 10.0, 20.0)); + () -> Validate.checkWithinRange(5.0, "arg", 10.0, 20.0), + "'arg' (5.0) must be within the range [10.0, 20.0]"); } @Test @@ -302,24 +300,24 @@ public class ValidateTest { Validate.checkPathExists(tempDir, "tempDir"); // Verify it throws. - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "'nullArg' must not be null", - () -> Validate.checkPathExists(null, "nullArg")); + () -> Validate.checkPathExists(null, "nullArg"), + "'nullArg' must not be null"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "Path notFound (<not-found>) does not exist", - () -> Validate.checkPathExists(notFound, "notFound")); + () -> Validate.checkPathExists(notFound, "notFound"), + "Path notFound (<not-found>) does not exist"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "must point to a directory", - () -> Validate.checkPathExistsAsDir(tempFile, "tempFile")); + () -> Validate.checkPathExistsAsDir(tempFile, "tempFile"), + "must point to a directory"); - ExceptionAsserts.assertThrows( + assertThrows( IllegalArgumentException.class, - "must point to a file", - () -> Validate.checkPathExistsAsFile(tempDir, "tempDir")); + () -> Validate.checkPathExistsAsFile(tempDir, "tempDir"), + "must point to a file"); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java b/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java index e88160759..6b60c99bb 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/BenchmarkProtocols.java @@ -63,8 +63,8 @@ public class BenchmarkProtocols { long start = System.currentTimeMillis(); for (int rep = 0; rep < NUM_REPS; rep++) { TProtocol proto = factory.getProtocol(new TMemoryBuffer(128*1024)); - Fixtures.compactProtoTestStruct.write(proto); - Fixtures.nesting.write(proto); + Fixtures.getCompactProtoTestStruct().write(proto); + Fixtures.getNesting().write(proto); } long end = System.currentTimeMillis(); timesByFactory.get(factory).add(end-start); diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java b/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java index a87327121..8bf5c6e44 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/ProtocolTestBase.java @@ -18,9 +18,23 @@ */ package org.apache.thrift.protocol; -import java.lang.Exception; -import java.lang.Integer; -import java.lang.String; +import org.apache.thrift.Fixtures; +import org.apache.thrift.TBase; +import org.apache.thrift.TConfiguration; +import org.apache.thrift.TDeserializer; +import org.apache.thrift.TException; +import org.apache.thrift.TSerializer; +import org.apache.thrift.server.ServerTestBase; +import org.apache.thrift.transport.TMemoryBuffer; +import org.apache.thrift.transport.TTransportException; +import org.junit.jupiter.api.Test; +import thrift.test.CompactProtoTestStruct; +import thrift.test.HolyMoley; +import thrift.test.Nesting; +import thrift.test.OneOfEach; +import thrift.test.Srv; +import thrift.test.ThriftTest; + import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; @@ -30,16 +44,10 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.apache.thrift.*; -import org.apache.thrift.server.ServerTestBase; -import org.apache.thrift.transport.TMemoryBuffer; - -import org.apache.thrift.transport.TTransportException; -import thrift.test.*; - -public abstract class ProtocolTestBase extends TestCase { +public abstract class ProtocolTestBase { /** Does it make sense to call methods like writeI32 directly on your protocol? */ protected abstract boolean canBeUsedNaked(); @@ -47,6 +55,7 @@ public abstract class ProtocolTestBase extends TestCase { /** The protocol factory for the protocol being tested. */ protected abstract TProtocolFactory getFactory(); + @Test public void testDouble() throws Exception { if (canBeUsedNaked()) { TMemoryBuffer buf = new TMemoryBuffer(1000); @@ -68,13 +77,15 @@ public abstract class ProtocolTestBase extends TestCase { }); } + @Test public void testSerialization() throws Exception { - internalTestSerialization(OneOfEach.class, Fixtures.oneOfEach); - internalTestSerialization(Nesting.class, Fixtures.nesting); - internalTestSerialization(HolyMoley.class, Fixtures.holyMoley); - internalTestSerialization(CompactProtoTestStruct.class, Fixtures.compactProtoTestStruct); + internalTestSerialization(OneOfEach.class, Fixtures.getOneOfEach()); + internalTestSerialization(Nesting.class, Fixtures.getNesting()); + internalTestSerialization(HolyMoley.class, Fixtures.getHolyMoley()); + internalTestSerialization(CompactProtoTestStruct.class, Fixtures.getCompactProtoTestStruct()); } + @Test public void testBinary() throws Exception { for (byte[] b : Arrays.asList(new byte[0], new byte[]{0,1,2,3,4,5,6,7,8,9,10}, @@ -100,7 +111,7 @@ public abstract class ProtocolTestBase extends TestCase { assertEquals(ByteBuffer.wrap(data, 1, 5), proto.readBinary()); } } - +@Test public void testString() throws Exception { for (String s : Arrays.asList("", "short", "borderlinetiny", "a bit longer than the smallest possible")) { if (canBeUsedNaked()) { @@ -110,6 +121,7 @@ public abstract class ProtocolTestBase extends TestCase { } } + @Test public void testLong() throws Exception { if (canBeUsedNaked()) { internalTestNakedI64(0); @@ -125,6 +137,7 @@ public abstract class ProtocolTestBase extends TestCase { } } + @Test public void testInt() throws Exception { for (int i : Arrays.asList(0, 1, 7, 150, 15000, 31337, 0xffff, 0xffffff, -1, -7, -150, -15000, -0xffff, -0xffffff)) { if (canBeUsedNaked()) { @@ -134,6 +147,7 @@ public abstract class ProtocolTestBase extends TestCase { } } + @Test public void testShort() throws Exception { for (int s : Arrays.asList(0, 1, 7, 150, 15000, 0x7fff, -1, -7, -150, -15000, -0x7fff)) { if (canBeUsedNaked()) { @@ -143,6 +157,7 @@ public abstract class ProtocolTestBase extends TestCase { } } + @Test public void testByte() throws Exception { if (canBeUsedNaked()) { internalTestNakedByte(); @@ -284,6 +299,7 @@ public abstract class ProtocolTestBase extends TestCase { assertEquals(expected, actual); } + @Test public void testMessage() throws Exception { List<TMessage> msgs = Arrays.asList(new TMessage[]{ new TMessage("short message name", TMessageType.CALL, 0), @@ -306,6 +322,7 @@ public abstract class ProtocolTestBase extends TestCase { } } + @Test public void testServerRequest() throws Exception { Srv.Iface handler = new Srv.Iface() { public int Janky(int i32arg) throws TException { @@ -352,15 +369,16 @@ public abstract class ProtocolTestBase extends TestCase { assertEquals(2, testClient.recv_Janky()); } + @Test public void testTDeserializer() throws TException { TSerializer ser = new TSerializer(getFactory()); - byte[] bytes = ser.serialize(Fixtures.compactProtoTestStruct); + byte[] bytes = ser.serialize(Fixtures.getCompactProtoTestStruct()); TDeserializer deser = new TDeserializer(getFactory()); CompactProtoTestStruct cpts = new CompactProtoTestStruct(); deser.deserialize(cpts, bytes); - assertEquals(Fixtures.compactProtoTestStruct, cpts); + assertEquals(Fixtures.getCompactProtoTestStruct(), cpts); } // @@ -407,7 +425,7 @@ public abstract class ProtocolTestBase extends TestCase { byte[] serialized = null; long serStart = System.currentTimeMillis(); for (int rep = 0; rep < NUM_REPS; rep++) { - serialized = ser.serialize(Fixtures.holyMoley); + serialized = ser.serialize(Fixtures.getHolyMoley()); } long serEnd = System.currentTimeMillis(); long serElapsed = serEnd - serStart; @@ -427,7 +445,7 @@ public abstract class ProtocolTestBase extends TestCase { } } - private ServerTestBase.TestHandler testHandler = new ServerTestBase.TestHandler() { + private final ServerTestBase.TestHandler testHandler = new ServerTestBase.TestHandler() { @Override public String testString(String thing) { thing = thing + " Apache Thrift Java " + thing; @@ -466,6 +484,7 @@ public abstract class ProtocolTestBase extends TestCase { return getFactory().getProtocol(bufferTrans); } + @Test public void testReadCheckMaxMessageRequestForString() throws TException{ TProtocol clientOutProto = initConfig(15); TProtocol clientInProto = initConfig(15); @@ -481,21 +500,21 @@ public abstract class ProtocolTestBase extends TestCase { } } + @Test public void testReadCheckMaxMessageRequestForList() throws TException{ TProtocol clientOutProto = initConfig(15); TProtocol clientInProto = initConfig(15); ThriftTest.Client testClient = new ThriftTest.Client(clientInProto, clientOutProto); ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); - try { + TTransportException e = assertThrows(TTransportException.class, () -> { testClient.send_testList(Arrays.asList(1, 23242346, 888888, 90)); testProcessor.process(clientOutProto, clientInProto); testClient.recv_testList(); - fail("Limitations not achieved as expected"); - } catch (TTransportException e) { - assertEquals("MaxMessageSize reached", e.getMessage()); - } + }, "Limitations not achieved as expected"); + assertEquals("MaxMessageSize reached", e.getMessage()); } + @Test public void testReadCheckMaxMessageRequestForMap() throws TException{ TProtocol clientOutProto = initConfig(13); TProtocol clientInProto = initConfig(13); @@ -503,28 +522,28 @@ public abstract class ProtocolTestBase extends TestCase { ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); Map<String, String> thing = new HashMap<>(); thing.put("key", "Thrift"); - try { + + TTransportException e = assertThrows(TTransportException.class, () -> { testClient.send_testStringMap(thing); testProcessor.process(clientOutProto, clientInProto); testClient.recv_testStringMap(); - fail("Limitations not achieved as expected"); - } catch (TTransportException e) { - assertEquals("MaxMessageSize reached", e.getMessage()); - } + }, "Limitations not achieved as expected"); + + assertEquals("MaxMessageSize reached", e.getMessage()); } + @Test public void testReadCheckMaxMessageRequestForSet() throws TException{ TProtocol clientOutProto = initConfig(10); TProtocol clientInProto = initConfig(10); ThriftTest.Client testClient = new ThriftTest.Client(clientInProto, clientOutProto); ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); - try { - testClient.send_testSet(Stream.of(234, 0, 987087, 45, 88888888, 9).collect(Collectors.toSet())); - testProcessor.process(clientOutProto, clientInProto); - testClient.recv_testSet(); - fail("Limitations not achieved as expected"); - } catch (TTransportException e) { - assertEquals("MaxMessageSize reached", e.getMessage()); - } + TTransportException e = + assertThrows(TTransportException.class, () -> { + testClient.send_testSet(Stream.of(234, 0, 987087, 45, 88888888, 9).collect(Collectors.toSet())); + testProcessor.process(clientOutProto, clientInProto); + testClient.recv_testSet(); + }, "Limitations not achieved as expected"); + assertEquals("MaxMessageSize reached", e.getMessage()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java index c8e78eee6..24541ebef 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestShortStack.java @@ -18,10 +18,15 @@ */ package org.apache.thrift.protocol; -import junit.framework.TestCase; -public class TestShortStack extends TestCase { +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TestShortStack { + + @Test public void testOps() throws Exception { ShortStack s = new ShortStack(1); s.push((short)10); @@ -32,11 +37,6 @@ public class TestShortStack extends TestCase { s.push((short)40); assertEquals((short)40, s.pop()); assertEquals((short)10, s.pop()); - try { - s.pop(); - fail("should have thrown an exception!"); - } catch (Exception e) { - // yay - } + assertThrows(Exception.class, s::pop); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java index 67220b0f5..acc46e9d8 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTBinaryProtocol.java @@ -20,10 +20,6 @@ package org.apache.thrift.protocol; -import org.apache.thrift.TDeserializer; -import org.apache.thrift.TException; -import thrift.test.Bonk; - public class TestTBinaryProtocol extends ProtocolTestBase { @Override protected TProtocolFactory getFactory() { diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java index b4c0888a4..b2c29f7dd 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTCompactProtocol.java @@ -23,6 +23,7 @@ package org.apache.thrift.protocol; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; +import org.junit.jupiter.api.Test; import thrift.test.Bonk; public class TestTCompactProtocol extends ProtocolTestBase { @@ -36,6 +37,7 @@ public class TestTCompactProtocol extends ProtocolTestBase { return true; } + @Test public void testOOMDenialOfService() throws Exception { // Struct header, Integer.MAX_VALUE length, and only one real // byte of data @@ -53,4 +55,4 @@ public class TestTCompactProtocol extends ProtocolTestBase { public static void main(String args[]) throws Exception { new TestTCompactProtocol().benchmark(); } -}
\ No newline at end of file +} diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java index f72c25972..62b8d3f66 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTField.java @@ -18,11 +18,15 @@ */ package org.apache.thrift.protocol; -import junit.framework.TestCase; -import static org.junit.Assert.assertNotEquals; -public abstract class TestTField extends TestCase { +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +public abstract class TestTField { + + @Test public void testConstructor() { TField uut = new TField(); assertEquals("", uut.name); @@ -35,6 +39,7 @@ public abstract class TestTField extends TestCase { assertEquals(42, uut.id); } + @Test public void testEquality() { TField uut1 = new TField(); TField uut2 = new TField(); diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java index ecbd10188..993362993 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTJSONProtocol.java @@ -18,11 +18,13 @@ */ package org.apache.thrift.protocol; -import java.nio.charset.StandardCharsets; - import org.apache.thrift.TException; -import org.apache.thrift.protocol.TJSONProtocol; import org.apache.thrift.transport.TMemoryBuffer; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestTJSONProtocol extends ProtocolTestBase { @Override @@ -35,6 +37,7 @@ public class TestTJSONProtocol extends ProtocolTestBase { return false; } + @Test public void testEscapedUnicode() throws TException { String jsonString = "\"hello unicode \\u0e01\\ud834\\udd1e world\""; String expectedString = "hello unicode \u0e01\ud834\udd1e world"; @@ -46,6 +49,7 @@ public class TestTJSONProtocol extends ProtocolTestBase { assertEquals(expectedString, protocol.readString()); } + @Test public void testExactlySizedBuffer() throws TException { // Regression test for https://issues.apache.org/jira/browse/THRIFT-5383. // Ensures that a JSON string can be read after writing to a buffer just diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java index 89cf5366e..937e9130e 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTProtocolUtil.java @@ -18,14 +18,16 @@ */ package org.apache.thrift.protocol; -import junit.framework.TestCase; - import org.apache.thrift.TSerializer; - +import org.junit.jupiter.api.Test; import thrift.test.GuessProtocolStruct; -public class TestTProtocolUtil extends TestCase { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestTProtocolUtil { + @Test public void testGuessProtocolFactory_JSON() throws Exception { byte[] data = "{foo}".getBytes(); @@ -42,6 +44,7 @@ public class TestTProtocolUtil extends TestCase { assertFalse(factory instanceof TJSONProtocol.Factory); } + @Test public void testGuessProtocolFactory_Binary() throws Exception { // Check that a last byte != 0 is correctly reported as Binary @@ -58,10 +61,11 @@ public class TestTProtocolUtil extends TestCase { assertTrue(factory instanceof TBinaryProtocol.Factory); } + @Test public void testGuessProtocolFactory_Compact() throws Exception { // Check that a first byte > 0x10 is reported as Compact byte[] buf = new byte[3]; - buf[0] = 0x11; + buf[0] = 0x11; TProtocolFactory factory = TProtocolUtil.guessProtocolFactory(buf, new TBinaryProtocol.Factory()); assertTrue(factory instanceof TCompactProtocol.Factory); @@ -74,6 +78,7 @@ public class TestTProtocolUtil extends TestCase { } } + @Test public void testGuessProtocolFactory_Undecided() throws Exception { byte[] buf = new byte[3]; buf[1] = 0x7e; diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java index bc20e313f..b1fc04e4f 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTSimpleJSONProtocol.java @@ -18,25 +18,27 @@ */ package org.apache.thrift.protocol; -import java.nio.charset.StandardCharsets; - -import junit.framework.TestCase; - import org.apache.thrift.Fixtures; import org.apache.thrift.TDeserializer; import org.apache.thrift.TException; import org.apache.thrift.transport.TMemoryBuffer; - import org.apache.thrift.transport.TTransportException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import thrift.test.CompactProtoTestStruct; import thrift.test.HolyMoley; -public class TestTSimpleJSONProtocol extends TestCase { +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TestTSimpleJSONProtocol { private TMemoryBuffer buf; private TSimpleJSONProtocol proto; - @Override - protected void setUp() throws Exception { + @BeforeEach + public void setUp() throws Exception { buf = new TMemoryBuffer(1000); proto = new TSimpleJSONProtocol(buf); } @@ -45,8 +47,9 @@ public class TestTSimpleJSONProtocol extends TestCase { return buf.toString(StandardCharsets.UTF_8); } + @Test public void testHolyMoley() throws TException { - final HolyMoley holyMoley = Fixtures.holyMoley.deepCopy(); + final HolyMoley holyMoley = Fixtures.getHolyMoley().deepCopy(); // unset sets that produce inconsistent ordering between JDK7/8 holyMoley.unsetBonks(); holyMoley.unsetContain(); @@ -54,19 +57,22 @@ public class TestTSimpleJSONProtocol extends TestCase { assertEquals("{\"big\":[{\"im_true\":1,\"im_false\":0,\"a_bite\":35,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]},{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}]}", bufToString()); } + @Test public void testNesting() throws TException { - Fixtures.nesting.write(proto); + Fixtures.getNesting().write(proto); assertEquals("{\"my_bonk\":{\"type\":31337,\"message\":\"I am a bonk... xor!\"},\"my_ooe\":{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}}", bufToString()); } + @Test public void testOneOfEach() throws TException { - Fixtures.oneOfEach.write(proto); + Fixtures.getOneOfEach().write(proto); assertEquals("{\"im_true\":1,\"im_false\":0,\"a_bite\":-42,\"integer16\":27000,\"integer32\":16777216,\"integer64\":6000000000,\"double_precision\":3.141592653589793,\"some_characters\":\"JSON THIS! \\\"\\u0001\",\"zomg_unicode\":\"ӀⅮΝ Нοⅿоɡгаρℎ Αttαⅽκ�‼\",\"what_who\":0,\"base64\":\"base64\",\"byte_list\":[1,2,3],\"i16_list\":[1,2,3],\"i64_list\":[1,2,3]}", bufToString()); } + @Test public void testSanePartsOfCompactProtoTestStruct() throws TException { // unset all the maps with container keys - CompactProtoTestStruct struct = Fixtures.compactProtoTestStruct.deepCopy(); + CompactProtoTestStruct struct = Fixtures.getCompactProtoTestStruct().deepCopy(); struct.unsetList_byte_map(); struct.unsetSet_byte_map(); struct.unsetMap_byte_map(); @@ -85,23 +91,18 @@ public class TestTSimpleJSONProtocol extends TestCase { assertEquals("{\"a_byte\":127,\"a_i16\":32000,\"a_i32\":1000000000,\"a_i64\":1099511627775,\"a_double\":5.6789,\"a_string\":\"my string\",\"a_binary\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\",\"true_field\":1,\"false_field\":0,\"empty_struct_field\":{},\"byte_list\":[-127,-1,0,1,127],\"i16_list\":[-1,0,1,32767],\"i32_list\":[-1,0,255,65535,16777215,2147483647],\"i64_list\":[-1,0,255,65535,16777215,4294967295,1099511627775,281474976710655,72057594037927935,9223372036854775807],\"double_list\":[0.1,0.2,0.3],\"string_list\":[\"first\",\"second\",\"third\"],\"boolean_list\":[1,1,1,0,0,0],\"struct_list\":[{},{}],\"i32_set\":[1,2,3],\"boolean_set\":[0,1],\"struct_set\":[{}],\"byte_byte_map\":{\"1\":2},\"boolean_byte_map\":{\"0\":0,\"1\":1},\"byte_i16_map\":{\"1\":1,\"2\":-1,\"3\":32767},\"byte_i32_map\":{\"1\":1,\"2\":-1,\"3\":2147483647},\"byte_i64_map\":{\"1\":1,\"2\":-1,\"3\":9223372036854775807},\"byte_double_map\":{\"1\":0.1,\"2\":-0.1,\"3\":1000000.1},\"byte_string_map\":{\"1\":\"\",\"2\":\"blah\",\"3\":\"loooooooooooooong string\"},\"byte_boolean_map\":{\"1\":1,\"2\":0},\"byte_map_map\":{\"0\":{},\"1\":{\"1\":1},\"2\":{\"1\":1,\"2\":2}},\"byte_set_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"byte_list_map\":{\"0\":[],\"1\":[1],\"2\":[1,2]},\"field500\":500,\"field5000\":5000,\"field20000\":20000}", bufToString()); } + @Test public void testThrowsOnCollectionKeys() throws TException { - try { - Fixtures.compactProtoTestStruct.write(proto); - fail("this should throw a CollectionMapKeyException"); - } catch (TSimpleJSONProtocol.CollectionMapKeyException e) { - // - } + assertThrows(TSimpleJSONProtocol.CollectionMapKeyException.class, () -> Fixtures.getCompactProtoTestStruct().write(proto)); } + @Test public void testReadingThrows() throws TTransportException { String input = "{\"test\": \"value\"}"; TDeserializer deserializer = new TDeserializer(new TSimpleJSONProtocol.Factory()); - try { - deserializer.fromString(Fixtures.oneOfEach, input); - fail("Was able to read SimpleJSON"); - } catch (TException e) { - assertEquals("Not implemented", e.getMessage()); - } + TException e = assertThrows(TException.class, ()->{ + deserializer.fromString(Fixtures.getOneOfEach(), input); + }); + assertEquals("Not implemented", e.getMessage()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java b/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java index b654db3f8..b0e3bcda5 100644 --- a/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java +++ b/lib/java/src/test/java/org/apache/thrift/protocol/TestTTupleProtocol.java @@ -2,7 +2,7 @@ package org.apache.thrift.protocol; import org.apache.thrift.TDeserializer; import org.apache.thrift.TSerializer; - +import org.junit.jupiter.api.Test; import thrift.test.TupleProtocolTestStruct; @@ -18,6 +18,7 @@ public class TestTTupleProtocol extends ProtocolTestBase { return new TTupleProtocol.Factory(); } + @Test public void testBitsetLengthIssue() throws Exception { final TupleProtocolTestStruct t1 = new TupleProtocolTestStruct(); t1.setField1(0); diff --git a/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java b/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java index 43e40c223..f5f0e0bb8 100644 --- a/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java +++ b/lib/java/src/test/java/org/apache/thrift/scheme/TestStandardScheme.java @@ -1,7 +1,5 @@ package org.apache.thrift.scheme; -import junit.framework.TestCase; - import org.apache.thrift.Fixtures; import org.apache.thrift.TBase; import org.apache.thrift.TDeserializer; @@ -11,13 +9,15 @@ import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TMemoryBuffer; import org.apache.thrift.transport.TTransport; - import org.apache.thrift.transport.TTransportException; +import org.junit.jupiter.api.Test; import thrift.test.HolyMoley; import thrift.test.Nesting; import thrift.test.OneOfEach; -public class TestStandardScheme extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TestStandardScheme { TSerializer serializer = new TSerializer(); TDeserializer deserializer = new TDeserializer(); @@ -28,13 +28,14 @@ public class TestStandardScheme extends TestCase { * This tests whether the Standard Scheme properly reads structs serialized * using an older version of thrift. */ + @Test public void testPersistentStructs() throws TException { - readAndCompare(new OneOfEach(), Fixtures.oneOfEach, Fixtures.persistentBytesOneOfEach); - readAndCompare(new HolyMoley(), Fixtures.holyMoley, Fixtures.persistentBytesHolyMoley); - readAndCompare(new Nesting(), Fixtures.nesting, Fixtures.persistentBytesNesting); + readAndCompare(new OneOfEach(), Fixtures.getOneOfEach(), Fixtures.getPersistentBytesOneOfEach()); + readAndCompare(new HolyMoley(), Fixtures.getHolyMoley(), Fixtures.getPersistentBytesHolyMoley()); + readAndCompare(new Nesting(), Fixtures.getNesting(), Fixtures.getPersistentBytesNesting()); } - public void readAndCompare(TBase struct, TBase fixture, byte[] inputBytes) throws TException { + private void readAndCompare(TBase struct, TBase fixture, byte[] inputBytes) throws TException { TTransport trans = new TMemoryBuffer(0); trans.write(inputBytes, 0, inputBytes.length); TProtocol iprot = new TBinaryProtocol(trans); diff --git a/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java b/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java index e2bf96a1a..3c40262b4 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java +++ b/lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java @@ -18,18 +18,6 @@ */ package org.apache.thrift.server; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import java.nio.ByteBuffer; - -import junit.framework.TestCase; - import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.async.AsyncMethodCallback; @@ -37,13 +25,13 @@ import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.transport.TTransportException; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TTransportFactory; +import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.layered.TFramedTransport.Factory; - +import org.junit.jupiter.api.Test; import thrift.test.Insanity; import thrift.test.Numberz; import thrift.test.ThriftTest; @@ -52,46 +40,66 @@ import thrift.test.Xception2; import thrift.test.Xtruct; import thrift.test.Xtruct2; -public abstract class ServerTestBase extends TestCase { +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public abstract class ServerTestBase { public static class TestHandler implements ThriftTest.Iface { public TestHandler() {} + @Override public void testVoid() { System.out.print("testVoid()\n"); } + @Override public String testString(String thing) { System.out.print("testString(\"" + thing + "\")\n"); return thing; } + @Override public boolean testBool(boolean thing) { System.out.print("testBool(" + thing + ")\n"); return thing; } + @Override public byte testByte(byte thing) { System.out.print("testByte(" + thing + ")\n"); return thing; } + @Override public int testI32(int thing) { System.out.print("testI32(" + thing + ")\n"); return thing; } + @Override public long testI64(long thing) { System.out.print("testI64(" + thing + ")\n"); return thing; } + @Override public double testDouble(double thing) { System.out.print("testDouble(" + thing + ")\n"); return thing; } + @Override public ByteBuffer testBinary(ByteBuffer thing) { StringBuilder sb = new StringBuilder(thing.remaining() * 3); thing.mark(); @@ -102,11 +110,12 @@ public abstract class ServerTestBase extends TestCase { if(thing.remaining() > 0) { sb.append("..."); // indicate we have more date } - System.out.print("testBinary(" + sb.toString() + ")\n"); + System.out.print("testBinary(" + sb + ")\n"); thing.reset(); return thing; } + @Override public Xtruct testStruct(Xtruct thing) { System.out.print("testStruct({" + "\"" + thing.string_thing + "\", " + @@ -116,6 +125,7 @@ public abstract class ServerTestBase extends TestCase { return thing; } + @Override public Xtruct2 testNest(Xtruct2 nest) { Xtruct thing = nest.struct_thing; System.out.print("testNest({" + @@ -128,6 +138,7 @@ public abstract class ServerTestBase extends TestCase { return nest; } + @Override public Map<Integer,Integer> testMap(Map<Integer,Integer> thing) { System.out.print("testMap({"); System.out.print(thing); @@ -135,6 +146,7 @@ public abstract class ServerTestBase extends TestCase { return thing; } + @Override public Map<String,String> testStringMap(Map<String,String> thing) { System.out.print("testStringMap({"); System.out.print(thing); @@ -142,6 +154,7 @@ public abstract class ServerTestBase extends TestCase { return thing; } + @Override public Set<Integer> testSet(Set<Integer> thing) { System.out.print("testSet({"); boolean first = true; @@ -157,6 +170,7 @@ public abstract class ServerTestBase extends TestCase { return thing; } + @Override public List<Integer> testList(List<Integer> thing) { System.out.print("testList({"); boolean first = true; @@ -172,23 +186,26 @@ public abstract class ServerTestBase extends TestCase { return thing; } + @Override public Numberz testEnum(Numberz thing) { System.out.print("testEnum(" + thing + ")\n"); return thing; } + @Override public long testTypedef(long thing) { System.out.print("testTypedef(" + thing + ")\n"); return thing; } + @Override public Map<Integer,Map<Integer,Integer>> testMapMap(int hello) { System.out.print("testMapMap(" + hello + ")\n"); Map<Integer,Map<Integer,Integer>> mapmap = - new HashMap<Integer,Map<Integer,Integer>>(); + new HashMap<>(); - HashMap<Integer,Integer> pos = new HashMap<Integer,Integer>(); - HashMap<Integer,Integer> neg = new HashMap<Integer,Integer>(); + HashMap<Integer,Integer> pos = new HashMap<>(); + HashMap<Integer,Integer> neg = new HashMap<>(); for (int i = 1; i < 5; i++) { pos.put(i, i); neg.put(-i, -i); @@ -200,11 +217,12 @@ public abstract class ServerTestBase extends TestCase { return mapmap; } + @Override public Map<Long, Map<Numberz,Insanity>> testInsanity(Insanity argument) { System.out.print("testInsanity()\n"); - HashMap<Numberz,Insanity> first_map = new HashMap<Numberz, Insanity>(); - HashMap<Numberz,Insanity> second_map = new HashMap<Numberz, Insanity>(); + HashMap<Numberz,Insanity> first_map = new HashMap<>(); + HashMap<Numberz,Insanity> second_map = new HashMap<>(); first_map.put(Numberz.TWO, argument); first_map.put(Numberz.THREE, argument); @@ -213,13 +231,14 @@ public abstract class ServerTestBase extends TestCase { second_map.put(Numberz.SIX, looney); Map<Long,Map<Numberz,Insanity>> insane = - new HashMap<Long, Map<Numberz,Insanity>>(); + new HashMap<>(); insane.put((long)1, first_map); insane.put((long)2, second_map); return insane; } + @Override public Xtruct testMulti(byte arg0, int arg1, long arg2, Map<Short,String> arg3, Numberz arg4, long arg5) { System.out.print("testMulti()\n"); @@ -231,7 +250,8 @@ public abstract class ServerTestBase extends TestCase { return hello; } - public void testException(String arg) throws Xception, TException { + @Override + public void testException(String arg) throws TException { System.out.print("testException("+arg+")\n"); if ("Xception".equals(arg)) { Xception x = new Xception(); @@ -248,6 +268,7 @@ public abstract class ServerTestBase extends TestCase { return; } + @Override public Xtruct testMultiException(String arg0, String arg1) throws Xception, Xception2 { System.out.print("testMultiException(" + arg0 + ", " + arg1 + ")\n"); if (arg0.equals("Xception")) { @@ -268,6 +289,7 @@ public abstract class ServerTestBase extends TestCase { return result; } + @Override public void testOneway(int sleepFor) { System.out.println("testOneway(" + sleepFor + ") => sleeping..."); @@ -285,9 +307,9 @@ public abstract class ServerTestBase extends TestCase { new TCompactProtocol.Factory()); public static final String HOST = "localhost"; - public static final int PORT = Integer.valueOf( + public static final int PORT = Integer.parseInt( System.getProperty("test.port", "9090")); - protected static final int SLEEP_DELAY = 1000; + protected static final long SLEEP_DELAY = 1000; protected static final int SOCKET_TIMEOUT = 1500; private static final Xtruct XSTRUCT = new Xtruct("Zero", (byte) 1, -3, -5); private static final Xtruct2 XSTRUCT2 = new Xtruct2((byte)1, XSTRUCT, 5); @@ -342,14 +364,14 @@ public abstract class ServerTestBase extends TestCase { Insanity insane; insane = new Insanity(); - insane.userMap = new HashMap<Numberz, Long>(); + insane.userMap = new HashMap<>(); insane.userMap.put(Numberz.FIVE, (long)5000); Xtruct truck = new Xtruct(); truck.string_thing = "Truck"; truck.byte_thing = (byte)8; truck.i32_thing = 8; truck.i64_thing = 8; - insane.xtructs = new ArrayList<Xtruct>(); + insane.xtructs = new ArrayList<>(); insane.xtructs.add(truck); System.out.print("testInsanity()"); Map<Long,Map<Numberz,Insanity>> whoa = @@ -391,10 +413,11 @@ public abstract class ServerTestBase extends TestCase { return false; } + @Test public void testIt() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { - TProcessor processor = useAsyncProcessor() ? new ThriftTest.AsyncProcessor<AsyncTestHandler>(new AsyncTestHandler()) : new ThriftTest.Processor<TestHandler>(new TestHandler()); + TProcessor processor = useAsyncProcessor() ? new ThriftTest.AsyncProcessor<>(new AsyncTestHandler()) : new ThriftTest.Processor<>(new TestHandler()); startServer(processor, protoFactory); @@ -442,7 +465,7 @@ public abstract class ServerTestBase extends TestCase { } private void testList(ThriftTest.Client testClient) throws TException { - List<Integer> listout = new ArrayList<Integer>(); + List<Integer> listout = new ArrayList<>(); for (int i = -2; i < 3; ++i) { listout.add(i); } @@ -451,7 +474,7 @@ public abstract class ServerTestBase extends TestCase { } private void testMap(ThriftTest.Client testClient) throws TException { - Map<Integer,Integer> mapout = new HashMap<Integer,Integer>(); + Map<Integer,Integer> mapout = new HashMap<>(); for (int i = 0; i < 5; ++i) { mapout.put(i, i-10); } @@ -460,7 +483,7 @@ public abstract class ServerTestBase extends TestCase { } private void testStringMap(ThriftTest.Client testClient) throws TException { - Map<String,String> mapout = new HashMap<String,String>(); + Map<String,String> mapout = new HashMap<>(); mapout.put("a", "123"); mapout.put(" x y ", " with spaces "); mapout.put("same", "same"); @@ -473,10 +496,10 @@ public abstract class ServerTestBase extends TestCase { Map<Integer,Map<Integer,Integer>> mm = testClient.testMapMap(1); Map<Integer,Map<Integer,Integer>> mapmap = - new HashMap<Integer,Map<Integer,Integer>>(); + new HashMap<>(); - HashMap<Integer,Integer> pos = new HashMap<Integer,Integer>(); - HashMap<Integer,Integer> neg = new HashMap<Integer,Integer>(); + HashMap<Integer,Integer> pos = new HashMap<>(); + HashMap<Integer,Integer> neg = new HashMap<>(); for (int i = 1; i < 5; i++) { pos.put(i, i); neg.put(-i, -i); @@ -500,7 +523,7 @@ public abstract class ServerTestBase extends TestCase { } private void testSet(ThriftTest.Client testClient) throws TException { - Set<Integer> setout = new HashSet<Integer>(); + Set<Integer> setout = new HashSet<>(); for (int i = -2; i < 3; ++i) { setout.add(i); } @@ -540,10 +563,11 @@ public abstract class ServerTestBase extends TestCase { } } + @Test public void testTransportFactory() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { TestHandler handler = new TestHandler(); - ThriftTest.Processor<TestHandler> processor = new ThriftTest.Processor<TestHandler>(handler); + ThriftTest.Processor<TestHandler> processor = new ThriftTest.Processor<>(handler); final CallCountingTransportFactory factory = new CallCountingTransportFactory(new TFramedTransport.Factory()); @@ -564,7 +588,7 @@ public abstract class ServerTestBase extends TestCase { } } - private void testException(ThriftTest.Client testClient) throws TException, Xception { + private void testException(ThriftTest.Client testClient) throws TException { try { testClient.testException("Xception"); assert false; diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java index 2c779080e..927635b61 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestNonblockingServer.java @@ -18,20 +18,21 @@ */ package org.apache.thrift.server; - import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.server.TNonblockingServer.Args; -import org.apache.thrift.transport.layered.TFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TTransportFactory; - +import org.apache.thrift.transport.layered.TFramedTransport; +import org.junit.jupiter.api.Test; import thrift.test.ThriftTest; +import static org.junit.jupiter.api.Assertions.fail; + public class TestNonblockingServer extends ServerTestBase { private Thread serverThread; @@ -84,6 +85,7 @@ public class TestNonblockingServer extends ServerTestBase { } + @Test public void testCleanupAllSelectionKeys() throws Exception { for (TProtocolFactory protoFactory : getProtocols()) { TestHandler handler = new TestHandler(); diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java index d0a674674..fb7bbdc13 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestSaslNonblockingServer.java @@ -31,9 +31,12 @@ import org.apache.thrift.transport.TTransportFactory; import org.apache.thrift.transport.TestTSaslTransports; import org.apache.thrift.transport.TestTSaslTransports.TestSaslCallbackHandler; import org.apache.thrift.transport.sasl.TSaslNegotiationException; +import org.junit.jupiter.api.Test; import thrift.test.ThriftTest; import static org.apache.thrift.transport.sasl.TSaslNegotiationException.ErrorType.AUTHENTICATION_FAILURE; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestSaslNonblockingServer extends TestTSaslTransports.TestTSaslTransportsWithServer { @@ -61,10 +64,12 @@ public class TestSaslNonblockingServer extends TestTSaslTransports.TestTSaslTran } @Override + @Test public void testIt() throws Exception { super.testIt(); } + @Test public void testBadPassword() throws Exception { TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); TProcessor processor = new ThriftTest.Processor<>(new TestHandler()); @@ -72,23 +77,20 @@ public class TestSaslNonblockingServer extends TestTSaslTransports.TestTSaslTran TSocket socket = new TSocket(HOST, PORT); socket.setTimeout(SOCKET_TIMEOUT); - TSaslClientTransport client = new TSaslClientTransport(TestTSaslTransports.WRAPPED_MECHANISM, - TestTSaslTransports.PRINCIPAL, TestTSaslTransports.SERVICE, TestTSaslTransports.HOST, - TestTSaslTransports.WRAPPED_PROPS, new TestSaslCallbackHandler("bad_password"), socket); - try { - client.open(); - fail("Client should fail with sasl negotiation."); - } catch (TTransportException error) { + try (TSaslClientTransport client = new TSaslClientTransport(TestTSaslTransports.WRAPPED_MECHANISM, + TestTSaslTransports.PRINCIPAL, TestTSaslTransports.SERVICE, TestTSaslTransports.HOST, + TestTSaslTransports.WRAPPED_PROPS, new TestSaslCallbackHandler("bad_password"), socket)) { + TTransportException error = assertThrows(TTransportException.class, client::open, "Client should fail with sasl negotiation."); TSaslNegotiationException serverSideError = new TSaslNegotiationException(AUTHENTICATION_FAILURE, - "Authentication failed with " + TestTSaslTransports.WRAPPED_MECHANISM); - assertTrue("Server should return error message \"" + serverSideError.getSummary() + "\"", - error.getMessage().contains(serverSideError.getSummary())); + "Authentication failed with " + TestTSaslTransports.WRAPPED_MECHANISM); + assertTrue(error.getMessage().contains(serverSideError.getSummary()), + "Server should return error message \"" + serverSideError.getSummary() + "\""); } finally { stopServer(); - client.close(); } } + @Test @Override public void testTransportFactory() { // This test is irrelevant here, so skipped. diff --git a/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java b/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java index 4c84dc18d..f532ed4c2 100644 --- a/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java +++ b/lib/java/src/test/java/org/apache/thrift/server/TestThreadPoolServer.java @@ -23,12 +23,14 @@ import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TSocket; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import thrift.test.ThriftTest; import java.util.concurrent.ThreadPoolExecutor; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TestThreadPoolServer { /** @@ -38,24 +40,24 @@ public class TestThreadPoolServer { public void testStopServerWithOpenClient() throws Exception { TServerSocket serverSocket = new TServerSocket(0, 3000); TThreadPoolServer server = buildServer(serverSocket); - Thread serverThread = new Thread(() -> server.serve()); + Thread serverThread = new Thread(server::serve); serverThread.start(); try (TSocket client = new TSocket("localhost", serverSocket.getServerSocket().getLocalPort())) { client.open(); Thread.sleep(1000); // There is a thread listening to the client - Assert.assertEquals(1, ((ThreadPoolExecutor) server.getExecutorService()).getActiveCount()); + assertEquals(1, ((ThreadPoolExecutor) server.getExecutorService()).getActiveCount()); // Trigger the server to stop, but it does not wait server.stop(); - Assert.assertTrue(server.waitForShutdown()); + assertTrue(server.waitForShutdown()); // After server is stopped, the executor thread pool should be shut down - Assert.assertTrue("Server thread pool should be terminated", server.getExecutorService().isTerminated()); + assertTrue(server.getExecutorService().isTerminated(), "Server thread pool should be terminated"); // TODO: The socket is actually closed (timeout) but the client code // ignores the timeout Exception and maintains the socket open state - Assert.assertTrue("Client should be closed after server shutdown", client.isOpen()); + assertTrue(client.isOpen(), "Client should be closed after server shutdown"); } } diff --git a/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java b/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java index 7e3b091d4..4cc8f8003 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java +++ b/lib/java/src/test/java/org/apache/thrift/test/ReadStruct.java @@ -51,11 +51,11 @@ public class ReadStruct { cpts.read(proto); - if (cpts.equals(Fixtures.compactProtoTestStruct)) { + if (cpts.equals(Fixtures.getCompactProtoTestStruct())) { System.out.println("Object verified successfully!"); } else { System.out.println("Object failed verification!"); - System.out.println("Expected: " + Fixtures.compactProtoTestStruct + " but got " + cpts); + System.out.println("Expected: " + Fixtures.getCompactProtoTestStruct() + " but got " + cpts); } } diff --git a/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java b/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java index de22556f8..8085ef485 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java +++ b/lib/java/src/test/java/org/apache/thrift/test/SerializationBenchmark.java @@ -39,8 +39,8 @@ public class SerializationBenchmark { public static void main(String[] args) throws Exception { TProtocolFactory factory = new TBinaryProtocol.Factory(); - testSerialization(factory, Fixtures.oneOfEach); - testDeserialization(factory, Fixtures.oneOfEach, OneOfEach.class); + testSerialization(factory, Fixtures.getOneOfEach()); + testDeserialization(factory, Fixtures.getOneOfEach(), OneOfEach.class); } public static void testSerialization(TProtocolFactory factory, TBase object) throws Exception { @@ -74,7 +74,7 @@ public class SerializationBenchmark { long startTime = System.currentTimeMillis(); for (int i = 0; i < HOW_MANY; i++) { - T o2 = klass.newInstance(); + T o2 = klass.getConstructor().newInstance(); o2.read(factory.getProtocol(new TMemoryInputTransport(new TConfiguration(), serialized))); } long endTime = System.currentTimeMillis(); diff --git a/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java b/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java index a0013a93a..cb60bcaa7 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java +++ b/lib/java/src/test/java/org/apache/thrift/test/WriteStruct.java @@ -34,14 +34,14 @@ public class WriteStruct { System.out.println("usage: java -cp build/classes org.apache.thrift.test.WriteStruct filename proto_factory_class"); System.out.println("Write out an instance of Fixtures.compactProtocolTestStruct to 'file'. Use a protocol from 'proto_factory_class'."); } - + TTransport trans = new TIOStreamTransport(new BufferedOutputStream(new FileOutputStream(args[0]))); - + TProtocolFactory factory = (TProtocolFactory)Class.forName(args[1]).newInstance(); - + TProtocol proto = factory.getProtocol(trans); - - Fixtures.compactProtoTestStruct.write(proto); + + Fixtures.getCompactProtoTestStruct().write(proto); trans.flush(); } diff --git a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java index af39262bb..b6853bd2b 100644 --- a/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java +++ b/lib/java/src/test/java/org/apache/thrift/test/voidmethexceptions/TestVoidMethExceptions.java @@ -33,13 +33,8 @@ import org.apache.thrift.transport.TNonblockingSocket; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.layered.TFramedTransport; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import thrift.test.voidmethexceptions.TAppService01; @@ -49,501 +44,517 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -@RunWith(Parameterized.class) public class TestVoidMethExceptions { - private static final Logger log = LoggerFactory.getLogger(TestVoidMethExceptions.class); + private static final Logger log = LoggerFactory.getLogger(TestVoidMethExceptions.class); - private static final int TIMEOUT_MILLIS = 5_000; + private static Stream<TestParameters> provideParameters() throws Exception { + return Stream.<TestParameters>builder() + .add(new TestParameters(ServerImplementationType.SYNC_SERVER)) + .add(new TestParameters(ServerImplementationType.ASYNC_SERVER)) + .build(); + } - private final ServerImplementationType serverImplementationType; + public static class TestParameters { + private static final int TIMEOUT_MILLIS = 5_000; + private final TServer server; + private final Thread serverThread; + private final TNonblockingServerSocket serverTransport; + private int serverPort; + private final ServerImplementationType serverImplementationType; + private final CompletableFuture<Void> futureServerStarted = new CompletableFuture<>(); + + TestParameters(ServerImplementationType serverImplementationType) throws Exception { + this.serverImplementationType = serverImplementationType; + serverPort = -1; + serverImplementationType.service.setCancelled(false); + serverTransport = new TNonblockingServerSocket(0); + TNonblockingServer.Args args = new TNonblockingServer.Args(serverTransport); + args.processor(serverImplementationType.processor); + server = new TNonblockingServer(args) { + @Override + protected void setServing(boolean serving) { + super.setServing(serving); + + if (serving) { + serverPort = serverTransport.getPort(); + futureServerStarted.complete(null); + } + } + + }; + serverThread = new Thread(server::serve, "thrift-server"); + serverThread.setDaemon(true); + } - private TServer server; - private Thread serverThread; - private int serverPort; + public AutoCloseable start() throws Exception { + serverThread.start(); + futureServerStarted.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + return () -> { + serverImplementationType.service.setCancelled(true); + server.stop(); + serverThread.join(TIMEOUT_MILLIS); + }; + } + private void checkSyncClient(String desc, + String msg, + boolean throwException, + String expectedResult, + Class<? extends Exception> expectedExceptionClass, + String expectedExceptionMsg, + SyncCall<TAppService01.Iface, String, Boolean, String> call) throws Exception { + if (log.isInfoEnabled()) { + log.info("start test checkSyncClient::" + desc + ", throwException: " + throwException + + ", serverImplementationType: " + + serverImplementationType); + } + assertNotEquals(-1, serverPort); + try (TTransport clientTransport = new TFramedTransport(new TSocket(new TConfiguration(), + "localhost", + serverPort, + TIMEOUT_MILLIS))) { + clientTransport.open(); + TAppService01.Iface client = new TAppService01.Client(new TBinaryProtocol(clientTransport)); + if (throwException && expectedExceptionClass != null) { + Exception ex = assertThrows(expectedExceptionClass, () -> { + call.apply(client, msg, throwException); + }); + assertEquals(expectedExceptionClass, ex.getClass()); + if (expectedExceptionMsg != null) { + assertEquals(expectedExceptionMsg, ex.getMessage()); + } + } else { + // expected + String result = call.apply(client, msg, throwException); + assertEquals(expectedResult, result); + } + } + } - public TestVoidMethExceptions(ServerImplementationType serverImplementationType) { - Assert.assertNotNull(serverImplementationType); - this.serverImplementationType = serverImplementationType; - } + private <T> void checkAsyncClient(String desc, + String msg, + boolean throwException, + T expectedResult, + Class<? extends Exception> expectedExceptionClass, + String expectedExceptionMsg, + AsyncCall<TAppService01.AsyncClient, String, Boolean, AsyncMethodCallback<T>> call) throws Throwable { + if (log.isInfoEnabled()) { + log.info("start test checkAsyncClient::" + desc + ", throwException: " + throwException + + ", serverImplementationType: " + + serverImplementationType); + } + assertNotEquals(serverPort, -1); + try (TNonblockingSocket clientTransportAsync = new TNonblockingSocket("localhost", serverPort, TIMEOUT_MILLIS)) { + TAsyncClientManager asyncClientManager = new TAsyncClientManager(); + try { + TAppService01.AsyncClient asyncClient = new TAppService01.AsyncClient(new TBinaryProtocol.Factory(), + asyncClientManager, + clientTransportAsync); + asyncClient.setTimeout(TIMEOUT_MILLIS); + + CompletableFuture<T> futureResult = new CompletableFuture<>(); + + call.apply(asyncClient, msg, throwException, new AsyncMethodCallback<T>() { + + @Override + public void onError(Exception exception) { + futureResult.completeExceptionally(exception); + } + + @Override + public void onComplete(T response) { + futureResult.complete(response); + } + + }); + if (throwException && expectedExceptionClass != null) { + Exception ex = assertThrows(expectedExceptionClass, () -> { + try { + futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (ExecutionException x) { + throw x.getCause(); + } + }); + assertEquals(expectedExceptionClass, ex.getClass()); + if (expectedExceptionMsg != null) { + assertEquals(expectedExceptionMsg, ex.getMessage()); + } + } else { + T result; + try { + result = futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (ExecutionException x) { + throw x.getCause(); + } + assertEquals(expectedResult, result); + } + } finally { + asyncClientManager.stop(); + } + } + } + public TServer getServer() { + return server; + } + } - @Parameters(name = "serverImplementationType = {0}") - public static Object[][] parameters() { - return new Object[][]{{ServerImplementationType.SYNC_SERVER}, - {ServerImplementationType.ASYNC_SERVER}}; - } + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnString(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnString", + "sent msg", + false, + "sent msg", + null, + null, + TAppService01.Iface::returnString); + } + } - @Before - public void setUp() throws Exception { - serverPort = -1; - serverImplementationType.service.setCancelled(false); - CompletableFuture<Void> futureServerStarted = new CompletableFuture<>(); - TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(0); - TNonblockingServer.Args args = new TNonblockingServer.Args(serverTransport); - args.processor(serverImplementationType.processor); - server = new TNonblockingServer(args) { + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnVoidThrows(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnVoidThrows", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.returnVoidThrows(msg, throwException); + return null; + }); + } + } - @Override - protected void setServing(boolean serving) { - super.setServing(serving); + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnVoidNoThrowsRuntimeException(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnVoidNoThrowsRuntimeException", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.returnVoidNoThrowsRuntimeException(msg, throwException); + return null; + }); + } + } - if (serving) { - serverPort = serverTransport.getPort(); - futureServerStarted.complete(null); + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustReturnResultReturnVoidNoThrowsTApplicationException(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnVoidNoThrowsTApplicationException", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.returnVoidNoThrowsTApplicationException(msg, throwException); + return null; + }); } - } - - }; - - serverThread = new Thread(() -> { - server.serve(); - }, "thrift-server"); - serverThread.setDaemon(true); - serverThread.start(); - futureServerStarted.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } - - @After - public void tearDown() throws Exception { - serverImplementationType.service.setCancelled(true); - server.stop(); - serverThread.join(TIMEOUT_MILLIS); - } - - - @Test - public void testSyncClientMustReturnResultReturnString() throws Exception { - checkSyncClient("returnString", - "sent msg", - false, - "sent msg", - null, - null, - (client, msg, throwException) -> { - return client.returnString(msg, throwException); - }); - } - - @Test - public void testSyncClientMustReturnResultReturnVoidThrows() throws Exception { - checkSyncClient("returnVoidThrows", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.returnVoidThrows(msg, throwException); - return null; - }); - } - - @Test - public void testSyncClientMustReturnResultReturnVoidNoThrowsRuntimeException() throws Exception { - checkSyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.returnVoidNoThrowsRuntimeException(msg, throwException); - return null; - }); - } - - @Test - public void testSyncClientMustReturnResultReturnVoidNoThrowsTApplicationException() throws Exception { - checkSyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.returnVoidNoThrowsTApplicationException(msg, throwException); - return null; - }); - } - - - @Test - public void testSyncClientMustThrowExceptionReturnString() throws Exception { - checkSyncClient("returnString", - "sent msg", - true, - null, - TExampleException.class, - "sent msg", - (client, msg, throwException) -> { - return client.returnString(msg, throwException); - }); - } - - @Test - public void testSyncClientMustThrowExceptionReturnVoidThrows() throws Exception { - checkSyncClient("returnVoidThrows", - "sent msg", - true, - null, - TExampleException.class, - "sent msg", - (client, msg, throwException) -> { - client.returnVoidThrows(msg, throwException); - return null; - }); - } - - @Test - public void testSyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException() throws Exception { - checkSyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - true, - null, - TApplicationException.class, - serverImplementationType == ServerImplementationType.ASYNC_SERVER ? "sent msg" - : null, // sync server return "Internal error processing returnVoidNoThrowsRuntimeException" message - (client, msg, throwException) -> { - client.returnVoidNoThrowsRuntimeException(msg, throwException); - return null; - }); - } - - @Test - public void testSyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException() throws Exception { - checkSyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - true, - null, - TApplicationException.class, - "sent msg", - (client, msg, throwException) -> { - client.returnVoidNoThrowsTApplicationException(msg, throwException); - return null; - }); - } - - - @Test - public void testAsyncClientMustReturnResultReturnString() throws Throwable { - checkAsyncClient("returnString", - "sent msg", - false, - "sent msg", - null, - null, - (client, msg, throwException, resultHandler) -> { - client.returnString(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientMustReturnResultReturnVoidThrows() throws Throwable { - checkAsyncClient("returnVoidThrows", - "sent msg", - false, - (Void) null, - null, - null, - (client, msg, throwException, resultHandler) -> { - client.returnVoidThrows(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientMustReturnResultReturnVoidNoThrowsRuntimeException() throws Throwable { - checkAsyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - false, - (Void) null, - null, - null, - (client, msg, throwException, resultHandler) -> { - client.returnVoidNoThrowsRuntimeException(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientMustReturnResultReturnVoidNoThrowsTApplicationException() throws Throwable { - checkAsyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - false, - (Void) null, - null, - null, - (client, msg, throwException, resultHandler) -> { - client.returnVoidNoThrowsTApplicationException(msg, throwException, resultHandler); - }); - } - - - @Test - public void testAsyncClientMustThrowExceptionReturnString() throws Throwable { - checkAsyncClient("returnString", - "sent msg", - true, - (String) null, - TExampleException.class, - "sent msg", - (client, msg, throwException, resultHandler) -> { - client.returnString(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientMustThrowExceptionReturnVoidThrows() throws Throwable { - checkAsyncClient("returnVoidThrows", - "sent msg", - true, - (Void) null, - TExampleException.class, - "sent msg", - (client, msg, throwException, resultHandler) -> { - client.returnVoidThrows(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException() throws Throwable { - checkAsyncClient("returnVoidNoThrowsRuntimeException", - "sent msg", - true, - (Void) null, - TApplicationException.class, - serverImplementationType == ServerImplementationType.ASYNC_SERVER ? "sent msg" - : null, // sync server return "Internal error processing returnVoidNoThrowsRuntimeException" message - (client, msg, throwException, resultHandler) -> { - client.returnVoidNoThrowsRuntimeException(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException() throws Throwable { - checkAsyncClient("returnVoidNoThrowsTApplicationException", - "sent msg", - true, - (Void) null, - TApplicationException.class, - "sent msg", - (client, msg, throwException, resultHandler) -> { - client.returnVoidNoThrowsTApplicationException(msg, throwException, resultHandler); - }); - } - - - @Test - public void testSyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows() throws Exception { - checkSyncClient("onewayVoidNoThrows", - "sent msg", - false, - null, - null, - null, - (client, msg, throwException) -> { - client.onewayVoidNoThrows(msg, throwException); - return null; - }); - } - - @Test - public void testSyncClientNoWaitForResultExceptionOnewayVoidNoThrows() throws Exception { - checkSyncClient("onewayVoidNoThrows", - "sent msg", - true, - null, - null, - null, - (client, msg, throwException) -> { - client.onewayVoidNoThrows(msg, throwException); - return null; - }); - } - - @Test - public void testAsyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows() throws Throwable { - checkAsyncClient("onewayVoidNoThrows", - "sent msg", - false, - (Void) null, - null, - null, - (client, msg, throwException, resultHandler) -> { - client.onewayVoidNoThrows(msg, throwException, resultHandler); - }); - } - - @Test - public void testAsyncClientNoWaitForResultExceptionOnewayVoidNoThrows() throws Throwable { - checkAsyncClient("onewayVoidNoThrows", - "sent msg", - true, - (Void) null, - null, - null, - (client, msg, throwException, resultHandler) -> { - client.onewayVoidNoThrows(msg, throwException, resultHandler); - }); - } - - - private void checkSyncClient(String desc, - String msg, - boolean throwException, - String expectedResult, - Class<?> expectedExceptionClass, - String expectedExceptionMsg, - SyncCall<TAppService01.Iface, String, Boolean, String> call) throws Exception { - if (log.isInfoEnabled()) { - log.info("start test checkSyncClient::" + desc + ", throwException: " + throwException - + ", serverImplementationType: " - + serverImplementationType); } - Assert.assertNotEquals(-1, serverPort); - try (TTransport clientTransport = new TFramedTransport(new TSocket(new TConfiguration(), - "localhost", - serverPort, - TIMEOUT_MILLIS))) { - clientTransport.open(); - TAppService01.Iface client = new TAppService01.Client(new TBinaryProtocol(clientTransport)); - - try { - - String result = call.apply(client, msg, throwException); - - if (throwException && expectedExceptionClass != null) { - Assert.fail("No exception, but must!!!"); - } else { - // expected - Assert.assertEquals(expectedResult, result); + + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnString(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnString", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + TAppService01.Iface::returnString); } - } catch (TExampleException | TApplicationException x) { - if (log.isInfoEnabled()) { - log.info("Exception: " + x, x); + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnVoidThrows(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnVoidThrows", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + (client, msg, throwException) -> { + client.returnVoidThrows(msg, throwException); + return null; + }); } - if (throwException) { - // expected - Assert.assertEquals(expectedExceptionClass, x.getClass()); - if (expectedExceptionMsg != null) { - Assert.assertEquals(expectedExceptionMsg, x.getMessage()); - } - } else { - Assert.fail(); + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException(TestParameters p) throws + Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnVoidNoThrowsRuntimeException", + "sent msg", + true, + null, + TApplicationException.class, + p.serverImplementationType == ServerImplementationType.ASYNC_SERVER ? "sent msg" + : null, // sync server return "Internal error processing returnVoidNoThrowsRuntimeException" message + (client, msg, throwException) -> { + client.returnVoidNoThrowsRuntimeException(msg, throwException); + return null; + }); } - } } - } - - private <T> void checkAsyncClient(String desc, - String msg, - boolean throwException, - T expectedResult, - Class<?> expectedExceptionClass, - String expectedExceptionMsg, - AsyncCall<TAppService01.AsyncClient, String, Boolean, AsyncMethodCallback<T>> call) throws Throwable { - if (log.isInfoEnabled()) { - log.info("start test checkAsyncClient::" + desc + ", throwException: " + throwException - + ", serverImplementationType: " - + serverImplementationType); + + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException(TestParameters p) throws + Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("returnVoidNoThrowsTApplicationException", + "sent msg", + true, + null, + TApplicationException.class, + "sent msg", + (client, msg, throwException) -> { + client.returnVoidNoThrowsTApplicationException(msg, throwException); + return null; + }); + } } - Assert.assertNotEquals(serverPort, -1); - try (TNonblockingSocket clientTransportAsync = new TNonblockingSocket("localhost", serverPort, TIMEOUT_MILLIS)) { - TAsyncClientManager asyncClientManager = new TAsyncClientManager(); - try { - TAppService01.AsyncClient asyncClient = new TAppService01.AsyncClient(new TBinaryProtocol.Factory(), - asyncClientManager, - clientTransportAsync); - asyncClient.setTimeout(TIMEOUT_MILLIS); - CompletableFuture<T> futureResult = new CompletableFuture<>(); - call.apply(asyncClient, msg, throwException, new AsyncMethodCallback<T>() { + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnString(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnString", + "sent msg", + false, + "sent msg", + null, + null, + TAppService01.AsyncClient::returnString); + } + } + + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnVoidThrows(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnVoidThrows", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::returnVoidThrows); + } + } - @Override - public void onError(Exception exception) { - futureResult.completeExceptionally(exception); - } + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnVoidNoThrowsRuntimeException(TestParameters p) throws + Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnVoidNoThrowsRuntimeException", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::returnVoidNoThrowsRuntimeException); + } + } - @Override - public void onComplete(T response) { - futureResult.complete(response); - } + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustReturnResultReturnVoidNoThrowsTApplicationException(TestParameters p) throws + Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnVoidNoThrowsTApplicationException", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::returnVoidNoThrowsTApplicationException); + } + } - }); - try { - T result; - try { - result = futureResult.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - } catch (ExecutionException x) { - throw x.getCause(); - } - - if (throwException && expectedExceptionClass != null) { - Assert.fail("No exception, but must!!!"); - } else { - // expected - Assert.assertEquals(expectedResult, result); - } - } catch (TExampleException | TApplicationException x) { - if (log.isInfoEnabled()) { - log.info("Exception: " + x, x); - } - if (throwException) { - // expected - Assert.assertEquals(expectedExceptionClass, x.getClass()); - if (expectedExceptionMsg != null) { - Assert.assertEquals(expectedExceptionMsg, x.getMessage()); - } - } else { - Assert.fail(); - } + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnString(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnString", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + TAppService01.AsyncClient::returnString); } - } finally { - asyncClientManager.stop(); - } } - } + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnVoidThrows(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnVoidThrows", + "sent msg", + true, + null, + TExampleException.class, + "sent msg", + TAppService01.AsyncClient::returnVoidThrows); + } + } - private enum ServerImplementationType { + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsRuntimeException(TestParameters p) throws + Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnVoidNoThrowsRuntimeException", + "sent msg", + true, + null, + TApplicationException.class, + p.serverImplementationType == ServerImplementationType.ASYNC_SERVER ? "sent msg" + : null, // sync server return "Internal error processing returnVoidNoThrowsRuntimeException" message + TAppService01.AsyncClient::returnVoidNoThrowsRuntimeException); + } + } - SYNC_SERVER(() -> { - ServiceSyncImp service = new ServiceSyncImp(); - return Pair.of(new TAppService01.Processor<>(service), service); - }), - ASYNC_SERVER(() -> { - ServiceAsyncImp service = new ServiceAsyncImp(); - return Pair.of(new TAppService01.AsyncProcessor<>(service), service); - }); + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientMustThrowExceptionReturnVoidNoThrowsTApplicationException(TestParameters p) throws + Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("returnVoidNoThrowsTApplicationException", + "sent msg", + true, + null, + TApplicationException.class, + "sent msg", + TAppService01.AsyncClient::returnVoidNoThrowsTApplicationException); + } + } - final TProcessor processor; - final ServiceBase service; - ServerImplementationType(Supplier<Pair<TProcessor, ServiceBase>> supplier) { - Pair<TProcessor, ServiceBase> pair = supplier.get(); - this.processor = pair.getLeft(); - this.service = pair.getRight(); + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("onewayVoidNoThrows", + "sent msg", + false, + null, + null, + null, + (client, msg, throwException) -> { + client.onewayVoidNoThrows(msg, throwException); + return null; + }); + } } - } + @ParameterizedTest + @MethodSource("provideParameters") + public void testSyncClientNoWaitForResultExceptionOnewayVoidNoThrows(TestParameters p) throws Exception { + try (AutoCloseable ignored = p.start()) { + p.checkSyncClient("onewayVoidNoThrows", + "sent msg", + true, + null, + null, + null, + (client, msg, throwException) -> { + client.onewayVoidNoThrows(msg, throwException); + return null; + }); + } + } - @FunctionalInterface - private interface SyncCall<T, U, V, R> { + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientNoWaitForResultNoExceptionOnewayVoidNoThrows(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("onewayVoidNoThrows", + "sent msg", + false, + null, + null, + null, + TAppService01.AsyncClient::onewayVoidNoThrows); + } + } - R apply(T t, U u, V v) throws Exception; + @ParameterizedTest + @MethodSource("provideParameters") + public void testAsyncClientNoWaitForResultExceptionOnewayVoidNoThrows(TestParameters p) throws Throwable { + try (AutoCloseable ignored = p.start()) { + p.checkAsyncClient("onewayVoidNoThrows", + "sent msg", + true, + null, + null, + null, + TAppService01.AsyncClient::onewayVoidNoThrows); + } + } - } + private enum ServerImplementationType { - @FunctionalInterface - private interface AsyncCall<T, U, V, X> { + SYNC_SERVER(() -> { + ServiceSyncImp service = new ServiceSyncImp(); + return Pair.of(new TAppService01.Processor<>(service), service); + }), + ASYNC_SERVER(() -> { + ServiceAsyncImp service = new ServiceAsyncImp(); + return Pair.of(new TAppService01.AsyncProcessor<>(service), service); + }); + + final TProcessor processor; + final ServiceBase service; + + ServerImplementationType(Supplier<Pair<TProcessor, ServiceBase>> supplier) { + Pair<TProcessor, ServiceBase> pair = supplier.get(); + this.processor = pair.getLeft(); + this.service = pair.getRight(); + } + } - void apply(T t, U u, V v, X x) throws Exception; - } + @FunctionalInterface + private interface SyncCall<T, U, V, R> { + R apply(T t, U u, V v) throws Exception; + } + + + @FunctionalInterface + private interface AsyncCall<T, U, V, X> { + void apply(T t, U u, V v, X x) throws Exception; + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java index c35348953..0b7e4ada8 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBuffer.java @@ -18,9 +18,14 @@ */ package org.apache.thrift.transport; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -public class TestAutoExpandingBuffer extends TestCase { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class TestAutoExpandingBuffer { + @Test public void testExpands() throws Exception { // has expected initial capacity AutoExpandingBuffer b = new AutoExpandingBuffer(10); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java index b635e60fa..090191312 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferReadTransport.java @@ -18,12 +18,14 @@ */ package org.apache.thrift.transport; +import org.apache.thrift.TConfiguration; +import org.junit.jupiter.api.Test; + import java.nio.ByteBuffer; -import junit.framework.TestCase; -import org.apache.thrift.TConfiguration; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class TestAutoExpandingBufferReadTransport extends TestCase { +public class TestAutoExpandingBufferReadTransport { private static final byte[] HUNDRED_BYTES = new byte[100]; static { @@ -32,6 +34,7 @@ public class TestAutoExpandingBufferReadTransport extends TestCase { } } + @Test public void testIt() throws Exception { AutoExpandingBufferReadTransport t = new AutoExpandingBufferReadTransport(new TConfiguration(), 150); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java index c3e021ccd..24249908a 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestAutoExpandingBufferWriteTransport.java @@ -18,56 +18,59 @@ */ package org.apache.thrift.transport; +import org.apache.thrift.TConfiguration; +import org.junit.jupiter.api.Test; + import java.nio.ByteBuffer; -import org.apache.thrift.TConfiguration; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestAutoExpandingBufferWriteTransport { - private TConfiguration config = new TConfiguration(); + private final TConfiguration config = new TConfiguration(); - @Test - public void testIt() throws Exception { - AutoExpandingBufferWriteTransport t = new AutoExpandingBufferWriteTransport(config, 1, 0); - assertEquals(0, t.getLength()); - assertEquals(1, t.getBuf().array().length); - byte[] b1 = new byte[]{1,2,3}; - t.write(b1); - assertEquals(3, t.getLength()); - assertTrue(t.getBuf().array().length >= 3); - assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(t.getBuf().array(), 0, 3)); + @Test + public void testIt() throws Exception { + AutoExpandingBufferWriteTransport t = new AutoExpandingBufferWriteTransport(config, 1, 0); + assertEquals(0, t.getLength()); + assertEquals(1, t.getBuf().array().length); + byte[] b1 = new byte[]{1, 2, 3}; + t.write(b1); + assertEquals(3, t.getLength()); + assertTrue(t.getBuf().array().length >= 3); + assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(t.getBuf().array(), 0, 3)); - t.reset(); - assertEquals(0, t.getLength()); - assertTrue(t.getBuf().array().length >= 3); - byte[] b2 = new byte[]{4,5}; - t.write(b2); - assertEquals(2, t.getLength()); - assertEquals(ByteBuffer.wrap(b2), ByteBuffer.wrap(t.getBuf().array(), 0, 2)); + t.reset(); + assertEquals(0, t.getLength()); + assertTrue(t.getBuf().array().length >= 3); + byte[] b2 = new byte[]{4, 5}; + t.write(b2); + assertEquals(2, t.getLength()); + assertEquals(ByteBuffer.wrap(b2), ByteBuffer.wrap(t.getBuf().array(), 0, 2)); - AutoExpandingBufferWriteTransport uut = new AutoExpandingBufferWriteTransport(config, 8, 4); - assertEquals(4, uut.getLength()); - assertEquals(8, uut.getBuf().array().length); - uut.write(b1); - assertEquals(7, uut.getLength()); - assertEquals(8, uut.getBuf().array().length); - assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(uut.getBuf().array(), 4, 3)); - } + AutoExpandingBufferWriteTransport uut = new AutoExpandingBufferWriteTransport(config, 8, 4); + assertEquals(4, uut.getLength()); + assertEquals(8, uut.getBuf().array().length); + uut.write(b1); + assertEquals(7, uut.getLength()); + assertEquals(8, uut.getBuf().array().length); + assertEquals(ByteBuffer.wrap(b1), ByteBuffer.wrap(uut.getBuf().array(), 4, 3)); + } - @Test(expected = IllegalArgumentException.class) - public void testBadInitialSize() throws IllegalArgumentException, TTransportException { - new AutoExpandingBufferWriteTransport(config, 0, 0); - } + @Test + public void testBadInitialSize() throws TTransportException { + assertThrows(IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 0, 0)); + } - @Test(expected = IllegalArgumentException.class) - public void testBadFrontReserveSize() throws IllegalArgumentException, TTransportException { - new AutoExpandingBufferWriteTransport(config, 4, -1); - } + @Test + public void testBadFrontReserveSize() throws IllegalArgumentException, TTransportException { + assertThrows(IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 4, -1)); + } - @Test(expected = IllegalArgumentException.class) - public void testTooSmallFrontReserveSize() throws IllegalArgumentException, TTransportException { - new AutoExpandingBufferWriteTransport(config, 4, 5); - } + @Test + public void testTooSmallFrontReserveSize() throws IllegalArgumentException, TTransportException { + assertThrows(IllegalArgumentException.class, () -> new AutoExpandingBufferWriteTransport(config, 4, 5)); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java b/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java index 6b28dfd51..6bde36c15 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestNonblockingServerSocket.java @@ -19,18 +19,19 @@ package org.apache.thrift.transport; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.channels.ServerSocketChannel; +import static org.junit.jupiter.api.Assertions.assertFalse; + public class TestNonblockingServerSocket { @Test public void testSocketChannelBlockingMode() throws TTransportException { try (TNonblockingServerSocket nonblockingServer = new TNonblockingServerSocket(0)){ ServerSocketChannel socketChannel = nonblockingServer.getServerSocketChannel(); - Assert.assertFalse("Socket channel should be nonblocking", socketChannel.isBlocking()); + assertFalse(socketChannel.isBlocking(), "Socket channel should be nonblocking"); } } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java index bdc0a848a..33977645d 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTByteBuffer.java @@ -1,18 +1,22 @@ package org.apache.thrift.transport; -import junit.framework.TestCase; -import java.nio.charset.StandardCharsets; -import org.apache.thrift.TException; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class TestTByteBuffer extends TestCase { +public class TestTByteBuffer { + @Test public void testReadWrite() throws Exception { final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(16)); byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8)); assertEquals("Hello World", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); } + @Test public void testReuseReadWrite() throws Exception { final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(16)); byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8)); @@ -24,13 +28,10 @@ public class TestTByteBuffer extends TestCase { assertEquals("Goodbye Horses", new String(byteBuffer.flip().toByteArray(), StandardCharsets.UTF_8)); } + @Test public void testOverflow() throws Exception { final TByteBuffer byteBuffer = new TByteBuffer(ByteBuffer.allocate(4)); - try { - byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8)); - fail("Expected write operation to fail with TTransportException"); - } catch (TTransportException e) { - assertEquals("Not enough room in output buffer", e.getMessage()); - } + TTransportException e = assertThrows(TTransportException.class, ()-> byteBuffer.write("Hello World".getBytes(StandardCharsets.UTF_8))); + assertEquals("Not enough room in output buffer", e.getMessage()); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java index fc3dd5b6b..0d861bdc6 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTFramedTransport.java @@ -18,19 +18,25 @@ */ package org.apache.thrift.transport; +import org.apache.thrift.transport.layered.TFastFramedTransport; +import org.apache.thrift.transport.layered.TFramedTransport; +import org.junit.jupiter.api.Test; + import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.util.Arrays; -import junit.framework.TestCase; -import org.apache.thrift.transport.layered.TFastFramedTransport; -import org.apache.thrift.transport.layered.TFramedTransport; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class TestTFramedTransport extends TestCase { +public class TestTFramedTransport { protected TTransport getTransport(TTransport underlying) throws TTransportException { return new TFramedTransport(underlying); @@ -48,6 +54,7 @@ public class TestTFramedTransport extends TestCase { return result; } + @Test public void testRead() throws IOException, TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); @@ -65,11 +72,11 @@ public class TestTFramedTransport extends TestCase { byte[] readBuf = new byte[10]; trans.read(readBuf, 0, 10); - assertTrue(Arrays.equals(readBuf, byteSequence(0,9))); + assertArrayEquals(readBuf, byteSequence(0, 9)); assertEquals(2, countTrans.readCount); trans.read(readBuf, 0, 10); - assertTrue(Arrays.equals(readBuf, byteSequence(10,19))); + assertArrayEquals(readBuf, byteSequence(10, 19)); assertEquals(2, countTrans.readCount); assertEquals(30, trans.read(new byte[30], 0, 30)); @@ -78,10 +85,11 @@ public class TestTFramedTransport extends TestCase { // Known message size exceeded readBuf = new byte[220]; assertEquals(220, trans.read(readBuf, 0, 220)); - assertTrue(Arrays.equals(readBuf, byteSequence(0, 219))); + assertArrayEquals(readBuf, byteSequence(0, 219)); assertEquals(4, countTrans.readCount); } + @Test public void testInvalidFrameSize() throws IOException, TTransportException { int maxLength = 128; @@ -97,25 +105,17 @@ public class TestTFramedTransport extends TestCase { TTransport trans = getTransport(countTrans, maxLength); byte[] readBuf = new byte[10]; - try { - trans.read(readBuf, 0, 4); - fail("Expected a TTransportException"); - } catch (TTransportException e) { - // We expect this exception because the frame we're trying to read is larger than our max frame length - assertEquals(TTransportException.CORRUPTED_DATA, e.getType()); - } - + TTransportException e = assertThrows(TTransportException.class, () -> trans.read(readBuf, 0, 4)); + // We expect this exception because the frame we're trying to read is larger than our max frame length + assertEquals(TTransportException.CORRUPTED_DATA, e.getType()); assertFalse(trans.isOpen()); - try { - trans.read(readBuf, 0, 4); - fail("Expected a TTransportException"); - } catch (TTransportException e) { - // This time we get an exception indicating the connection was closed - assertEquals(TTransportException.NOT_OPEN, e.getType()); - } + TTransportException e2 = assertThrows(TTransportException.class, () -> trans.read(readBuf, 0, 4)); + // This time we get an exception indicating the connection was closed + assertEquals(TTransportException.NOT_OPEN, e2.getType()); } + @Test public void testWrite() throws TTransportException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); @@ -138,15 +138,16 @@ public class TestTFramedTransport extends TestCase { assertEquals(256, din.readInt()); byte[] buf = new byte[256]; - din.read(buf, 0, 256); - assertTrue(Arrays.equals(byteSequence(0,255), buf)); + int readBytes = din.read(buf, 0, 256); + assertArrayEquals(byteSequence(0, 255), buf); assertEquals(246, din.readInt()); buf = new byte[246]; - din.read(buf, 0, 246); - assertTrue(Arrays.equals(byteSequence(0,245), buf)); + int readBytes2 = din.read(buf, 0, 246); + assertArrayEquals(byteSequence(0, 245), buf); } + @Test public void testDirectRead() throws IOException, TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); @@ -165,7 +166,7 @@ public class TestTFramedTransport extends TestCase { byte[] readBuf = new byte[10]; trans.read(readBuf, 0, 10); - assertTrue(Arrays.equals(readBuf, byteSequence(0,9))); + assertArrayEquals(readBuf, byteSequence(0, 9)); assertEquals(40, trans.getBytesRemainingInBuffer()); assertEquals(10, trans.getBufferPosition()); @@ -183,11 +184,12 @@ public class TestTFramedTransport extends TestCase { // Known message size exceeded trans.read(readBuf, 0, 10); assertEquals(4, countTrans.readCount); - assertTrue(Arrays.equals(readBuf, byteSequence(125,134))); + assertArrayEquals(readBuf, byteSequence(125, 134)); assertEquals(40, trans.getBytesRemainingInBuffer()); assertEquals(10, trans.getBufferPosition()); } + @Test public void testClear() throws IOException, TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); @@ -202,17 +204,17 @@ public class TestTFramedTransport extends TestCase { byte[] readBuf = new byte[220]; trans.read(readBuf, 0, 220); - assertTrue(Arrays.equals(readBuf, byteSequence(0,219))); + assertArrayEquals(readBuf, byteSequence(0, 219)); assertTrue(trans instanceof TFramedTransport || trans instanceof TFastFramedTransport); if (trans instanceof TFramedTransport) { assertTrue(trans.getBuffer() != null && trans.getBuffer().length > 0); ((TFramedTransport) trans).clear(); - assertTrue(trans.getBuffer() == null); - } else if (trans instanceof TFastFramedTransport) { + assertNull(trans.getBuffer()); + } else { assertTrue(trans.getBuffer().length > TestTFastFramedTransport.INITIAL_CAPACITY); ((TFastFramedTransport) trans).clear(); - assertTrue(trans.getBuffer().length == TestTFastFramedTransport.INITIAL_CAPACITY); + assertEquals(TestTFastFramedTransport.INITIAL_CAPACITY, trans.getBuffer().length); } } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java index 5965446f8..4e66cf5fa 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTIOStreamTransport.java @@ -18,45 +18,50 @@ package org.apache.thrift.transport; +import org.junit.jupiter.api.Test; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; -import junit.framework.TestCase; - -public class TestTIOStreamTransport extends TestCase { - - // THRIFT-5022 - public void testOpenClose_2streams() throws TTransportException { - byte[] dummy = {20}; // So the input stream isn't EOF immediately. - InputStream input = new ByteArrayInputStream(dummy); - OutputStream output = new ByteArrayOutputStream(); - TTransport transport = new TIOStreamTransport(input, output); - runOpenClose(transport); - } - - // THRIFT-5022 - public void testOpenClose_1input() throws TTransportException { - byte[] dummy = {20}; - InputStream input = new ByteArrayInputStream(dummy); - TTransport transport = new TIOStreamTransport(input); - runOpenClose(transport); - } - - // THRIFT-5022 - public void testIOpenClose_1output() throws TTransportException { - OutputStream output = new ByteArrayOutputStream(); - TTransport transport = new TIOStreamTransport(output); - runOpenClose(transport); - } - - private void runOpenClose(TTransport transport) throws TTransportException { - transport.open(); - boolean b1 = transport.isOpen(); - assertTrue(b1); - transport.close(); - boolean b2 = transport.isOpen(); - assertFalse(b2); - } +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TestTIOStreamTransport { + // THRIFT-5022 + @Test + public void testOpenClose_2streams() throws TTransportException { + byte[] dummy = {20}; // So the input stream isn't EOF immediately. + InputStream input = new ByteArrayInputStream(dummy); + OutputStream output = new ByteArrayOutputStream(); + TTransport transport = new TIOStreamTransport(input, output); + runOpenClose(transport); + } + + // THRIFT-5022 + @Test + public void testOpenClose_1input() throws TTransportException { + byte[] dummy = {20}; + InputStream input = new ByteArrayInputStream(dummy); + TTransport transport = new TIOStreamTransport(input); + runOpenClose(transport); + } + + // THRIFT-5022 + @Test + public void testIOpenClose_1output() throws TTransportException { + OutputStream output = new ByteArrayOutputStream(); + TTransport transport = new TIOStreamTransport(output); + runOpenClose(transport); + } + + private void runOpenClose(TTransport transport) throws TTransportException { + transport.open(); + boolean b1 = transport.isOpen(); + assertTrue(b1); + transport.close(); + boolean b2 = transport.isOpen(); + assertFalse(b2); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java index bd9443683..482bb3a3a 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryInputTransport.java @@ -18,11 +18,14 @@ */ package org.apache.thrift.transport; -import java.util.Arrays; +import org.junit.jupiter.api.Test; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class TestTMemoryInputTransport extends TestCase { +public class TestTMemoryInputTransport { + @Test public void testFresh() throws Exception { byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TMemoryInputTransport trans = new TMemoryInputTransport(input_buf); @@ -32,7 +35,7 @@ public class TestTMemoryInputTransport extends TestCase { byte[] buf1 = new byte[4]; trans.readAll(buf1, 0, 4); - assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); + assertArrayEquals(new byte[]{1, 2, 3, 4}, buf1); assertEquals(4, trans.getBufferPosition()); assertEquals(6, trans.getBytesRemainingInBuffer()); @@ -42,11 +45,12 @@ public class TestTMemoryInputTransport extends TestCase { assertEquals(4, trans.getBytesRemainingInBuffer()); trans.readAll(buf1, 0, 4); - assertTrue(Arrays.equals(new byte[]{7, 8, 9, 10}, buf1)); + assertArrayEquals(new byte[]{7, 8, 9, 10}, buf1); assertEquals(10, trans.getBufferPosition()); assertEquals(0, trans.getBytesRemainingInBuffer()); } + @Test public void testReused() throws Exception { byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TMemoryInputTransport trans = new TMemoryInputTransport(input_buf); @@ -61,25 +65,25 @@ public class TestTMemoryInputTransport extends TestCase { assertEquals(3, trans.getBytesRemainingInBuffer()); } + @Test public void testWithOffsetAndLength() throws TTransportException { byte[] input_buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TMemoryInputTransport trans = new TMemoryInputTransport(input_buf, 1, 3); assertEquals(1, trans.getBufferPosition()); assertEquals(3, trans.getBytesRemainingInBuffer()); - byte[] readBuffer = new byte[3]; - trans.readAll(readBuffer, 0, 3); - assertTrue(Arrays.equals(new byte[]{2, 3, 4}, readBuffer)); - try { - assertEquals(0, trans.readAll(readBuffer, 0, 3)); - fail("should have thrown an exception"); - } catch (Exception e) { - // yay + { + byte[] readBuffer = new byte[3]; + trans.readAll(readBuffer, 0, 3); + assertArrayEquals(new byte[]{2, 3, 4}, readBuffer); + assertThrows(Exception.class, () -> trans.readAll(readBuffer, 0, 3)); } - trans.reset(input_buf, 3, 4); - readBuffer = new byte[4]; - trans.readAll(readBuffer, 0, 4); - assertTrue(Arrays.equals(new byte[]{4, 5, 6, 7}, readBuffer)); + { + trans.reset(input_buf, 3, 4); + byte[] readBuffer2 = new byte[4]; + trans.readAll(readBuffer2, 0, 4); + assertArrayEquals(new byte[]{4, 5, 6, 7}, readBuffer2); + } } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java index 2e20ffea7..6d221db96 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTMemoryTransport.java @@ -20,12 +20,15 @@ package org.apache.thrift.transport; import org.apache.thrift.TByteArrayOutputStream; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import java.nio.ByteBuffer; import java.util.Random; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class TestTMemoryTransport { @Test @@ -41,14 +44,19 @@ public class TestTMemoryTransport { for (int i = 0; i < inputBytes.length; i++) { equal = equal && inputBytes[i] == read[i]; } - Assert.assertEquals(ByteBuffer.wrap(inputBytes), ByteBuffer.wrap(read)); + assertEquals(ByteBuffer.wrap(inputBytes), ByteBuffer.wrap(read)); } - @Test (expected = TTransportException.class) + @Test public void testReadMoreThanRemaining() throws TTransportException { TMemoryTransport transport = new TMemoryTransport(new byte[] {0x00, 0x32}); byte[] read = new byte[3]; - transport.read(read, 0, 3); + assertThrows(TTransportException.class, new Executable() { + @Override + public void execute() throws Throwable { + transport.read(read, 0, 3); + } + }); } @Test @@ -60,6 +68,6 @@ public class TestTMemoryTransport { transport.write(output2, 0, 2); byte[] expected = {0x72, 0x56, 0x29, (byte) 0xAF, (byte) 0x9B, (byte) 0x83, 0x10}; TByteArrayOutputStream outputByteArray = transport.getOutput(); - Assert.assertEquals(ByteBuffer.wrap(expected), ByteBuffer.wrap(outputByteArray.get(), 0, outputByteArray.len())); + assertEquals(ByteBuffer.wrap(expected), ByteBuffer.wrap(outputByteArray.get(), 0, outputByteArray.len())); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java index 032c2eb71..b5186c060 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactory.java @@ -20,6 +20,7 @@ package org.apache.thrift.transport; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.apache.thrift.TProcessor; @@ -27,17 +28,35 @@ import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.server.ServerTestBase; import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.server.TServer.Args; +import org.apache.thrift.server.TSimpleServer; public class TestTSSLTransportFactory extends ServerTestBase { private Thread serverThread; private TServer server; - private static final List<TProtocolFactory> protocols = new ArrayList<TProtocolFactory>(); - static { - // TODO: Only supported on TBinaryProtocol. Doesn't work for TCompactProtocol - protocols.add(new TBinaryProtocol.Factory()); + // TODO: Only supported on TBinaryProtocol. Doesn't work for TCompactProtocol + private static final List<TProtocolFactory> protocols = Collections.singletonList(new TBinaryProtocol.Factory()); + + private static final String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore"); + private static final String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); + private static final String trustStoreLocation = System.getProperty("javax.net.ssl.trustStore"); + private static final String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); + + protected final String getKeyStoreLocation() { + return keyStoreLocation; + } + + protected final String getKeyStorePassword() { + return keyStorePassword; + } + + protected final String getTrustStoreLocation() { + return trustStoreLocation; + } + + protected final String getTrustStorePassword() { + return trustStorePassword; } @Override @@ -45,7 +64,7 @@ public class TestTSSLTransportFactory extends ServerTestBase { throws Exception { return TSSLTransportFactory.getClientSocket(HOST, PORT); } - + protected TServerSocket getServerTransport() throws Exception { return TSSLTransportFactory.getServerSocket(PORT); } @@ -53,19 +72,17 @@ public class TestTSSLTransportFactory extends ServerTestBase { @Override public void startServer(final TProcessor processor, final TProtocolFactory protoFactory, final TTransportFactory factory) throws Exception { - serverThread = new Thread() { - public void run() { - try { - TServerTransport serverTransport = getServerTransport(); - final Args args = new Args(serverTransport).processor(processor); - server = new TSimpleServer(args); - server.serve(); - } catch (Exception e) { - e.printStackTrace(); - assert false; - } + serverThread = new Thread(() -> { + try { + TServerTransport serverTransport = getServerTransport(); + final Args args = new Args(serverTransport).processor(processor); + server = new TSimpleServer(args); + server.serve(); + } catch (Exception e) { + e.printStackTrace(); + assert false; } - }; + }); serverThread.start(); Thread.sleep(SLEEP_DELAY); diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java index da1659f9d..6b543e3a3 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient1.java @@ -26,10 +26,7 @@ public class TestTSSLTransportFactoryCustomClient1 extends TestTSSLTransportFact throws Exception { TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters(); - - params.setTrustStore(System.getProperty("javax.net.ssl.trustStore"), - System.getProperty("javax.net.ssl.trustStorePassword")); - + params.setTrustStore(getTrustStoreLocation(), getTrustStorePassword()); return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java index eaed46057..2427b9be3 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryCustomClient2.java @@ -26,9 +26,7 @@ public class TestTSSLTransportFactoryCustomClient2 extends TestTSSLTransportFact throws Exception { TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters(); - - params.setTrustStore(System.getProperty("javax.net.ssl.trustStore"), null); - + params.setTrustStore(getTrustStoreLocation(), null); return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java index 25bf5cebb..cc3cb68ca 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSSLTransportFactoryStreamedStore.java @@ -23,19 +23,6 @@ import java.io.FileInputStream; import java.net.InetAddress; public class TestTSSLTransportFactoryStreamedStore extends TestTSSLTransportFactory { - private static String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore"); - private static String trustStoreLocation = System.getProperty("javax.net.ssl.trustStore"); - - public TestTSSLTransportFactoryStreamedStore() { - super(); - - /** - * Override system properties to be able to test passing - * the trustStore and keyStore as input stream - */ - System.setProperty("javax.net.ssl.trustStore", ""); - System.setProperty("javax.net.ssl.keyStore", ""); - } @Override public TTransport getClientTransport(TTransport underlyingTransport) @@ -43,9 +30,8 @@ public class TestTSSLTransportFactoryStreamedStore extends TestTSSLTransportFact TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters(); - params.setTrustStore(new FileInputStream(trustStoreLocation), - System.getProperty("javax.net.ssl.trustStorePassword")); - + params.setTrustStore(new FileInputStream(getTrustStoreLocation()), getTrustStorePassword()); + return TSSLTransportFactory.getClientSocket(HOST, PORT, 0/*timeout*/, params); } @@ -53,10 +39,9 @@ public class TestTSSLTransportFactoryStreamedStore extends TestTSSLTransportFact protected TServerSocket getServerTransport() throws Exception { TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters(); - - params.setKeyStore(new FileInputStream(keyStoreLocation), - System.getProperty("javax.net.ssl.keyStorePassword")); - + + params.setKeyStore(new FileInputStream(getKeyStoreLocation()), getKeyStorePassword()); + return TSSLTransportFactory.getServerSocket(PORT, 0/*timeout*/, InetAddress.getByName(HOST), params); } -}
\ No newline at end of file +} diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java index d384d7fa3..7cc5ca6c6 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSaslTransports.java @@ -19,10 +19,16 @@ package org.apache.thrift.transport; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; +import org.apache.thrift.TConfiguration; +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TProtocolFactory; +import org.apache.thrift.server.ServerTestBase; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TServer.Args; +import org.apache.thrift.server.TSimpleServer; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -37,20 +43,19 @@ import javax.security.sasl.SaslClientFactory; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; -import junit.framework.TestCase; - -import org.apache.thrift.TConfiguration; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.server.ServerTestBase; -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TSimpleServer; -import org.apache.thrift.server.TServer.Args; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -public class TestTSaslTransports extends TestCase { +public class TestTSaslTransports { private static final Logger LOGGER = LoggerFactory.getLogger(TestTSaslTransports.class); @@ -106,7 +111,7 @@ public class TestTSaslTransports extends TestCase { } } - private class ServerThread extends Thread { + private static class ServerThread extends Thread { final String mechanism; final Map<String, String> props; volatile Throwable thrown; @@ -125,13 +130,10 @@ public class TestTSaslTransports extends TestCase { } private void internalRun() throws Exception { - TServerSocket serverSocket = new TServerSocket( - new TServerSocket.ServerSocketTransportArgs(). - port(ServerTestBase.PORT)); - try { + try (TServerSocket serverSocket = new TServerSocket( + new TServerSocket.ServerSocketTransportArgs(). + port(ServerTestBase.PORT))) { acceptAndWrite(serverSocket); - } finally { - serverSocket.close(); } } @@ -210,14 +212,17 @@ public class TestTSaslTransports extends TestCase { } } + @Test public void testUnwrappedOpen() throws Exception { testSaslOpen(UNWRAPPED_MECHANISM, UNWRAPPED_PROPS); } + @Test public void testWrappedOpen() throws Exception { testSaslOpen(WRAPPED_MECHANISM, WRAPPED_PROPS); } + @Test public void testAnonymousOpen() throws Exception { testSaslOpen("ANONYMOUS", null); } @@ -226,6 +231,7 @@ public class TestTSaslTransports extends TestCase { * Test that we get the proper exceptions thrown back the server when * the client provides invalid password. */ + @Test public void testBadPassword() throws Exception { ServerThread serverThread = new ServerThread(UNWRAPPED_MECHANISM, UNWRAPPED_PROPS); serverThread.start(); @@ -236,32 +242,23 @@ public class TestTSaslTransports extends TestCase { // Ah well. } - boolean clientSidePassed = true; - - try { + TTransportException tte = assertThrows(TTransportException.class, () -> { TSocket clientSocket = new TSocket(HOST, ServerTestBase.PORT); TTransport saslClientTransport = new TSaslClientTransport( - UNWRAPPED_MECHANISM, PRINCIPAL, SERVICE, HOST, UNWRAPPED_PROPS, - new TestSaslCallbackHandler("NOT THE PASSWORD"), clientSocket); + UNWRAPPED_MECHANISM, PRINCIPAL, SERVICE, HOST, UNWRAPPED_PROPS, + new TestSaslCallbackHandler("NOT THE PASSWORD"), clientSocket); saslClientTransport.open(); - clientSidePassed = false; - fail("Was able to open transport with bad password"); - } catch (TTransportException tte) { - LOGGER.error("Exception for bad password", tte); - assertNotNull(tte.getMessage()); - assertTrue(tte.getMessage().contains("Invalid response")); - - } finally { - serverThread.interrupt(); - serverThread.join(); - - if (clientSidePassed) { - assertNotNull(serverThread.thrown); - assertTrue(serverThread.thrown.getMessage().contains("Invalid response")); - } - } + }, "Was able to open transport with bad password"); + LOGGER.error("Exception for bad password", tte); + assertNotNull(tte.getMessage()); + assertTrue(tte.getMessage().contains("Invalid response")); + serverThread.interrupt(); + serverThread.join(); + assertNotNull(serverThread.thrown); + assertTrue(serverThread.thrown.getMessage().contains("Invalid response")); } + @Test public void testWithServer() throws Exception { new TestTSaslTransportsWithServer().testIt(); } @@ -296,7 +293,7 @@ public class TestTSaslTransports extends TestCase { server.serve(); } catch (Exception e) { e.printStackTrace(); - fail(); + fail(e); } } }; @@ -309,7 +306,9 @@ public class TestTSaslTransports extends TestCase { server.stop(); try { serverThread.join(); - } catch (InterruptedException e) {} + } catch (InterruptedException e) { + LOGGER.debug("interrupted during sleep", e); + } } } @@ -327,8 +326,11 @@ public class TestTSaslTransports extends TestCase { this.username = username; } + @Override public String getMechanismName() { return "ANONYMOUS"; } + @Override public boolean hasInitialResponse() { return true; } + @Override public byte[] evaluateChallenge(byte[] challenge) throws SaslException { if (hasProvidedInitialResponse) { throw new SaslException("Already complete!"); @@ -337,33 +339,46 @@ public class TestTSaslTransports extends TestCase { hasProvidedInitialResponse = true; return username.getBytes(StandardCharsets.UTF_8); } + @Override public boolean isComplete() { return hasProvidedInitialResponse; } + @Override public byte[] unwrap(byte[] incoming, int offset, int len) { throw new UnsupportedOperationException(); } + @Override public byte[] wrap(byte[] outgoing, int offset, int len) { throw new UnsupportedOperationException(); } + @Override public Object getNegotiatedProperty(String propName) { return null; } + @Override public void dispose() {} } private static class AnonymousServer implements SaslServer { private String user; + @Override public String getMechanismName() { return "ANONYMOUS"; } + @Override public byte[] evaluateResponse(byte[] response) throws SaslException { this.user = new String(response, StandardCharsets.UTF_8); return null; } + @Override public boolean isComplete() { return user != null; } + @Override public String getAuthorizationID() { return user; } + @Override public byte[] unwrap(byte[] incoming, int offset, int len) { throw new UnsupportedOperationException(); } + @Override public byte[] wrap(byte[] outgoing, int offset, int len) { throw new UnsupportedOperationException(); } + @Override public Object getNegotiatedProperty(String propName) { return null; } + @Override public void dispose() {} } @@ -371,6 +386,7 @@ public class TestTSaslTransports extends TestCase { public static class SaslAnonymousFactory implements SaslClientFactory, SaslServerFactory { + @Override public SaslClient createSaslClient( String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String,?> props, CallbackHandler cbh) @@ -383,6 +399,7 @@ public class TestTSaslTransports extends TestCase { return null; } + @Override public SaslServer createSaslServer( String mechanism, String protocol, String serverName, Map<String,?> props, CallbackHandler cbh) { @@ -391,6 +408,7 @@ public class TestTSaslTransports extends TestCase { } return null; } + @Override public String[] getMechanismNames(Map<String, ?> props) { return new String[] { "ANONYMOUS" }; } @@ -410,7 +428,7 @@ public class TestTSaslTransports extends TestCase { private static class MockTTransport extends TTransport { byte[] badHeader = null; - private TMemoryInputTransport readBuffer; + private final TMemoryInputTransport readBuffer; public MockTTransport(int mode) throws TTransportException { readBuffer = new TMemoryInputTransport(); @@ -462,6 +480,7 @@ public class TestTSaslTransports extends TestCase { } } + @Test public void testBadHeader() { TSaslTransport saslTransport; try { diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java index 7b880f499..926b78220 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTSimpleFileTransport.java @@ -18,12 +18,17 @@ */ package org.apache.thrift.transport; +import org.junit.jupiter.api.Test; + import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; -import junit.framework.TestCase; -public class TestTSimpleFileTransport extends TestCase { +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class TestTSimpleFileTransport { + @Test public void testFresh() throws Exception { //Test write side Path tempFilePathName = Files.createTempFile("TSimpleFileTransportTest", null); @@ -43,31 +48,31 @@ public class TestTSimpleFileTransport extends TestCase { assert(trans.isOpen()); //Simple file trans provides no buffer access - assert(0 == trans.getBufferPosition()); - assert(null == trans.getBuffer()); - assert(-1 == trans.getBytesRemainingInBuffer()); + assertEquals(0, trans.getBufferPosition()); + assertNull(trans.getBuffer()); + assertEquals(-1, trans.getBytesRemainingInBuffer()); //Test file pointer operations - assert(0 == trans.getFilePointer()); - assert(12 == trans.length()); + assertEquals(0, trans.getFilePointer()); + assertEquals(12, trans.length()); final int BUFSIZ = 4; byte[] buf1 = new byte[BUFSIZ]; trans.readAll(buf1, 0, BUFSIZ); - assert(BUFSIZ == trans.getFilePointer()); - assert(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); + assertEquals(BUFSIZ, trans.getFilePointer()); + assertArrayEquals(new byte[]{1, 2, 3, 4}, buf1); int bytesRead = trans.read(buf1, 0, BUFSIZ); assert(bytesRead > 0); for (int i = 0; i < bytesRead; ++i) { - assert(buf1[i] == i+5); + assertEquals(buf1[i], i + 5); } trans.seek(0); - assert(0 == trans.getFilePointer()); + assertEquals(0, trans.getFilePointer()); trans.readAll(buf1, 0, BUFSIZ); - assert(Arrays.equals(new byte[]{1, 2, 3, 4}, buf1)); - assert(BUFSIZ == trans.getFilePointer()); + assertArrayEquals(new byte[]{1, 2, 3, 4}, buf1); + assertEquals(BUFSIZ, trans.getFilePointer()); trans.close(); Files.delete(tempFilePathName); } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java b/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java index 1b3970012..75e917f6a 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/TestTZlibTransport.java @@ -18,20 +18,22 @@ */ package org.apache.thrift.transport; +import org.junit.jupiter.api.Test; + import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.util.Arrays; import java.util.zip.DataFormatException; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class TestTZlibTransport extends TestCase { +public class TestTZlibTransport { protected TTransport getTransport(TTransport underlying) throws TTransportException { return new TZlibTransport(underlying); @@ -45,6 +47,7 @@ public class TestTZlibTransport extends TestCase { return result; } + @Test public void testClose() throws TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream @@ -55,6 +58,7 @@ public class TestTZlibTransport extends TestCase { trans.close(); } + @Test public void testCloseOpen() throws TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport trans = getTransport(new TIOStreamTransport(baos)); @@ -70,6 +74,7 @@ public class TestTZlibTransport extends TestCase { transRead.close(); } + @Test public void testRead() throws IOException, TTransportException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(baos); @@ -87,11 +92,11 @@ public class TestTZlibTransport extends TestCase { byte[] readBuf = new byte[10]; trans.read(readBuf, 0, 10); - assertTrue(Arrays.equals(readBuf, byteSequence(0,9))); + assertArrayEquals(readBuf, byteSequence(0, 9)); assertEquals(1, countTrans.readCount); trans.read(readBuf, 0, 10); - assertTrue(Arrays.equals(readBuf, byteSequence(10,19))); + assertArrayEquals(readBuf, byteSequence(10, 19)); assertEquals(1, countTrans.readCount); assertEquals(30, trans.read(new byte[30], 0, 30)); @@ -99,10 +104,11 @@ public class TestTZlibTransport extends TestCase { readBuf = new byte[220]; assertEquals(220, trans.read(readBuf, 0, 220)); - assertTrue(Arrays.equals(readBuf, byteSequence(0, 219))); + assertArrayEquals(readBuf, byteSequence(0, 219)); assertEquals(1, countTrans.readCount); } + @Test public void testWrite() throws TTransportException, IOException, DataFormatException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WriteCountingTransport countingTrans = new WriteCountingTransport(new TIOStreamTransport(new BufferedOutputStream(baos))); @@ -125,16 +131,16 @@ public class TestTZlibTransport extends TestCase { byte[] buf = new byte[256]; int n = din.read(buf, 0, 256); assertEquals(n, 256); - assertTrue(Arrays.equals(byteSequence(0, 255), buf)); + assertArrayEquals(byteSequence(0, 255), buf); buf = new byte[246]; n = din.read(buf, 0, 246); assertEquals(n, 246); for (int i = 0; i<buf.length; i++) { - assertEquals("for "+i, byteSequence(0,245)[i], buf[i]); + assertEquals(byteSequence(0,245)[i], buf[i], "for "+i); } - assertTrue(Arrays.equals(byteSequence(0,245), buf)); + assertArrayEquals(byteSequence(0, 245), buf); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java index 9ae0e1ead..4b90cceca 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameReader.java @@ -21,11 +21,14 @@ package org.apache.thrift.transport.sasl; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TTransportException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TestDataFrameReader { @Test @@ -43,19 +46,19 @@ public class TestDataFrameReader { DataFrameReader dataFrameReader = new DataFrameReader(); // No bytes received. dataFrameReader.read(transport); - Assert.assertFalse("No bytes received", dataFrameReader.isComplete()); - Assert.assertFalse("No bytes received", dataFrameReader.getHeader().isComplete()); + assertFalse(dataFrameReader.isComplete(), "No bytes received"); + assertFalse(dataFrameReader.getHeader().isComplete(), "No bytes received"); // Payload size (header) and part of the payload are received. transport.reset(buffer.array(), 0, 6); dataFrameReader.read(transport); - Assert.assertFalse("Only header is complete", dataFrameReader.isComplete()); - Assert.assertTrue("Header should be complete", dataFrameReader.getHeader().isComplete()); - Assert.assertEquals("Payload size should be " + payloadSize, payloadSize, dataFrameReader.getHeader().payloadSize()); + assertFalse(dataFrameReader.isComplete(), "Only header is complete"); + assertTrue(dataFrameReader.getHeader().isComplete(), "Header should be complete"); + assertEquals(payloadSize, dataFrameReader.getHeader().payloadSize(), "Payload size should be " + payloadSize); // Read the rest of payload. transport.reset(buffer.array(), 6, 21); dataFrameReader.read(transport); - Assert.assertTrue("Reader should be complete", dataFrameReader.isComplete()); + assertTrue(dataFrameReader.isComplete(), "Reader should be complete"); buffer.position(DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES); - Assert.assertEquals("Payload should be the same as from the transport", buffer, ByteBuffer.wrap(dataFrameReader.getPayload())); + assertEquals(buffer, ByteBuffer.wrap(dataFrameReader.getPayload()), "Payload should be the same as from the transport"); } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java index 60fe5c96b..b6f4529e7 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestDataFrameWriter.java @@ -19,83 +19,87 @@ package org.apache.thrift.transport.sasl; -import java.io.IOException; -import java.nio.ByteBuffer; - import org.apache.thrift.EncodingUtils; import org.apache.thrift.transport.TNonblockingTransport; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import java.nio.ByteBuffer; + import static org.apache.thrift.transport.sasl.DataFrameHeaderReader.PAYLOAD_LENGTH_BYTES; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestDataFrameWriter { - private static final byte[] BYTES = new byte[]{0x32, 0x2A, (byte) 0xE1, 0x18, (byte) 0x90, 0x75}; + private static final byte[] BYTES = new byte[]{0x32, 0x2A, (byte) 0xE1, 0x18, (byte) 0x90, 0x75}; - @Test - public void testProvideEntireByteArrayAsPayload() { - DataFrameWriter frameWriter = new DataFrameWriter(); - frameWriter.withOnlyPayload(BYTES); - byte[] expectedBytes = new byte[BYTES.length + PAYLOAD_LENGTH_BYTES]; - EncodingUtils.encodeBigEndian(BYTES.length, expectedBytes); - System.arraycopy(BYTES, 0, expectedBytes, PAYLOAD_LENGTH_BYTES, BYTES.length); - Assert.assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); - } + @Test + public void testProvideEntireByteArrayAsPayload() { + DataFrameWriter frameWriter = new DataFrameWriter(); + frameWriter.withOnlyPayload(BYTES); + byte[] expectedBytes = new byte[BYTES.length + PAYLOAD_LENGTH_BYTES]; + EncodingUtils.encodeBigEndian(BYTES.length, expectedBytes); + System.arraycopy(BYTES, 0, expectedBytes, PAYLOAD_LENGTH_BYTES, BYTES.length); + assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); + } - @Test - public void testProvideByteArrayPortionAsPayload() { - DataFrameWriter frameWriter = new DataFrameWriter(); - int portionOffset = 2; - int portionLength = 3; - frameWriter.withOnlyPayload(BYTES, portionOffset, portionLength); - byte[] expectedBytes = new byte[portionLength + PAYLOAD_LENGTH_BYTES]; - EncodingUtils.encodeBigEndian(portionLength, expectedBytes); - System.arraycopy(BYTES, portionOffset, expectedBytes, PAYLOAD_LENGTH_BYTES, portionLength); - Assert.assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); - } + @Test + public void testProvideByteArrayPortionAsPayload() { + DataFrameWriter frameWriter = new DataFrameWriter(); + int portionOffset = 2; + int portionLength = 3; + frameWriter.withOnlyPayload(BYTES, portionOffset, portionLength); + byte[] expectedBytes = new byte[portionLength + PAYLOAD_LENGTH_BYTES]; + EncodingUtils.encodeBigEndian(portionLength, expectedBytes); + System.arraycopy(BYTES, portionOffset, expectedBytes, PAYLOAD_LENGTH_BYTES, portionLength); + assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); + } - @Test(expected = IllegalArgumentException.class) - public void testProvideHeaderAndPayload() { - DataFrameWriter frameWriter = new DataFrameWriter(); - frameWriter.withHeaderAndPayload(new byte[1], new byte[1]); - } + @Test + public void testProvideHeaderAndPayload() { + DataFrameWriter frameWriter = new DataFrameWriter(); + assertThrows(IllegalArgumentException.class, () -> frameWriter.withHeaderAndPayload(new byte[1], new byte[1])); + } - @Test(expected = IllegalStateException.class) - public void testProvidePayloadToIncompleteFrame() { - DataFrameWriter frameWriter = new DataFrameWriter(); - frameWriter.withOnlyPayload(BYTES); - frameWriter.withOnlyPayload(new byte[1]); - } + @Test + public void testProvidePayloadToIncompleteFrame() { + DataFrameWriter frameWriter = new DataFrameWriter(); + assertThrows(IllegalStateException.class, () -> { + frameWriter.withOnlyPayload(BYTES); + frameWriter.withOnlyPayload(new byte[1]); + }); + } - @Test - public void testWrite() throws Exception { - DataFrameWriter frameWriter = new DataFrameWriter(); - frameWriter.withOnlyPayload(BYTES); - // Slow socket which writes one byte per call. - TNonblockingTransport transport = Mockito.mock(TNonblockingTransport.class); - SlowWriting slowWriting = new SlowWriting(); - Mockito.when(transport.write(frameWriter.frameBytes)).thenAnswer(slowWriting); - frameWriter.write(transport); - while (slowWriting.written < frameWriter.frameBytes.limit()) { - Assert.assertFalse("Frame writer should not be complete", frameWriter.isComplete()); - frameWriter.write(transport); + @Test + public void testWrite() throws Exception { + DataFrameWriter frameWriter = new DataFrameWriter(); + frameWriter.withOnlyPayload(BYTES); + // Slow socket which writes one byte per call. + TNonblockingTransport transport = Mockito.mock(TNonblockingTransport.class); + SlowWriting slowWriting = new SlowWriting(); + Mockito.when(transport.write(frameWriter.frameBytes)).thenAnswer(slowWriting); + frameWriter.write(transport); + while (slowWriting.written < frameWriter.frameBytes.limit()) { + assertFalse(frameWriter.isComplete(), "Frame writer should not be complete"); + frameWriter.write(transport); + } + assertTrue(frameWriter.isComplete(), "Frame writer should be complete"); } - Assert.assertTrue("Frame writer should be complete", frameWriter.isComplete()); - } - private static class SlowWriting implements Answer<Integer> { - int written = 0; + private static class SlowWriting implements Answer<Integer> { + int written = 0; - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - ByteBuffer bytes = (ByteBuffer) invocation.getArguments()[0]; - bytes.get(); - written ++; - return 1; + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + ByteBuffer bytes = (ByteBuffer) invocation.getArguments()[0]; + bytes.get(); + written++; + return 1; + } } - } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java index f2abbe658..7c4556a6c 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameReader.java @@ -21,44 +21,50 @@ package org.apache.thrift.transport.sasl; import org.apache.thrift.transport.TMemoryInputTransport; import org.apache.thrift.transport.TTransportException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class TestSaslNegotiationFrameReader { - @Test - public void testRead() throws TTransportException { - TMemoryInputTransport transport = new TMemoryInputTransport(); - SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); - // No bytes received - negotiationReader.read(transport); - Assert.assertFalse("No bytes received", negotiationReader.isComplete()); - Assert.assertFalse("No bytes received", negotiationReader.getHeader().isComplete()); - // Read header - ByteBuffer buffer = ByteBuffer.allocate(5); - buffer.put(0, NegotiationStatus.OK.getValue()); - buffer.putInt(1, 10); - transport.reset(buffer.array()); - negotiationReader.read(transport); - Assert.assertFalse("Only header is complete", negotiationReader.isComplete()); - Assert.assertTrue("Header should be complete", negotiationReader.getHeader().isComplete()); - Assert.assertEquals("Payload size should be 10", 10, negotiationReader.getHeader().payloadSize()); - // Read payload - transport.reset(new byte[20]); - negotiationReader.read(transport); - Assert.assertTrue("Reader should be complete", negotiationReader.isComplete()); - Assert.assertEquals("Payload length should be 10", 10, negotiationReader.getPayload().length); - } + @Test + public void testRead() throws TTransportException { + TMemoryInputTransport transport = new TMemoryInputTransport(); + SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); + // No bytes received + negotiationReader.read(transport); + assertFalse(negotiationReader.isComplete(), "No bytes received"); + assertFalse(negotiationReader.getHeader().isComplete(), "No bytes received"); + // Read header + ByteBuffer buffer = ByteBuffer.allocate(5); + buffer.put(0, NegotiationStatus.OK.getValue()); + buffer.putInt(1, 10); + transport.reset(buffer.array()); + negotiationReader.read(transport); + assertFalse(negotiationReader.isComplete(), "Only header is complete"); + assertTrue(negotiationReader.getHeader().isComplete(), "Header should be complete"); + assertEquals(10, negotiationReader.getHeader().payloadSize(), "Payload size should be 10"); + // Read payload + transport.reset(new byte[20]); + negotiationReader.read(transport); + assertTrue(negotiationReader.isComplete(), "Reader should be complete"); + assertEquals(10, negotiationReader.getPayload().length, "Payload length should be 10"); + } - @Test (expected = TSaslNegotiationException.class) - public void testReadInvalidNegotiationStatus() throws TTransportException { - byte[] bytes = new byte[5]; - // Invalid status byte. - bytes[0] = -1; - TMemoryInputTransport transport = new TMemoryInputTransport(bytes); - SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); - negotiationReader.read(transport); - } + @Test + public void testReadInvalidNegotiationStatus() throws TTransportException { + byte[] bytes = new byte[5]; + // Invalid status byte. + bytes[0] = -1; + TMemoryInputTransport transport = new TMemoryInputTransport(bytes); + SaslNegotiationFrameReader negotiationReader = new SaslNegotiationFrameReader(); + assertThrows(TSaslNegotiationException.class, () -> { + negotiationReader.read(transport); + }); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java index ce7ff295c..49110e473 100644 --- a/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java +++ b/lib/java/src/test/java/org/apache/thrift/transport/sasl/TestSaslNegotiationFrameWriter.java @@ -19,38 +19,39 @@ package org.apache.thrift.transport.sasl; -import java.nio.ByteBuffer; - import org.apache.thrift.EncodingUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; import static org.apache.thrift.transport.sasl.SaslNegotiationFrameWriter.HEADER_BYTES; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class TestSaslNegotiationFrameWriter { - private static final byte[] PAYLOAD = {0x11, 0x08, 0x3F, 0x58, 0x73, 0x22, 0x00, (byte) 0xFF}; - - @Test - public void testWithHeaderAndPayload() { - SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); - frameWriter.withHeaderAndPayload(new byte[] {NegotiationStatus.OK.getValue()}, PAYLOAD); - byte[] expectedBytes = new byte[HEADER_BYTES + PAYLOAD.length]; - expectedBytes[0] = NegotiationStatus.OK.getValue(); - EncodingUtils.encodeBigEndian(PAYLOAD.length, expectedBytes, 1); - System.arraycopy(PAYLOAD, 0, expectedBytes, HEADER_BYTES, PAYLOAD.length); - Assert.assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); - } - - @Test(expected = IllegalArgumentException.class) - public void testWithInvalidHeaderLength() { - SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); - frameWriter.withHeaderAndPayload(new byte[5], 0, 2, PAYLOAD, 0, 1); - } - - @Test(expected = UnsupportedOperationException.class) - public void testWithOnlyPayload() { - SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); - frameWriter.withOnlyPayload(new byte[0]); - } + private static final byte[] PAYLOAD = {0x11, 0x08, 0x3F, 0x58, 0x73, 0x22, 0x00, (byte) 0xFF}; + + @Test + public void testWithHeaderAndPayload() { + SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); + frameWriter.withHeaderAndPayload(new byte[]{NegotiationStatus.OK.getValue()}, PAYLOAD); + byte[] expectedBytes = new byte[HEADER_BYTES + PAYLOAD.length]; + expectedBytes[0] = NegotiationStatus.OK.getValue(); + EncodingUtils.encodeBigEndian(PAYLOAD.length, expectedBytes, 1); + System.arraycopy(PAYLOAD, 0, expectedBytes, HEADER_BYTES, PAYLOAD.length); + assertEquals(ByteBuffer.wrap(expectedBytes), frameWriter.frameBytes); + } + + @Test + public void testWithInvalidHeaderLength() { + SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); + assertThrows(IllegalArgumentException.class, () -> frameWriter.withHeaderAndPayload(new byte[5], 0, 2, PAYLOAD, 0, 1)); + } + + @Test + public void testWithOnlyPayload() { + SaslNegotiationFrameWriter frameWriter = new SaslNegotiationFrameWriter(); + assertThrows(UnsupportedOperationException.class, () -> frameWriter.withOnlyPayload(new byte[0])); + } } diff --git a/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java b/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java index 3224e77b3..272815765 100644 --- a/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java +++ b/lib/java/src/test/java/org/apache/thrift/utils/TestStringUtils.java @@ -19,41 +19,44 @@ package org.apache.thrift.utils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; public class TestStringUtils { - @Test - public void testToHexString() { - byte[] bytes = {0x00, 0x1A, (byte) 0xEF, (byte) 0xAB, (byte) 0x92}; - Assert.assertEquals("001AEFAB92", StringUtils.bytesToHexString(bytes)); - Assert.assertEquals("EFAB92", StringUtils.bytesToHexString(bytes, 2, 3)); - Assert.assertNull(StringUtils.bytesToHexString(null)); - } + @Test + public void testToHexString() { + byte[] bytes = {0x00, 0x1A, (byte) 0xEF, (byte) 0xAB, (byte) 0x92}; + assertEquals("001AEFAB92", StringUtils.bytesToHexString(bytes)); + assertEquals("EFAB92", StringUtils.bytesToHexString(bytes, 2, 3)); + assertNull(StringUtils.bytesToHexString(null)); + } - private byte[] bytes; + private byte[] bytes; - @Before - public void setUp() throws Exception { - bytes = new byte[]{1, 2, 3, 4, 5}; - } + @BeforeEach + public void setUp() throws Exception { + bytes = new byte[]{1, 2, 3, 4, 5}; + } - @Test(expected = IllegalArgumentException.class) - public void testNegativeLength() { - StringUtils.bytesToHexString(bytes, 0, -1); - } + @Test + public void testNegativeLength() { + assertThrows(IllegalArgumentException.class, () -> StringUtils.bytesToHexString(bytes, 0, -1)); + } - @Test(expected = IndexOutOfBoundsException.class) - public void testNegativeStartOffset() { - StringUtils.bytesToHexString(bytes, -1, 1); - } + @Test + public void testNegativeStartOffset() { + assertThrows(IndexOutOfBoundsException.class, () -> StringUtils.bytesToHexString(bytes, -1, 1)); + } - @Test(expected = IndexOutOfBoundsException.class) - public void testInvalidRange() { - StringUtils.bytesToHexString(bytes, 5, 1); - } + @Test + public void testInvalidRange() { + assertThrows(IndexOutOfBoundsException.class, () -> StringUtils.bytesToHexString(bytes, 5, 1)); + } } |