Package org.objectweb.util.monolog

Source Code of org.objectweb.util.monolog.TestHelper

/**
* Copyright (C) 2002
*/

package org.objectweb.util.monolog;

import junit.framework.TestCase;
import junit.textui.TestRunner;
import org.objectweb.util.monolog.api.Handler;
import org.objectweb.util.monolog.api.HandlerFactory;
import org.objectweb.util.monolog.api.LevelFactory;
import org.objectweb.util.monolog.api.LoggerFactory;
import org.objectweb.util.monolog.api.TopicalLogger;

import java.io.*;
import java.util.Vector;

/**
* This class is test helper which provides tool methods to check a log file.
* It extends TestCase to support the use with JUnit.
* @author Sebastien Chassande-Barrioz
*/
public class TestHelper extends TestCase {
  /**
   * This constant field contains the list of the setter name needed to
   * initialize this class.
   */
  public static final String[] SETTER_METHODS = {"setLoggerFactoryClassName",
  };

  /**
   * The Logger factory used during the test
   */
  public static LoggerFactory lf = null;

  /**
   * The handler factory used during the test
   */
  public static HandlerFactory hf = null;

  /**
   * The level factory used during the test
   */
  public static LevelFactory lef = null;

  /**
   * The default file name specify by a setter method.
   */
  protected String fileName = null;

  public TestHelper() {
    super("");
  }

  public TestHelper(String s) {
    super(s);
  }

  protected void setUp() throws Exception {
    if (lf == null) {
      synchronized(TestHelper.class) {
        lf = Monolog.getMonologFactory("monolog.properties");
        hf = (HandlerFactory) lf;
        lef = (LevelFactory) lf;
      }
    }
  }

  /**
   * It assigns the LoggerFactory class name. This method tries to get an
   * instance with this class name.
   */
  public void setLoggerFactoryClassName(String lfcn) {
    try {
      lf = (LoggerFactory) Class.forName(lfcn).newInstance();
    }
    catch (ClassCastException e) {
      throw new UnsupportedOperationException(
        "The specified class is not a Logger factory: " + lfcn);
    }
    catch (Exception e) {
      throw new UnsupportedOperationException(
        "Logger factory class is not availlable: " + lfcn);
    }
    if (lf instanceof HandlerFactory) {
      hf = (HandlerFactory) lf;
    }
    if (lf instanceof LevelFactory) {
      lef = (LevelFactory) lf;
    }
  }

  /**
   * It assigns the default log file name.
   */
  public void setOutputFile(String filename) {
    fileName = filename;
  }

