View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.sift;
15  
16  import ch.qos.logback.classic.Level;
17  import ch.qos.logback.classic.Logger;
18  import ch.qos.logback.classic.LoggerContext;
19  
20  import ch.qos.logback.classic.spi.LoggingEvent;
21  import ch.qos.logback.core.testUtil.RandomUtil;
22  import org.junit.After;
23  import org.junit.Before;
24  import org.junit.Test;
25  
26  import org.slf4j.MDC;
27  
28  import java.util.HashMap;
29  
30  import static org.junit.Assert.assertEquals;
31  import static org.junit.Assert.assertTrue;
32  
33  /**
34   * @author Ceki Gülcü
35   */
36  public class MDCBasedDiscriminatorTest {
37  
38      static String DEFAULT_VAL = "DEFAULT_VAL";
39  
40      MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
41      LoggerContext context = new LoggerContext();
42      Logger logger = context.getLogger(this.getClass());
43  
44      int diff = RandomUtil.getPositiveInt();
45      String key = "MDCBasedDiscriminatorTest_key" + diff;
46      String value = "MDCBasedDiscriminatorTest_val" + diff;
47      LoggingEvent event;
48  
49      @Before
50      public void setUp() {
51          MDC.clear();
52          discriminator.setContext(context);
53          discriminator.setKey(key);
54          discriminator.setDefaultValue(DEFAULT_VAL);
55          discriminator.start();
56          assertTrue(discriminator.isStarted());
57      }
58  
59      @After
60      public void teaDown() {
61          MDC.clear();
62      }
63  
64      @Test
65      public void smoke() {
66          MDC.put(key, value);
67          event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
68  
69          String discriminatorValue = discriminator.getDiscriminatingValue(event);
70          assertEquals(value, discriminatorValue);
71      }
72  
73      @Test
74      public void nullMDC() {
75          event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
76          assertEquals(new HashMap<String, String>(), event.getMDCPropertyMap());
77          String discriminatorValue = discriminator.getDiscriminatingValue(event);
78          assertEquals(DEFAULT_VAL, discriminatorValue);
79      }
80  }