package org.sewatech.logging.issue;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import org.junit.Before;
import org.junit.Test;

import ch.qos.logback.classic.LoggerContext;
import org.slf4j.MDC;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class Issue776Test {
    public static final String PRE_STRING = "PRE ";
    public static final String POST_STRING = " POST";
    public static final String BRACKET = ")";

    private PatternLayout pl = new PatternLayout();
    private LoggerContext lc = new LoggerContext();
    ch.qos.logback.classic.Logger logger = lc.getLogger(Issue776Test.class);

    @Before
    public void setUp() {
        pl.setContext(lc);
    }

    @Test
    public void testMDC_OK() {
        pl.setPattern(PRE_STRING + "%X{key}" + POST_STRING);
        pl.start();

        MDC.put("key", "VALUE");
        String val = pl.doLayout(getEventObject());

        assertEquals(PRE_STRING + "VALUE" + POST_STRING, val);
    }

    @Test
    public void testMDC_Fail() {
        pl.setPattern(PRE_STRING + "%X{key}" + BRACKET + POST_STRING);
        pl.start();

        MDC.put("key", "VALUE");
        String val = pl.doLayout(getEventObject());

        assertEquals(PRE_STRING + "VALUE" + BRACKET + POST_STRING, val);
    }

    private ILoggingEvent getEventObject() {
        return new LoggingEvent(
                ch.qos.logback.core.pattern.FormattingConverter.class.getName(),
                logger, Level.INFO, "MESSAGE", null, null);
    }

}
