TestMethods.java :  » Test-Coverage » salome-tmf » org » objectweb » salome_tmf » ihm » datawrapper » Java Open Source

Java Open Source » Test Coverage » salome tmf 
salome tmf » org » objectweb » salome_tmf » ihm » datawrapper » TestMethods.java
/*
* SalomeTMF is a Test Management Framework
* Copyright (C) 2005 France Telecom R&D
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @author Fayal SOUGRATI, Vincent Pautret, Marche Mikael
*
* Contact: mikael.marche@rd.francetelecom.com
*/

package org.objectweb.salome_tmf.ihm.datawrapper;

import java.awt.Component;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;

import javax.swing.JOptionPane;

import org.java.plugin.Extension;
import org.objectweb.salome_tmf.api.Api;
import org.objectweb.salome_tmf.api.ApiConstants;
import org.objectweb.salome_tmf.data.AutomaticTest;
import org.objectweb.salome_tmf.data.Campaign;
import org.objectweb.salome_tmf.data.ConnectionData;
import org.objectweb.salome_tmf.data.DataConstants;
import org.objectweb.salome_tmf.data.DataSet;
import org.objectweb.salome_tmf.data.Element;
import org.objectweb.salome_tmf.data.Environment;
import org.objectweb.salome_tmf.data.Execution;
import org.objectweb.salome_tmf.data.ExecutionResult;
import org.objectweb.salome_tmf.data.ExecutionTestResult;
import org.objectweb.salome_tmf.data.ManualTest;
import org.objectweb.salome_tmf.data.Parameter;
import org.objectweb.salome_tmf.data.Project;
import org.objectweb.salome_tmf.data.ProjectData;
import org.objectweb.salome_tmf.data.Script;
import org.objectweb.salome_tmf.data.Test;
import org.objectweb.salome_tmf.ihm.AutomaticExecution;
import org.objectweb.salome_tmf.ihm.ManualExecution;
import org.objectweb.salome_tmf.ihm.SalomeTMF;
import org.objectweb.salome_tmf.ihm.languages.Language;
import org.objectweb.salome_tmf.ihm.models.ScriptExecutionException;
import org.objectweb.salome_tmf.ihm.tools.Tools;
import org.objectweb.salome_tmf.plugins.core.ScriptEngine;
import org.objectweb.salome_tmf.plugins.core.TestDriver;



public class TestMethods implements ApiConstants, DataConstants {
    
    //  static CallScript c = null;
    static ScriptEngine pEngine = null;
    static TestDriver driver = null;
    
   
    public static String notValuedParamListCreation(HashSet setOfParam, Environment env, DataSet dataSet, ArrayList notValuedParamList) {
        String message = "";
        for (Iterator iter = setOfParam.iterator(); iter.hasNext();) {
            Parameter param = (Parameter)iter.next();
            if (!env.containsParameter(param) && !dataSet.getParametersHashMap().containsKey(param.getName())) {
                notValuedParamList.add(param);
                message = message + "* " + param.getName() + "\n";
            }
        }
        return message;
    }
    
    public static String notValuedParamListInDataSet(HashSet setOfParam, DataSet dataSet, ArrayList notValuedParamList) {
        String message = "";
        for (Iterator iter = setOfParam.iterator(); iter.hasNext();) {
            Parameter param = (Parameter)iter.next();
            if (!dataSet.getParametersHashMap().containsKey(param.getName())) {
                notValuedParamList.add(param);
                message = message + "* " + param.getName() + "\n";
            }
        }
        return message;
    }
   
