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.encoder;
015
016import static org.junit.Assert.*;
017
018import java.io.ByteArrayOutputStream;
019import java.io.IOException;
020import java.nio.charset.Charset;
021
022import ch.qos.logback.classic.PatternLayout;
023import org.junit.Before;
024import org.junit.Test;
025
026import ch.qos.logback.classic.Level;
027import ch.qos.logback.classic.Logger;
028import ch.qos.logback.classic.LoggerContext;
029import ch.qos.logback.classic.spi.ILoggingEvent;
030import ch.qos.logback.classic.spi.LoggingEvent;
031
032public class PatternLayoutEncoderTest {
033
034    PatternLayoutEncoder ple = new PatternLayoutEncoder();
035    LoggerContext context = new LoggerContext();
036    ByteArrayOutputStream baos = new ByteArrayOutputStream();
037    Logger logger = context.getLogger(PatternLayoutEncoderTest.class);
038    Charset utf8Charset = Charset.forName("UTF-8");
039
040    @Before
041    public void setUp() {
042        ple.setPattern("%m");
043        ple.setContext(context);
044    }
045
046    ILoggingEvent makeLoggingEvent(String message) {
047        return new LoggingEvent("", logger, Level.DEBUG, message, null, null);
048    }
049
050    @Test
051    public void smoke() throws IOException {
052        init(baos);
053        String msg = "hello";
054        ILoggingEvent event = makeLoggingEvent(msg);
055        byte[] eventBytes = ple.encode(event);
056        baos.write(eventBytes);
057        ple.footerBytes();
058        assertEquals(msg, baos.toString());
059    }
060
061    void init(ByteArrayOutputStream baos) throws IOException {
062        ple.start();
063        ((PatternLayout) ple.getLayout()).setOutputPatternAsHeader(false);
064        byte[] header = ple.headerBytes();
065        baos.write(header);
066    }
067
068    @Test
069    public void charset() throws IOException {
070        ple.setCharset(utf8Charset);
071        init(baos);
072        String msg = "\u03b1";
073        ILoggingEvent event = makeLoggingEvent(msg);
074        byte[] eventBytes = ple.encode(event);
075        baos.write(eventBytes);
076        ple.footerBytes();
077        assertEquals(msg, new String(baos.toByteArray(), utf8Charset));
078    }
079
080}