Package de.innovationgate.wgpublisher

Source Code of de.innovationgate.wgpublisher.TestCore$JavaAssertion

/*******************************************************************************
* Copyright 2009, 2010 Innovation Gate GmbH. All Rights Reserved.
*
* This file is part of the OpenWGA server platform.
*
* OpenWGA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, a special exception is granted by the copyright holders
* of OpenWGA called "OpenWGA plugin exception". You should have received
* a copy of this exception along with OpenWGA in file COPYING.
* If not, see <http://www.openwga.com/gpl-plugin-exception>.
*
* OpenWGA 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenWGA in file COPYING.
* If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.innovationgate.wgpublisher;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.Dom4JDriver;

import de.innovationgate.webgate.api.WGAPIException;
import de.innovationgate.wgpublisher.expressions.ExpressionEngine;
import de.innovationgate.wgpublisher.expressions.ExpressionEngineFactory;
import de.innovationgate.wgpublisher.expressions.ExpressionResult;
import de.innovationgate.wgpublisher.expressions.tmlscript.RhinoExpressionEngine;
import de.innovationgate.wgpublisher.webtml.Root;
import de.innovationgate.wgpublisher.webtml.utils.TMLContext;
/**
* implements assert functions for tmlscript
*
*/
public class TestCore {
   
    private static boolean _javaAssertionsEnabled = false;
    static {
        assert _javaAssertionsEnabled = true;
    }
   
    public interface JavaAssertion {
        public void exec() throws Exception;
    }
   
    // map containing assertions mapped by category, value is a list of assertions
    private HashMap _assertions = new HashMap();
   
    // set containing preregistered assertions mapped by id;
    private HashMap _registeredAssertions = new HashMap();
   
    // registered assertions that have been executed
    private HashSet _executedRegisteredAssertions = new HashSet();
   
    // enable tests (true/false)
    private boolean _enabled;
   
    private boolean _logEnabled;
   
    // stop on assertions and start tmlscript:debugger
    private boolean _debugAssertions;
   
    private String _logDir;  
   
    private RhinoExpressionEngine _engine;
   
    private WGACore _core;
   
    private static final String ASSERTION_XML_DATA_FILE = "testresult.xml";
    private static final String ASSERTION_ASCII_LOG_FILE = "testresult.log";
   
    private static final String FILESEPARATOR = System.getProperty("file.separator");
   
    private FileWriter _foutASCII;
   
    public TestCore(WGACore core, boolean enabled, String logDir) {
        _core = core;
        _enabled = enabled;
        _logDir = logDir;
        _logEnabled = true;
        init();
    }
   
    public TestCore(WGACore core, boolean enabled) {
        _core = core;
        _enabled = enabled;
        _logEnabled = false;
        init();
    }
   
    private void init() {
        if (_logEnabled) {           
            String asciiFilePath = "";
           
            if (_logDir.endsWith(FILESEPARATOR)) {
                asciiFilePath = _logDir + ASSERTION_ASCII_LOG_FILE;
            } else {
                asciiFilePath = _logDir + FILESEPARATOR + ASSERTION_ASCII_LOG_FILE;
            }
               
            try {
                if (_foutASCII != null) {
                    _foutASCII.close();
                }
                _foutASCII = new FileWriter(asciiFilePath);
            }
            catch (IOException e) {
                _core.getLog().error("Cannot initialize TestCore-logFacility. Logging of TestCore disabled.", e);
                _logEnabled = false;
            }
           
        }
       
        // init expression engine
        _engine = ExpressionEngineFactory.getTMLScriptEngine();
        if (_engine == null) {
            throw new RuntimeException("cannot initialize tmlExpression-Engine");
        }        
    }
   
    public void assertTrue(String title, String category, String condition, TMLContext context) {
        if (!_enabled) {
            return;
        } else {
            // create assertion
            Assertion assertion = new Assertion(Assertion.TYPE_ASSERT_TRUE, title, category);
            doAssertTrue(condition, context, assertion);
        }                       
    }
   
    public void assertTrue(String id, String condition, TMLContext context) {
        if (!_enabled) {
            return;
        } else {
            // get preregistered assertion
            Assertion assertion = (Assertion) _registeredAssertions.get(id);
            if (assertion != null) {                            
                doAssertTrue(condition, context, assertion);
                // remove assertion
                _registeredAssertions.remove(id);
                _executedRegisteredAssertions.add(id);
            }
        }                       
    }   