    /**
     * M?thode pour appeler un script bsh
     * @param args les param?tres du script
     * @param script le script
     */
    public static String callScript(HashMap params, Script script, AutomaticTest test, Campaign campaign, Project project, Environment env, ExecutionResult execResult, Execution exec, ExecutionTestResult execTestResult)  throws ScriptExecutionException {
        String result = null;
        File file = null;
        String scriptFile = "";
        
        try {
            if (ConnectionData.isConnected()) {
                try {
                    if (script.getType().equals(POST_SCRIPT)) {
                        //file = ConnectionData.getCampTestSelect().getScriptOfExecution(campaign.getName(), exec.getName(), script.getName(), POST_SCRIPT);
                        file = exec.getExecScriptFromDB(script.getName(),POST_SCRIPT);
                    } else if (script.getType().equals(PRE_SCRIPT)) {
                        //file = ConnectionData.getCampTestSelect().getScriptOfExecution(campaign.getName(), exec.getName(), script.getName(), PRE_SCRIPT);
                        file = exec.getExecScriptFromDB(script.getName(), PRE_SCRIPT);
                    } else if (script.getType().equals(INIT_SCRIPT)) {
                        //file = ConnectionData.getCampTestSelect().getScriptOfEnvironment(env.getName(), script.getName());
                        file = env.getEnvScriptFromDB(script.getName());
                    } else {
                        //file = ConnectionData.getSuiteTestSelect().getScriptOfTest(test.getTestList().getFamily().getName(), test.getTestList().getName(), test.getName(), script.getName());
                        file = test.getTestScriptFromDB(script.getName());
                    }
                    //c = new CallScript(Tools.speedpurge(file.getAbsolutePath()));
                    scriptFile = Tools.speedpurge(file.getAbsolutePath());
                } catch (Exception exception) {
                    Tools.ihmExceptionView(exception.toString());
                }
                
            } else {
                //c = new CallScript(Tools.speedpurge(script.getName()));
                scriptFile = Tools.speedpurge(script.getName());
            }
        }  catch (Exception e) {
            if (script.getType().equals(TEST_SCRIPT)) {
                result = UNKNOWN;
                fileCreationAndAttachToExecResult(execResult, execTestResult, e.toString(), exec, Language.getInstance().getText("erreur_exec_") + test.getName());
            } else {
                throw new ScriptExecutionException(e);
            }
            return result;
        }
        
        Hashtable pParams = new Hashtable(params);
        //if (script.getClassPath() != null) {
        //  obj.eval("addClassPath(\""+ Tools.speedpurge(script.getClassPath()) +"\")");
        //}
        pParams.put("date", new Date(GregorianCalendar.getInstance().getTimeInMillis()));
        pParams.put("time", new Time(GregorianCalendar.getInstance().getTimeInMillis()));
        //On ajoute une r?f?rence sur l'obejt de r?sultat de test
        
        //obj.eval("setAccessibility(true)"); // turn off access restrictions
        pParams.put("salome_projectName", project.getName());
        pParams.put("salome_ProjectObject", project);
        pParams.put("salome_debug", new Boolean(false));
        if (execResult != null){
            pParams.put("salome_ExecResultObject", execResult);
        }
        if (execTestResult != null){
            pParams.put("salome_ExecTestResultObject", execTestResult);
        }
        if (campaign != null){
            pParams.put("salome_CampagneName", campaign.getName());
            pParams.put("salome_CampagneObject", campaign);
        } else {
            pParams.put("salome_CampagneName", "");
        }
        if (env != null){
            pParams.put("salome_environmentName", env.getName()); // Add MM
            pParams.put("salome_environmentObject", env); // Add MM
        } else {
            pParams.put("salome_environmentName", ""); // Add MM
        }
        if (exec != null) {
            pParams.put("salome_ExecName",exec.getName()); // Add MM
            pParams.put("salome_ExecObject", exec); // Add MM
        } else {
            pParams.put("salome_ExecName","");
        }
        if (test != null) {
            pParams.put("salome_TestName", test.getName());
            pParams.put("salome_TestObject", test);
            if (test.getTestList() != null) {
                pParams.put("salome_SuiteTestName", test.getTestList().getName());
                pParams.put("salome_SuiteTestObject", test.getTestList());
            } else {
                pParams.put("salome_SuiteTestName", "");
            }
            if (test.getTestList().getFamily() != null) {
                pParams.put("salome_FamilyName", test.getTestList().getFamily().getName());
                pParams.put("salome_FamilyObject", test.getTestList().getFamily());
            } else {
                pParams.put("salome_FamilyName", "");
            }
        } else {
            pParams.put("salome_TestName", "");
            pParams.put("salome_SuiteTestName", "");
        }
        
        pParams.put("testLog","");
        pParams.put("Verdict", "");
        
        // valuation des parametres de tests
        if (params != null) {
            Set keysSet = params.keySet();
            for (Iterator iter = keysSet.iterator(); iter.hasNext();) {
                String paramName;
                Object o = iter.next();
                if (o instanceof Element){
                    paramName = ((Element)o).getName();
                } else {
                    paramName = (String)o;
                }
                Object val = params.get(o);
                Api.log(Language.getInstance().getText("valeur_de_")+  paramName + " = " + val);
                pParams.put(paramName, params.get(o));
            }
        }
        
        // Lancement du script
        int plugScriptType = -1;
        //Script pScript = null;
        pEngine = null;
        driver = null;
        String plugArg = "";
        String log;
        int status = -3;
        try  {
            if (script.getType().equals(PRE_SCRIPT)) {
                //script = exec.getInitScript();
                pEngine = script.getScriptEngine((Extension)SalomeTMF.associatedExtension.get(script. getScriptExtension() ), SalomeTMF.urlSalome, SalomeTMF.jpf);
                plugScriptType = ScriptEngine.PRE_SCRIPT;
                plugArg = script.getPlugArg();
            } else if (script.getType().equals(POST_SCRIPT)) {
                //script = exec.getPostScript();
                pEngine = script.getScriptEngine((Extension)SalomeTMF.associatedExtension.get(script. getScriptExtension() ), SalomeTMF.urlSalome, SalomeTMF.jpf);
                plugScriptType = ScriptEngine.POST_SCRIPT;
                plugArg = script.getPlugArg();
            } else if (script.getType().equals(INIT_SCRIPT)) {
                //script = exec.getPostScript();
                pEngine = script.getScriptEngine((Extension)SalomeTMF.associatedExtension.get(script. getScriptExtension() ), SalomeTMF.urlSalome, SalomeTMF.jpf);
                plugScriptType = ScriptEngine.ENV_SCRIPT;
                plugArg = script.getPlugArg();
            } else {
                driver = test.ActivateExtention((Extension)SalomeTMF.associatedExtension.get(test.getExtension() ), SalomeTMF.urlSalome, SalomeTMF.jpf);
                plugArg = test.getScript().getPlugArg();
            }
            
           
            if (driver != null) {
                status = driver.runTest(scriptFile, test, pParams, plugArg );
                log = driver.getTestLog();
                // Erreur; -1 : Inconclusif; 2 : Fail; 1 : Pass 0
                if (status == -1){
                    result = FAIL;
                    execResult.addFail(1);
                    if (log == null) {
                        log = "unknow";
                    }
                    fileCreationAndAttachToExecResult(execResult, execTestResult, log, exec, Language.getInstance().getText("erreur_exec_") + test.getName());
                } else  if (status == 0){
                    result = SUCCESS;
                    execResult.addSuccess(1);
                } if (status == 1){
                    result = FAIL;
                    execResult.addFail(1);
                } if (status == 2){
                    result = UNKNOWN;
                    execResult.addUnknow(1);
                }
                if (log != null && !log.equals("")){
                    fileCreationAndAttachToExecResult(execResult, execTestResult, log, exec, "log_exec_" + test.getName());
                }
            } else if (pEngine != null) {
                status = pEngine.runScript(plugScriptType, scriptFile, script, pParams, plugArg);
                //log = pEngine.
                if (status != 0) {
                    throw new ScriptExecutionException(new Exception(pEngine.getScriptLog()));
                }
                
            } else throw new Exception("No plugin foud");
        } catch (Exception ePlug) {
            log = ePlug.toString();
            if (driver != null) {
                if (status == -3) {
                    result = FAIL;
                    execResult.addFail(1);
                }
                fileCreationAndAttachToExecResult(execResult, execTestResult, log, exec, Language.getInstance().getText("erreur_exec_") + test.getName());
            } else {
                if (status == -3) {
                    result = UNKNOWN;
                    execResult.addUnknow(1);
                }
                throw new ScriptExecutionException(ePlug);
            }
        }
        Api.log("stop");
        if (file != null) file.delete();
        
        return result;
    }
    
