1   package ch.qos.logback.core.util;
2   
3   import static org.junit.Assert.assertEquals;
4   import static org.junit.Assert.fail;
5   
6   import java.util.HashMap;
7   import java.util.Map;
8   
9   import org.junit.Before;
10  import org.junit.Test;
11  
12  import ch.qos.logback.core.Context;
13  import ch.qos.logback.core.ContextBase;
14  
15  
16  public class OptionHelperTest  {
17  
18    String text = "Testing ${v1} variable substitution ${v2}";
19    String expected = "Testing if variable substitution works";
20    Context context = new ContextBase();
21    Map<String, String> secondaryMap;
22    
23    
24    
25    @Before
26    public void setUp() throws Exception {
27      secondaryMap = new HashMap<String, String>();
28    }
29  
30    @Test
31    public void testLiteral() {
32      String noSubst = "hello world";
33      String result = OptionHelper.substVars(noSubst, context);
34      assertEquals(noSubst, result);
35    }
36  
37    @Test
38    public void testUndefinedValues() {
39      String withUndefinedValues = "${axyz}";
40      
41      String result = OptionHelper.substVars(withUndefinedValues, context);
42      assertEquals("axyz"+OptionHelper._IS_UNDEFINED, result);
43    }
44    
45    @Test
46    public void testSubstVarsVariableNotClosed() {
47      String noSubst = "testing if ${v1 works";
48      
49      try {
50        @SuppressWarnings("unused")
51        String result = OptionHelper.substVars(noSubst, context);
52        fail();
53      } catch (IllegalArgumentException e) {
54        //ok
55      }
56    }
57    @Test
58    public void testSubstVarsContextOnly() {
59      context.putProperty("v1", "if");
60      context.putProperty("v2", "works");
61      
62      String result = OptionHelper.substVars(text, context);
63      assertEquals(expected, result); 
64    }
65    
66    @Test
67    public void testSubstVarsSystemProperties() { 
68      System.setProperty("v1", "if");
69      System.setProperty("v2", "works");
70      
71      String result = OptionHelper.substVars(text, context);
72      assertEquals(expected, result); 
73      
74      System.clearProperty("v1");
75      System.clearProperty("v2");
76    }
77    
78    @Test
79    public void testSubstVarsWithDefault() {   
80      context.putProperty("v1", "if");
81      String textWithDefault = "Testing ${v1} variable substitution ${v2:-toto}";
82      String resultWithDefault = "Testing if variable substitution toto";
83      
84      String result = OptionHelper.substVars(textWithDefault, context);
85      assertEquals(resultWithDefault, result); 
86    }
87    
88    @Test
89    public void testSubstVarsRecursive() {
90      context.putProperty("v1", "if");
91      context.putProperty("v2", "${v3}");
92      context.putProperty("v3", "works");
93      
94      String result = OptionHelper.substVars(text, context);
95      assertEquals(expected, result); 
96    }
97    
98  }