package oving6.logger;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

public class StreamLoggerTest {

	private static final String formatString = "%s: %s (%s)";
	private static final String melding = "En melding ble logget!";

	private ByteArrayOutputStream stream;
	private StreamLogger logger;

	@BeforeEach
	public void setUp() {
		stream = new ByteArrayOutputStream();
		logger = new StreamLogger(stream);
	}

	@Test
	@DisplayName("Logs info message")
	public void testLog() {
		logger.log(ILogger.INFO, melding, null);
		assertTrue(stream.toString().contains(melding),
				"Test that the stream contains the message after it has been logged");
		assertTrue(stream.toString().contains(ILogger.INFO),
				"Test that the stream contains a message of type info after it has been logged");
	}

	@Test
	@DisplayName("Logs exception")
	public void testLogException() {
		assertThrows(IllegalArgumentException.class, () -> {
			logger.setFormatString(null);
		}, "Test that IllegalArgumentException is thrown when the format is null");

		IllegalStateException exception = new IllegalStateException();
		logger.setFormatString(formatString);
		logger.log(ILogger.INFO, melding, exception);
		assertEquals(String.format(formatString, ILogger.INFO, melding, exception),
				stream.toString().trim(),
				"Test the format of the message that was logged with an exception");
	}
}