    private void doAssertTrue(String condition, TMLContext context, Assertion assertion) {
       
        if (context != null) {
            try {
                assertion.setContextPath(context.getpath());
            }
            catch (WGAPIException e) {
                assertion.setContextPath("Unable to retrieve contextpath bc. of exception: " + e.getClass().getName() + " message: " + e.getMessage());
            }
        }
        else {
          assertion.setContextPath("(none)");
        }
       
        assertion.setExpression(condition);
        // evaluate expression
        ExpressionResult result = _engine.evaluateExpression(condition, context, ExpressionEngine.TYPE_EXPRESSION, null);
        if (result.isError()) {
            assertion.setResult(false);
            assertion.setExpressionError(true);  
            assertion.setExpressionErrorMsg(result.getException().getMessage());
            // break if debugmode enabled
            if (_debugAssertions) {
                _engine.debug();
            }
        } else {
            assertion.setResult(result.isTrue());
            // break if result is false and debugmode enabled
            if (result.isFalse() && _debugAssertions) {
                _engine.debug();
            }
        }
        
        assertion.setTime(new Date(System.currentTimeMillis()));
       
        if (context.iswebenvironment()) {
            assertion.setTmlModule(context.option(Root.OPTION_TMLMODULE_NAME) + "/" + context.option(Root.OPTION_TMLMODULE_MEDIAKEY));
        }
       
        addAssertion(assertion);
    }
   
    public boolean assertEquals(String title, String category, Object obj1, Object obj2, TMLContext context) {
        if (!_enabled) {
            return false;
        } else {
            // create assertion
            Assertion assertion = new Assertion(Assertion.TYPE_ASSERT_EQUALS, title, category);
            return doAssertEquals(obj1, obj2, context, assertion);                         
        }
    }
   
    public void assertEquals(String id, Object obj1, Object obj2, TMLContext context) {
        if (!_enabled) {
            return;
        } else {
            // get preregistered assertion
            Assertion assertion = (Assertion) _registeredAssertions.get(id);
            if (assertion != null) {           
                doAssertEquals(obj1, obj2, context, assertion);
                // remove assertion
                _registeredAssertions.remove(id);     
                _executedRegisteredAssertions.add(id);
            }
           
        }
    }   

   
   
    private boolean doAssertEquals(Object obj1, Object obj2, TMLContext context, Assertion assertion) {
       
        if (context != null) {
            try {
                assertion.setContextPath(context.getpath());
            }
            catch (WGAPIException e) {
                assertion.setContextPath("Unable to retrieve contextpath bc. of exception: " + e.getClass().getName() + " message: " + e.getMessage());
            }
        }
        else {
            assertion.setContextPath("(none)");
        }
       
        assertion.setTime(new Date(System.currentTimeMillis()));

        assertion.setValueObj1(obj1);
        assertion.setValueObj2(obj2);
       
        if (obj1 != null) {         
            // test for equals
            if (obj1 == null) {
                if (obj2 == null) {
                    assertion.setResult(true);
                }
                else {
                    assertion.setResult(false);
                }
            }
            else {
                if (obj2 == null) {
                    assertion.setResult(false);
                }
                else {
                    assertion.setResult(obj1.equals(obj2));
                }
            }
           
            // break if result is false and debugmode enabled
            if (!assertion.isResult() && _debugAssertions) {
                _engine.debug();
            }
        } else {
            if (obj2 == null) {
                assertion.setResult(true);
            } else {
                assertion.setResult(false);
                // break if debugmode enabled
                if (_debugAssertions) {
                    _engine.debug();
                }
            }
        }
       
        if (context != null && context.iswebenvironment()) {
            assertion.setTmlModule(context.option(Root.OPTION_TMLMODULE_NAME) + "/" + context.option(Root.OPTION_TMLMODULE_MEDIAKEY));
        }
       
        addAssertion(assertion);
       
        return assertion.isResult();
    }
   