    public static void fileCreationAndAttachToExecResult(ExecutionResult execResult, ExecutionTestResult execTestResult, String text, Execution exec, String fileName) {
        
        Properties sys = System.getProperties();
        String tempDir = sys.getProperty("java.io.tmpdir");
        String fs = sys.getProperty("file.separator");
        int num = 0;
        String pFileName = tempDir + fs + fileName + ".txt";
        File errorFile = new File(pFileName);
        while (errorFile.exists()) {
            pFileName = tempDir + fs + fileName + num + ".txt";
            errorFile = new File(pFileName);
            num++;
            //errorFile.delete();
        }
        try {
            errorFile.createNewFile();
            
            //BufferedWriter a besoin d un FileWriter,
            //les 2 vont ensemble, on donne comme argument le nom du fichier
            //true signifie qu on ajoute dans le fichier (append), on ne marque pas par dessus
            FileWriter fw = new FileWriter(pFileName, true);
            
            // le BufferedWriter output auquel on donne comme argument le FileWriter fw cree juste au dessus
            BufferedWriter output = new BufferedWriter(fw);
            
            
            //on marque dans le fichier ou plutot dans le BufferedWriter qui sert comme un tampon(stream)
            output.write(text);
            //on peut utiliser plusieurs fois methode write
            
            output.flush();
            //ensuite flush envoie dans le fichier, ne pas oublier cette methode pour le BufferedWriter
            
            output.close();
            //et on le ferme
            
        }
        catch(IOException ioe){Api.log(Language.getInstance().getText("erreur_lors_de_la_cration_du_fichier_d'erreur:_") + ioe );
        //on "catch" l exception ici si il y en a une, et on l affiche sur la console
        return;
        }
        
        if (execTestResult == null && execResult != null) {
            execResult.addAttchment(errorFile);
            //execResult.setAttachmentMap(attachMap);
        } else if (execTestResult != null){
            //execTestResult.setAttachmentMap(attachMap);
            execTestResult.addAttchment(errorFile);
        }
        
        
    }
    /**
     * @return
     */
    public static void annulScript() {
        try {
            if (driver != null){
                driver.stopTest();
            } else if (pEngine != null){
                pEngine.stopScript();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    
    public static void continueExecution(Execution exec, ExecutionResult finalExecResult, Component pComponent, boolean stopOnError){
      finalExecResult.setExecutionDate(new Date(GregorianCalendar.getInstance().getTimeInMillis()));
      finalExecResult.setTester(ProjectData.getCurrentUser().getLastName() + " " + ProjectData.getCurrentUser().getFirstName());
      
      Vector pAllTestToExecute = new Vector();
      //Liste des tests groups en sous-listes (manuels/automatiques)
      ArrayList splittedListOfTest = Tools.getListOfTestManualOrAutomatic(DataModel.getCurrentCampaign().getTestList(),   finalExecResult, pAllTestToExecute);
      Vector listExec = new Vector();
      // On parcourt la liste des sous-listes
      for (int h =0; h < splittedListOfTest.size(); h++) {
        if (((ArrayList)splittedListOfTest.get(h)).get(0) instanceof ManualTest) {
          listExec.add(new ManualExecution((ArrayList)splittedListOfTest.get(h), exec,  finalExecResult));
          
        } else {
          //Sous liste de tests automatiques
          ArrayList automaticTestList = (ArrayList)splittedListOfTest.get(h);
          listExec.add(new AutomaticExecution(automaticTestList, exec, finalExecResult));
        }
      }
      //new callExecThread(listExec, exec, splittedListOfTest, selectedRowIndex, attachToBeSuppress, false, finalExecResult, null, pAllTestToExecute.toArray()).start();
      new CallExecThread(listExec, exec, splittedListOfTest, false, finalExecResult, null, pAllTestToExecute.toArray(), pComponent, stopOnError).start();
      
    }
    public static void runExecution(ArrayList pListExec, Component pComponent, boolean stopOnError) {
      //Campaign pCapaign = exec.getCampagne();
      Execution pExec;
      Campaign pCapaign;
      // il doit y avoir au moins une excution slectionne
      int nbExec = pListExec.size();
      if (nbExec > 0) {
        String message = "";
        for (int i = 0;  i < nbExec; i ++) { // FOR 1
          HashSet setOfParam = new HashSet();
          pExec = (Execution) pListExec.get(i);
          pCapaign = pExec.getCampagne();
          // Rcupration de tous les paramtres de la campagne
          for (int k = 0; k < pCapaign.getTestList().size(); k++) {
            Test test = (Test)pCapaign.getTestList().get(k);
            for (int j = 0; j < test.getParameterList().size(); j++) {
              setOfParam.add(test.getParameterList().get(j));
            }
          }
          // On vrifie que tous les paramtres ont une valuation;
          ArrayList notValuedParamList = new ArrayList();
          message = TestMethods.notValuedParamListInDataSet(setOfParam, pExec.getDataSet(), notValuedParamList);
          if (notValuedParamList.size() > 0) {
            message = Language.getInstance().getText("Les_paramtres_:\n") + message + Language.getInstance().getText("de_l'excution_<") + pExec.getName() + Language.getInstance().getText(">_ne_sont_pas_valus.");
          }
        }
        
        if (!message.equals("") && pComponent != null) {
          JOptionPane.showMessageDialog(pComponent,
              Language.getInstance().getText("Attention_!\n") + message,
            Language.getInstance().getText("Attention_!"),
            JOptionPane.INFORMATION_MESSAGE);
        }
        
        CallExecThread precCallExecThread = null;
        // on parcourt la liste des excutions selectionnes
        for (int i = nbExec-1; i >= 0 ; i --) { // FOR 1
          // Execution courante
          pExec = (Execution) pListExec.get(i);
          pCapaign = pExec.getCampagne();
          Api.log(">>>>EXEC LANCEE = " + pExec.getName());
          // R?sultat d'ex?cution final
          ExecutionResult finalExecResult = new ExecutionResult();
          finalExecResult.setNumberOfFail(0);
          finalExecResult.setNumberOfSuccess(0);
          finalExecResult.setNumberOfUnknow(0);
          finalExecResult.setName(pExec.getName() + "_" + pExec.getExecutionResultList().size());
          finalExecResult.setExecutionDate(new Date(GregorianCalendar.getInstance().getTimeInMillis()));
          finalExecResult.setTester(ProjectData.getCurrentUser().getLastName() + " " + ProjectData.getCurrentUser().getFirstName());
          
          Tools.initExecutionResultMap(pCapaign.getTestList(), finalExecResult, pCapaign);
          Vector pAllTestToExecute = new Vector();
          ArrayList splittedListOfTest = Tools.getListOfTestManualOrAutomatic(pCapaign.getTestList(), null, pAllTestToExecute);
          Vector listExec = new Vector();
          // On parcourt la liste des sous-listes
          for (int h =0; h < splittedListOfTest.size(); h++) {
            if (((ArrayList)splittedListOfTest.get(h)).get(0) instanceof ManualTest) {
              // Sous liste de tests manuels
              listExec.add(new ManualExecution((ArrayList)splittedListOfTest.get(h), pExec, finalExecResult));
              
            } else {
              //Sous liste de tests automatiques
              ArrayList automaticTestList = (ArrayList)splittedListOfTest.get(h);
              listExec.add(new AutomaticExecution(automaticTestList, pExec, finalExecResult));
            }
          }
          precCallExecThread = new CallExecThread(listExec, pExec, splittedListOfTest, true, finalExecResult, precCallExecThread, pAllTestToExecute.toArray(), pComponent, stopOnError);
          //
        } // FIN FOR 1
        precCallExecThread.start();
      } else {
        if (pComponent != null) {
          JOptionPane.showMessageDialog(pComponent,
              Language.getInstance().getText("Vous_devez_slectionner_au_moins_une_excution..."),
            Language.getInstance().getText("Attention_!"),
            JOptionPane.WARNING_MESSAGE);
        }
      }
    }
    
} // Fin de la classe TestMethods
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.