diff --git a/.classpath b/.classpath index 667f602e3d..c267d8cd3a 100644 --- a/.classpath +++ b/.classpath @@ -181,5 +181,7 @@ + + diff --git a/build.xml b/build.xml index 54efc02a7a..1a775b8e10 100644 --- a/build.xml +++ b/build.xml @@ -85,6 +85,12 @@ under the License. + + + + + + diff --git a/framework/testtools/OFBizSeleniumXmlIntro.pdf b/framework/testtools/OFBizSeleniumXmlIntro.pdf new file mode 100644 index 0000000000..ef9c44d24a Binary files /dev/null and b/framework/testtools/OFBizSeleniumXmlIntro.pdf differ diff --git a/framework/testtools/build.xml b/framework/testtools/build.xml index 36d576ba1a..7122e7a019 100644 --- a/framework/testtools/build.xml +++ b/framework/testtools/build.xml @@ -30,17 +30,24 @@ under the License. - + + - + + + + + + + @@ -50,6 +57,13 @@ under the License. + + + + + + diff --git a/framework/testtools/config/seleniumXml.properties b/framework/testtools/config/seleniumXml.properties new file mode 100644 index 0000000000..ac5f3ad00b --- /dev/null +++ b/framework/testtools/config/seleniumXml.properties @@ -0,0 +1,5 @@ +serverHost=localhost +proxyPort=4444 +browser=*firefox +startUrl=http://localhost:8080/ +log4jFile=./config/log4j.properties diff --git a/framework/testtools/convertSeleniumIDE.bat b/framework/testtools/convertSeleniumIDE.bat new file mode 100644 index 0000000000..09a515d87a --- /dev/null +++ b/framework/testtools/convertSeleniumIDE.bat @@ -0,0 +1,16 @@ +set OFBIZ_HOME=../.. +set CP=./build/lib/ofbiz-testtools.jar +set CP=%CP%;./lib/httpclient-4.0-beta1.jar +set CP=%CP%;./lib/selenium-java-client-driver.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/jdom-1.1.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/scripting/jython-nooro.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/junit.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/commons/commons-lang-2.3.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/log4j-1.2.15.jar + +rem echo %CP% + +rem For Example: +rem convertSeleniumIDE.bat + +"%JAVA_HOME%/bin/java.exe" -cp %CP% org.ofbiz.testtools.seleniumxml.SeleniumIDEConverter %1 %2 diff --git a/framework/testtools/convertSeleniumIDE.sh b/framework/testtools/convertSeleniumIDE.sh new file mode 100755 index 0000000000..97e649e9c4 --- /dev/null +++ b/framework/testtools/convertSeleniumIDE.sh @@ -0,0 +1,24 @@ +#!/bin/sh +export OFBIZ_HOME=../.. +export CP=./build/lib/ofbiz-testtools.jar +export CP=$CP:./lib/httpclient-4.0-beta1.jar +export CP=$CP:./lib/selenium-java-client-driver.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/jdom-1.1.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/scripting/jython-nooro.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/junit.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/commons/commons-lang-2.3.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/log4j-1.2.15.jar + +# echo $CP + +# For Example: +# convertSeleniumIDE.bat + +if [ -f "$JAVA_HOME/bin/java" ]; then + JAVA="$JAVA_HOME/bin/java" +else + JAVA=java +fi + +"$JAVA" -cp $CP org.ofbiz.testtools.seleniumxml.SeleniumIDEConverter "$@" +exit 0 diff --git a/framework/testtools/dtd/SeleniumXml.xsd b/framework/testtools/dtd/SeleniumXml.xsd new file mode 100644 index 0000000000..0e0b868e08 --- /dev/null +++ b/framework/testtools/dtd/SeleniumXml.xsd @@ -0,0 +1,507 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/framework/testtools/lib/httpclient-4.0-beta1.jar b/framework/testtools/lib/httpclient-4.0-beta1.jar new file mode 100755 index 0000000000..9f4abd50a8 Binary files /dev/null and b/framework/testtools/lib/httpclient-4.0-beta1.jar differ diff --git a/framework/testtools/lib/httpcore-4.0-beta2.jar b/framework/testtools/lib/httpcore-4.0-beta2.jar new file mode 100755 index 0000000000..b4126f45ae Binary files /dev/null and b/framework/testtools/lib/httpcore-4.0-beta2.jar differ diff --git a/framework/testtools/lib/httpmime-4.0-beta1.jar b/framework/testtools/lib/httpmime-4.0-beta1.jar new file mode 100755 index 0000000000..2564dcff8b Binary files /dev/null and b/framework/testtools/lib/httpmime-4.0-beta1.jar differ diff --git a/framework/testtools/lib/json-lib-2.2.3-jdk15.jar b/framework/testtools/lib/json-lib-2.2.3-jdk15.jar new file mode 100755 index 0000000000..8c92fab083 Binary files /dev/null and b/framework/testtools/lib/json-lib-2.2.3-jdk15.jar differ diff --git a/framework/testtools/lib/ofbiz-testtools.jar b/framework/testtools/lib/ofbiz-testtools.jar new file mode 100755 index 0000000000..7648745081 Binary files /dev/null and b/framework/testtools/lib/ofbiz-testtools.jar differ diff --git a/framework/testtools/lib/selenium-java-client-driver.jar b/framework/testtools/lib/selenium-java-client-driver.jar new file mode 100755 index 0000000000..4a1269853f Binary files /dev/null and b/framework/testtools/lib/selenium-java-client-driver.jar differ diff --git a/framework/testtools/ofbiz-component.xml b/framework/testtools/ofbiz-component.xml index b31dcda58f..64ddcbd117 100644 --- a/framework/testtools/ofbiz-component.xml +++ b/framework/testtools/ofbiz-component.xml @@ -23,11 +23,13 @@ under the License. xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/ofbiz-component.xsd"> + + diff --git a/framework/testtools/runSeleniumServer.bat b/framework/testtools/runSeleniumServer.bat new file mode 100644 index 0000000000..4025d39f51 --- /dev/null +++ b/framework/testtools/runSeleniumServer.bat @@ -0,0 +1 @@ +java -jar ../../framework/testtools/lib/selenium-server.jar -timeout 240 diff --git a/framework/testtools/runSeleniumServer.sh b/framework/testtools/runSeleniumServer.sh new file mode 100755 index 0000000000..61a8942b7b --- /dev/null +++ b/framework/testtools/runSeleniumServer.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# location of java executable +if [ -f "$JAVA_HOME/bin/java" ]; then + JAVA="$JAVA_HOME/bin/java" +else + JAVA=java +fi + +"$JAVA" -jar ../../framework/testtools/lib/selenium-server.jar -timeout 240 +exit 0 + diff --git a/framework/testtools/runSeleniumXml.bat b/framework/testtools/runSeleniumXml.bat new file mode 100644 index 0000000000..ed4dc0e227 --- /dev/null +++ b/framework/testtools/runSeleniumXml.bat @@ -0,0 +1,14 @@ +rem set JAVA_HOME=%JDK_15% +set OFBIZ_HOME=../.. +set CP=./build/lib/ofbiz-testtools.jar +set CP=%CP%;./lib/httpclient-4.0-beta1.jar +set CP=%CP%;./lib/selenium-java-client-driver.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/jdom-1.1.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/scripting/jython-nooro.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/junit.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/commons/commons-lang-2.3.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/log4j-1.2.15.jar + +echo %CP% + +"%JAVA_HOME%/bin/java.exe" -Dselenium.config=./config/seleniumXml.properties -cp %CP% org.ofbiz.testtools.seleniumxml.SeleniumXml %1 diff --git a/framework/testtools/runSeleniumXml.sh b/framework/testtools/runSeleniumXml.sh new file mode 100755 index 0000000000..8684b27b70 --- /dev/null +++ b/framework/testtools/runSeleniumXml.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# export JAVA_HOME=$JDK_15 +export OFBIZ_HOME=../.. +export CP=./build/lib/ofbiz-testtools.jar +export CP=$CP:./lib/httpclient-4.0-beta1.jar +export CP=$CP:./lib/selenium-java-client-driver.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/jdom-1.1.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/scripting/jython-nooro.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/junit.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/commons/commons-lang-2.3.jar +export CP=$CP:$OFBIZ_HOME/framework/base/lib/log4j-1.2.15.jar + +echo $CP + +if [ -f "$JAVA_HOME/bin/java" ]; then + JAVA="$JAVA_HOME/bin/java" +else + JAVA=java +fi + +"$JAVA" -Dselenium.config=./config/seleniumXml.properties -cp $CP org.ofbiz.testtools.seleniumxml.SeleniumXml $1; + + + + + diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java new file mode 100644 index 0000000000..ed3376d461 --- /dev/null +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.testtools.seleniumxml; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jdom.Element; +import org.python.core.PyArray; +import org.python.core.PyDictionary; +import org.python.core.PyList; +import org.python.core.PyObject; +import org.python.util.PythonInterpreter; + +public class DataLoader { + + private String file; + private String iterations; + private SeleniumXml parent; + private SeleniumXml currentTest; + private List children; + + private int currentRowIndx; + + + //Objects initialized from csvreader script. + private PyDictionary fieldNameMap; + private PyList dataList; + private PyList fieldNames; + + + + + public DataLoader(String file, String iterations, SeleniumXml parent, List children) { + super(); + this.file = file; + this.iterations = iterations; + this.parent = parent; + this.children = children; + initData(); + } + + private void initData() { + // Run the python script + // Read header and get record count + PythonInterpreter interp = InitJython.getInterpreter(); + + Map map = new HashMap(); + map.put("file", this.file); + interp.set("params", map); + interp.exec("from csvreader import CSVReader"); + String cmd = "reader = CSVReader('" + this.file + "')"; + interp.exec(cmd); + this.dataList = (PyList) interp.eval("reader.dataList"); + this.fieldNames = (PyList) interp.eval("reader.fieldNames"); + this.fieldNameMap = (PyDictionary) interp.eval("reader.fieldNameMap"); + //interp.execfile("c:/dev/ag/seleniumxml/plugins/csvreader.py"); + //interp.execfile("c:/dev/ag/seleniumxml/plugins/TestCSVReader.py"); + + //Now get output from script + //this.dataList = (PyArray) map.get("dataList"); + //this.fieldNames = (PyDictionary) map.get("fieldNames"); + + } + + private void next() { + this.currentRowIndx = (this.currentRowIndx + 1) % this.dataList.__len__(); + } + + private void loadData() { + + int size = this.fieldNames.__len__(); + for(int i=0; i children) { + super(); + this.dataListName = dataListName; + this.parent = parent; + this.children = children; + } + + public void runTest() { + + this.currentTest = new SeleniumXml(this.parent); + Map dataMap = this.parent.getMap(); + List dataList = (List)dataMap.get(this.dataListName); + Iterator iter = dataList.iterator(); + while (iter.hasNext()) { + Map mp = (Map)iter.next(); + // TODO, WARNING - these name could collide with names already in the test context + Set eSet = mp.entrySet(); + Iterator iter2 = eSet.iterator(); + while(iter2.hasNext()) { + Map.Entry entry = (Map.Entry)iter2.next(); + String name = (String)entry.getKey(); + Object value = entry.getValue(); + dataMap.put(name, value); + } + currentTest.runCommands(this.children); + } + + } +} diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java new file mode 100644 index 0000000000..c201aed8e5 --- /dev/null +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.testtools.seleniumxml; + +import groovy.lang.Binding; +import groovy.lang.GroovyClassLoader; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.codehaus.groovy.runtime.InvokerHelper; +import org.jdom.Element; +import org.ofbiz.testtools.seleniumxml.util.TestUtils; + +public class GroovyRunner { + + private String urlName; + private SeleniumXml parent; + private SeleniumXml currentTest; + + private int currentRowIndx; + public static GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); + + + public GroovyRunner(String urlName, SeleniumXml parent) { + super(); + this.urlName = urlName; + this.parent = parent; + } + + public void runTest() { + + Map map = this.parent.getMap(); + map.put("url", this.urlName); + try { + String scriptText = TestUtils.readUrlText(this.urlName); + Class scriptClass = groovyClassLoader.parseClass(scriptText); + + Binding binding = new Binding(); + binding.setVariable("context", map); + binding.setVariable("seleniumXml", this.parent); + InvokerHelper.createScript(scriptClass, binding).run(); + } catch(MalformedURLException e) { + System.out.println("Scriptrunner, runTest, MalformedURLException error: " + e.getMessage()); + } catch(IOException e) { + System.out.println("Scriptrunner, runTest, IOException error: " + e.getMessage()); + } + + + } + +} diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/InitJython.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/InitJython.java new file mode 100644 index 0000000000..f4fd6e56bd --- /dev/null +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/InitJython.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.testtools.seleniumxml; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + + +import org.apache.log4j.Logger; + +import org.python.core.PySystemState; +import org.python.util.PythonInterpreter; + +/** + * + */ +public class InitJython { + +// public Logger logger = Logger.getLogger(InitJython.class.getName()); + + private static PythonInterpreter SINGLETON; + + /** Only allow creation through the factory method */ + protected InitJython() { +// logger.setLevel(Level.DEBUG); + } + + /** + * getInterpreter initializes the Python environment the first time. It then issues a + * new Interpreter for each request. + * @return PythonInterpreter + */ + public static PythonInterpreter getInterpreter() { + + if (SINGLETON == null) { + synchronized (InitJython.class) { + Properties props = System.getProperties(); + //String ofbizHome = props.getProperty("ofbiz.home"); + + Properties pyProps = new Properties(); + + if( props.getProperty("python.home") == null) { + //pyProps.setProperty("python.home", "c:/devtools/jython2.2rc2"); + pyProps.setProperty("python.home", "c:/devtools/Python24"); + } + + //Debug.logInfo(props.toString(), module); + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + PySystemState.initialize(props, pyProps, new String[0], loader); + + SINGLETON = new PythonInterpreter(); + + SINGLETON.exec("import sys"); + SINGLETON.exec("sys.path.append(\"c:/dev/ag/seleniumXml/plugins\")"); + } + } + + return SINGLETON; + } +} diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java new file mode 100644 index 0000000000..7a1c11ff51 --- /dev/null +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.testtools.seleniumxml; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jdom.Element; +import org.ofbiz.testtools.seleniumxml.util.TestUtils; +import org.python.core.PyArray; +import org.python.core.PyDictionary; +import org.python.core.PyList; +import org.python.core.PyObject; +import org.python.util.PythonInterpreter; + +public class JythonRunner { + + private String urlName; + private SeleniumXml parent; + private SeleniumXml currentTest; + + private int currentRowIndx; + + + public JythonRunner(String urlName, SeleniumXml parent) { + super(); + this.urlName = urlName; + this.parent = parent; + } + + public void runTest() { + + PythonInterpreter interp = InitJython.getInterpreter(); + + Map map = this.parent.getMap(); + map.put("url", this.urlName); + try { + String scriptText = TestUtils.readUrlText(this.urlName); + interp.set("context", map); + interp.exec(scriptText); + } catch(MalformedURLException e) { + System.out.println("Scriptrunner, runTest, MalformedURLException error: " + e.getMessage()); + } catch(IOException e) { + System.out.println("Scriptrunner, runTest, IOException error: " + e.getMessage()); + } + + + } + +} diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/RemoteRequest.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/RemoteRequest.java new file mode 100644 index 0000000000..ac405a40cd --- /dev/null +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/RemoteRequest.java @@ -0,0 +1,333 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.testtools.seleniumxml; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CookieStore; +import org.apache.http.client.HttpResponseException; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.params.HttpClientParams; +import org.apache.http.client.protocol.ClientContext; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.scheme.SocketFactory; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.message.BasicHttpRequest; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.EntityUtils; +import org.jdom.Element; + +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + + +public class RemoteRequest { + + public static final String module = RemoteRequest.class.getName(); + + /** + * The default parameters. + * Instantiated in {@link #setup setup}. + */ + private static HttpParams defaultParameters = null; + + /** + * The scheme registry. + * Instantiated in {@link #setup setup}. + */ + private static SchemeRegistry supportedSchemes; + final private static String JsonHandleMode = "JSON_HANDLE"; + final private static String HttpHandleMode = "HTTP_HANDLE"; + + private SeleniumXml parent; + private SeleniumXml currentTest; + private List children; + private Map inMap; + private Map outMap; + private String requestUrl; + private String host; + private String responseHandlerMode; + + private int currentRowIndx; + + static { + + supportedSchemes = new SchemeRegistry(); + + // Register the "http" protocol scheme, it is required + // by the default operator to look up socket factories. + SocketFactory sf = PlainSocketFactory.getSocketFactory(); + supportedSchemes.register(new Scheme("http", sf, 80)); + + // prepare parameters + HttpParams params = new BasicHttpParams(); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + HttpProtocolParams.setContentCharset(params, "UTF-8"); + HttpProtocolParams.setUseExpectContinue(params, true); + //HttpClientParams.setAuthenticating(params, true); + defaultParameters = params; + + } + public RemoteRequest(SeleniumXml parent, List children, String requestUrl, String hostString, String responseHandlerMode) { + super(); + this.parent = parent; + this.requestUrl = requestUrl; + this.host = hostString; + this.children = children; + this.responseHandlerMode = (HttpHandleMode.equals(responseHandlerMode)) ? HttpHandleMode : JsonHandleMode; + initData(); + } + + private void initData() { + + this.inMap = new HashMap(); + this.outMap = new HashMap(); + String nm, name, value, fieldName = null; + for(Element elem: this.children) { + nm = elem.getName(); + if (nm.equals("param-in")) { + name = elem.getAttributeValue("name"); + value = this.parent.replaceParam(elem.getAttributeValue("value")); + this.inMap.put(name, value); + } else if (nm.equals("param-out")) { + name = elem.getAttributeValue("result-name"); + fieldName = elem.getAttributeValue("field-name"); + if (fieldName == null || fieldName.length() == 0) { + fieldName = name; + } + this.outMap.put(name, fieldName); + } + } + return; + } + + public void runTest() { + + ClientConnectionManager ccm = + new ThreadSafeClientConnManager(defaultParameters, supportedSchemes); + // new SingleClientConnManager(getParams(), supportedSchemes); + + DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters); + client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); + + //HttpContext clientContext = client. + //HttpHost target = new HttpHost(this.host, 80, "http"); + HttpEntity entity = null; + ResponseHandler responseHandler = null; + try { + BasicHttpContext localContext = new BasicHttpContext(); + // Create a local instance of cookie store + CookieStore cookieStore = new BasicCookieStore(); + localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); + //this.login(client, localContext); + String paramString2 = "USERNAME=" + this.parent.getUserName() + + "&PASSWORD=" + this.parent.getPassword(); + String thisUri2 = this.host + "/eng/control/login?" + paramString2; + HttpGet req2 = new HttpGet ( thisUri2 ); + req2.setHeader("Connection","Keep-Alive"); + HttpResponse rsp = client.execute(req2, localContext); + + Header sessionHeader = null; + Header[] headers = rsp.getAllHeaders(); + for (int i=0; i cookies = cookieStore.getCookies(); + System.out.println("cookies.size(): " + cookies.size()); + for (int i = 0; i < cookies.size(); i++) { + System.out.println("Local cookie(0): " + cookies.get(i)); + } + if (HttpHandleMode.equals(this.responseHandlerMode)) { + + } else { + responseHandler = new JsonResponseHandler(this); + } + String paramString = urlEncodeArgs(this.inMap, false); + String sessionHeaderValue = sessionHeader.getValue(); + int pos1 = sessionHeaderValue.indexOf("="); + int pos2 = sessionHeaderValue.indexOf(";"); + String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); + System.out.println("sessionId: " + sessionId); + String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; + //String thisUri = this.host + this.requestUrl + "?" + paramString; + System.out.println("thisUri: " + thisUri); + HttpGet req = new HttpGet ( thisUri ); + System.out.println("sessionHeader: " + sessionHeader); + req.setHeader(sessionHeader); + + String responseBody = client.execute( req, responseHandler, localContext); + /* + entity = rsp.getEntity(); + + System.out.println("----------------------------------------"); + System.out.println(rsp.getStatusLine()); + Header[] headers = rsp.getAllHeaders(); + for (int i=0; i args, boolean useExpandedEntites) { + StringBuilder buf = new StringBuilder(); + if (args != null) { + for (Map.Entry entry: args.entrySet()) { + String name = entry.getKey(); + Object value = entry.getValue(); + String valueStr = null; + if (name != null && value != null) { + if (value instanceof String) { + valueStr = (String) value; + } else { + valueStr = value.toString(); + } + + if (valueStr != null && valueStr.length() > 0) { + if (buf.length() > 0) { + if (useExpandedEntites) { + buf.append("&"); + } else { + buf.append("&"); + } + } + try { + buf.append(URLEncoder.encode(name, "UTF-8")); + } catch (UnsupportedEncodingException e) { + //Debug.logError(e, module); + } + buf.append('='); + try { + buf.append(URLEncoder.encode(valueStr, "UTF-8")); + } catch (UnsupportedEncodingException e) { + // Debug.logError(e, module); + } + } + } + } + } + return buf.toString(); + } + + public class JsonResponseHandler extends BasicResponseHandler { + + private RemoteRequest parentRemoteRequest; + + public JsonResponseHandler(RemoteRequest parentRemoteRequest) { + super(); + this.parentRemoteRequest = parentRemoteRequest; + } + public String handleResponse(org.apache.http.HttpResponse response) + throws HttpResponseException, IOException { + + String bodyString = super.handleResponse(response); + JSONObject jsonObject = null; + try { + jsonObject = JSONObject.fromObject( bodyString ); + } catch(JSONException e) { + throw new HttpResponseException(0, e.getMessage()); + } + Set> paramSet = this.parentRemoteRequest.outMap.entrySet(); + Iterator> paramIter = paramSet.iterator(); + Map parentDataMap = this.parentRemoteRequest.parent.getMap(); + while (paramIter.hasNext()) { + Map.Entry paramPair = paramIter.next(); + if (jsonObject.containsKey(paramPair.getKey())) { + Object obj = jsonObject.get(paramPair.getKey()); + parentDataMap.put(paramPair.getKey(), obj); + } + } + return bodyString; + } + + } +} diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java new file mode 100644 index 0000000000..de06c614b4 --- /dev/null +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java @@ -0,0 +1,183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.testtools.seleniumxml; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.ParserConfigurationException; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.Namespace; +import org.jdom.Attribute; +import org.jdom.filter.ElementFilter; +import org.jdom.input.SAXBuilder; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; +import org.jdom.xpath.XPath; +import org.xml.sax.SAXException; + +public class SeleniumIDEConverter { + + private Document ideFile; + private Element xmlDestRoot; + + private Namespace ns = Namespace.getNamespace("http://www.w3.org/1999/xhtml"); + private Map root; + + public void convert(String ideFile, String xmlFile) throws JDOMException, IOException, SAXException, ParserConfigurationException { + + readInputFile(ideFile); + + convertIDECommands(); + + createSeleniumXml(xmlFile); + } + + + private void readInputFile(String input) throws JDOMException, IOException, SAXException, ParserConfigurationException { + + File xmlFile = new File(input); + SAXBuilder builder = new SAXBuilder(); + this.ideFile = builder.build(xmlFile); + + //this.root = new HashMap(); + //this.root.put("doc", freemarker.ext.dom.NodeModel.parse(xmlFile)); + } + + + private void convertIDECommands() throws JDOMException { + + //XPath path = XPath.newInstance("html/body/table/tbody"); + Element root = this.ideFile.getRootElement(); + + this.xmlDestRoot = new Element("testcase"); + + //TODO: there must be a better way to do this with JDom + Element e1 = root.getChild("body",ns); + Element e2 = e1.getChild("table",ns); + Element e3 = e2.getChild("tbody",ns); + List list = e3.getChildren("tr", ns); + List commands = root.getChild("body",ns).getChild("table",ns).getChild("tbody",ns).getChildren("tr", ns); + for(Element elem: commands) { + processIDECommand(elem); + } + + } + + private void processIDECommand(Element elem) throws JDOMException { + + + List cmd = elem.getChildren("td", ns); + Element cmdElem = cmd.get(0); + + String cmdToCompare = cmdElem.getValue(); + System.out.println("Checking for cmd: " + cmdToCompare); + if("clickAndWait".compareTo(cmdElem.getValue()) == 0 ) { + System.out.println("Found clickAndWait"); + this.xmlDestRoot.addContent( buildCommand("click", "locator", cmd.get(1).getValue(), null, null) ); + this.xmlDestRoot.addContent( buildCommand("waitForPageToLoad", "value", "10000", null, null) ); + + } else if("type".compareTo( cmdElem.getValue()) == 0 ) { + System.out.println("Found type"); + this.xmlDestRoot.addContent ( buildCommand("type", "name", cmd.get(1).getValue(), "value", cmd.get(2).getValue()) ); + + } else if("select".compareTo(cmdElem.getValue()) == 0 ) { + System.out.println("Found select"); + this.xmlDestRoot.addContent( buildCommand("select", "locator", cmd.get(1).getValue(), "option", cmd.get(2).getValue()) ); + + } else if("open".compareTo(cmdElem.getValue()) == 0 ) { + System.out.println("Found open"); + this.xmlDestRoot.addContent( buildCommand("open", "value", cmd.get(1).getValue(), null, null) ); + + } else if("click".compareTo(cmdElem.getValue()) == 0 ) { + Element newCmd = new Element("click"); + newCmd.setAttribute("locator", cmd.get(1).getValue()); + this.xmlDestRoot.addContent(newCmd); + + } else if("doubleClick".compareTo(cmdElem.getValue()) == 0 ) { + Element newCmd = new Element("doubleClick"); + newCmd.setAttribute("locator", cmd.get(1).getValue()); + this.xmlDestRoot.addContent(newCmd); + + } else { + System.out.println("WARNING: No definition for " + cmdElem.getValue() + " defaulting to us 'reflection'."); + Element newCmd = new Element(cmdElem.getValue()); + //List attributes = cmdElem.getAttributes(); + int size = cmd.size()-1; + for(int i=1; i map; + private Document doc; + private DefaultSelenium sel; + private static Properties props; + private String testSourcePath; + private String username; + private String password; + + public static void main(String[] args) throws JDOMException, IOException{ + if(args.length == 0) { + System.out.println("Please include a path for the selenium XML test file."); + } else { + SeleniumXml sel = new SeleniumXml(); + for (String arg: args) { + if (arg.startsWith("-username")) { + sel.username = arg.substring(10); + } else if (arg.startsWith("-password")) { + sel.password = arg.substring(10); + } else { + sel.testSourcePath = arg; + } + } + sel.runTest(args[0]); + } + } + + public SeleniumXml() throws IOException { + this.map = new HashMap(); + if (props == null) { + props = new Properties(); + initConfig(); + } + logger.setLevel(Level.DEBUG); + } + + private static void initConfig() throws IOException { + try { + String configFile = System.getProperty(PROPS_NAME); + if (configFile == null) { + String errMsg = "The Java environment (-Dxxx=yyy) variable with name " + PROPS_NAME + " is not set, cannot resolve location."; + throw new MalformedURLException(errMsg); + } + BasicConfigurator.configure(); + InputStream in = new FileInputStream(configFile); + props.load(in); + in.close(); + + + } catch (IOException e) { + e.printStackTrace(); + throw e; + } + } + + /** + * Constructor to preset with an existing Map of parameters. Intended to be used + * for nested Selenium tests. + * @param map + */ + public SeleniumXml(SeleniumXml selenium) { + this.sel = selenium.getSelenium(); + this.map = selenium.getParameterMap(); + } + + public DefaultSelenium getSelenium() { + return this.sel; + } + public Map getParameterMap() { + return this.map; + } + public void runTest(String fileName) throws JDOMException, IOException { + readFile(fileName); + setupSelenium(); + runCommands(); + } + + public void runCommands(){ + Element root = this.doc.getRootElement(); + List nodes = root.getChildren(); + runCommands(nodes); + } + + public void runCommands(List nodes){ + + for(Element elem: nodes) { + if("type" == elem.getName()) { + typeCmd(elem); + + } else if("clickAt" == elem.getName()) { + clickAt(elem); + } else if("waitForValue" == elem.getName()) { + waitForValue(elem); + } else if("waitForCondition" == elem.getName()) { + waitForCondition(elem); + } else if("loadData" == elem.getName()) { + loadData(elem); + } else if("loadData" == elem.getName()) { + loadData(elem); + } else if("jythonRunner" == elem.getName()) { + jythonRunner(elem); + } else if("groovyRunner" == elem.getName()) { + groovyRunner(elem); + } else if("dataLoop" == elem.getName()) { + dataLoop(elem); + } else if("remoteRequest" == elem.getName()) { + remoteRequest(elem); + } else if("selectPopup" == elem.getName()) { + selectPopup(elem); + } else if("getAllWindowIds" == elem.getName()) { + getAllWindowIds(elem); + } else if("captureTextInPage" == elem.getName()) { + captureTextInPageCmd(elem); + } else if("getSelectedLabel" == elem.getName()) { + getSelectedLabel(elem); + } else if("getSelectedValue" == elem.getName()) { + getSelectedValue(elem); + } else if("getSelectedId" == elem.getName()) { + getSelectedId(elem); + } else if("testcase" == elem.getName()) { + testcase(elem); + } else if("assertContains" == elem.getName()) { + assertContains(elem); + } else if("getHtmlSource" == elem.getName()) { + getHtmlSource(elem); + } else if("getBodyText" == elem.getName()) { + getBodyText(elem); + } else if("setup" == elem.getName()) { + continue; //setup is handled previously + } else if("print" == elem.getName()) { + printCmd(elem); + } else if("waitForPageToLoad" == elem.getName()) { + waitForPageToLoadCmd(elem); + } else if("getSelectedIds" == elem.getName()) { + getSelectedIdsCmd(elem); + } else if("copy" == elem.getName()) { + copyCmd(elem); + } else if("append" == elem.getName()) { + appendCmd(elem); + } else if("open" == elem.getName()) { + openCmd(elem); + } else if("click" == elem.getName()) { + clickCmd(elem); + } else if("select" == elem.getName()) { + selectCmd(elem); + } else if("uniqueId" == elem.getName()) { + uniqueIdCmd(elem); + } else if("randomAlphaString" == elem.getName()) { + randomAlphaStringCmd(elem); + } else if("randomString" == elem.getName()) { + randomStringCmd(elem); + } else if("setSpeed" == elem.getName()) { + setSpeed(elem); + } else { + //logger.error("Unknown SeleniumXml command found:"+elem.getName()); + //Use reflection with parameters using the naming convention param1, param2, and any return results stored + //in map using "out" + logger.info("Undefined command calling by reflection for command: " + elem.getName()); + callByReflection(elem); + } + } + + } + + private void callByReflection(Element elem) { + + String methodName = elem.getName(); + //Support two parameters for all selenium RC calls + String param1 = elem.getAttributeValue("param1"); + String param2 = elem.getAttributeValue("param2"); + + Class[] paramTypes = null; + Object[] args = null; + if( (param1 != null) && (param2 != null) ) { + paramTypes = new Class[] {String.class, String.class}; + args = new Object[] {param1, param2}; + } else if (param1 != null) { + paramTypes = new Class[] {String.class}; + args = new Object[] {param1}; + } else { + paramTypes = new Class[] {}; + args = new Object[] {}; + } + + //Capture the output name for "get" methods + String out = elem.getAttributeValue("out"); + + Method m; + try { + m = (Method) this.sel.getClass().getDeclaredMethod(methodName, paramTypes); + Object results = m.invoke(this.sel, args); + + //Add output parameter to common map + if( (out != null) && (results != null)) { + addParam(out, results); + } + } catch (Exception e) { + // TODO Auto-generated catch block + logger.error("Exception occurred when Unknown SeleniumXml command found:"+elem.getName()); + e.printStackTrace(); + } + + + } + + public void waitForValue(Element elem) { + + String locator = elem.getAttributeValue("locator"); + String timeout = elem.getAttributeValue("timeout"); + String outParam = elem.getAttributeValue("out"); + + int maxTime = Integer.parseInt(timeout); + int maxSeconds = maxTime/1000; + logger.debug("waitForValue: locator=" + locator + " timeout=" + timeout); + //this.sel.waitForCondition(script, timeout); + String foundValue = null; + for(int second=0;; second++) { + if(second >= maxSeconds) { +// throw new SeleniumException("waitForValue exceeded timeout: " + maxTime); + } + try{ + //getValue throws an exception if it can't find locator + // - sleep for 1 sec and try again + // - otherwise break as we found the value + foundValue = sel.getValue(locator); + if(outParam != null) { + this.addParam(outParam, foundValue); + } + break; // + } catch(Exception e) { + //wait for 1 second and then resume + try { + Thread.sleep(1000); + } catch (InterruptedException threadE) { + // TODO Auto-generated catch block + threadE.printStackTrace(); + + } + } + } + } + + public void waitForCondition(Element elem) { + + String script = elem.getAttributeValue("script"); + String timeout = elem.getAttributeValue("timeout"); + + logger.debug("waitForCondition: script=" + script + " timeout=" + timeout); + this.sel.waitForCondition(script, timeout); + } + + public void loadData(Element elem) { + + String file = elem.getAttributeValue("file"); + String iterations = elem.getAttributeValue("iterations"); + List children = elem.getChildren(); + + DataLoader loader = new DataLoader(file, iterations, this, children); + loader.runTest(); + } + + public void groovyRunner(Element elem) { + + String urlName = elem.getAttributeValue("srcUrl"); + GroovyRunner runner = new GroovyRunner(urlName, this); + runner.runTest(); + } + + public void jythonRunner(Element elem) { + + String urlName = elem.getAttributeValue("srcUrl"); + JythonRunner runner = new JythonRunner(urlName, this); + runner.runTest(); + } + + public void dataLoop(Element elem) { + + String dataListName = elem.getAttributeValue("dataListName"); + List children = elem.getChildren(); + + DataLoop looper = new DataLoop(dataListName, this, children); + looper.runTest(); + } + + public void remoteRequest(Element elem) { + + String requestUrl = elem.getAttributeValue("url"); + String host = elem.getAttributeValue("host"); + if (host == null || host.length() == 0) { + host = props.getProperty("startUrl"); + } + String responseHandlerMode = elem.getAttributeValue("responseHandlerMode"); + List children = elem.getChildren(); + + RemoteRequest loader = new RemoteRequest( this, children, requestUrl, host, responseHandlerMode); + loader.runTest(); + } + + public String getParamValue(String key) { + return (String) this.map.get(key); + } + + public Object getParamValue(Object key) { + return this.map.get(key); + } + + public void addParam(String name, String value) { + //logger.info("addParam: name=" + name + " value="+value); + this.map.put(name, value); + } + + public void addParam(String name, Object value) { + //logger.info("addParam: name=" + name + " value="+value); + this.map.put(name, value); + } + + private void assertContains(Element elem) { + String src = replaceParam(elem.getAttributeValue("src")); + String test = replaceParam(elem.getAttributeValue("test")); + int indxSearch = src.indexOf(test); + if(indxSearch == -1) { + logger.info("assertContains didn't find " + test + " in the src"); + } else { + logger.info("assertContains found " + test + " in the src"); + } + Assert.assertTrue(indxSearch != -1); + //String text = this.sel.getHtmlSource(); + } + + private void selectPopup(Element elem) { + String locator = elem.getAttributeValue("locator"); +// String winId = elem.getAttributeValue("windowId"); + String timeout = elem.getAttributeValue("timeout"); + + //this.sel.waitForPopUp(winId, timeout); + this.sel.click(locator); + + String[] winNames = this.sel.getAllWindowNames(); + this.sel.selectWindow("name=" + winNames[1]); + } + + private void getAllWindowIds(Element elem) { + String[] winIds = this.sel.getAllWindowIds(); + for(int i=0; i