  /**
   * It runs the test.
   */
  public static void run(Class c, String[] methods, String params[],
               String lfcn, String fn) {
    try {
      TestRunner.run(getTestSuite(c, methods, params, lfcn, fn));
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * It runs the test.
   */
  public static void run(Class c, String[] methods,
               String params[], String lfcn) {
    try {
      TestRunner.run(getTestSuite(c, methods, params, lfcn));
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * It retrieves a test suite.
   */
  public static TestSuite getTestSuite(Class c,
                     String[] methods,
                     String params[],
                     String lfcn,
                     String fn) {
    Object[] myparams = new Object[params.length + 2];
    myparams[0] = lfcn;
    myparams[1] = fn;
    for (int i = 0; i < params.length; i++) {
      myparams[i + 2] = params[i];
    }
    String[] mymethods = new String[methods.length + 2];
    mymethods[0] = "setLoggerFactoryClassName";
    mymethods[1] = "setOutputFile";
    for (int i = 0; i < methods.length; i++) {
      mymethods[i + 2] = methods[i];
    }
    try {
      return new TestSuite(c, mymethods, myparams);
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static TestSuite getTestSuite(Class c,
                     String[] methods,
                     String params[],
                     String lfcn) {
    Object[] myparams = new Object[params.length + 1];
    myparams[0] = lfcn;
    for (int i = 0; i < params.length; i++) {
      myparams[i + 1] = params[i];
    }
    String[] mymethods = new String[methods.length + 1];
    mymethods[0] = "setLoggerFactoryClassName";
    for (int i = 0; i < methods.length; i++) {
      mymethods[i + 1] = methods[i];
    }
    try {
      return new TestSuite(c, mymethods, myparams);
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public static void main(String[] args) {
    if (args == null || args.length <= 1) {
      System.out.println("Invalid argument");
      System.exit(1);
    }
    try {
      File f = new File(args[0]);
      f.delete();
      f.createNewFile();
      PrintStream ps = new PrintStream(new FileOutputStream(f));
      String[] required = new String[args.length - 1];
      for (int i = 0; i < required.length; i++) {
        required[i] = args[i + 1];
        ps.println(required[i]);
      }
      ps.flush();
      ps.close();
      TestHelper to = new TestHelper();
      to.setOutputFile(args[0]);
      to.assertInFileEquals("my message", required);
      f.delete();
    }
    catch (IOException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }

  /**
   * It checks that the last line of the default log file is equals to a
   * specified string.
   * @param message is the error message if the string is not found.
   * @param required is the string which must be file in the default log file
   */
  public void assertInFileEquals(String message, String required) {
    String[] r = new String[1];
    r[0] = required;
    assertInFileEquals(message, fileName, r);
  }

  /**
   * It checks that the last line of the specified log file is equals to a
   * specified string.
   * @param message is the error message if the string is not found.
   * @param filename is the log file name
   * @param required is the string which must be file in the default log file
   */
  public void assertInFileEquals(String message, String filename,
                   String required) {
    String[] r = new String[1];
    r[0] = required;
    assertInFileEquals(message, filename, r);
  }

  /**
   * It checks that the last lines of the default log file is equals to a
   * specified string string.
   * @param message is the error message if the string array is not found.
   * @param required is the string array which must be file in the default
   * log file.
   */
  public void assertInFileEquals(String message, String[] required) {
    String[] text = getFirstLines(fileName, required.length);
    // Check the String
    for (int i = 0; i < required.length; i++) {
      debug("found : text[" + i + "]=" + text[i] + " text[i].length = " + text[i].length());
      debug("required : required[" + i + "]=" + required[i] + " required[i].length = " + required[i].length());
      assertEquals(message + " " + i, required[i], text[i]);
    }
  }

  /**
   * It checks that the last lines of the specified log file is equals to a
   * specified string string.
   * @param message is the error message if the string array is not found.
   * @param filename is the log file name
   * @param required is the string array which must be file in the default
   * log file.
   */
  public void assertInFileEquals(String message, String filename,
                   String[] required) {
    String[] text = getFirstLines(filename, required.length);
    // Check the String
    for (int i = 0; i < required.length; i++) {
      debug("found : text[" + i + "]=" + text[i]);
      debug("required : required[" + i + "]=" + required[i]);
      assertEquals(message + " " + i, required[i], text[i]);
    }
  }

  /**
   * Return the last lines of the default log file.
   * @param linenumber is the number of line which must be retrieved.
   * @return a string array which matches to the last line.
   */
  public String[] getLastLines(int linenumber) {
    return getLastLines(fileName, linenumber);
  }

  /**
   * Return the last lines of the default log file.
   * @param linenumber is the number of line which must be retrieved.
   * @return a string array which matches to the last line.
   */
  public String[] getFirstLines(int linenumber) {
    return getFirstLines(fileName, linenumber);
  }

  /**
   * Return the first lines of the specified log file.
   * @param linenumber is the number of line which must be retrieved.
   * @param filename is the log file name
   * @return a string array which matches to the last line.
   */
  public String[] getFirstLines(String filename, int linenumber) {
        if (filename==null || linenumber==0)
            return(null);
    Vector v = new Vector(linenumber);
        try {
            FileReader fr= new FileReader(filename);
            LineNumberReader lnr = new LineNumberReader(fr);
            String str = lnr.readLine();
            int i=0;
            while(i<linenumber && str != null) {
                v.addElement(str);
                str = lnr.readLine();
                i++;
            }
            int size = v.size();
            String[] res = new String[size];
            for (int j = 0; j < size; j++) {
                res[j] = (String) v.elementAt(j);
            }
            return res;
    }
    catch (Exception e) {
            e.printStackTrace();
//      fail(e.getMessage());
            return null;
    }
  }
  /**
   * Return the last lines of the specified log file.
   * @param linenumber is the number of line which must be retrieved.
   * @param filename is the log file name
   * @return a string array which matches to the last line.
   */
  public String[] getLastLines(String filename, int linenumber) {
        if (filename==null || linenumber==0)
            return(null);
    Vector v = new Vector(linenumber);
        try {
            FileReader fr= new FileReader(filename);
            LineNumberReader lnr = new LineNumberReader(fr);
            String str = lnr.readLine();
            int i=0;
            while(str != null) {
                v.addElement(str);
                str = lnr.readLine();
                i++;
            }
            int size = v.size();
            String[] res = new String[size];
            for (int j = 0; j < size; j++) {
                res[j] = (String) v.elementAt(size-1-j);
            }
            return res;
    }
    catch (Exception e) {
            e.printStackTrace();
//      fail(e.getMessage());
            return null;
    }
  }

  /**
   * It removes all handlers of the root logger.
   */
  public void quietRootLogger() {
    TopicalLogger l = (TopicalLogger) lf.getLogger("root");
    Handler[] hcs = l.getHandler();
    Handler hc = hf.createHandler("handlerOfroot", "file");
    hc.setAttribute(Handler.OUTPUT_ATTRIBUTE, "rootLogger.log");
    hc.setAttribute(Handler.PATTERN_ATTRIBUTE, "%m%n");
    hc.setAttribute("activation", lf);
    try {
      l.addHandler(hc);
      for (int i = 0; i < hcs.length; i++) {
        l.removeHandler(hcs[i]);
      }
    }
    catch (Exception e) {
      fail("error" + e.getMessage());
    }
    l = null;
  }

    static boolean debug =
            Boolean.valueOf(System.getProperty("monolog.test.debug")).booleanValue();

  /**
   * This methods is used to debug this helper.
   */
  protected void debug(String m) {
       if (debug)
        System.out.println(m);
  }

  private int next(int i, int max) {
    return (i + 1 == max ? 0 : i + 1);
  }
}
TOP

Related Classes of org.objectweb.util.monolog.TestHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.