/*
 * The MIT License (MIT)
 * Copyright (c) 2017 Nicholas Wright
 * http://opensource.org/licenses/MIT
 */
package com.github.dozedoff.commonj.io;

import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.isEmptyString;
import static org.junit.Assert.assertThat;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import org.awaitility.Duration;
import org.junit.Before;
import org.junit.Test;

public class StreamGobblerTest {
	private StreamGobbler cut;
	private static final String TEST_TEXT = "This is a test.";
	private static final Duration DURATION = new Duration(200, TimeUnit.MILLISECONDS);

	@Before
	public void setUp() throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(TEST_TEXT.getBytes(StandardCharsets.UTF_8));
		cut = new StreamGobbler(bais);

	}

	@Test
	public void testGetBuffer() throws Exception {
		cut.start();

		await().atMost(DURATION).until(cut::getBuffer, is(TEST_TEXT));
	}

	@Test
	public void testGetBufferOnThreadInNewState() throws Exception {
		assertThat(cut.getBuffer(), isEmptyString());
	}
}

@@ -327,16 +327,121 @@
 rtThat;%0A
+import static org.mockito.Mockito.when;%0A%0Aimport java.io.ByteArrayInputStream;%0Aimport java.io.IOException;
 %0Aimport 
@@ -444,33 +444,24 @@
 ort java.io.
-ByteArray
 InputStream;
@@ -621,16 +621,44 @@
 it.Test;
+%0Aimport org.mockito.Mockito;
 %0A%0Apublic
@@ -857,16 +857,49 @@
 ONDS);%0A%0A
+%09private InputStream failingIO;%0A%0A
 %09@Before
@@ -1073,16 +1073,118 @@
 bais);%0A%0A
+%09%09failingIO = Mockito.mock(InputStream.class);%0A%09%09when(failingIO.read()).thenThrow(new IOException());%0A
 %09%7D%0A%0A%09@Te
@@ -1442,11 +1442,192 @@
 g());%0A%09%7D
+%0A%0A%09@Test%0A%09public void testReadError() throws Exception %7B%0A%09%09cut = new StreamGobbler(failingIO);%0A%0A%09%09cut.start();%0A%0A%09%09await().atMost(DURATION).until(cut::getBuffer, isEmptyString());%0A%09%7D
 %0A%7D%0A

Test for IO error