Skip to content

Instantly share code, notes, and snippets.

@MoriTanosuke
Created October 24, 2013 01:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MoriTanosuke/7129937 to your computer and use it in GitHub Desktop.
Save MoriTanosuke/7129937 to your computer and use it in GitHub Desktop.
Simple unit test showing kind of surprising behavior of Base64OutputStream. Basically, you *have* to call #close() on the OutputStream to get valid base64. After stumbling upon this I switched to Base64InputStream, because I can not close the Input/OutputStreams in my original code as I have to write additional non-base64 bytes into them too.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64InputStream;
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
public class Base64OutputStreamTest {
final String original = "this is a message";
final String originalAsBase64 = "dGhpcyBpcyBhIG1lc3NhZ2U=\r\n";
@Test
public void testBase64OutputStreamDoesNotConvertAllBytesIfNotClosed()
throws IOException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
OutputStream out = new Base64OutputStream(byteOut);
out.write(original.getBytes());
// in my original code, I can't close the stream here, because I need to
// stream non-base64 bytes into it. All I can do is call #flush(), but
// that does not write the missing bytes neither
// why is this false?
assertFalse(originalAsBase64.equals(byteOut.toString()));
}
@Test
public void testBase64OutputStreamDoesConvertAllBytesIfClosed()
throws IOException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
OutputStream out = new Base64OutputStream(byteOut);
out.write(original.getBytes());
out.close();
// calling out#close() does write the missing bytes and line delimiters
assertEquals(originalAsBase64, byteOut.toString());
}
@Test
public void testBase64InputStreamWorks() throws IOException {
ByteArrayInputStream byteIn = new ByteArrayInputStream(
originalAsBase64.getBytes());
InputStream in = new Base64InputStream(byteIn, false);
String result = IOUtils.toString(in);
assertEquals(original, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment