/*
 * Created on 30 ao˚t 2004
 */
package fr.sgf.tools.pyjunit;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestSuite;
import org.python.util.PythonInterpreter;

/**
 * @author ploix Class used to build test suites from python classes. Should be
 *         used by the Jython test case Wrapper only.
 */
public class JythonTestExtractor {

    private PythonInterpreter interp;

    public JythonTestExtractor(String path) {
        Properties post = new Properties();
        post.setProperty("python.path", path);
        PythonInterpreter.initialize(System.getProperties(),
                                     post,
                                     new String[0]);
        interp = new PythonInterpreter();
        interp.exec("import sys, junit");
    }

    /**
     * @param pathEntries
     *            be careful : with slashes, not backslashes
     * @param module
     *            to be scanned for tests
     * @param test
     *            the class from which getting the test methods
     */
    public TestSuite extract(String module, String[] tests) {
        try {
            interp.exec("suite = junit.framework.TestSuite()");
            for(int i = 0; i < tests.length; i++) {
                String test = tests[i];
                interp.exec("from " + module + " import " + test);
                interp.exec("[suite.addTest(" + test + "(f)) for f in dir("
                        + test + ") if f.startswith(\"test\")]");
            }
            TestSuite suite = (TestSuite)interp.get("suite")
                    .__tojava__(TestSuite.class);
            suite.setName(module);
            return suite;
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param path
     *            python path
     * @param module
     *            to be scanned for tests
     * @param test
     *            the class with test methods
     */
    public static TestSuite extract(String path, String module, String test) {
        return extract(path, module, new String[] {test});
    }

    /**
     * @param path
     *            python path
     * @param module
     *            to be scanned for tests
     * @param tests
     *            the classes with test methods
     */
    public static TestSuite extract(String path, String module, String[] test) {
        JythonTestExtractor extractor = (JythonTestExtractor)interpsForPath.get(path);
        if(extractor == null) {
            extractor = new JythonTestExtractor(path);
            interpsForPath.put(path, extractor);
        }
        return extractor.extract(module, test);
    }

    private static Map interpsForPath = new HashMap();
}