@Test
public void testRotateBucketOnIOException() throws IOException, InterruptedException {

  MockHDFSWriter hdfsWriter = Mockito.spy(new MockHDFSWriter());
  PrivilegedExecutor ugiProxy =
      FlumeAuthenticationUtil.getAuthenticator(null, null).proxyAs("alice");
  final int ROLL_COUNT = 1; // Cause a roll after every successful append().
  BucketWriter bucketWriter = new BucketWriterBuilder(hdfsWriter)
      .setProxyUser(ugiProxy)
      .setRollCount(ROLL_COUNT)
      .build();
  Event e = EventBuilder.withBody("foo", Charsets.UTF_8);
  // Write one event successfully.
  bucketWriter.append(e);
  // Fail the next write.
  IOException expectedIOException = new IOException("Test injected IOException");
  Mockito.doThrow(expectedIOException).when(hdfsWriter)
      .append(Mockito.any(Event.class));
  // The second time we try to write we should get an IOException.
  try {
    bucketWriter.append(e);
    Assert.fail("Expected IOException wasn't thrown during append");
  } catch (IOException ex) {
    Assert.assertEquals(expectedIOException, ex);
    logger.info("Caught expected IOException", ex);
  }
  // The third time we try to write we should get a BucketClosedException, because the
  // BucketWriter should attempt to close itself before rethrowing the IOException on the first
  // call.
  try {
    bucketWriter.append(e);
    Assert.fail("BucketWriter should be already closed, BucketClosedException expected");
  } catch (BucketClosedException ex) {
    logger.info("Caught expected BucketClosedException", ex);
  }
  Assert.assertEquals("events written", 1, hdfsWriter.getEventsWritten());
  Assert.assertEquals("2 files should be closed", 2, hdfsWriter.getFilesClosed());
}