1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2024, 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  
15  package ch.qos.logback.classic.pattern;
16  
17  import ch.qos.logback.classic.Level;
18  import ch.qos.logback.classic.LoggerContext;
19  import ch.qos.logback.classic.PatternLayout;
20  import ch.qos.logback.classic.spi.LoggingEvent;
21  import ch.qos.logback.core.CoreConstants;
22  import org.junit.jupiter.api.Test;
23  
24  import java.util.HashMap;
25  import java.util.Map;
26  
27  import static org.junit.jupiter.api.Assertions.assertEquals;
28  import static org.junit.jupiter.api.Assertions.assertNull;
29  
30  public class LegacyPatternLayoutTest {
31  
32      LoggerContext context = new LoggerContext();
33  
34      /**
35       * Test backward compatibility for classes derived from
36       * PatternLayout that add custom conversion words.
37       */
38      @Test public void subPattern() {
39          SubPatternLayout layout = new SubPatternLayout();
40          layout.setPattern("%"+SubPatternLayout.DOOO);
41          layout.setContext(context);
42          layout.start();
43          LoggingEvent event = new LoggingEvent();
44          event.setTimeStamp(0);
45          event.setLevel(Level.INFO);
46  
47          String result = layout.doLayout(event);
48          assertEquals("INFO", result);
49      }
50  
51      @Test
52      public void fromContext() {
53          Map<String, String> registry = (Map<String, String>) this.context
54                          .getObject(CoreConstants.PATTERN_RULE_REGISTRY);
55          //
56          assertNull(registry);
57          if(registry == null) {
58              registry = new HashMap<String, String>();
59              this.context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, registry);
60          }
61  
62          registry.put("legacy", LevelConverter.class.getName());
63  
64          PatternLayout patternLayout = new PatternLayout();
65          patternLayout.setPattern("%legacy");
66          patternLayout.setContext(context);
67          patternLayout.start();
68          LoggingEvent event = new LoggingEvent();
69          event.setLevel(Level.WARN);
70          String result = patternLayout.doLayout(event);
71          assertEquals("WARN", result);
72      }
73  
74  }