    public boolean assertJava(String title, String category, JavaAssertion javaAssertion) {
       
        if (!_enabled) {
            return true;
        } else {
           
           
           
            // create assertion
            Assertion assertion = new Assertion(Assertion.TYPE_ASSERT_JAVA, title, category);
            assertion.setContextPath("");
            assertion.setExpression("(java code)");

//          Test enablement of java assertions
            if (_javaAssertionsEnabled) {

           
            // execute java assertion
            try {
               javaAssertion.exec();
               assertion.setResult(true);
            }
            catch (AssertionError e) {
                assertion.setResult(false);
            }
            catch (Exception e) {
                assertion.setResult(false);
            }
           
            }
            else {
                assertion.setResult(false);
                assertion.setExpression("Java Assertions are disabled. This test will not work");
            }
          
            assertion.setTime(new Date(System.currentTimeMillis()));
            addAssertion(assertion);
            return assertion.isResult();
        }
       
    }
   
    /**
     * preregisters an assertion with result==false by given id
     * @param id
     */
    public void registerAssertTrue(String id, String title, String category) { 
        Assertion assertion = new Assertion(Assertion.TYPE_ASSERT_TRUE, title, category);
        assertion.setResult(false);
        assertion.setTime(new Date(System.currentTimeMillis()));
        assertion.setPreregistered(true);
        _registeredAssertions.put(id, assertion);
    }
   
    /**
     * preregisters an assertion with result==false by given id
     * @param id
     */
    public void registerAssertEquals(String id, String title, String category) { 
        Assertion assertion = new Assertion(Assertion.TYPE_ASSERT_EQUALS, title, category);
        assertion.setResult(false);
        assertion.setTime(new Date(System.currentTimeMillis()));
        assertion.setPreregistered(true);
        _registeredAssertions.put(id, assertion);
    }
   
   
   
    private void addAssertion(Assertion assertion) {
        // add to map, if category not exist - create
        List assertList = null;
        if (_assertions.containsKey(assertion.getCategory())) {
            assertList = (ArrayList) _assertions.get(assertion.getCategory());           
        } else {
            assertList = new ArrayList();
            _assertions.put(assertion.getCategory(), assertList);           
       
        assertList.add(assertion);
       
        // if log enabled refresh filesystem
        if (_logEnabled) {
            try {
               
                String xmlFilePath = "";
               
                if (_logDir.endsWith(FILESEPARATOR)) {
                    xmlFilePath = _logDir + ASSERTION_XML_DATA_FILE;
                } else {
                    xmlFilePath = _logDir + FILESEPARATOR + ASSERTION_XML_DATA_FILE;
                }
               
                // write Ascii
                _foutASCII.write(assertion.toString() + "\n");
                _foutASCII.flush();
                // write XML
                FileWriter foutXML = new FileWriter(xmlFilePath);
                new XStream(new Dom4JDriver()).toXML(_assertions, foutXML);
                foutXML.close();
               
            }
            catch (IOException e) {
                _logEnabled = false;               
                _core.getLog().error("Cannot initialize TestCore-logFacility. Logging of TestCore disabled.", e);
            }           
        }
    }

    public boolean isEnabled() {
        return _enabled;
    }

    public void finalize() {
        try {
            _foutASCII.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   
    public List getAllAssertions() {
       
        List list = new ArrayList();
        List assertCategories = new ArrayList(_assertions.keySet());
        //Collections.sort(assertCategories);
       
       
        Iterator assertCatIt = assertCategories.iterator();
        List assertList;
        while (assertCatIt.hasNext()) {
            assertList = (List) _assertions.get(assertCatIt.next());
            list.addAll(assertList);
        }
        return list;
       
    }
   
    public void reset() {
        _assertions.clear();
        _registeredAssertions.clear();
        _executedRegisteredAssertions.clear();
        init();
    }
   
    /**
     * put not executed but registered assertions in _assertions-Map
     *
     */
    public void testDone() {       
        Iterator it = _registeredAssertions.values().iterator();
        while (it.hasNext()) {
            Assertion assertion = (Assertion) it.next();
            addAssertion(assertion);
        }       
    }

    public boolean isDebugAssertions() {
        return _debugAssertions;
    }

    public void setDebugAssertions(boolean debugAssertions) {
        _debugAssertions = debugAssertions;
    }

    public boolean assertIsRegisteredOrExecuted(String id) {
        return _registeredAssertions.containsKey(id) || _executedRegisteredAssertions.contains(id);       
    }

    public boolean isLogEnabled() {
        return _logEnabled;
    }

    public void setLogEnabled(boolean logEnabled) {
        _logEnabled = logEnabled;
    }
}
TOP

Related Classes of de.innovationgate.wgpublisher.TestCore$JavaAssertion

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.