001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.sift;
015
016import ch.qos.logback.classic.Level;
017import ch.qos.logback.classic.Logger;
018import ch.qos.logback.classic.LoggerContext;
019
020import ch.qos.logback.classic.spi.LoggingEvent;
021import ch.qos.logback.core.testUtil.RandomUtil;
022import org.junit.After;
023import org.junit.Before;
024import org.junit.Test;
025
026import org.slf4j.MDC;
027
028import java.util.HashMap;
029
030import static org.junit.Assert.assertEquals;
031import static org.junit.Assert.assertTrue;
032
033/**
034 * @author Ceki Gülcü
035 */
036public class MDCBasedDiscriminatorTest {
037
038    static String DEFAULT_VAL = "DEFAULT_VAL";
039
040    MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
041    LoggerContext context = new LoggerContext();
042    Logger logger = context.getLogger(this.getClass());
043
044    int diff = RandomUtil.getPositiveInt();
045    String key = "MDCBasedDiscriminatorTest_key" + diff;
046    String value = "MDCBasedDiscriminatorTest_val" + diff;
047    LoggingEvent event;
048
049    @Before
050    public void setUp() {
051        MDC.clear();
052        discriminator.setContext(context);
053        discriminator.setKey(key);
054        discriminator.setDefaultValue(DEFAULT_VAL);
055        discriminator.start();
056        assertTrue(discriminator.isStarted());
057    }
058
059    @After
060    public void teaDown() {
061        MDC.clear();
062    }
063
064    @Test
065    public void smoke() {
066        MDC.put(key, value);
067        event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
068
069        String discriminatorValue = discriminator.getDiscriminatingValue(event);
070        assertEquals(value, discriminatorValue);
071    }
072
073    @Test
074    public void nullMDC() {
075        event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
076        assertEquals(new HashMap<String, String>(), event.getMDCPropertyMap());
077        String discriminatorValue = discriminator.getDiscriminatingValue(event);
078        assertEquals(DEFAULT_VAL, discriminatorValue);
079    }
080}