lukecwik commented on a change in pull request #11397: [BEAM-9743] Fix 
TFRecordCodec to try harder to read/write
URL: https://github.com/apache/beam/pull/11397#discussion_r408996520
 
 

 ##########
 File path: 
sdks/java/core/src/test/java/org/apache/beam/sdk/io/TFRecordIOTest.java
 ##########
 @@ -440,4 +456,115 @@ public void processElement(ProcessContext c) {
       c.output(c.element().getBytes(Charsets.UTF_8));
     }
   }
+
+  static boolean maybeThisTime() {
+    return ThreadLocalRandom.current().nextBoolean();
+  }
+
+  static class PickyReadChannel extends FilterInputStream implements 
ReadableByteChannel {
+    protected PickyReadChannel(InputStream in) {
+      super(in);
+    }
+
+    @Override
+    public int read(byte[] b, int off, int len) {
+      throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public int read(ByteBuffer dst) throws IOException {
+      if (!maybeThisTime() || !dst.hasRemaining()) {
+        return 0;
+      }
+      int n = read();
+      if (n == -1) {
+        return -1;
+      }
+      dst.put((byte) n);
+      return 1;
+    }
+
+    @Override
+    public boolean isOpen() {
+      throw new UnsupportedOperationException();
+    }
+  }
+
+  static class PickyWriteChannel extends FilterOutputStream implements 
WritableByteChannel {
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+      throw new UnsupportedOperationException();
+    }
+
+    public PickyWriteChannel(OutputStream out) {
+      super(out);
+    }
+
+    @Override
+    public int write(ByteBuffer src) throws IOException {
+      if (!maybeThisTime() || !src.hasRemaining()) {
+        return 0;
+      }
+      write(src.get());
+      return 1;
+    }
+
+    @Override
+    public boolean isOpen() {
+      throw new UnsupportedOperationException();
+    }
+  }
+
+  @Test
+  public void testReadFully() throws IOException {
+    byte[] data = "Hello World".getBytes(StandardCharsets.UTF_8);
+    ReadableByteChannel chan = new PickyReadChannel(new 
ByteArrayInputStream(data));
+
+    ByteBuffer buffer = ByteBuffer.allocate(data.length);
+    TFRecordCodec.readFully(chan, buffer);
+
+    assertArrayEquals(data, buffer.array());
+  }
+
+  @Test(expected = IOException.class)
 
 Review comment:
   You want to ensure that the exception is because of having a truncated read 
so it is useful to check that the message contains a part of what you think it 
should have such as `expected` and `but got`. Check out 
https://junit.org/junit4/javadoc/4.12/org/junit/rules/ExpectedException.html or 
anything like it.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to