1   package ch.qos.logback.classic.selector;
2   
3   import static org.junit.Assert.assertEquals;
4   
5   import org.junit.After;
6   import org.junit.Before;
7   import org.junit.Test;
8   import org.slf4j.LoggerFactory;
9   import org.slf4j.impl.StaticLoggerBinder;
10  import org.slf4j.impl.StaticLoggerBinderFriend;
11  
12  import ch.qos.logback.classic.ClassicGlobal;
13  import ch.qos.logback.classic.util.MockInitialContext;
14  import ch.qos.logback.classic.util.MockInitialContextFactory;
15  import ch.qos.logback.core.Context;
16  
17  public class ContextJNDISelectorTest  {
18    
19    static String INITIAL_CONTEXT_KEY = "java.naming.factory.initial";
20  
21    @Before
22    public void setUp() throws Exception {    
23      
24      System.setProperty(ClassicGlobal.LOGBACK_CONTEXT_SELECTOR, "JNDI");
25      StaticLoggerBinderFriend.reset();
26      
27      MockInitialContextFactory.initialize();
28      MockInitialContext mic = MockInitialContextFactory.getContext();
29      mic.map.put(ClassicGlobal.JNDI_CONTEXT_NAME, "toto");
30      
31      //The property must be set after we setup the Mock
32      System.setProperty(INITIAL_CONTEXT_KEY, MockInitialContextFactory.class.getName());
33      
34      //this call will create the context "toto"
35      LoggerFactory.getLogger(ContextDetachingSCLTest.class);
36    }
37  
38    @After
39    public void tearDown() throws Exception {
40      System.clearProperty(INITIAL_CONTEXT_KEY);
41    }
42  
43    @Test
44    public void testGetExistingContext() {
45      ContextSelector selector = StaticLoggerBinder.getSingleton().getContextSelector();
46      Context context = selector.getLoggerContext();
47      assertEquals("toto", context.getName());
48    }
49    
50    @Test
51    public void testCreateContext() {
52      MockInitialContext mic = MockInitialContextFactory.getContext();
53      mic.map.put(ClassicGlobal.JNDI_CONTEXT_NAME, "tata");
54      
55      LoggerFactory.getLogger(ContextDetachingSCLTest.class);
56      
57      ContextJNDISelector selector = (ContextJNDISelector)StaticLoggerBinder.getSingleton().getContextSelector();
58      Context context = selector.getLoggerContext();
59      assertEquals("tata", context.getName());
60      System.out.println(selector.getContextNames());
61      assertEquals(2, selector.getCount());
62    }
63    
64    @Test
65    public void defaultContext() {
66      MockInitialContext mic = MockInitialContextFactory.getContext();
67      mic.map.put(ClassicGlobal.JNDI_CONTEXT_NAME, null);
68  
69      ContextJNDISelector selector = (ContextJNDISelector)StaticLoggerBinder.getSingleton().getContextSelector();
70      Context context = selector.getLoggerContext();
71      
72      assertEquals("default", context.getName());    
73    }
74    
75  }