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.turbo;
015
016import static org.junit.Assert.assertEquals;
017import static org.junit.Assert.assertFalse;
018
019import org.junit.After;
020import org.junit.Before;
021import org.junit.Test;
022import org.slf4j.MDC;
023
024import ch.qos.logback.core.spi.FilterReply;
025import ch.qos.logback.core.testUtil.RandomUtil;
026
027public class MDCFilterTest {
028
029    int diff = RandomUtil.getPositiveInt();
030    String key = "myKey" + diff;
031    String value = "val" + diff;
032
033    private MDCFilter filter;
034
035    @Before
036    public void setUp() {
037        filter = new MDCFilter();
038        filter.setOnMatch("ACCEPT");
039        filter.setOnMismatch("DENY");
040        filter.setMDCKey(key);
041        filter.setValue(value);
042
043        MDC.clear();
044    }
045
046    @After
047    public void tearDown() {
048        MDC.clear();
049    }
050
051    @Test
052    public void smoke() {
053        filter.start();
054        MDC.put(key, "other" + diff);
055        assertEquals(FilterReply.DENY, filter.decide(null, null, null, null, null, null));
056        MDC.put(key, null);
057        assertEquals(FilterReply.DENY, filter.decide(null, null, null, null, null, null));
058        MDC.put(key, value);
059        assertEquals(FilterReply.ACCEPT, filter.decide(null, null, null, null, null, null));
060    }
061
062    @Test
063    public void testNoValueOption() {
064
065        filter.setValue(null);
066        filter.start();
067        assertFalse(filter.isStarted());
068        MDC.put(key, null);
069        assertEquals(FilterReply.NEUTRAL, filter.decide(null, null, null, null, null, null));
070        MDC.put(key, value);
071        assertEquals(FilterReply.NEUTRAL, filter.decide(null, null, null, null, null, null));
072    }
073
074    @Test
075    public void testNoMDCKeyOption() {
076        filter.setMDCKey(null);
077        filter.start();
078        assertFalse(filter.isStarted());
079        MDC.put(key, null);
080        assertEquals(FilterReply.NEUTRAL, filter.decide(null, null, null, null, null, null));
081        MDC.put(key, value);
082        assertEquals(FilterReply.NEUTRAL, filter.decide(null, null, null, null, null, null));
083    }
084
085}