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.encoder;
15  
16  import static org.junit.Assert.*;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.io.IOException;
20  import java.nio.charset.Charset;
21  
22  import ch.qos.logback.classic.PatternLayout;
23  import org.junit.Before;
24  import org.junit.Test;
25  
26  import ch.qos.logback.classic.Level;
27  import ch.qos.logback.classic.Logger;
28  import ch.qos.logback.classic.LoggerContext;
29  import ch.qos.logback.classic.spi.ILoggingEvent;
30  import ch.qos.logback.classic.spi.LoggingEvent;
31  
32  public class PatternLayoutEncoderTest {
33  
34      PatternLayoutEncoder ple = new PatternLayoutEncoder();
35      LoggerContext context = new LoggerContext();
36      ByteArrayOutputStream baos = new ByteArrayOutputStream();
37      Logger logger = context.getLogger(PatternLayoutEncoderTest.class);
38      Charset utf8Charset = Charset.forName("UTF-8");
39  
40      @Before
41      public void setUp() {
42          ple.setPattern("%m");
43          ple.setContext(context);
44      }
45  
46      ILoggingEvent makeLoggingEvent(String message) {
47          return new LoggingEvent("", logger, Level.DEBUG, message, null, null);
48      }
49  
50      @Test
51      public void smoke() throws IOException {
52          init(baos);
53          String msg = "hello";
54          ILoggingEvent event = makeLoggingEvent(msg);
55          byte[] eventBytes = ple.encode(event);
56          baos.write(eventBytes);
57          ple.footerBytes();
58          assertEquals(msg, baos.toString());
59      }
60  
61      void init(ByteArrayOutputStream baos) throws IOException {
62          ple.start();
63          ((PatternLayout) ple.getLayout()).setOutputPatternAsHeader(false);
64          byte[] header = ple.headerBytes();
65          baos.write(header);
66      }
67  
68      @Test
69      public void charset() throws IOException {
70          ple.setCharset(utf8Charset);
71          init(baos);
72          String msg = "\u03b1";
73          ILoggingEvent event = makeLoggingEvent(msg);
74          byte[] eventBytes = ple.encode(event);
75          baos.write(eventBytes);
76          ple.footerBytes();
77          assertEquals(msg, new String(baos.toByteArray(), utf8Charset));
78      }
79  
80  }