Migrate buffer tests to JUnit 5 (#11305)

Motivation:

JUnit 5 is more expressive, extensible, and composable in many ways, and it's better able to run tests in parallel.

Modifications:

Use JUnit5 in tests

Result:

Related to https://github.com/netty/netty/issues/10757
This commit is contained in:
Riley Park 2021-05-27 00:22:02 -07:00 committed by GitHub
parent 65e1f0e27c
commit 56a186e41f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 1228 additions and 1104 deletions

View File

@ -16,11 +16,11 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.fail;
public abstract class AbstractByteBufAllocatorTest<T extends AbstractByteBufAllocator> extends ByteBufAllocatorTest { public abstract class AbstractByteBufAllocatorTest<T extends AbstractByteBufAllocator> extends ByteBufAllocatorTest {
@ -108,7 +108,7 @@ public abstract class AbstractByteBufAllocatorTest<T extends AbstractByteBufAllo
// Double the size of the buffer // Double the size of the buffer
buffer.capacity(capacity << 1); buffer.capacity(capacity << 1);
capacity = buffer.capacity(); capacity = buffer.capacity();
assertEquals(buffer.toString(), expectedUsedMemory(allocator, capacity), metric.usedDirectMemory()); assertEquals(expectedUsedMemory(allocator, capacity), metric.usedDirectMemory(), buffer.toString());
buffer.release(); buffer.release();
assertEquals(expectedUsedMemoryAfterRelease(allocator, capacity), metric.usedDirectMemory()); assertEquals(expectedUsedMemoryAfterRelease(allocator, capacity), metric.usedDirectMemory());

File diff suppressed because it is too large Load Diff

View File

@ -16,8 +16,8 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@ -39,14 +39,15 @@ import static io.netty.util.internal.EmptyArrays.EMPTY_BYTES;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* An abstract test class for composite channel buffers * An abstract test class for composite channel buffers
@ -63,7 +64,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
@Override @Override
protected ByteBuf newBuffer(int length, int maxCapacity) { protected ByteBuf newBuffer(int length, int maxCapacity) {
Assume.assumeTrue(maxCapacity == Integer.MAX_VALUE); Assumptions.assumeTrue(maxCapacity == Integer.MAX_VALUE);
List<ByteBuf> buffers = new ArrayList<>(); List<ByteBuf> buffers = new ArrayList<>();
for (int i = 0; i < length + 45; i += 45) { for (int i = 0; i < length + 45; i += 45) {
@ -1243,7 +1244,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
cbuf.release(); cbuf.release();
} }
@Test(expected = ConcurrentModificationException.class) @Test
public void testIteratorConcurrentModificationAdd() { public void testIteratorConcurrentModificationAdd() {
CompositeByteBuf cbuf = newCompositeBuffer(); CompositeByteBuf cbuf = newCompositeBuffer();
cbuf.addComponent(EMPTY_BUFFER); cbuf.addComponent(EMPTY_BUFFER);
@ -1253,13 +1254,13 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
assertTrue(it.hasNext()); assertTrue(it.hasNext());
try { try {
it.next(); assertThrows(ConcurrentModificationException.class, it::next);
} finally { } finally {
cbuf.release(); cbuf.release();
} }
} }
@Test(expected = ConcurrentModificationException.class) @Test
public void testIteratorConcurrentModificationRemove() { public void testIteratorConcurrentModificationRemove() {
CompositeByteBuf cbuf = newCompositeBuffer(); CompositeByteBuf cbuf = newCompositeBuffer();
cbuf.addComponent(EMPTY_BUFFER); cbuf.addComponent(EMPTY_BUFFER);
@ -1269,7 +1270,7 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
assertTrue(it.hasNext()); assertTrue(it.hasNext());
try { try {
it.next(); assertThrows(ConcurrentModificationException.class, it::next);
} finally { } finally {
cbuf.release(); cbuf.release();
} }
@ -1554,52 +1555,58 @@ public abstract class AbstractCompositeByteBufTest extends AbstractByteBufTest {
assertTrue(cbuf.release()); assertTrue(cbuf.release());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testOverflowWhileAddingComponent() { public void testOverflowWhileAddingComponent() {
int capacity = 1024 * 1024; // 1MB int capacity = 1024 * 1024; // 1MB
ByteBuf buffer = Unpooled.buffer(capacity).writeZero(capacity); ByteBuf buffer = Unpooled.buffer(capacity).writeZero(capacity);
CompositeByteBuf compositeByteBuf = compositeBuffer(Integer.MAX_VALUE); CompositeByteBuf compositeByteBuf = compositeBuffer(Integer.MAX_VALUE);
try { try {
assertThrows(IllegalArgumentException.class, () -> {
for (int i = 0; i >= 0; i += buffer.readableBytes()) { for (int i = 0; i >= 0; i += buffer.readableBytes()) {
ByteBuf duplicate = buffer.duplicate(); ByteBuf duplicate = buffer.duplicate();
compositeByteBuf.addComponent(duplicate); compositeByteBuf.addComponent(duplicate);
duplicate.retain(); duplicate.retain();
} }
});
} finally { } finally {
compositeByteBuf.release(); compositeByteBuf.release();
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testOverflowWhileAddingComponentsViaVarargs() { public void testOverflowWhileAddingComponentsViaVarargs() {
int capacity = 1024 * 1024; // 1MB int capacity = 1024 * 1024; // 1MB
ByteBuf buffer = Unpooled.buffer(capacity).writeZero(capacity); ByteBuf buffer = Unpooled.buffer(capacity).writeZero(capacity);
CompositeByteBuf compositeByteBuf = compositeBuffer(Integer.MAX_VALUE); CompositeByteBuf compositeByteBuf = compositeBuffer(Integer.MAX_VALUE);
try { try {
assertThrows(IllegalArgumentException.class, () -> {
for (int i = 0; i >= 0; i += buffer.readableBytes()) { for (int i = 0; i >= 0; i += buffer.readableBytes()) {
ByteBuf duplicate = buffer.duplicate(); ByteBuf duplicate = buffer.duplicate();
compositeByteBuf.addComponents(duplicate); compositeByteBuf.addComponents(duplicate);
duplicate.retain(); duplicate.retain();
} }
});
} finally { } finally {
compositeByteBuf.release(); compositeByteBuf.release();
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testOverflowWhileAddingComponentsViaIterable() { public void testOverflowWhileAddingComponentsViaIterable() {
int capacity = 1024 * 1024; // 1MB int capacity = 1024 * 1024; // 1MB
ByteBuf buffer = Unpooled.buffer(capacity).writeZero(capacity); ByteBuf buffer = Unpooled.buffer(capacity).writeZero(capacity);
CompositeByteBuf compositeByteBuf = compositeBuffer(Integer.MAX_VALUE); CompositeByteBuf compositeByteBuf = compositeBuffer(Integer.MAX_VALUE);
try { try {
assertThrows(IllegalArgumentException.class, () -> {
for (int i = 0; i >= 0; i += buffer.readableBytes()) { for (int i = 0; i >= 0; i += buffer.readableBytes()) {
ByteBuf duplicate = buffer.duplicate(); ByteBuf duplicate = buffer.duplicate();
compositeByteBuf.addComponents(Collections.singletonList(duplicate)); compositeByteBuf.addComponents(Collections.singletonList(duplicate));
duplicate.retain(); duplicate.retain();
} }
});
} finally { } finally {
compositeByteBuf.release(); compositeByteBuf.release();
} }

View File

@ -15,15 +15,15 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
public abstract class AbstractPooledByteBufTest extends AbstractByteBufTest { public abstract class AbstractPooledByteBufTest extends AbstractByteBufTest {
@ -47,12 +47,11 @@ public abstract class AbstractPooledByteBufTest extends AbstractByteBufTest {
buf.release(); buf.release();
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void ensureWritableWithNotEnoughSpaceShouldThrow() { public void ensureWritableWithNotEnoughSpaceShouldThrow() {
ByteBuf buf = newBuffer(1, 10); ByteBuf buf = newBuffer(1, 10);
try { try {
buf.ensureWritable(11); assertThrows(IndexOutOfBoundsException.class, () -> buf.ensureWritable(11));
fail();
} finally { } finally {
buf.release(); buf.release();
} }

View File

@ -16,7 +16,7 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.IllegalReferenceCountException; import io.netty.util.IllegalReferenceCountException;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -27,33 +27,34 @@ import java.nio.channels.FileChannel;
import java.nio.channels.GatheringByteChannel; import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel; import java.nio.channels.ScatteringByteChannel;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class AbstractReferenceCountedByteBufTest { public class AbstractReferenceCountedByteBufTest {
@Test(expected = IllegalReferenceCountException.class) @Test
public void testRetainOverflow() { public void testRetainOverflow() {
AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted(); AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted();
referenceCounted.setRefCnt(Integer.MAX_VALUE); referenceCounted.setRefCnt(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, referenceCounted.refCnt()); assertEquals(Integer.MAX_VALUE, referenceCounted.refCnt());
referenceCounted.retain(); assertThrows(IllegalReferenceCountException.class, referenceCounted::retain);
} }
@Test(expected = IllegalReferenceCountException.class) @Test
public void testRetainOverflow2() { public void testRetainOverflow2() {
AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted(); AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted();
assertEquals(1, referenceCounted.refCnt()); assertEquals(1, referenceCounted.refCnt());
referenceCounted.retain(Integer.MAX_VALUE); assertThrows(IllegalReferenceCountException.class, () -> referenceCounted.retain(Integer.MAX_VALUE));
} }
@Test(expected = IllegalReferenceCountException.class) @Test
public void testReleaseOverflow() { public void testReleaseOverflow() {
AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted(); AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted();
referenceCounted.setRefCnt(0); referenceCounted.setRefCnt(0);
assertEquals(0, referenceCounted.refCnt()); assertEquals(0, referenceCounted.refCnt());
referenceCounted.release(Integer.MAX_VALUE); assertThrows(IllegalReferenceCountException.class, () -> referenceCounted.release(Integer.MAX_VALUE));
} }
@Test @Test
@ -68,20 +69,20 @@ public class AbstractReferenceCountedByteBufTest {
} }
} }
@Test(expected = IllegalReferenceCountException.class) @Test
public void testRetainResurrect() { public void testRetainResurrect() {
AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted(); AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted();
assertTrue(referenceCounted.release()); assertTrue(referenceCounted.release());
assertEquals(0, referenceCounted.refCnt()); assertEquals(0, referenceCounted.refCnt());
referenceCounted.retain(); assertThrows(IllegalReferenceCountException.class, referenceCounted::retain);
} }
@Test(expected = IllegalReferenceCountException.class) @Test
public void testRetainResurrect2() { public void testRetainResurrect2() {
AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted(); AbstractReferenceCountedByteBuf referenceCounted = newReferenceCounted();
assertTrue(referenceCounted.release()); assertTrue(referenceCounted.release());
assertEquals(0, referenceCounted.refCnt()); assertEquals(0, referenceCounted.refCnt());
referenceCounted.retain(2); assertThrows(IllegalReferenceCountException.class, () -> referenceCounted.retain(2));
} }
private static AbstractReferenceCountedByteBuf newReferenceCounted() { private static AbstractReferenceCountedByteBuf newReferenceCounted() {

View File

@ -16,9 +16,9 @@
package io.netty.buffer; package io.netty.buffer;
import static io.netty.buffer.Unpooled.*; import static io.netty.buffer.Unpooled.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test; import org.junit.jupiter.api.Test;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.ResourceLeakTracker; import io.netty.util.ResourceLeakTracker;

View File

@ -15,8 +15,7 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.jupiter.api.Test;
import org.junit.Test;
/** /**
* Tests big-endian composite channel buffers * Tests big-endian composite channel buffers
@ -27,9 +26,9 @@ public class BigEndianCompositeByteBufTest extends AbstractCompositeByteBufTest
} }
@Override @Override
@Test(expected = UnsupportedOperationException.class) @Test
public void testInternalNioBufferAfterRelease() { public void testInternalNioBufferAfterRelease() {
super.testInternalNioBufferAfterRelease(); testInternalNioBufferAfterRelease0(UnsupportedOperationException.class);
} }
} }

View File

@ -15,11 +15,13 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Tests big-endian direct channel buffers * Tests big-endian direct channel buffers

View File

@ -15,9 +15,10 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
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.assertThrows;
/** /**
* Tests big-endian heap channel buffers * Tests big-endian heap channel buffers
@ -31,13 +32,14 @@ public class BigEndianHeapByteBufTest extends AbstractByteBufTest {
return buffer; return buffer;
} }
@Test(expected = NullPointerException.class) @Test
public void shouldNotAllowNullInConstructor1() { public void shouldNotAllowNullInConstructor1() {
new UnpooledHeapByteBuf(null, new byte[1], 0); assertThrows(NullPointerException.class, () -> new UnpooledHeapByteBuf(null, new byte[1], 0));
} }
@Test(expected = NullPointerException.class) @Test
public void shouldNotAllowNullInConstructor2() { public void shouldNotAllowNullInConstructor2() {
new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT, null, 0); assertThrows(NullPointerException.class,
() -> new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT, null, 0));
} }
} }

View File

@ -17,15 +17,15 @@ package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
public class BigEndianUnsafeDirectByteBufTest extends BigEndianDirectByteBufTest { public class BigEndianUnsafeDirectByteBufTest extends BigEndianDirectByteBufTest {
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
Assume.assumeTrue("sun.misc.Unsafe not found, skip tests", PlatformDependent.hasUnsafe()); Assumptions.assumeTrue(PlatformDependent.hasUnsafe(), "sun.misc.Unsafe not found, skip tests");
super.init(); super.init();
} }

View File

@ -15,18 +15,17 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
public class BigEndianUnsafeNoCleanerDirectByteBufTest extends BigEndianDirectByteBufTest { public class BigEndianUnsafeNoCleanerDirectByteBufTest extends BigEndianDirectByteBufTest {
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
Assume.assumeTrue("java.nio.DirectByteBuffer.<init>(long, int) not found, skip tests", Assumptions.assumeTrue(PlatformDependent.useDirectBufferNoCleaner(),
PlatformDependent.useDirectBufferNoCleaner()); "java.nio.DirectByteBuffer.<init>(long, int) not found, skip tests");
super.init(); super.init();
} }

View File

@ -15,9 +15,9 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public abstract class ByteBufAllocatorTest { public abstract class ByteBufAllocatorTest {

View File

@ -16,7 +16,7 @@
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.Random; import java.util.Random;

View File

@ -15,13 +15,20 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.EOFException; import java.io.EOFException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import static io.netty.util.internal.EmptyArrays.*; import static io.netty.util.internal.EmptyArrays.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* Tests channel buffer streams * Tests channel buffer streams
@ -279,7 +286,7 @@ public class ByteBufStreamTest {
in2.close(); in2.close();
} }
@Test(expected = EOFException.class) @Test
public void testReadByteLengthRespected() throws Exception { public void testReadByteLengthRespected() throws Exception {
// case1 // case1
ByteBuf buf = Unpooled.buffer(16); ByteBuf buf = Unpooled.buffer(16);
@ -287,7 +294,7 @@ public class ByteBufStreamTest {
ByteBufInputStream in = new ByteBufInputStream(buf, 0); ByteBufInputStream in = new ByteBufInputStream(buf, 0);
try { try {
in.readByte(); assertThrows(EOFException.class, in::readByte);
} finally { } finally {
buf.release(); buf.release();
in.close(); in.close();

View File

@ -17,9 +17,9 @@ package io.netty.buffer;
import io.netty.util.AsciiString; import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runners.Parameterized; import org.junit.jupiter.params.provider.MethodSource;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -35,23 +35,22 @@ import static io.netty.buffer.Unpooled.unreleasableBuffer;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assume.assumeThat; 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;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@RunWith(Parameterized.class)
public class ByteBufUtilTest { public class ByteBufUtilTest {
private static final String PARAMETERIZED_NAME = "bufferType = {0}";
private enum BufferType { private enum BufferType {
DIRECT_UNPOOLED, DIRECT_POOLED, HEAP_POOLED, HEAP_UNPOOLED DIRECT_UNPOOLED, DIRECT_POOLED, HEAP_POOLED, HEAP_UNPOOLED
} }
private final BufferType bufferType; private ByteBuf buffer(BufferType bufferType, int capacity) {
public ByteBufUtilTest(BufferType bufferType) {
this.bufferType = bufferType;
}
private ByteBuf buffer(int capacity) {
switch (bufferType) { switch (bufferType) {
case DIRECT_UNPOOLED: case DIRECT_UNPOOLED:
@ -67,7 +66,6 @@ public class ByteBufUtilTest {
} }
} }
@Parameterized.Parameters(name = "bufferType = {0}")
public static Collection<Object[]> noUnsafe() { public static Collection<Object[]> noUnsafe() {
return Arrays.asList(new Object[][] { return Arrays.asList(new Object[][] {
{ BufferType.DIRECT_POOLED }, { BufferType.DIRECT_POOLED },
@ -99,14 +97,14 @@ public class ByteBufUtilTest {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeHexDumpWithOddLength() { public void decodeHexDumpWithOddLength() {
ByteBufUtil.decodeHexDump("abc"); assertThrows(IllegalArgumentException.class, () -> ByteBufUtil.decodeHexDump("abc"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeHexDumpWithInvalidChar() { public void decodeHexDumpWithInvalidChar() {
ByteBufUtil.decodeHexDump("fg"); assertThrows(IllegalArgumentException.class, () -> ByteBufUtil.decodeHexDump("fg"));
} }
@Test @Test
@ -160,7 +158,7 @@ public class ByteBufUtilTest {
Math.max(b1.length, b2.length) * 2)); Math.max(b1.length, b2.length) * 2));
} }
@Test (expected = IllegalArgumentException.class) @Test
public void notEqualsBufferUnderflow() { public void notEqualsBufferUnderflow() {
byte[] b1 = new byte[8]; byte[] b1 = new byte[8];
byte[] b2 = new byte[16]; byte[] b2 = new byte[16];
@ -171,23 +169,24 @@ public class ByteBufUtilTest {
final int iB2 = iB1 + b1.length; final int iB2 = iB1 + b1.length;
final int length = b1.length - iB1; final int length = b1.length - iB1;
System.arraycopy(b1, iB1, b2, iB2, length - 1); System.arraycopy(b1, iB1, b2, iB2, length - 1);
assertFalse(ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, assertThrows(IllegalArgumentException.class,
-1)); () -> ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, -1));
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void writeShortBE() { @MethodSource("noUnsafe")
public void writeShortBE(BufferType bufferType) {
int expected = 0x1234; int expected = 0x1234;
ByteBuf buf = buffer(2).order(ByteOrder.BIG_ENDIAN); ByteBuf buf = buffer(bufferType, 2).order(ByteOrder.BIG_ENDIAN);
ByteBufUtil.writeShortBE(buf, expected); ByteBufUtil.writeShortBE(buf, expected);
assertEquals(expected, buf.readShort()); assertEquals(expected, buf.readShort());
buf.readerIndex(0); buf.readerIndex(0);
assertEquals(ByteBufUtil.swapShort((short) expected), buf.readShortLE()); assertEquals(ByteBufUtil.swapShort((short) expected), buf.readShortLE());
buf.release(); buf.release();
buf = buffer(2).order(ByteOrder.LITTLE_ENDIAN); buf = buffer(bufferType, 2).order(ByteOrder.LITTLE_ENDIAN);
ByteBufUtil.writeShortBE(buf, expected); ByteBufUtil.writeShortBE(buf, expected);
assertEquals(ByteBufUtil.swapShort((short) expected), buf.readShortLE()); assertEquals(ByteBufUtil.swapShort((short) expected), buf.readShortLE());
buf.readerIndex(0); buf.readerIndex(0);
@ -216,18 +215,19 @@ public class ByteBufUtilTest {
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void writeMediumBE() { @MethodSource("noUnsafe")
public void writeMediumBE(BufferType bufferType) {
int mediumValue = 0x123456; int mediumValue = 0x123456;
ByteBuf buf = buffer(4).order(ByteOrder.BIG_ENDIAN); ByteBuf buf = buffer(bufferType, 4).order(ByteOrder.BIG_ENDIAN);
ByteBufUtil.writeMediumBE(buf, mediumValue); ByteBufUtil.writeMediumBE(buf, mediumValue);
assertEquals(mediumValue, buf.readMedium()); assertEquals(mediumValue, buf.readMedium());
buf.readerIndex(0); buf.readerIndex(0);
assertEquals(ByteBufUtil.swapMedium(mediumValue), buf.readMediumLE()); assertEquals(ByteBufUtil.swapMedium(mediumValue), buf.readMediumLE());
buf.release(); buf.release();
buf = buffer(4).order(ByteOrder.LITTLE_ENDIAN); buf = buffer(bufferType, 4).order(ByteOrder.LITTLE_ENDIAN);
ByteBufUtil.writeMediumBE(buf, mediumValue); ByteBufUtil.writeMediumBE(buf, mediumValue);
assertEquals(ByteBufUtil.swapMedium(mediumValue), buf.readMediumLE()); assertEquals(ByteBufUtil.swapMedium(mediumValue), buf.readMediumLE());
buf.readerIndex(0); buf.readerIndex(0);
@ -235,12 +235,13 @@ public class ByteBufUtilTest {
buf.release(); buf.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUsAscii() { @MethodSource("noUnsafe")
public void testWriteUsAscii(BufferType bufferType) {
String usAscii = "NettyRocks"; String usAscii = "NettyRocks";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII)); buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeAscii(buf2, usAscii); ByteBufUtil.writeAscii(buf2, usAscii);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -249,12 +250,13 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUsAsciiSwapped() { @MethodSource("noUnsafe")
public void testWriteUsAsciiSwapped(BufferType bufferType) {
String usAscii = "NettyRocks"; String usAscii = "NettyRocks";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII)); buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII));
SwappedByteBuf buf2 = new SwappedByteBuf(buffer(16)); SwappedByteBuf buf2 = new SwappedByteBuf(buffer(bufferType, 16));
ByteBufUtil.writeAscii(buf2, usAscii); ByteBufUtil.writeAscii(buf2, usAscii);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -263,13 +265,14 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUsAsciiWrapped() { @MethodSource("noUnsafe")
public void testWriteUsAsciiWrapped(BufferType bufferType) {
String usAscii = "NettyRocks"; String usAscii = "NettyRocks";
ByteBuf buf = unreleasableBuffer(buffer(16)); ByteBuf buf = unreleasableBuffer(buffer(bufferType, 16));
assertWrapped(buf); assertWrapped(buf);
buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII)); buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII));
ByteBuf buf2 = unreleasableBuffer(buffer(16)); ByteBuf buf2 = unreleasableBuffer(buffer(bufferType, 16));
assertWrapped(buf2); assertWrapped(buf2);
ByteBufUtil.writeAscii(buf2, usAscii); ByteBufUtil.writeAscii(buf2, usAscii);
@ -279,13 +282,14 @@ public class ByteBufUtilTest {
buf2.unwrap().release(); buf2.unwrap().release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUsAsciiComposite() { @MethodSource("noUnsafe")
public void testWriteUsAsciiComposite(BufferType bufferType) {
String usAscii = "NettyRocks"; String usAscii = "NettyRocks";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII)); buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII));
ByteBuf buf2 = Unpooled.compositeBuffer().addComponent( ByteBuf buf2 = Unpooled.compositeBuffer().addComponent(
buffer(8)).addComponent(buffer(24)); buffer(bufferType, 8)).addComponent(buffer(bufferType, 24));
// write some byte so we start writing with an offset. // write some byte so we start writing with an offset.
buf2.writeByte(1); buf2.writeByte(1);
ByteBufUtil.writeAscii(buf2, usAscii); ByteBufUtil.writeAscii(buf2, usAscii);
@ -297,13 +301,14 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUsAsciiCompositeWrapped() { @MethodSource("noUnsafe")
public void testWriteUsAsciiCompositeWrapped(BufferType bufferType) {
String usAscii = "NettyRocks"; String usAscii = "NettyRocks";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII)); buf.writeBytes(usAscii.getBytes(CharsetUtil.US_ASCII));
ByteBuf buf2 = new WrappedCompositeByteBuf(Unpooled.compositeBuffer().addComponent( ByteBuf buf2 = new WrappedCompositeByteBuf(Unpooled.compositeBuffer().addComponent(
buffer(8)).addComponent(buffer(24))); buffer(bufferType, 8)).addComponent(buffer(bufferType, 24)));
// write some byte so we start writing with an offset. // write some byte so we start writing with an offset.
buf2.writeByte(1); buf2.writeByte(1);
ByteBufUtil.writeAscii(buf2, usAscii); ByteBufUtil.writeAscii(buf2, usAscii);
@ -315,12 +320,13 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8() { @MethodSource("noUnsafe")
public void testWriteUtf8(BufferType bufferType) {
String usAscii = "Some UTF-8 like äÄ∏ŒŒ"; String usAscii = "Some UTF-8 like äÄ∏ŒŒ";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(usAscii.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, usAscii); ByteBufUtil.writeUtf8(buf2, usAscii);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -329,13 +335,14 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8Composite() { @MethodSource("noUnsafe")
public void testWriteUtf8Composite(BufferType bufferType) {
String utf8 = "Some UTF-8 like äÄ∏ŒŒ"; String utf8 = "Some UTF-8 like äÄ∏ŒŒ";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(utf8.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(utf8.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = Unpooled.compositeBuffer().addComponent( ByteBuf buf2 = Unpooled.compositeBuffer().addComponent(
buffer(8)).addComponent(buffer(24)); buffer(bufferType, 8)).addComponent(buffer(bufferType, 24));
// write some byte so we start writing with an offset. // write some byte so we start writing with an offset.
buf2.writeByte(1); buf2.writeByte(1);
ByteBufUtil.writeUtf8(buf2, utf8); ByteBufUtil.writeUtf8(buf2, utf8);
@ -347,13 +354,14 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8CompositeWrapped() { @MethodSource("noUnsafe")
public void testWriteUtf8CompositeWrapped(BufferType bufferType) {
String utf8 = "Some UTF-8 like äÄ∏ŒŒ"; String utf8 = "Some UTF-8 like äÄ∏ŒŒ";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(utf8.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(utf8.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = new WrappedCompositeByteBuf(Unpooled.compositeBuffer().addComponent( ByteBuf buf2 = new WrappedCompositeByteBuf(Unpooled.compositeBuffer().addComponent(
buffer(8)).addComponent(buffer(24))); buffer(bufferType, 8)).addComponent(buffer(bufferType, 24)));
// write some byte so we start writing with an offset. // write some byte so we start writing with an offset.
buf2.writeByte(1); buf2.writeByte(1);
ByteBufUtil.writeUtf8(buf2, utf8); ByteBufUtil.writeUtf8(buf2, utf8);
@ -365,8 +373,9 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8Surrogates() { @MethodSource("noUnsafe")
public void testWriteUtf8Surrogates(BufferType bufferType) {
// leading surrogate + trailing surrogate // leading surrogate + trailing surrogate
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('a') .append('a')
@ -374,9 +383,9 @@ public class ByteBufUtilTest {
.append('\uDC00') .append('\uDC00')
.append('b') .append('b')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -386,16 +395,17 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidOnlyTrailingSurrogate() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidOnlyTrailingSurrogate(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('a') .append('a')
.append('\uDC00') .append('\uDC00')
.append('b') .append('b')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -405,16 +415,17 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidOnlyLeadingSurrogate() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidOnlyLeadingSurrogate(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('a') .append('a')
.append('\uD800') .append('\uD800')
.append('b') .append('b')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -424,17 +435,18 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidSurrogatesSwitched() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidSurrogatesSwitched(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('a') .append('a')
.append('\uDC00') .append('\uDC00')
.append('\uD800') .append('\uD800')
.append('b') .append('b')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -444,17 +456,18 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidTwoLeadingSurrogates() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidTwoLeadingSurrogates(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('a') .append('a')
.append('\uD800') .append('\uD800')
.append('\uD800') .append('\uD800')
.append('b') .append('b')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -463,17 +476,18 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidTwoTrailingSurrogates() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidTwoTrailingSurrogates(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('a') .append('a')
.append('\uDC00') .append('\uDC00')
.append('\uDC00') .append('\uDC00')
.append('b') .append('b')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -483,14 +497,15 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidEndOnLeadingSurrogate() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidEndOnLeadingSurrogate(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('\uD800') .append('\uD800')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -500,14 +515,15 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidEndOnTrailingSurrogate() { @MethodSource("noUnsafe")
public void testWriteUtf8InvalidEndOnTrailingSurrogate(BufferType bufferType) {
String surrogateString = new StringBuilder(2) String surrogateString = new StringBuilder(2)
.append('\uDC00') .append('\uDC00')
.toString(); .toString();
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(surrogateString.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, surrogateString); ByteBufUtil.writeUtf8(buf2, surrogateString);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -517,13 +533,14 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUsAsciiString() { @MethodSource("noUnsafe")
public void testWriteUsAsciiString(BufferType bufferType) {
AsciiString usAscii = new AsciiString("NettyRocks"); AsciiString usAscii = new AsciiString("NettyRocks");
int expectedCapacity = usAscii.length(); int expectedCapacity = usAscii.length();
ByteBuf buf = buffer(expectedCapacity); ByteBuf buf = buffer(bufferType, expectedCapacity);
buf.writeBytes(usAscii.toString().getBytes(CharsetUtil.US_ASCII)); buf.writeBytes(usAscii.toString().getBytes(CharsetUtil.US_ASCII));
ByteBuf buf2 = buffer(expectedCapacity); ByteBuf buf2 = buffer(bufferType, expectedCapacity);
ByteBufUtil.writeAscii(buf2, usAscii); ByteBufUtil.writeAscii(buf2, usAscii);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -532,13 +549,14 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8Wrapped() { @MethodSource("noUnsafe")
public void testWriteUtf8Wrapped(BufferType bufferType) {
String usAscii = "Some UTF-8 like äÄ∏ŒŒ"; String usAscii = "Some UTF-8 like äÄ∏ŒŒ";
ByteBuf buf = unreleasableBuffer(buffer(16)); ByteBuf buf = unreleasableBuffer(buffer(bufferType, 16));
assertWrapped(buf); assertWrapped(buf);
buf.writeBytes(usAscii.getBytes(CharsetUtil.UTF_8)); buf.writeBytes(usAscii.getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = unreleasableBuffer(buffer(16)); ByteBuf buf2 = unreleasableBuffer(buffer(bufferType, 16));
assertWrapped(buf2); assertWrapped(buf2);
ByteBufUtil.writeUtf8(buf2, usAscii); ByteBufUtil.writeUtf8(buf2, usAscii);
@ -552,12 +570,13 @@ public class ByteBufUtilTest {
assertTrue(buf instanceof WrappedByteBuf); assertTrue(buf instanceof WrappedByteBuf);
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8Subsequence() { @MethodSource("noUnsafe")
public void testWriteUtf8Subsequence(BufferType bufferType) {
String usAscii = "Some UTF-8 like äÄ∏ŒŒ"; String usAscii = "Some UTF-8 like äÄ∏ŒŒ";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.substring(5, 18).getBytes(CharsetUtil.UTF_8)); buf.writeBytes(usAscii.substring(5, 18).getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, usAscii, 5, 18); ByteBufUtil.writeUtf8(buf2, usAscii, 5, 18);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -566,12 +585,13 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8SubsequenceSplitSurrogate() { @MethodSource("noUnsafe")
public void testWriteUtf8SubsequenceSplitSurrogate(BufferType bufferType) {
String usAscii = "\uD800\uDC00"; // surrogate pair: one code point, two chars String usAscii = "\uD800\uDC00"; // surrogate pair: one code point, two chars
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.substring(0, 1).getBytes(CharsetUtil.UTF_8)); buf.writeBytes(usAscii.substring(0, 1).getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
ByteBufUtil.writeUtf8(buf2, usAscii, 0, 1); ByteBufUtil.writeUtf8(buf2, usAscii, 0, 1);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -580,12 +600,13 @@ public class ByteBufUtilTest {
buf2.release(); buf2.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testReserveAndWriteUtf8Subsequence() { @MethodSource("noUnsafe")
public void testReserveAndWriteUtf8Subsequence(BufferType bufferType) {
String usAscii = "Some UTF-8 like äÄ∏ŒŒ"; String usAscii = "Some UTF-8 like äÄ∏ŒŒ";
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
buf.writeBytes(usAscii.substring(5, 18).getBytes(CharsetUtil.UTF_8)); buf.writeBytes(usAscii.substring(5, 18).getBytes(CharsetUtil.UTF_8));
ByteBuf buf2 = buffer(16); ByteBuf buf2 = buffer(bufferType, 16);
int count = ByteBufUtil.reserveAndWriteUtf8(buf2, usAscii, 5, 18, 16); int count = ByteBufUtil.reserveAndWriteUtf8(buf2, usAscii, 5, 18, 16);
assertEquals(buf, buf2); assertEquals(buf, buf2);
@ -610,9 +631,9 @@ public class ByteBufUtilTest {
int invoke(Object... args); int invoke(Object... args);
} }
private void testInvalidSubsequences(TestMethod method) { private void testInvalidSubsequences(BufferType bufferType, TestMethod method) {
for (int [] range : INVALID_RANGES) { for (int [] range : INVALID_RANGES) {
ByteBuf buf = buffer(16); ByteBuf buf = buffer(bufferType, 16);
try { try {
method.invoke(buf, "Some UTF-8 like äÄ∏ŒŒ", range[0], range[1]); method.invoke(buf, "Some UTF-8 like äÄ∏ŒŒ", range[0], range[1]);
fail("Did not throw IndexOutOfBoundsException for range (" + range[0] + ", " + range[1] + ")"); fail("Did not throw IndexOutOfBoundsException for range (" + range[0] + ", " + range[1] + ")");
@ -625,21 +646,25 @@ public class ByteBufUtilTest {
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testWriteUtf8InvalidSubsequences() { @MethodSource("noUnsafe")
testInvalidSubsequences(args -> ByteBufUtil.writeUtf8((ByteBuf) args[0], (String) args[1], public void testWriteUtf8InvalidSubsequences(BufferType bufferType) {
testInvalidSubsequences(bufferType, args -> ByteBufUtil.writeUtf8((ByteBuf) args[0], (String) args[1],
(Integer) args[2], (Integer) args[3])); (Integer) args[2], (Integer) args[3]));
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testReserveAndWriteUtf8InvalidSubsequences() { @MethodSource("noUnsafe")
testInvalidSubsequences(args -> ByteBufUtil.reserveAndWriteUtf8((ByteBuf) args[0], (String) args[1], public void testReserveAndWriteUtf8InvalidSubsequences(BufferType bufferType) {
testInvalidSubsequences(bufferType, args -> ByteBufUtil.reserveAndWriteUtf8((ByteBuf) args[0], (String) args[1],
(Integer) args[2], (Integer) args[3], 32)); (Integer) args[2], (Integer) args[3], 32));
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testUtf8BytesInvalidSubsequences() { @MethodSource("noUnsafe")
testInvalidSubsequences(args -> ByteBufUtil.utf8Bytes((String) args[1], (Integer) args[2], (Integer) args[3])); public void testUtf8BytesInvalidSubsequences(BufferType bufferType) {
testInvalidSubsequences(bufferType,
args -> ByteBufUtil.utf8Bytes((String) args[1], (Integer) args[2], (Integer) args[3]));
} }
@Test @Test
@ -658,21 +683,23 @@ public class ByteBufUtilTest {
buffer.release(); buffer.release();
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testToStringDoesNotThrowIndexOutOfBounds() { @MethodSource("noUnsafe")
public void testToStringDoesNotThrowIndexOutOfBounds(BufferType bufferType) {
CompositeByteBuf buffer = Unpooled.compositeBuffer(); CompositeByteBuf buffer = Unpooled.compositeBuffer();
try { try {
byte[] bytes = "1234".getBytes(CharsetUtil.UTF_8); byte[] bytes = "1234".getBytes(CharsetUtil.UTF_8);
buffer.addComponent(buffer(bytes.length).writeBytes(bytes)); buffer.addComponent(buffer(bufferType, bytes.length).writeBytes(bytes));
buffer.addComponent(buffer(bytes.length).writeBytes(bytes)); buffer.addComponent(buffer(bufferType, bytes.length).writeBytes(bytes));
assertEquals("1234", buffer.toString(bytes.length, bytes.length, CharsetUtil.UTF_8)); assertEquals("1234", buffer.toString(bytes.length, bytes.length, CharsetUtil.UTF_8));
} finally { } finally {
buffer.release(); buffer.release();
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testIsTextWithUtf8() { @MethodSource("noUnsafe")
public void testIsTextWithUtf8(BufferType bufferType) {
byte[][] validUtf8Bytes = { byte[][] validUtf8Bytes = {
"netty".getBytes(CharsetUtil.UTF_8), "netty".getBytes(CharsetUtil.UTF_8),
{(byte) 0x24}, {(byte) 0x24},
@ -685,7 +712,7 @@ public class ByteBufUtilTest {
(byte) 0xF0, (byte) 0x90, (byte) 0x8D, (byte) 0x88} // multiple characters (byte) 0xF0, (byte) 0x90, (byte) 0x8D, (byte) 0x88} // multiple characters
}; };
for (byte[] bytes : validUtf8Bytes) { for (byte[] bytes : validUtf8Bytes) {
assertIsText(bytes, true, CharsetUtil.UTF_8); assertIsText(bufferType, bytes, true, CharsetUtil.UTF_8);
} }
byte[][] invalidUtf8Bytes = { byte[][] invalidUtf8Bytes = {
{(byte) 0x80}, {(byte) 0x80},
@ -701,31 +728,34 @@ public class ByteBufUtilTest {
{(byte) 0xED, (byte) 0xAF, (byte) 0x80} // out of upper bound {(byte) 0xED, (byte) 0xAF, (byte) 0x80} // out of upper bound
}; };
for (byte[] bytes : invalidUtf8Bytes) { for (byte[] bytes : invalidUtf8Bytes) {
assertIsText(bytes, false, CharsetUtil.UTF_8); assertIsText(bufferType, bytes, false, CharsetUtil.UTF_8);
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testIsTextWithoutOptimization() { @MethodSource("noUnsafe")
public void testIsTextWithoutOptimization(BufferType bufferType) {
byte[] validBytes = {(byte) 0x01, (byte) 0xD8, (byte) 0x37, (byte) 0xDC}; byte[] validBytes = {(byte) 0x01, (byte) 0xD8, (byte) 0x37, (byte) 0xDC};
byte[] invalidBytes = {(byte) 0x01, (byte) 0xD8}; byte[] invalidBytes = {(byte) 0x01, (byte) 0xD8};
assertIsText(validBytes, true, CharsetUtil.UTF_16LE); assertIsText(bufferType, validBytes, true, CharsetUtil.UTF_16LE);
assertIsText(invalidBytes, false, CharsetUtil.UTF_16LE); assertIsText(bufferType, invalidBytes, false, CharsetUtil.UTF_16LE);
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testIsTextWithAscii() { @MethodSource("noUnsafe")
public void testIsTextWithAscii(BufferType bufferType) {
byte[] validBytes = {(byte) 0x00, (byte) 0x01, (byte) 0x37, (byte) 0x7F}; byte[] validBytes = {(byte) 0x00, (byte) 0x01, (byte) 0x37, (byte) 0x7F};
byte[] invalidBytes = {(byte) 0x80, (byte) 0xFF}; byte[] invalidBytes = {(byte) 0x80, (byte) 0xFF};
assertIsText(validBytes, true, CharsetUtil.US_ASCII); assertIsText(bufferType, validBytes, true, CharsetUtil.US_ASCII);
assertIsText(invalidBytes, false, CharsetUtil.US_ASCII); assertIsText(bufferType, invalidBytes, false, CharsetUtil.US_ASCII);
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testIsTextWithInvalidIndexAndLength() { @MethodSource("noUnsafe")
ByteBuf buffer = buffer(4); public void testIsTextWithInvalidIndexAndLength(BufferType bufferType) {
ByteBuf buffer = buffer(bufferType, 4);
try { try {
buffer.writeBytes(new byte[4]); buffer.writeBytes(new byte[4]);
int[][] validIndexLengthPairs = { int[][] validIndexLengthPairs = {
@ -757,33 +787,37 @@ public class ByteBufUtilTest {
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testUtf8Bytes() { @MethodSource("noUnsafe")
public void testUtf8Bytes(BufferType bufferType) {
final String s = "Some UTF-8 like äÄ∏ŒŒ"; final String s = "Some UTF-8 like äÄ∏ŒŒ";
checkUtf8Bytes(s); checkUtf8Bytes(bufferType, s);
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testUtf8BytesWithSurrogates() { @MethodSource("noUnsafe")
public void testUtf8BytesWithSurrogates(BufferType bufferType) {
final String s = "a\uD800\uDC00b"; final String s = "a\uD800\uDC00b";
checkUtf8Bytes(s); checkUtf8Bytes(bufferType, s);
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testUtf8BytesWithNonSurrogates3Bytes() { @MethodSource("noUnsafe")
public void testUtf8BytesWithNonSurrogates3Bytes(BufferType bufferType) {
final String s = "a\uE000b"; final String s = "a\uE000b";
checkUtf8Bytes(s); checkUtf8Bytes(bufferType, s);
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testUtf8BytesWithNonSurrogatesNonAscii() { @MethodSource("noUnsafe")
public void testUtf8BytesWithNonSurrogatesNonAscii(BufferType bufferType) {
final char nonAscii = (char) 0x81; final char nonAscii = (char) 0x81;
final String s = "a" + nonAscii + "b"; final String s = "a" + nonAscii + "b";
checkUtf8Bytes(s); checkUtf8Bytes(bufferType, s);
} }
private void checkUtf8Bytes(final CharSequence charSequence) { private void checkUtf8Bytes(BufferType bufferType, final CharSequence charSequence) {
final ByteBuf buf = buffer(ByteBufUtil.utf8MaxBytes(charSequence)); final ByteBuf buf = buffer(bufferType, ByteBufUtil.utf8MaxBytes(charSequence));
try { try {
final int writtenBytes = ByteBufUtil.writeUtf8(buf, charSequence); final int writtenBytes = ByteBufUtil.writeUtf8(buf, charSequence);
final int utf8Bytes = ByteBufUtil.utf8Bytes(charSequence); final int utf8Bytes = ByteBufUtil.utf8Bytes(charSequence);
@ -793,8 +827,8 @@ public class ByteBufUtilTest {
} }
} }
private void assertIsText(byte[] bytes, boolean expected, Charset charset) { private void assertIsText(BufferType bufferType, byte[] bytes, boolean expected, Charset charset) {
ByteBuf buffer = buffer(bytes.length); ByteBuf buffer = buffer(bufferType, bytes.length);
try { try {
buffer.writeBytes(bytes); buffer.writeBytes(bytes);
assertEquals(expected, ByteBufUtil.isText(buffer, charset)); assertEquals(expected, ByteBufUtil.isText(buffer, charset));
@ -803,9 +837,10 @@ public class ByteBufUtilTest {
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testIsTextMultiThreaded() throws Throwable { @MethodSource("noUnsafe")
assumeThat(bufferType, is(BufferType.HEAP_UNPOOLED)); public void testIsTextMultiThreaded(BufferType bufferType) throws Throwable {
assumeTrue(bufferType == BufferType.HEAP_UNPOOLED);
final ByteBuf buffer = Unpooled.copiedBuffer("Hello, World!", CharsetUtil.ISO_8859_1); final ByteBuf buffer = Unpooled.copiedBuffer("Hello, World!", CharsetUtil.ISO_8859_1);
try { try {
@ -841,9 +876,10 @@ public class ByteBufUtilTest {
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testGetBytes() { @MethodSource("noUnsafe")
final ByteBuf buf = buffer(4); public void testGetBytes(BufferType bufferType) {
final ByteBuf buf = buffer(bufferType, 4);
try { try {
checkGetBytes(buf); checkGetBytes(buf);
} finally { } finally {
@ -851,10 +887,11 @@ public class ByteBufUtilTest {
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testGetBytesHeapWithNonZeroArrayOffset() { @MethodSource("noUnsafe")
assumeThat(bufferType, is(BufferType.HEAP_UNPOOLED)); public void testGetBytesHeapWithNonZeroArrayOffset(BufferType bufferType) {
final ByteBuf buf = buffer(5); assumeTrue(bufferType == BufferType.HEAP_UNPOOLED);
final ByteBuf buf = buffer(bufferType, 5);
try { try {
buf.setByte(0, 0x05); buf.setByte(0, 0x05);
@ -871,10 +908,11 @@ public class ByteBufUtilTest {
} }
} }
@Test @ParameterizedTest(name = PARAMETERIZED_NAME)
public void testGetBytesHeapWithArrayLengthGreaterThanCapacity() { @MethodSource("noUnsafe")
assumeThat(bufferType, is(BufferType.HEAP_UNPOOLED)); public void testGetBytesHeapWithArrayLengthGreaterThanCapacity(BufferType bufferType) {
final ByteBuf buf = buffer(5); assumeTrue(bufferType == BufferType.HEAP_UNPOOLED);
final ByteBuf buf = buffer(bufferType, 5);
try { try {
buf.setByte(4, 0x05); buf.setByte(4, 0x05);

View File

@ -16,11 +16,11 @@
package io.netty.buffer; package io.netty.buffer;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import io.netty.util.ByteProcessor; import io.netty.util.ByteProcessor;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class ByteProcessorTest { public class ByteProcessorTest {
@Test @Test

View File

@ -16,10 +16,10 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static io.netty.buffer.Unpooled.*; import static io.netty.buffer.Unpooled.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Tests buffer consolidation * Tests buffer consolidation

View File

@ -15,9 +15,12 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DefaultByteBufHolderTest { public class DefaultByteBufHolderTest {

View File

@ -15,9 +15,10 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
* Tests duplicated channel buffers * Tests duplicated channel buffers
@ -40,9 +41,9 @@ public class DuplicatedByteBufTest extends AbstractByteBufTest {
buf.release(); buf.release();
} }
@Test(expected = NullPointerException.class) @Test
public void shouldNotAllowNullInConstructor() { public void shouldNotAllowNullInConstructor() {
new DuplicatedByteBuf(null); assertThrows(NullPointerException.class, () -> new DuplicatedByteBuf(null));
} }
// See https://github.com/netty/netty/issues/1800 // See https://github.com/netty/netty/issues/1800

View File

@ -12,14 +12,18 @@
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations * License for the specific language governing permissions and limitations
* under the License. * under the License.
*/package io.netty.buffer; */
package io.netty.buffer;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class EmptyByteBufTest { public class EmptyByteBufTest {

View File

@ -15,9 +15,8 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.jupiter.api.Assumptions;
import org.junit.Assume; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@ -28,7 +27,12 @@ import java.nio.channels.ScatteringByteChannel;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import static io.netty.buffer.Unpooled.*; import static io.netty.buffer.Unpooled.*;
import static org.junit.Assert.*; 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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class FixedCompositeByteBufTest { public class FixedCompositeByteBufTest {
@ -36,63 +40,64 @@ public class FixedCompositeByteBufTest {
return new FixedCompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, buffers); return new FixedCompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, buffers);
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBoolean() { public void testSetBoolean() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setBoolean(0, true); assertThrows(ReadOnlyBufferException.class, () -> buf.setBoolean(0, true));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetByte() { public void testSetByte() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setByte(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setByte(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesWithByteBuf() { public void testSetBytesWithByteBuf() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
ByteBuf src = wrappedBuffer(new byte[4]); ByteBuf src = wrappedBuffer(new byte[4]);
try { try {
buf.setBytes(0, src); assertThrows(ReadOnlyBufferException.class, () -> buf.setBytes(0, src));
} finally { } finally {
buf.release(); buf.release();
src.release(); src.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesWithByteBuffer() { public void testSetBytesWithByteBuffer() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setBytes(0, ByteBuffer.wrap(new byte[4])); assertThrows(ReadOnlyBufferException.class, () -> buf.setBytes(0, ByteBuffer.wrap(new byte[4])));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesWithInputStream() throws IOException { public void testSetBytesWithInputStream() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setBytes(0, new ByteArrayInputStream(new byte[4]), 4); assertThrows(ReadOnlyBufferException.class,
() -> buf.setBytes(0, new ByteArrayInputStream(new byte[4]), 4));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesWithChannel() throws IOException { public void testSetBytesWithChannel() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setBytes(0, new ScatteringByteChannel() { assertThrows(ReadOnlyBufferException.class, () -> buf.setBytes(0, new ScatteringByteChannel() {
@Override @Override
public long read(ByteBuffer[] dsts, int offset, int length) { public long read(ByteBuffer[] dsts, int offset, int length) {
return 0; return 0;
@ -116,67 +121,67 @@ public class FixedCompositeByteBufTest {
@Override @Override
public void close() { public void close() {
} }
}, 4); }, 4));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetChar() throws IOException { public void testSetChar() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setChar(0, 'b'); assertThrows(ReadOnlyBufferException.class, () -> buf.setChar(0, 'b'));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetDouble() throws IOException { public void testSetDouble() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setDouble(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setDouble(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetFloat() throws IOException { public void testSetFloat() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setFloat(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setFloat(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetInt() throws IOException { public void testSetInt() throws IOException {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setInt(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setInt(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetLong() { public void testSetLong() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setLong(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setLong(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetMedium() throws IOException { public void testSetMedium() {
ByteBuf buf = newBuffer(wrappedBuffer(new byte[8])); ByteBuf buf = newBuffer(wrappedBuffer(new byte[8]));
try { try {
buf.setMedium(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setMedium(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
@ -394,7 +399,7 @@ public class FixedCompositeByteBufTest {
@Test @Test
public void testHasMemoryAddressWhenEmpty() { public void testHasMemoryAddressWhenEmpty() {
Assume.assumeTrue(EMPTY_BUFFER.hasMemoryAddress()); Assumptions.assumeTrue(EMPTY_BUFFER.hasMemoryAddress());
ByteBuf buf = newBuffer(new ByteBuf[0]); ByteBuf buf = newBuffer(new ByteBuf[0]);
assertTrue(buf.hasMemoryAddress()); assertTrue(buf.hasMemoryAddress());
assertEquals(EMPTY_BUFFER.memoryAddress(), buf.memoryAddress()); assertEquals(EMPTY_BUFFER.memoryAddress(), buf.memoryAddress());
@ -441,15 +446,14 @@ public class FixedCompositeByteBufTest {
buf.release(); buf.release();
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void testHasNoArrayWhenMultipleBuffers() { public void testHasNoArrayWhenMultipleBuffers() {
ByteBuf buf1 = buffer(10); ByteBuf buf1 = buffer(10);
ByteBuf buf2 = buffer(10); ByteBuf buf2 = buffer(10);
ByteBuf buf = newBuffer(buf1, buf2); ByteBuf buf = newBuffer(buf1, buf2);
assertFalse(buf.hasArray()); assertFalse(buf.hasArray());
try { try {
buf.array(); assertThrows(UnsupportedOperationException.class, buf::array);
fail();
} finally { } finally {
buf.release(); buf.release();
} }

View File

@ -15,7 +15,8 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.nio.ByteOrder; import java.nio.ByteOrder;

View File

@ -15,7 +15,7 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.ByteOrder; import java.nio.ByteOrder;

View File

@ -16,15 +16,15 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
public class LittleEndianUnsafeDirectByteBufTest extends LittleEndianDirectByteBufTest { public class LittleEndianUnsafeDirectByteBufTest extends LittleEndianDirectByteBufTest {
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
Assume.assumeTrue("sun.misc.Unsafe not found, skip tests", PlatformDependent.hasUnsafe()); Assumptions.assumeTrue(PlatformDependent.hasUnsafe(), "sun.misc.Unsafe not found, skip tests");
super.init(); super.init();
} }

View File

@ -16,16 +16,16 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
public class LittleEndianUnsafeNoCleanerDirectByteBufTest extends LittleEndianDirectByteBufTest { public class LittleEndianUnsafeNoCleanerDirectByteBufTest extends LittleEndianDirectByteBufTest {
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
Assume.assumeTrue("java.nio.DirectByteBuffer.<init>(long, int) not found, skip tests", Assumptions.assumeTrue(PlatformDependent.useDirectBufferNoCleaner(),
PlatformDependent.useDirectBufferNoCleaner()); "java.nio.DirectByteBuffer.<init>(long, int) not found, skip tests");
super.init(); super.init();
} }

View File

@ -16,7 +16,6 @@
package io.netty.buffer; package io.netty.buffer;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -30,12 +29,7 @@ class LongPriorityQueueTest {
@Test @Test
public void mustThrowWhenAddingNoValue() { public void mustThrowWhenAddingNoValue() {
final LongPriorityQueue pq = new LongPriorityQueue(); final LongPriorityQueue pq = new LongPriorityQueue();
assertThrows(IllegalArgumentException.class, new Executable() { assertThrows(IllegalArgumentException.class, () -> pq.offer(LongPriorityQueue.NO_VALUE));
@Override
public void execute() throws Throwable {
pq.offer(LongPriorityQueue.NO_VALUE);
}
});
} }
@Test @Test

View File

@ -17,13 +17,13 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assume.*; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class PoolArenaTest { public class PoolArenaTest {
@ -38,7 +38,7 @@ public class PoolArenaTest {
int[] reqCapacities = {0, 15, 510, 1024, 1023, 1025}; int[] reqCapacities = {0, 15, 510, 1024, 1023, 1025};
int[] expectedResult = {16, 16, 512, 1024, 1024, 1280}; int[] expectedResult = {16, 16, 512, 1024, 1024, 1280};
for (int i = 0; i < reqCapacities.length; i ++) { for (int i = 0; i < reqCapacities.length; i ++) {
Assert.assertEquals(expectedResult[i], arena.sizeIdx2size(arena.size2SizeIdx(reqCapacities[i]))); assertEquals(expectedResult[i], arena.sizeIdx2size(arena.size2SizeIdx(reqCapacities[i])));
} }
} }
@ -48,7 +48,7 @@ public class PoolArenaTest {
int[] reqCapacities = {0, 15, 510, 1024, 1023, 1025}; int[] reqCapacities = {0, 15, 510, 1024, 1023, 1025};
int[] expectedResult = {16, 64, 512, 1024, 1024, 1280}; int[] expectedResult = {16, 64, 512, 1024, 1024, 1280};
for (int i = 0; i < reqCapacities.length; i ++) { for (int i = 0; i < reqCapacities.length; i ++) {
Assert.assertEquals(expectedResult[i], arena.sizeIdx2size(arena.size2SizeIdx(reqCapacities[i]))); assertEquals(expectedResult[i], arena.sizeIdx2size(arena.size2SizeIdx(reqCapacities[i])));
} }
} }
@ -58,9 +58,9 @@ public class PoolArenaTest {
for (int sz = 0; sz <= CHUNK_SIZE; sz++) { for (int sz = 0; sz <= CHUNK_SIZE; sz++) {
int sizeIdx = arena.size2SizeIdx(sz); int sizeIdx = arena.size2SizeIdx(sz);
Assert.assertTrue(sz <= arena.sizeIdx2size(sizeIdx)); assertTrue(sz <= arena.sizeIdx2size(sizeIdx));
if (sizeIdx > 0) { if (sizeIdx > 0) {
Assert.assertTrue(sz > arena.sizeIdx2size(sizeIdx - 1)); assertTrue(sz > arena.sizeIdx2size(sizeIdx - 1));
} }
} }
} }
@ -74,15 +74,15 @@ public class PoolArenaTest {
int maxPages = CHUNK_SIZE >> pageShifts; int maxPages = CHUNK_SIZE >> pageShifts;
for (int pages = 1; pages <= maxPages; pages++) { for (int pages = 1; pages <= maxPages; pages++) {
int pageIdxFloor = arena.pages2pageIdxFloor(pages); int pageIdxFloor = arena.pages2pageIdxFloor(pages);
Assert.assertTrue(pages << pageShifts >= arena.pageIdx2size(pageIdxFloor)); assertTrue(pages << pageShifts >= arena.pageIdx2size(pageIdxFloor));
if (pageIdxFloor > 0 && pages < maxPages) { if (pageIdxFloor > 0 && pages < maxPages) {
Assert.assertTrue(pages << pageShifts < arena.pageIdx2size(pageIdxFloor + 1)); assertTrue(pages << pageShifts < arena.pageIdx2size(pageIdxFloor + 1));
} }
int pageIdxCeiling = arena.pages2pageIdx(pages); int pageIdxCeiling = arena.pages2pageIdx(pages);
Assert.assertTrue(pages << pageShifts <= arena.pageIdx2size(pageIdxCeiling)); assertTrue(pages << pageShifts <= arena.pageIdx2size(pageIdxCeiling));
if (pageIdxCeiling > 0) { if (pageIdxCeiling > 0) {
Assert.assertTrue(pages << pageShifts > arena.pageIdx2size(pageIdxCeiling - 1)); assertTrue(pages << pageShifts > arena.pageIdx2size(pageIdxCeiling - 1));
} }
} }
} }
@ -122,24 +122,24 @@ public class PoolArenaTest {
// create normal buffer // create normal buffer
final ByteBuf b2 = allocator.directBuffer(8192 * 5); final ByteBuf b2 = allocator.directBuffer(8192 * 5);
Assert.assertNotNull(b1); assertNotNull(b1);
Assert.assertNotNull(b2); assertNotNull(b2);
// then release buffer to deallocated memory while threadlocal cache has been disabled // then release buffer to deallocated memory while threadlocal cache has been disabled
// allocations counter value must equals deallocations counter value // allocations counter value must equals deallocations counter value
Assert.assertTrue(b1.release()); assertTrue(b1.release());
Assert.assertTrue(b2.release()); assertTrue(b2.release());
Assert.assertTrue(allocator.directArenas().size() >= 1); assertTrue(allocator.directArenas().size() >= 1);
final PoolArenaMetric metric = allocator.directArenas().get(0); final PoolArenaMetric metric = allocator.directArenas().get(0);
Assert.assertEquals(2, metric.numDeallocations()); assertEquals(2, metric.numDeallocations());
Assert.assertEquals(2, metric.numAllocations()); assertEquals(2, metric.numAllocations());
Assert.assertEquals(1, metric.numSmallDeallocations()); assertEquals(1, metric.numSmallDeallocations());
Assert.assertEquals(1, metric.numSmallAllocations()); assertEquals(1, metric.numSmallAllocations());
Assert.assertEquals(1, metric.numNormalDeallocations()); assertEquals(1, metric.numNormalDeallocations());
Assert.assertEquals(1, metric.numNormalAllocations()); assertEquals(1, metric.numNormalAllocations());
} }
@Test @Test

View File

@ -15,18 +15,18 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
public class PooledAlignedBigEndianDirectByteBufTest extends PooledBigEndianDirectByteBufTest { public class PooledAlignedBigEndianDirectByteBufTest extends PooledBigEndianDirectByteBufTest {
private static final int directMemoryCacheAlignment = 1; private static final int directMemoryCacheAlignment = 1;
private static PooledByteBufAllocator allocator; private static PooledByteBufAllocator allocator;
@BeforeClass @BeforeAll
public static void setUpAllocator() { public static void setUpAllocator() {
allocator = new PooledByteBufAllocator( allocator = new PooledByteBufAllocator(
true, true,
@ -40,7 +40,7 @@ public class PooledAlignedBigEndianDirectByteBufTest extends PooledBigEndianDire
directMemoryCacheAlignment); directMemoryCacheAlignment);
} }
@AfterClass @AfterAll
public static void releaseAllocator() { public static void releaseAllocator() {
allocator = null; allocator = null;
} }

View File

@ -17,7 +17,7 @@ package io.netty.buffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertSame;
/** /**
* Tests big-endian direct channel buffers * Tests big-endian direct channel buffers

View File

@ -20,8 +20,8 @@ import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.concurrent.FastThreadLocalThread; import io.netty.util.concurrent.FastThreadLocalThread;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.SystemPropertyUtil;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.ArrayList;
@ -32,14 +32,15 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.LockSupport;
import org.junit.jupiter.api.Timeout;
import static io.netty.buffer.PoolChunk.runOffset; import static io.netty.buffer.PoolChunk.runOffset;
import static io.netty.buffer.PoolChunk.runPages; import static io.netty.buffer.PoolChunk.runPages;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<PooledByteBufAllocator> { public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<PooledByteBufAllocator> {
@ -144,13 +145,13 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<Poo
@Test @Test
public void testArenaMetricsNoCacheAlign() { public void testArenaMetricsNoCacheAlign() {
Assume.assumeTrue(PooledByteBufAllocator.isDirectMemoryCacheAlignmentSupported()); Assumptions.assumeTrue(PooledByteBufAllocator.isDirectMemoryCacheAlignmentSupported());
testArenaMetrics0(new PooledByteBufAllocator(true, 2, 2, 8192, 11, 0, 0, 0, true, 64), 100, 0, 100, 100); testArenaMetrics0(new PooledByteBufAllocator(true, 2, 2, 8192, 11, 0, 0, 0, true, 64), 100, 0, 100, 100);
} }
@Test @Test
public void testArenaMetricsCacheAlign() { public void testArenaMetricsCacheAlign() {
Assume.assumeTrue(PooledByteBufAllocator.isDirectMemoryCacheAlignmentSupported()); Assumptions.assumeTrue(PooledByteBufAllocator.isDirectMemoryCacheAlignmentSupported());
testArenaMetrics0(new PooledByteBufAllocator(true, 2, 2, 8192, 11, 1000, 1000, 1000, true, 64), 100, 1, 1, 0); testArenaMetrics0(new PooledByteBufAllocator(true, 2, 2, 8192, 11, 1000, 1000, 1000, true, 64), 100, 1, 1, 0);
} }
@ -338,12 +339,14 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<Poo
} }
} }
@Test (timeout = 4000) @Test
@Timeout(value = 4000, unit = MILLISECONDS)
public void testThreadCacheDestroyedByThreadCleaner() throws InterruptedException { public void testThreadCacheDestroyedByThreadCleaner() throws InterruptedException {
testThreadCacheDestroyed(false); testThreadCacheDestroyed(false);
} }
@Test (timeout = 4000) @Test
@Timeout(value = 4000, unit = MILLISECONDS)
public void testThreadCacheDestroyedAfterExitRun() throws InterruptedException { public void testThreadCacheDestroyedAfterExitRun() throws InterruptedException {
testThreadCacheDestroyed(true); testThreadCacheDestroyed(true);
} }
@ -400,7 +403,8 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<Poo
assertTrue(threadCachesCreated.get()); assertTrue(threadCachesCreated.get());
} }
@Test(timeout = 3000) @Test
@Timeout(value = 3000, unit = MILLISECONDS)
public void testNumThreadCachesWithNoDirectArenas() throws InterruptedException { public void testNumThreadCachesWithNoDirectArenas() throws InterruptedException {
int numHeapArenas = 1; int numHeapArenas = 1;
final PooledByteBufAllocator allocator = final PooledByteBufAllocator allocator =
@ -419,7 +423,8 @@ public class PooledByteBufAllocatorTest extends AbstractByteBufAllocatorTest<Poo
assertEquals(0, allocator.metric().numThreadLocalCaches()); assertEquals(0, allocator.metric().numThreadLocalCaches());
} }
@Test(timeout = 3000) @Test
@Timeout(value = 3000, unit = MILLISECONDS)
public void testThreadCacheToArenaMappings() throws InterruptedException { public void testThreadCacheToArenaMappings() throws InterruptedException {
int numArenas = 2; int numArenas = 2;
final PooledByteBufAllocator allocator = final PooledByteBufAllocator allocator =

View File

@ -17,7 +17,7 @@ package io.netty.buffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertSame;
/** /**
* Tests little-endian direct channel buffers * Tests little-endian direct channel buffers

View File

@ -17,7 +17,7 @@ package io.netty.buffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertSame;
/** /**
* Tests little-endian heap channel buffers * Tests little-endian heap channel buffers

View File

@ -15,7 +15,7 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -31,11 +31,11 @@ import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
import static io.netty.buffer.Unpooled.LITTLE_ENDIAN; import static io.netty.buffer.Unpooled.LITTLE_ENDIAN;
import static io.netty.buffer.Unpooled.buffer; import static io.netty.buffer.Unpooled.buffer;
import static io.netty.buffer.Unpooled.unmodifiableBuffer; import static io.netty.buffer.Unpooled.unmodifiableBuffer;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -44,9 +44,9 @@ import static org.mockito.Mockito.when;
*/ */
public class ReadOnlyByteBufTest { public class ReadOnlyByteBufTest {
@Test(expected = NullPointerException.class) @Test
public void shouldNotAllowNullInConstructor() { public void shouldNotAllowNullInConstructor() {
new ReadOnlyByteBuf(null); assertThrows(NullPointerException.class, () -> new ReadOnlyByteBuf(null));
} }
@Test @Test
@ -127,59 +127,65 @@ public class ReadOnlyByteBufTest {
assertEquals(27, roBuf.capacity()); assertEquals(27, roBuf.capacity());
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectDiscardReadBytes() { public void shouldRejectDiscardReadBytes() {
unmodifiableBuffer(EMPTY_BUFFER).discardReadBytes(); assertThrows(UnsupportedOperationException.class, () -> unmodifiableBuffer(EMPTY_BUFFER).discardReadBytes());
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetByte() { public void shouldRejectSetByte() {
unmodifiableBuffer(EMPTY_BUFFER).setByte(0, (byte) 0); assertThrows(UnsupportedOperationException.class, () -> unmodifiableBuffer(EMPTY_BUFFER).setByte(0, (byte) 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetShort() { public void shouldRejectSetShort() {
unmodifiableBuffer(EMPTY_BUFFER).setShort(0, (short) 0); assertThrows(UnsupportedOperationException.class,
() -> unmodifiableBuffer(EMPTY_BUFFER).setShort(0, (short) 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetMedium() { public void shouldRejectSetMedium() {
unmodifiableBuffer(EMPTY_BUFFER).setMedium(0, 0); assertThrows(UnsupportedOperationException.class, () -> unmodifiableBuffer(EMPTY_BUFFER).setMedium(0, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetInt() { public void shouldRejectSetInt() {
unmodifiableBuffer(EMPTY_BUFFER).setInt(0, 0); assertThrows(UnsupportedOperationException.class, () -> unmodifiableBuffer(EMPTY_BUFFER).setInt(0, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetLong() { public void shouldRejectSetLong() {
unmodifiableBuffer(EMPTY_BUFFER).setLong(0, 0); assertThrows(UnsupportedOperationException.class, () -> unmodifiableBuffer(EMPTY_BUFFER).setLong(0, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetBytes1() throws IOException { public void shouldRejectSetBytes1() {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (InputStream) null, 0); assertThrows(UnsupportedOperationException.class,
() -> unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (InputStream) null, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetBytes2() throws IOException { public void shouldRejectSetBytes2() {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ScatteringByteChannel) null, 0); assertThrows(UnsupportedOperationException.class,
() -> unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ScatteringByteChannel) null, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetBytes3() { public void shouldRejectSetBytes3() {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (byte[]) null, 0, 0); assertThrows(UnsupportedOperationException.class,
() -> unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (byte[]) null, 0, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetBytes4() { public void shouldRejectSetBytes4() {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ByteBuf) null, 0, 0); assertThrows(UnsupportedOperationException.class,
() -> unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ByteBuf) null, 0, 0));
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void shouldRejectSetBytes5() { public void shouldRejectSetBytes5() {
unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ByteBuffer) null); assertThrows(UnsupportedOperationException.class,
() -> unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ByteBuffer) null));
} }
@Test @Test
@ -211,13 +217,12 @@ public class ReadOnlyByteBufTest {
readOnly.release(); readOnly.release();
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void ensureWritableShouldThrow() { public void ensureWritableShouldThrow() {
ByteBuf buf = buffer(1); ByteBuf buf = buffer(1);
ByteBuf readOnly = buf.asReadOnly(); ByteBuf readOnly = buf.asReadOnly();
try { try {
readOnly.ensureWritable(1); assertThrows(ReadOnlyBufferException.class, () -> readOnly.ensureWritable(1));
fail();
} finally { } finally {
buf.release(); buf.release();
} }

View File

@ -15,12 +15,12 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReadOnlyByteBufferBufTest extends ReadOnlyDirectByteBufferBufTest { public class ReadOnlyByteBufferBufTest extends ReadOnlyDirectByteBufferBufTest {
@Override @Override

View File

@ -16,8 +16,7 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
@ -28,6 +27,12 @@ import java.nio.ReadOnlyBufferException;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
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;
import static org.junit.jupiter.api.Assertions.fail;
public class ReadOnlyDirectByteBufferBufTest { public class ReadOnlyDirectByteBufferBufTest {
protected ByteBuf buffer(ByteBuffer buffer) { protected ByteBuf buffer(ByteBuffer buffer) {
@ -41,20 +46,20 @@ public class ReadOnlyDirectByteBufferBufTest {
@Test @Test
public void testIsContiguous() { public void testIsContiguous() {
ByteBuf buf = buffer(allocate(4).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(4).asReadOnlyBuffer());
Assert.assertTrue(buf.isContiguous()); assertTrue(buf.isContiguous());
buf.release(); buf.release();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testConstructWithWritable() { public void testConstructWithWritable() {
buffer(allocate(1)); assertThrows(IllegalArgumentException.class, () -> buffer(allocate(1)));
} }
@Test @Test
public void shouldIndicateNotWritable() { public void shouldIndicateNotWritable() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try { try {
Assert.assertFalse(buf.isWritable()); assertFalse(buf.isWritable());
} finally { } finally {
buf.release(); buf.release();
} }
@ -64,7 +69,7 @@ public class ReadOnlyDirectByteBufferBufTest {
public void shouldIndicateNotWritableAnyNumber() { public void shouldIndicateNotWritableAnyNumber() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try { try {
Assert.assertFalse(buf.isWritable(1)); assertFalse(buf.isWritable(1));
} finally { } finally {
buf.release(); buf.release();
} }
@ -75,7 +80,7 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try { try {
int result = buf.ensureWritable(1, false); int result = buf.ensureWritable(1, false);
Assert.assertEquals(1, result); assertEquals(1, result);
} finally { } finally {
buf.release(); buf.release();
} }
@ -86,99 +91,100 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try { try {
int result = buf.ensureWritable(1, true); int result = buf.ensureWritable(1, true);
Assert.assertEquals(1, result); assertEquals(1, result);
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void ensureWritableShouldThrow() { public void ensureWritableShouldThrow() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear(); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()).clear();
try { try {
buf.ensureWritable(1); assertThrows(ReadOnlyBufferException.class, () -> buf.ensureWritable(1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetByte() { public void testSetByte() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
buf.setByte(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setByte(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetInt() { public void testSetInt() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
buf.setInt(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setInt(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetShort() { public void testSetShort() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
buf.setShort(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setShort(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetMedium() { public void testSetMedium() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
buf.setMedium(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setMedium(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetLong() { public void testSetLong() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
buf.setLong(0, 1); assertThrows(ReadOnlyBufferException.class, () -> buf.setLong(0, 1));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesViaArray() { public void testSetBytesViaArray() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
buf.setBytes(0, "test".getBytes()); assertThrows(ReadOnlyBufferException.class, () -> buf.setBytes(0, "test".getBytes()));
} finally { } finally {
buf.release(); buf.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesViaBuffer() { public void testSetBytesViaBuffer() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
ByteBuf copy = Unpooled.copyInt(1); ByteBuf copy = Unpooled.copyInt(1);
try { try {
buf.setBytes(0, copy); assertThrows(ReadOnlyBufferException.class, () -> buf.setBytes(0, copy));
} finally { } finally {
buf.release(); buf.release();
copy.release(); copy.release();
} }
} }
@Test(expected = ReadOnlyBufferException.class) @Test
public void testSetBytesViaStream() throws IOException { public void testSetBytesViaStream() throws IOException {
ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer()); ByteBuf buf = buffer(ByteBuffer.allocateDirect(8).asReadOnlyBuffer());
try { try {
buf.setBytes(0, new ByteArrayInputStream("test".getBytes()), 2); assertThrows(ReadOnlyBufferException.class,
() -> buf.setBytes(0, new ByteArrayInputStream("test".getBytes()), 2));
} finally { } finally {
buf.release(); buf.release();
} }
@ -189,12 +195,12 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer( ByteBuf buf = buffer(
((ByteBuffer) allocate(2).put(new byte[] { (byte) 1, (byte) 2 }).flip()).asReadOnlyBuffer()); ((ByteBuffer) allocate(2).put(new byte[] { (byte) 1, (byte) 2 }).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getByte(0)); assertEquals(1, buf.getByte(0));
Assert.assertEquals(2, buf.getByte(1)); assertEquals(2, buf.getByte(1));
Assert.assertEquals(1, buf.readByte()); assertEquals(1, buf.readByte());
Assert.assertEquals(2, buf.readByte()); assertEquals(2, buf.readByte());
Assert.assertFalse(buf.isReadable()); assertFalse(buf.isReadable());
buf.release(); buf.release();
} }
@ -203,12 +209,12 @@ public class ReadOnlyDirectByteBufferBufTest {
public void testGetReadInt() { public void testGetReadInt() {
ByteBuf buf = buffer(((ByteBuffer) allocate(8).putInt(1).putInt(2).flip()).asReadOnlyBuffer()); ByteBuf buf = buffer(((ByteBuffer) allocate(8).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getInt(0)); assertEquals(1, buf.getInt(0));
Assert.assertEquals(2, buf.getInt(4)); assertEquals(2, buf.getInt(4));
Assert.assertEquals(1, buf.readInt()); assertEquals(1, buf.readInt());
Assert.assertEquals(2, buf.readInt()); assertEquals(2, buf.readInt());
Assert.assertFalse(buf.isReadable()); assertFalse(buf.isReadable());
buf.release(); buf.release();
} }
@ -218,12 +224,12 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer(((ByteBuffer) allocate(8) ByteBuf buf = buffer(((ByteBuffer) allocate(8)
.putShort((short) 1).putShort((short) 2).flip()).asReadOnlyBuffer()); .putShort((short) 1).putShort((short) 2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getShort(0)); assertEquals(1, buf.getShort(0));
Assert.assertEquals(2, buf.getShort(2)); assertEquals(2, buf.getShort(2));
Assert.assertEquals(1, buf.readShort()); assertEquals(1, buf.readShort());
Assert.assertEquals(2, buf.readShort()); assertEquals(2, buf.readShort());
Assert.assertFalse(buf.isReadable()); assertFalse(buf.isReadable());
buf.release(); buf.release();
} }
@ -233,17 +239,17 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer(((ByteBuffer) allocate(16) ByteBuf buf = buffer(((ByteBuffer) allocate(16)
.putLong(1).putLong(2).flip()).asReadOnlyBuffer()); .putLong(1).putLong(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.getLong(0)); assertEquals(1, buf.getLong(0));
Assert.assertEquals(2, buf.getLong(8)); assertEquals(2, buf.getLong(8));
Assert.assertEquals(1, buf.readLong()); assertEquals(1, buf.readLong());
Assert.assertEquals(2, buf.readLong()); assertEquals(2, buf.readLong());
Assert.assertFalse(buf.isReadable()); assertFalse(buf.isReadable());
buf.release(); buf.release();
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testGetBytesByteBuffer() { public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is in the ByteBuf. // Ensure destination buffer is bigger then what is in the ByteBuf.
@ -251,7 +257,7 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buffer = buffer(((ByteBuffer) allocate(bytes.length) ByteBuf buffer = buffer(((ByteBuffer) allocate(bytes.length)
.put(bytes).flip()).asReadOnlyBuffer()); .put(bytes).flip()).asReadOnlyBuffer());
try { try {
buffer.getBytes(buffer.readerIndex(), nioBuffer); assertThrows(IndexOutOfBoundsException.class, () -> buffer.getBytes(buffer.readerIndex(), nioBuffer));
} finally { } finally {
buffer.release(); buffer.release();
} }
@ -262,7 +268,7 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy(); ByteBuf copy = buf.copy();
Assert.assertEquals(buf, copy); assertEquals(buf, copy);
buf.release(); buf.release();
copy.release(); copy.release();
@ -273,7 +279,7 @@ public class ReadOnlyDirectByteBufferBufTest {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer()); ByteBuf buf = buffer(((ByteBuffer) allocate(16).putLong(1).putLong(2).flip()).asReadOnlyBuffer());
ByteBuf copy = buf.copy(1, 9); ByteBuf copy = buf.copy(1, 9);
Assert.assertEquals(buf.slice(1, 9), copy); assertEquals(buf.slice(1, 9), copy);
buf.release(); buf.release();
copy.release(); copy.release();
@ -286,7 +292,7 @@ public class ReadOnlyDirectByteBufferBufTest {
.putLong(1).flip().position(1)).asReadOnlyBuffer()); .putLong(1).flip().position(1)).asReadOnlyBuffer());
ByteBuf slice = buf.slice(); ByteBuf slice = buf.slice();
Assert.assertEquals(buf, slice); assertEquals(buf, slice);
buf.release(); buf.release();
} }
@ -295,12 +301,12 @@ public class ReadOnlyDirectByteBufferBufTest {
public void testWrapBufferRoundTrip() { public void testWrapBufferRoundTrip() {
ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer()); ByteBuf buf = buffer(((ByteBuffer) allocate(16).putInt(1).putInt(2).flip()).asReadOnlyBuffer());
Assert.assertEquals(1, buf.readInt()); assertEquals(1, buf.readInt());
ByteBuffer nioBuffer = buf.nioBuffer(); ByteBuffer nioBuffer = buf.nioBuffer();
// Ensure this can be accessed without throwing a BufferUnderflowException // Ensure this can be accessed without throwing a BufferUnderflowException
Assert.assertEquals(2, nioBuffer.getInt()); assertEquals(2, nioBuffer.getInt());
buf.release(); buf.release();
} }
@ -330,7 +336,7 @@ public class ReadOnlyDirectByteBufferBufTest {
b2 = buffer(dup); b2 = buffer(dup);
Assert.assertEquals(b2, b1.slice(2, 2)); assertEquals(b2, b1.slice(2, 2));
} finally { } finally {
if (b1 != null) { if (b1 != null) {
b1.release(); b1.release();
@ -352,10 +358,10 @@ public class ReadOnlyDirectByteBufferBufTest {
public void testMemoryAddress() { public void testMemoryAddress() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
Assert.assertFalse(buf.hasMemoryAddress()); assertFalse(buf.hasMemoryAddress());
try { try {
buf.memoryAddress(); buf.memoryAddress();
Assert.fail(); fail();
} catch (UnsupportedOperationException expected) { } catch (UnsupportedOperationException expected) {
// expected // expected
} }

View File

@ -16,22 +16,22 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assert; import org.junit.jupiter.api.BeforeAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import static org.junit.Assume.assumeTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
public class ReadOnlyUnsafeDirectByteBufferBufTest extends ReadOnlyDirectByteBufferBufTest { public class ReadOnlyUnsafeDirectByteBufferBufTest extends ReadOnlyDirectByteBufferBufTest {
/** /**
* Needs unsafe to run * Needs unsafe to run
*/ */
@BeforeClass @BeforeAll
public static void assumeConditions() { public static void assumeConditions() {
assumeTrue("sun.misc.Unsafe not found, skip tests", PlatformDependent.hasUnsafe()); assumeTrue(PlatformDependent.hasUnsafe(), "sun.misc.Unsafe not found, skip tests");
} }
@Override @Override
@ -44,7 +44,7 @@ public class ReadOnlyUnsafeDirectByteBufferBufTest extends ReadOnlyDirectByteBuf
public void testMemoryAddress() { public void testMemoryAddress() {
ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer()); ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
try { try {
Assert.assertTrue(buf.hasMemoryAddress()); assertTrue(buf.hasMemoryAddress());
buf.memoryAddress(); buf.memoryAddress();
} finally { } finally {
buf.release(); buf.release();

View File

@ -16,7 +16,7 @@
package io.netty.buffer; package io.netty.buffer;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
public class RetainedDuplicatedByteBufTest extends DuplicatedByteBufTest { public class RetainedDuplicatedByteBufTest extends DuplicatedByteBufTest {
@Override @Override

View File

@ -16,8 +16,7 @@
package io.netty.buffer; package io.netty.buffer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Assert;
public class RetainedSlicedByteBufTest extends SlicedByteBufTest { public class RetainedSlicedByteBufTest extends SlicedByteBufTest {
@ -25,7 +24,7 @@ public class RetainedSlicedByteBufTest extends SlicedByteBufTest {
protected ByteBuf newSlice(ByteBuf buffer, int offset, int length) { protected ByteBuf newSlice(ByteBuf buffer, int offset, int length) {
ByteBuf slice = buffer.retainedSlice(offset, length); ByteBuf slice = buffer.retainedSlice(offset, length);
buffer.release(); buffer.release();
Assert.assertEquals(buffer.refCnt(), slice.refCnt()); assertEquals(buffer.refCnt(), slice.refCnt());
return slice; return slice;
} }
} }

View File

@ -16,15 +16,15 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.ResourceLeakTracker; import io.netty.util.ResourceLeakTracker;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Queue; import java.util.Queue;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class SimpleLeakAwareByteBufTest extends BigEndianHeapByteBufTest { public class SimpleLeakAwareByteBufTest extends BigEndianHeapByteBufTest {
private final Class<? extends ByteBuf> clazz = leakClass(); private final Class<? extends ByteBuf> clazz = leakClass();
@ -46,14 +46,14 @@ public class SimpleLeakAwareByteBufTest extends BigEndianHeapByteBufTest {
return new SimpleLeakAwareByteBuf(buffer, tracker); return new SimpleLeakAwareByteBuf(buffer, tracker);
} }
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
super.init(); super.init();
trackers.clear(); trackers.clear();
} }
@After @AfterEach
@Override @Override
public void dispose() { public void dispose() {
super.dispose(); super.dispose();

View File

@ -17,17 +17,17 @@ package io.netty.buffer;
import io.netty.util.ResourceLeakTracker; import io.netty.util.ResourceLeakTracker;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Queue; import java.util.Queue;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class SimpleLeakAwareCompositeByteBufTest extends WrappedCompositeByteBufTest { public class SimpleLeakAwareCompositeByteBufTest extends WrappedCompositeByteBufTest {
@ -46,14 +46,14 @@ public class SimpleLeakAwareCompositeByteBufTest extends WrappedCompositeByteBuf
return new SimpleLeakAwareCompositeByteBuf(buffer, tracker); return new SimpleLeakAwareCompositeByteBuf(buffer, tracker);
} }
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
super.init(); super.init();
trackers.clear(); trackers.clear();
} }
@After @AfterEach
@Override @Override
public void dispose() { public void dispose() {
super.dispose(); super.dispose();

View File

@ -15,17 +15,17 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Tests sliced channel buffers * Tests sliced channel buffers
@ -34,7 +34,7 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
@Override @Override
protected final ByteBuf newBuffer(int length, int maxCapacity) { protected final ByteBuf newBuffer(int length, int maxCapacity) {
Assume.assumeTrue(maxCapacity == Integer.MAX_VALUE); Assumptions.assumeTrue(maxCapacity == Integer.MAX_VALUE);
int offset = length == 0 ? 0 : ThreadLocalRandom.current().nextInt(length); int offset = length == 0 ? 0 : ThreadLocalRandom.current().nextInt(length);
ByteBuf buffer = Unpooled.buffer(length * 2); ByteBuf buffer = Unpooled.buffer(length * 2);
ByteBuf slice = newSlice(buffer, offset, length); ByteBuf slice = newSlice(buffer, offset, length);
@ -54,69 +54,69 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
buf.release(); buf.release();
} }
@Test(expected = NullPointerException.class) @Test
public void shouldNotAllowNullInConstructor() { public void shouldNotAllowNullInConstructor() {
new SlicedByteBuf(null, 0, 0); assertThrows(NullPointerException.class, () -> new SlicedByteBuf(null, 0, 0));
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testInternalNioBuffer() { public void testInternalNioBuffer() {
super.testInternalNioBuffer(); assertThrows(IndexOutOfBoundsException.class, super::testInternalNioBuffer);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testDuplicateReadGatheringByteChannelMultipleThreads() throws Exception { public void testDuplicateReadGatheringByteChannelMultipleThreads() {
super.testDuplicateReadGatheringByteChannelMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testDuplicateReadGatheringByteChannelMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testSliceReadGatheringByteChannelMultipleThreads() throws Exception { public void testSliceReadGatheringByteChannelMultipleThreads() {
super.testSliceReadGatheringByteChannelMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testSliceReadGatheringByteChannelMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testDuplicateReadOutputStreamMultipleThreads() throws Exception { public void testDuplicateReadOutputStreamMultipleThreads() {
super.testDuplicateReadOutputStreamMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testDuplicateReadOutputStreamMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testSliceReadOutputStreamMultipleThreads() throws Exception { public void testSliceReadOutputStreamMultipleThreads() {
super.testSliceReadOutputStreamMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testSliceReadOutputStreamMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testDuplicateBytesInArrayMultipleThreads() throws Exception { public void testDuplicateBytesInArrayMultipleThreads() {
super.testDuplicateBytesInArrayMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testDuplicateBytesInArrayMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testSliceBytesInArrayMultipleThreads() throws Exception { public void testSliceBytesInArrayMultipleThreads() {
super.testSliceBytesInArrayMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testSliceBytesInArrayMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testNioBufferExposeOnlyRegion() { public void testNioBufferExposeOnlyRegion() {
super.testNioBufferExposeOnlyRegion(); assertThrows(IndexOutOfBoundsException.class, super::testNioBufferExposeOnlyRegion);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testGetReadOnlyDirectDst() { public void testGetReadOnlyDirectDst() {
super.testGetReadOnlyDirectDst(); assertThrows(IndexOutOfBoundsException.class, super::testGetReadOnlyDirectDst);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testGetReadOnlyHeapDst() { public void testGetReadOnlyHeapDst() {
super.testGetReadOnlyHeapDst(); assertThrows(IndexOutOfBoundsException.class, super::testGetReadOnlyHeapDst);
} }
@Test @Test
@ -143,12 +143,12 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
// Ignore for SlicedByteBuf // Ignore for SlicedByteBuf
} }
@Ignore("Sliced ByteBuf objects don't allow the capacity to change. So this test would fail and shouldn't be run") @Disabled("Sliced ByteBuf objects don't allow the capacity to change. So this test would fail and shouldn't be run")
@Override @Override
public void testDuplicateCapacityChange() { public void testDuplicateCapacityChange() {
} }
@Ignore("Sliced ByteBuf objects don't allow the capacity to change. So this test would fail and shouldn't be run") @Disabled("Sliced ByteBuf objects don't allow the capacity to change. So this test would fail and shouldn't be run")
@Override @Override
public void testRetainedDuplicateCapacityChange() { public void testRetainedDuplicateCapacityChange() {
} }
@ -199,41 +199,42 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
} }
@Override @Override
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testGetBytesByteBuffer() { public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is wrapped in the ByteBuf. // Ensure destination buffer is bigger then what is wrapped in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1); ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bytes).slice(0, bytes.length - 1); ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bytes).slice(0, bytes.length - 1);
try { try {
wrappedBuffer.getBytes(wrappedBuffer.readerIndex(), nioBuffer); assertThrows(IndexOutOfBoundsException.class,
() -> wrappedBuffer.getBytes(wrappedBuffer.readerIndex(), nioBuffer));
} finally { } finally {
wrappedBuffer.release(); wrappedBuffer.release();
} }
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteUsAsciiCharSequenceExpand() { public void testWriteUsAsciiCharSequenceExpand() {
super.testWriteUsAsciiCharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteUsAsciiCharSequenceExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteUtf8CharSequenceExpand() { public void testWriteUtf8CharSequenceExpand() {
super.testWriteUtf8CharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteUtf8CharSequenceExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteIso88591CharSequenceExpand() { public void testWriteIso88591CharSequenceExpand() {
super.testWriteIso88591CharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteIso88591CharSequenceExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteUtf16CharSequenceExpand() { public void testWriteUtf16CharSequenceExpand() {
super.testWriteUtf16CharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteUtf16CharSequenceExpand);
} }
@Test @Test
@ -252,14 +253,13 @@ public class SlicedByteBufTest extends AbstractByteBufTest {
slice.release(); slice.release();
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void ensureWritableWithNotEnoughSpaceShouldThrow() { public void ensureWritableWithNotEnoughSpaceShouldThrow() {
ByteBuf slice = newBuffer(10); ByteBuf slice = newBuffer(10);
ByteBuf unwrapped = slice.unwrap(); ByteBuf unwrapped = slice.unwrap();
unwrapped.writerIndex(unwrapped.writerIndex() + 5); unwrapped.writerIndex(unwrapped.writerIndex() + 5);
try { try {
slice.ensureWritable(1); assertThrows(IndexOutOfBoundsException.class, () -> slice.ensureWritable(1));
fail();
} finally { } finally {
slice.release(); slice.release();
} }

View File

@ -16,7 +16,7 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import java.io.InputStream; import java.io.InputStream;
@ -31,7 +31,12 @@ import java.util.Map.Entry;
import static io.netty.buffer.Unpooled.*; import static io.netty.buffer.Unpooled.*;
import static io.netty.util.internal.EmptyArrays.*; import static io.netty.util.internal.EmptyArrays.*;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/** /**
* Tests channel buffers * Tests channel buffers
@ -694,11 +699,11 @@ public class UnpooledTest {
wrapped.release(); wrapped.release();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void skipBytesNegativeLength() { public void skipBytesNegativeLength() {
ByteBuf buf = buffer(8); ByteBuf buf = buffer(8);
try { try {
buf.skipBytes(-1); assertThrows(IllegalArgumentException.class, () -> buf.skipBytes(-1));
} finally { } finally {
buf.release(); buf.release();
} }
@ -722,27 +727,29 @@ public class UnpooledTest {
assertEquals(0, wrapped.refCnt()); assertEquals(0, wrapped.refCnt());
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testGetBytesByteBuffer() { public void testGetBytesByteBuffer() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is wrapped in the ByteBuf. // Ensure destination buffer is bigger then what is wrapped in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1); ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf wrappedBuffer = wrappedBuffer(bytes); ByteBuf wrappedBuffer = wrappedBuffer(bytes);
try { try {
wrappedBuffer.getBytes(wrappedBuffer.readerIndex(), nioBuffer); assertThrows(IndexOutOfBoundsException.class,
() -> wrappedBuffer.getBytes(wrappedBuffer.readerIndex(), nioBuffer));
} finally { } finally {
wrappedBuffer.release(); wrappedBuffer.release();
} }
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testGetBytesByteBuffer2() { public void testGetBytesByteBuffer2() {
byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; byte[] bytes = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
// Ensure destination buffer is bigger then what is wrapped in the ByteBuf. // Ensure destination buffer is bigger then what is wrapped in the ByteBuf.
ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1); ByteBuffer nioBuffer = ByteBuffer.allocate(bytes.length + 1);
ByteBuf wrappedBuffer = wrappedBuffer(bytes, 0, bytes.length); ByteBuf wrappedBuffer = wrappedBuffer(bytes, 0, bytes.length);
try { try {
wrappedBuffer.getBytes(wrappedBuffer.readerIndex(), nioBuffer); assertThrows(IndexOutOfBoundsException.class,
() -> wrappedBuffer.getBytes(wrappedBuffer.readerIndex(), nioBuffer));
} finally { } finally {
wrappedBuffer.release(); wrappedBuffer.release();
} }

View File

@ -15,13 +15,13 @@
*/ */
package io.netty.buffer; package io.netty.buffer;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static io.netty.buffer.Unpooled.buffer; import static io.netty.buffer.Unpooled.buffer;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
public class UnreleaseableByteBufTest { public class UnreleaseableByteBufTest {

View File

@ -16,21 +16,22 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import static io.netty.util.internal.PlatformDependent.directBufferAddress; import static io.netty.util.internal.PlatformDependent.directBufferAddress;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class UnsafeByteBufUtilTest { public class UnsafeByteBufUtilTest {
@Before @BeforeEach
public void checkHasUnsafe() { public void checkHasUnsafe() {
Assume.assumeTrue("sun.misc.Unsafe not found, skip tests", PlatformDependent.hasUnsafe()); Assumptions.assumeTrue(PlatformDependent.hasUnsafe(), "sun.misc.Unsafe not found, skip tests");
} }
@Test @Test
@ -49,7 +50,7 @@ public class UnsafeByteBufUtilTest {
byte[] check = new byte[length]; byte[] check = new byte[length];
targetBuffer.getBytes(0, check, 0, length); targetBuffer.getBytes(0, check, 0, length);
assertArrayEquals("The byte array's copy does not equal the original", testData, check); assertArrayEquals(testData, check, "The byte array's copy does not equal the original");
} finally { } finally {
targetBuffer.release(); targetBuffer.release();
} }
@ -82,7 +83,7 @@ public class UnsafeByteBufUtilTest {
byte[] check = new byte[length]; byte[] check = new byte[length];
targetBuffer.getBytes(0, check, 0, length); targetBuffer.getBytes(0, check, 0, length);
assertArrayEquals("The byte array's copy does not equal the original", testData, check); assertArrayEquals(testData, check, "The byte array's copy does not equal the original");
} finally { } finally {
targetBuffer.release(); targetBuffer.release();
b1.release(); b1.release();
@ -105,7 +106,7 @@ public class UnsafeByteBufUtilTest {
final byte[] check = new byte[length]; final byte[] check = new byte[length];
targetBuffer.getBytes(0, check, 0, length); targetBuffer.getBytes(0, check, 0, length);
assertArrayEquals("The byte array's copy does not equal the original", testData, check); assertArrayEquals(testData, check, "The byte array's copy does not equal the original");
} finally { } finally {
targetBuffer.release(); targetBuffer.release();
} }
@ -135,60 +136,74 @@ public class UnsafeByteBufUtilTest {
} }
} }
@Test(expected = NullPointerException.class) @Test
public void testSetBytesWithNullByteArray() { public void testSetBytesWithNullByteArray() {
final UnpooledByteBufAllocator alloc = new UnpooledByteBufAllocator(true); final UnpooledByteBufAllocator alloc = new UnpooledByteBufAllocator(true);
final UnpooledDirectByteBuf targetBuffer = new UnpooledDirectByteBuf(alloc, 8, 8); final UnpooledDirectByteBuf targetBuffer = new UnpooledDirectByteBuf(alloc, 8, 8);
try { try {
UnsafeByteBufUtil.setBytes(targetBuffer, assertThrows(NullPointerException.class, () -> UnsafeByteBufUtil.setBytes(targetBuffer,
directBufferAddress(targetBuffer.nioBuffer()), 0, (byte[]) null, 0, 8); directBufferAddress(targetBuffer.nioBuffer()), 0, (byte[]) null, 0, 8));
} finally { } finally {
targetBuffer.release(); targetBuffer.release();
} }
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds() { public void testSetBytesOutOfBounds() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// negative index // negative index
testSetBytesOutOfBounds0(4, 4, -1, 0, 4); testSetBytesOutOfBounds0(4, 4, -1, 0, 4);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds2() { public void testSetBytesOutOfBounds2() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// negative length // negative length
testSetBytesOutOfBounds0(4, 4, 0, 0, -1); testSetBytesOutOfBounds0(4, 4, 0, 0, -1);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds3() { public void testSetBytesOutOfBounds3() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// buffer length oversize // buffer length oversize
testSetBytesOutOfBounds0(4, 8, 0, 0, 5); testSetBytesOutOfBounds0(4, 8, 0, 0, 5);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds4() { public void testSetBytesOutOfBounds4() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// buffer length oversize // buffer length oversize
testSetBytesOutOfBounds0(4, 4, 3, 0, 3); testSetBytesOutOfBounds0(4, 4, 3, 0, 3);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds5() { public void testSetBytesOutOfBounds5() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// negative srcIndex // negative srcIndex
testSetBytesOutOfBounds0(4, 4, 0, -1, 4); testSetBytesOutOfBounds0(4, 4, 0, -1, 4);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds6() { public void testSetBytesOutOfBounds6() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// src length oversize // src length oversize
testSetBytesOutOfBounds0(8, 4, 0, 0, 5); testSetBytesOutOfBounds0(8, 4, 0, 0, 5);
});
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void testSetBytesOutOfBounds7() { public void testSetBytesOutOfBounds7() {
assertThrows(IndexOutOfBoundsException.class, () -> {
// src length oversize // src length oversize
testSetBytesOutOfBounds0(4, 4, 0, 1, 4); testSetBytesOutOfBounds0(4, 4, 0, 1, 4);
});
} }
private static void testSetBytesOutOfBounds0(int lengthOfBuffer, private static void testSetBytesOutOfBounds0(int lengthOfBuffer,

View File

@ -16,134 +16,136 @@
package io.netty.buffer; package io.netty.buffer;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
import org.junit.Assume; import org.junit.jupiter.api.Assumptions;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class WrappedUnpooledUnsafeByteBufTest extends BigEndianUnsafeDirectByteBufTest { public class WrappedUnpooledUnsafeByteBufTest extends BigEndianUnsafeDirectByteBufTest {
@Before @BeforeEach
@Override @Override
public void init() { public void init() {
Assume.assumeTrue("PlatformDependent.useDirectBufferNoCleaner() returned false, skip tests", Assumptions.assumeTrue(PlatformDependent.useDirectBufferNoCleaner(),
PlatformDependent.useDirectBufferNoCleaner()); "PlatformDependent.useDirectBufferNoCleaner() returned false, skip tests");
super.init(); super.init();
} }
@Override @Override
protected ByteBuf newBuffer(int length, int maxCapacity) { protected ByteBuf newBuffer(int length, int maxCapacity) {
Assume.assumeTrue(maxCapacity == Integer.MAX_VALUE); Assumptions.assumeTrue(maxCapacity == Integer.MAX_VALUE);
return new WrappedUnpooledUnsafeDirectByteBuf(UnpooledByteBufAllocator.DEFAULT, return new WrappedUnpooledUnsafeDirectByteBuf(UnpooledByteBufAllocator.DEFAULT,
PlatformDependent.allocateMemory(length), length, true); PlatformDependent.allocateMemory(length), length, true);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testInternalNioBuffer() { public void testInternalNioBuffer() {
super.testInternalNioBuffer(); assertThrows(IndexOutOfBoundsException.class, super::testInternalNioBuffer);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testDuplicateReadGatheringByteChannelMultipleThreads() throws Exception { public void testDuplicateReadGatheringByteChannelMultipleThreads() {
super.testDuplicateReadGatheringByteChannelMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testDuplicateReadGatheringByteChannelMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testSliceReadGatheringByteChannelMultipleThreads() throws Exception { public void testSliceReadGatheringByteChannelMultipleThreads() {
super.testSliceReadGatheringByteChannelMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testSliceReadGatheringByteChannelMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testDuplicateReadOutputStreamMultipleThreads() throws Exception { public void testDuplicateReadOutputStreamMultipleThreads() {
super.testDuplicateReadOutputStreamMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testDuplicateReadOutputStreamMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testSliceReadOutputStreamMultipleThreads() throws Exception { public void testSliceReadOutputStreamMultipleThreads() {
super.testSliceReadOutputStreamMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testSliceReadOutputStreamMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testDuplicateBytesInArrayMultipleThreads() throws Exception { public void testDuplicateBytesInArrayMultipleThreads() {
super.testDuplicateBytesInArrayMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testDuplicateBytesInArrayMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testSliceBytesInArrayMultipleThreads() throws Exception { public void testSliceBytesInArrayMultipleThreads() {
super.testSliceBytesInArrayMultipleThreads(); assertThrows(IndexOutOfBoundsException.class, super::testSliceBytesInArrayMultipleThreads);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testNioBufferExposeOnlyRegion() { public void testNioBufferExposeOnlyRegion() {
super.testNioBufferExposeOnlyRegion(); assertThrows(IndexOutOfBoundsException.class, super::testNioBufferExposeOnlyRegion);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testGetReadOnlyDirectDst() { public void testGetReadOnlyDirectDst() {
super.testGetReadOnlyDirectDst(); assertThrows(IndexOutOfBoundsException.class, super::testGetReadOnlyDirectDst);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testGetReadOnlyHeapDst() { public void testGetReadOnlyHeapDst() {
super.testGetReadOnlyHeapDst(); assertThrows(IndexOutOfBoundsException.class, super::testGetReadOnlyHeapDst);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testReadBytes() { public void testReadBytes() {
super.testReadBytes(); assertThrows(IndexOutOfBoundsException.class, super::testReadBytes);
} }
@Test(expected = IllegalArgumentException.class) @Test
@Override @Override
public void testDuplicateCapacityChange() { public void testDuplicateCapacityChange() {
super.testDuplicateCapacityChange(); assertThrows(IllegalArgumentException.class, super::testDuplicateCapacityChange);
} }
@Test(expected = IllegalArgumentException.class) @Test
@Override @Override
public void testRetainedDuplicateCapacityChange() { public void testRetainedDuplicateCapacityChange() {
super.testRetainedDuplicateCapacityChange(); assertThrows(IllegalArgumentException.class, super::testRetainedDuplicateCapacityChange);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testLittleEndianWithExpand() { public void testLittleEndianWithExpand() {
super.testLittleEndianWithExpand(); assertThrows(IndexOutOfBoundsException.class, super::testLittleEndianWithExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteUsAsciiCharSequenceExpand() { public void testWriteUsAsciiCharSequenceExpand() {
super.testWriteUsAsciiCharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteUsAsciiCharSequenceExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteUtf8CharSequenceExpand() { public void testWriteUtf8CharSequenceExpand() {
super.testWriteUtf8CharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteUtf8CharSequenceExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteIso88591CharSequenceExpand() { public void testWriteIso88591CharSequenceExpand() {
super.testWriteIso88591CharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteIso88591CharSequenceExpand);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
@Override @Override
public void testWriteUtf16CharSequenceExpand() { public void testWriteUtf16CharSequenceExpand() {
super.testWriteUtf16CharSequenceExpand(); assertThrows(IndexOutOfBoundsException.class, super::testWriteUtf16CharSequenceExpand);
} }
@Test @Test

View File

@ -15,7 +15,9 @@
*/ */
package io.netty.buffer.search; package io.netty.buffer.search;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class BitapSearchProcessorFactoryTest { public class BitapSearchProcessorFactoryTest {
@ -24,9 +26,9 @@ public class BitapSearchProcessorFactoryTest {
new BitapSearchProcessorFactory(new byte[64]); new BitapSearchProcessorFactory(new byte[64]);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectTooLongNeedle() { public void testRejectTooLongNeedle() {
new BitapSearchProcessorFactory(new byte[65]); assertThrows(IllegalArgumentException.class, () -> new BitapSearchProcessorFactory(new byte[65]));
} }
} }

View File

@ -18,9 +18,9 @@ package io.netty.buffer.search;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
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 MultiSearchProcessorTest { public class MultiSearchProcessorTest {

View File

@ -18,17 +18,13 @@ package io.netty.buffer.search;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled; import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.runner.RunWith; import org.junit.jupiter.params.provider.EnumSource;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(Parameterized.class)
public class SearchProcessorTest { public class SearchProcessorTest {
private enum Algorithm { private enum Algorithm {
@ -53,54 +49,48 @@ public class SearchProcessorTest {
abstract SearchProcessorFactory newFactory(byte[] needle); abstract SearchProcessorFactory newFactory(byte[] needle);
} }
@Parameters(name = "{0} algorithm") @ParameterizedTest
public static Object[] algorithms() { @EnumSource(Algorithm.class)
return Algorithm.values(); public void testSearch(Algorithm algorithm) {
}
@Parameter
public Algorithm algorithm;
@Test
public void testSearch() {
final ByteBuf haystack = Unpooled.copiedBuffer("abc☺", CharsetUtil.UTF_8); final ByteBuf haystack = Unpooled.copiedBuffer("abc☺", CharsetUtil.UTF_8);
assertEquals(0, haystack.forEachByte(factory("a").newSearchProcessor())); assertEquals(0, haystack.forEachByte(factory(algorithm, "a").newSearchProcessor()));
assertEquals(1, haystack.forEachByte(factory("ab").newSearchProcessor())); assertEquals(1, haystack.forEachByte(factory(algorithm, "ab").newSearchProcessor()));
assertEquals(2, haystack.forEachByte(factory("abc").newSearchProcessor())); assertEquals(2, haystack.forEachByte(factory(algorithm, "abc").newSearchProcessor()));
assertEquals(5, haystack.forEachByte(factory("abc☺").newSearchProcessor())); assertEquals(5, haystack.forEachByte(factory(algorithm, "abc☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("abc☺☺").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "abc☺☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("abc☺x").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "abc☺x").newSearchProcessor()));
assertEquals(1, haystack.forEachByte(factory("b").newSearchProcessor())); assertEquals(1, haystack.forEachByte(factory(algorithm, "b").newSearchProcessor()));
assertEquals(2, haystack.forEachByte(factory("bc").newSearchProcessor())); assertEquals(2, haystack.forEachByte(factory(algorithm, "bc").newSearchProcessor()));
assertEquals(5, haystack.forEachByte(factory("bc☺").newSearchProcessor())); assertEquals(5, haystack.forEachByte(factory(algorithm, "bc☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("bc☺☺").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "bc☺☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("bc☺x").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "bc☺x").newSearchProcessor()));
assertEquals(2, haystack.forEachByte(factory("c").newSearchProcessor())); assertEquals(2, haystack.forEachByte(factory(algorithm, "c").newSearchProcessor()));
assertEquals(5, haystack.forEachByte(factory("c☺").newSearchProcessor())); assertEquals(5, haystack.forEachByte(factory(algorithm, "c☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("c☺☺").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "c☺☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("c☺x").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "c☺x").newSearchProcessor()));
assertEquals(5, haystack.forEachByte(factory("").newSearchProcessor())); assertEquals(5, haystack.forEachByte(factory(algorithm, "").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("☺☺").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "☺☺").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("☺x").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "☺x").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("z").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "z").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("aa").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "aa").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("ba").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "ba").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("abcd").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "abcd").newSearchProcessor()));
assertEquals(-1, haystack.forEachByte(factory("abcde").newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, "abcde").newSearchProcessor()));
haystack.release(); haystack.release();
} }
@Test @ParameterizedTest
public void testRepeating() { @EnumSource(Algorithm.class)
public void testRepeating(Algorithm algorithm) {
final ByteBuf haystack = Unpooled.copiedBuffer("abcababc", CharsetUtil.UTF_8); final ByteBuf haystack = Unpooled.copiedBuffer("abcababc", CharsetUtil.UTF_8);
final int length = haystack.readableBytes(); final int length = haystack.readableBytes();
SearchProcessor processor = factory("ab").newSearchProcessor(); SearchProcessor processor = factory(algorithm, "ab").newSearchProcessor();
assertEquals(1, haystack.forEachByte(processor)); assertEquals(1, haystack.forEachByte(processor));
assertEquals(4, haystack.forEachByte(2, length - 2, processor)); assertEquals(4, haystack.forEachByte(2, length - 2, processor));
@ -110,11 +100,12 @@ public class SearchProcessorTest {
haystack.release(); haystack.release();
} }
@Test @ParameterizedTest
public void testOverlapping() { @EnumSource(Algorithm.class)
public void testOverlapping(Algorithm algorithm) {
final ByteBuf haystack = Unpooled.copiedBuffer("ababab", CharsetUtil.UTF_8); final ByteBuf haystack = Unpooled.copiedBuffer("ababab", CharsetUtil.UTF_8);
final int length = haystack.readableBytes(); final int length = haystack.readableBytes();
SearchProcessor processor = factory("bab").newSearchProcessor(); SearchProcessor processor = factory(algorithm, "bab").newSearchProcessor();
assertEquals(3, haystack.forEachByte(processor)); assertEquals(3, haystack.forEachByte(processor));
assertEquals(5, haystack.forEachByte(4, length - 4, processor)); assertEquals(5, haystack.forEachByte(4, length - 4, processor));
@ -123,8 +114,9 @@ public class SearchProcessorTest {
haystack.release(); haystack.release();
} }
@Test @ParameterizedTest
public void testLongInputs() { @EnumSource(Algorithm.class)
public void testLongInputs(Algorithm algorithm) {
final int haystackLen = 1024; final int haystackLen = 1024;
final int needleLen = 64; final int needleLen = 64;
@ -133,21 +125,22 @@ public class SearchProcessorTest {
final ByteBuf haystack = Unpooled.copiedBuffer(haystackBytes); // 00000...00001 final ByteBuf haystack = Unpooled.copiedBuffer(haystackBytes); // 00000...00001
final byte[] needleBytes = new byte[needleLen]; // 000...000 final byte[] needleBytes = new byte[needleLen]; // 000...000
assertEquals(needleLen - 1, haystack.forEachByte(factory(needleBytes).newSearchProcessor())); assertEquals(needleLen - 1, haystack.forEachByte(factory(algorithm, needleBytes).newSearchProcessor()));
needleBytes[needleLen - 1] = 1; // 000...001 needleBytes[needleLen - 1] = 1; // 000...001
assertEquals(haystackLen - 1, haystack.forEachByte(factory(needleBytes).newSearchProcessor())); assertEquals(haystackLen - 1, haystack.forEachByte(factory(algorithm, needleBytes).newSearchProcessor()));
needleBytes[needleLen - 1] = 2; // 000...002 needleBytes[needleLen - 1] = 2; // 000...002
assertEquals(-1, haystack.forEachByte(factory(needleBytes).newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, needleBytes).newSearchProcessor()));
needleBytes[needleLen - 1] = 0; needleBytes[needleLen - 1] = 0;
needleBytes[0] = 1; // 100...000 needleBytes[0] = 1; // 100...000
assertEquals(-1, haystack.forEachByte(factory(needleBytes).newSearchProcessor())); assertEquals(-1, haystack.forEachByte(factory(algorithm, needleBytes).newSearchProcessor()));
} }
@Test @ParameterizedTest
public void testUniqueLen64Substrings() { @EnumSource(Algorithm.class)
public void testUniqueLen64Substrings(Algorithm algorithm) {
final byte[] haystackBytes = new byte[32 * 65]; // 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, ... final byte[] haystackBytes = new byte[32 * 65]; // 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, ...
int pos = 0; int pos = 0;
for (int i = 1; i <= 64; i++) { for (int i = 1; i <= 64; i++) {
@ -159,16 +152,16 @@ public class SearchProcessorTest {
for (int start = 0; start < haystackBytes.length - 64; start++) { for (int start = 0; start < haystackBytes.length - 64; start++) {
final byte[] needle = Arrays.copyOfRange(haystackBytes, start, start + 64); final byte[] needle = Arrays.copyOfRange(haystackBytes, start, start + 64);
assertEquals(start + 63, haystack.forEachByte(factory(needle).newSearchProcessor())); assertEquals(start + 63, haystack.forEachByte(factory(algorithm, needle).newSearchProcessor()));
} }
} }
private SearchProcessorFactory factory(byte[] needle) { private SearchProcessorFactory factory(Algorithm algorithm, byte[] needle) {
return algorithm.newFactory(needle); return algorithm.newFactory(needle);
} }
private SearchProcessorFactory factory(String needle) { private SearchProcessorFactory factory(Algorithm algorithm, String needle) {
return factory(needle.getBytes(CharsetUtil.UTF_8)); return factory(algorithm, needle.getBytes(CharsetUtil.UTF_8));
} }
} }