2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.yangtools.checkstyle;
11 import static org.junit.Assert.assertTrue;
13 import java.io.ByteArrayOutputStream;
16 import org.junit.After;
17 import org.junit.Before;
18 import org.junit.Test;
19 import org.xml.sax.InputSource;
21 import com.google.common.collect.Lists;
22 import com.puppycrawl.tools.checkstyle.Checker;
23 import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
24 import com.puppycrawl.tools.checkstyle.DefaultLogger;
25 import com.puppycrawl.tools.checkstyle.PropertiesExpander;
26 import com.puppycrawl.tools.checkstyle.api.AuditListener;
27 import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
28 import com.puppycrawl.tools.checkstyle.api.Configuration;
30 public class CheckstyleTest {
32 private Checker checker;
33 private ByteArrayOutputStream baos;
36 public void setup() throws CheckstyleException {
37 baos = new ByteArrayOutputStream();
38 AuditListener listener = new DefaultLogger(baos, false);
40 InputSource inputSource = new InputSource(CheckstyleTest.class.getClassLoader().getResourceAsStream(
41 "checkstyle-logging.xml"));
42 Configuration configuration = ConfigurationLoader.loadConfiguration(inputSource,
43 new PropertiesExpander(System.getProperties()), false);
45 checker = new Checker();
46 checker.setModuleClassLoader(Checker.class.getClassLoader());
47 checker.configure(configuration);
48 checker.addListener(listener);
52 public void destroy() {
57 public void testLoggerChecks() throws Exception {
58 verify(CheckLoggingTestClass.class, "15: Logger must be declared as private static final.", "15: Logger name should be LOG.",
59 "16: Logger might be declared only once.", "16: Logger must be slf4j.", "22: Line contains printStacktrace",
60 "23: Line contains console output", "24: Line contains console output",
61 "15: LoggerFactory.getLogger Class argument is incorrect.", "20: Log message contains string concatenation.",
62 "26: Log message placeholders count is incorrect.", "32: Log message placeholders count is incorrect");
65 private void verify(final Class<?> testClass, final String... expectedMessages) {
66 final String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + testClass.getName().replaceAll("\\.", "/") + ".java";
67 final File testFile = new File(filePath);
68 checker.process(Lists.newArrayList(testFile));
69 final String output = baos.toString();
70 for(final String message : expectedMessages) {
71 assertTrue("Expected message not found: " + message, output.contains(message));