|
23 | 23 | import static org.junit.jupiter.api.Assertions.assertNotNull; |
24 | 24 | import static org.junit.jupiter.api.Assertions.assertTrue; |
25 | 25 | import static org.junit.jupiter.api.Assumptions.assumeTrue; |
| 26 | +import static org.mockito.AdditionalAnswers.delegatesTo; |
| 27 | +import static org.mockito.ArgumentMatchers.any; |
| 28 | +import static org.mockito.Mockito.doAnswer; |
26 | 29 | import static org.mockito.Mockito.mock; |
27 | 30 | import static org.mockito.Mockito.when; |
28 | 31 |
|
29 | 32 | import java.io.File; |
30 | 33 | import java.io.IOException; |
| 34 | +import java.net.InetSocketAddress; |
| 35 | +import java.nio.ByteBuffer; |
31 | 36 | import java.util.ArrayList; |
32 | 37 | import java.util.List; |
33 | 38 | import java.util.Random; |
@@ -364,4 +369,43 @@ public Void answer(InvocationOnMock invocation) throws Throwable { |
364 | 369 | IOUtils.closeStream(out); |
365 | 370 | } |
366 | 371 | } |
| 372 | + |
| 373 | + @Test |
| 374 | + @Timeout(value = 60) |
| 375 | + public void testAvoidsEmptyBufferRead() throws IOException { |
| 376 | + Configuration conf = new Configuration(); |
| 377 | + try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build()) { |
| 378 | + DistributedFileSystem fs = cluster.getFileSystem(); |
| 379 | + DFSClient client = fs.getClient(); |
| 380 | + Path file = new Path("/preadFile"); |
| 381 | + int fileLength = 8192; |
| 382 | + DFSTestUtil.createFile(fs, file, fileLength, (short) 1, 0L); |
| 383 | + |
| 384 | + AtomicInteger emptyBufferReads = new AtomicInteger(0); |
| 385 | + try (DFSInputStream in = new DFSInputStream(client, file.toString(), |
| 386 | + true, null) { |
| 387 | + @Override |
| 388 | + protected BlockReader getBlockReader(LocatedBlock targetBlock, |
| 389 | + long offsetInBlock, long length, InetSocketAddress targetAddr, |
| 390 | + StorageType storageType, DatanodeInfo datanode) |
| 391 | + throws IOException { |
| 392 | + BlockReader real = super.getBlockReader(targetBlock, offsetInBlock, |
| 393 | + length, targetAddr, storageType, datanode); |
| 394 | + BlockReader wrapped = mock(BlockReader.class, delegatesTo(real)); |
| 395 | + doAnswer(inv -> { |
| 396 | + if (!((ByteBuffer) inv.getArgument(0)).hasRemaining()) { |
| 397 | + emptyBufferReads.incrementAndGet(); |
| 398 | + } |
| 399 | + return real.read(inv.getArgument(0)); |
| 400 | + }).when(wrapped).read(any(ByteBuffer.class)); |
| 401 | + return wrapped; |
| 402 | + } |
| 403 | + }) { |
| 404 | + byte[] dest = new byte[fileLength]; |
| 405 | + assertEquals(fileLength, in.read(0L, dest, 0, dest.length)); |
| 406 | + assertEquals(0, emptyBufferReads.get(), |
| 407 | + "DFSInputStream should not call BlockReader.read with an empty buffer"); |
| 408 | + } |
| 409 | + } |
| 410 | + } |
367 | 411 | } |
0 commit comments