

package gov.va.med.cds.junit.runners;


import org.junit.runner.manipulation.Filter;
import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.manipulation.Sorter;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.List;


public class SuiteAwareSpringRunner
    extends
        SpringJUnit4ClassRunner
{
    private boolean keepExecution = true;


    public SuiteAwareSpringRunner( Class<?> klass )
        throws InitializationError
    {
        super( klass );
        filter( new GroupAwareFilter() );
        sort( new Sorter( new DependancyComparator() ) );
    }


    @Override
    protected List<FrameworkMethod> computeTestMethods( )
    {
    	 List<FrameworkMethod> methods = super.computeTestMethods();
         List<FrameworkMethod> modifiableMethods = new ArrayList<FrameworkMethod>(methods);
         RunnerUtils.addCustomBeforeAndAfterOnceMethods( getTestClass(), modifiableMethods );        
         return modifiableMethods;
    }


    @Override
    public void filter( Filter filter )
    {
        try
        {
            super.filter( filter );
        }
        catch ( NoTestsRemainException e )
        {
            keepExecution = false;
        }
    }


    @Override
    public void sort( Sorter sorter )
    {
        if ( !keepExecution )
            return;
        super.sort( sorter );
    }
}