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.pattern; 015 016import static org.junit.Assert.assertEquals; 017import static org.junit.Assert.assertTrue; 018 019import org.junit.After; 020import org.junit.Before; 021import org.junit.Test; 022import org.slf4j.MDC; 023 024import ch.qos.logback.classic.Level; 025import ch.qos.logback.classic.Logger; 026import ch.qos.logback.classic.LoggerContext; 027import ch.qos.logback.classic.spi.ILoggingEvent; 028import ch.qos.logback.classic.spi.LoggingEvent; 029import ch.qos.logback.core.testUtil.RandomUtil; 030 031public class MDCConverterTest { 032 033 LoggerContext lc; 034 MDCConverter converter; 035 int diff = RandomUtil.getPositiveInt(); 036 037 @Before 038 public void setUp() throws Exception { 039 lc = new LoggerContext(); 040 converter = new MDCConverter(); 041 converter.start(); 042 MDC.clear(); 043 } 044 045 @After 046 public void tearDown() throws Exception { 047 lc = null; 048 converter.stop(); 049 converter = null; 050 MDC.clear(); 051 } 052 053 @Test 054 public void testConvertWithOneEntry() { 055 String k = "MDCConverterTest_k" + diff; 056 String v = "MDCConverterTest_v" + diff; 057 058 MDC.put(k, v); 059 ILoggingEvent le = createLoggingEvent(); 060 String result = converter.convert(le); 061 assertEquals(k + "=" + v, result); 062 } 063 064 @Test 065 public void testConvertWithMultipleEntries() { 066 MDC.put("testKey", "testValue"); 067 MDC.put("testKey2", "testValue2"); 068 ILoggingEvent le = createLoggingEvent(); 069 String result = converter.convert(le); 070 boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?"); 071 assertTrue(result + " is not conform", isConform); 072 } 073 074 private ILoggingEvent createLoggingEvent() { 075 return new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null, null); 076 } 077}