/*
 * @(#)MultipleAnalyzersIUTest.java
 *
 * Copyright (C) 2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.codecoverage.v2.compiler;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import net.sourceforge.groboutils.autodoc.v1.AutoDoc;
import net.sourceforge.groboutils.codecoverage.v2.BytecodeLoaderUtil;
import net.sourceforge.groboutils.codecoverage.v2.CCCreatorUtil;
import net.sourceforge.groboutils.codecoverage.v2.IAnalysisModule;
import net.sourceforge.groboutils.codecoverage.v2.datastore.DirMetaDataWriter;
import net.sourceforge.groboutils.codecoverage.v2.module.BranchCountMeasure;
import net.sourceforge.groboutils.codecoverage.v2.module.BytecodeCountMeasure;
import net.sourceforge.groboutils.codecoverage.v2.module.CallPairMeasure;
import net.sourceforge.groboutils.codecoverage.v2.module.FunctionMeasure;
import net.sourceforge.groboutils.codecoverage.v2.module.LineCountMeasure;
import net.sourceforge.groboutils.junit.v1.SubTestTestCase;


/**
 * Attempts to load a collection of simple class files, add in all known
 * analyzer module markings on them, and run the recompiled classes.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   $Date: 2004/04/15 05:48:27 $
 * @since     May 2, 2003
 */
public class MultipleAnalyzersIUTest extends SubTestTestCase
{
    //-------------------------------------------------------------------------
    // Standard JUnit Class-specific declarations
    
    private static final Class THIS_CLASS = MultipleAnalyzersIUTest.class;
    private static final AutoDoc DOC = new AutoDoc( THIS_CLASS );
    
    public MultipleAnalyzersIUTest( String name )
    {
        super( name );
    }



    //-------------------------------------------------------------------------
    // Tests
    
    public static class MyLogger2
    {
        public static void cover( String classSig,
                short methodIndex, short channel, short markIndex )
        {
            System.out.println( "MyLogger2.cover" );
            DOC.getLog().info( getMeasureName( channel ) );
        }
    }
    
    
    private static final String COVER_METHOD_NAME = "cover";
    private static final String CLASSFILE_PATH =
        "net/sourceforge/groboutils/codecoverage/v2/compiler/testcode/";
    private static final String CLASSNAME_PACKAGE =
        "net.sourceforge.groboutils.codecoverage.v2.compiler.testcode.";
    private static final String MAIN_SIG = "main([Ljava/lang/String;)V";



    public static final String[] TESTCLASSNAMES = {
            "Main1",
            "If1",
            "If2",
            "If3",
            "Case1",
            "Case2",
            "Case3",
            "Case4",
            "Case5",
            "Except1",
            "Except2",
            "Finally1",
            "Finally2",
            "Finally3",
            "Finally4",
            "Finally5",
            "Synchronized1",
            "Synchronized2",
            "Synchronized3",
        };
    public void testRebuildMain()
            throws Exception
    {
        File metadir = CCCreatorUtil.createNewDirectory();
        for (int i = 0; i < TESTCLASSNAMES.length; ++i)
        {
            addSubTest( new Recompile( TESTCLASSNAMES[i], metadir ) );
        }
    }
    
    
    public static class Recompile extends TestCase
    {
        public String TESTNAME;
        public File dir;
        public Recompile( String testname, File dir )
        {
            super( "testRecompile" );
            this.TESTNAME = testname;
            this.dir = dir;
            DOC.getLog().info("===== Adding test for "+testname);
        }
        public String getName()
        {
            return "testRecompile:"+TESTNAME;
        }
        public void testRecompile() throws Exception
        {
            File f = new File( TESTNAME+".passed" );
            if (f.exists()) f.delete();
            
            String filename = CLASSFILE_PATH+TESTNAME+".class";
            String classname = CLASSNAME_PACKAGE+TESTNAME;
            byte[] bytecode = compileClass( dir, filename );
            //DOC.getLog().info( "Original Classfile:" );
            //RebuildClassIUTest.debugClass( origClassBytes, filename );
            DOC.getLog().info( "Recompiled Classfile:" );
            RebuildClassIUTest.debugClass( bytecode, filename );
            
            BytecodeLoaderUtil.verifyClass( classname, bytecode );
            Class clazz = BytecodeLoaderUtil.loadClassFromBytecode(
                classname, bytecode );
            BytecodeLoaderUtil.runMain( clazz );
            
            // check for errors
            assertTrue(
                TESTNAME+" failed: recompilation didn't work.",
                f.exists() );
        }
    }
    
    
    
    
    //-------------------------------------------------------------------------
    // helpers
    
    
    protected static byte[] compileClass( File metadir, String filename )
            throws IOException
    {
        byte[] bytecode = null;
        DirMetaDataWriter dmdw = new DirMetaDataWriter( metadir );
        try
        {
            PostCompileClass pcc = new PostCompileClass(
                new ParseCoverageLogger( MyLogger2.class,
                    COVER_METHOD_NAME ),
                dmdw, getAnalysisModules() );
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] origBytecode = BytecodeLoaderUtil.loadBytecode(
                filename );
            pcc.postCompile( filename, origBytecode, baos );
            bytecode = baos.toByteArray();
        }
        finally
        {
            dmdw.close();
        }
        return bytecode;
    }
    
    
    
    
    /**
     * 
     */
    private static IAnalysisModule[] getAnalysisModules()
    {
        final IAnalysisModule[] amL = new IAnalysisModule[] {
                new BranchCountMeasure(),
                new BytecodeCountMeasure(),
                new CallPairMeasure(),
                new FunctionMeasure(),
                new LineCountMeasure()
            };
        return amL;
    }
    
    
    private static String getMeasureName( short i )
    {
        if (i < 0) return null;
        String s[] = getMeasureNames();
        if (s.length <= i) return null;
        return s[i];
    }
    
    
    private static String[] getMeasureNames()
    {
        IAnalysisModule[] am = getAnalysisModules();
        String s[] = new String[ am.length ];
        for (int i = 0; i < am.length; ++i)
        {
            s[i] = am[i].getMeasureName();
        }
        return s;
    }
   
    
    
    
    //-------------------------------------------------------------------------
    // Standard JUnit declarations
    
    
    public static Test suite()
    {
        TestSuite suite = new TestSuite( THIS_CLASS );
        
        return suite;
    }
    
    public static void main( String[] args )
    {
        String[] name = { THIS_CLASS.getName() };
        
        // junit.textui.TestRunner.main( name );
        // junit.swingui.TestRunner.main( name );
        
        junit.textui.TestRunner.main( name );
    }
    
    
    /**
     * 
     * @exception Exception thrown under any exceptional condition.
     */
    protected void setUp() throws Exception
    {
        super.setUp();
        
        // set ourself up
    }
    
    
    /**
     * 
     * @exception Exception thrown under any exceptional condition.
     */
    protected void tearDown() throws Exception
    {
        // tear ourself down
        
        
        super.tearDown();
    }
}

