diff --git a/framework/testtools/build.xml b/framework/testtools/build.xml index db7707d8ac..dc070c48fd 100644 --- a/framework/testtools/build.xml +++ b/framework/testtools/build.xml @@ -32,8 +32,8 @@ under the License. - + @@ -45,7 +45,12 @@ under the License. + + + + + @@ -58,10 +63,34 @@ under the License. + + + + + + + + + + + + + + + + + + + + + + + + - diff --git a/framework/testtools/config/seleniumXml.properties b/framework/testtools/config/seleniumXml.properties index 8cc918d10f..86de10698c 100644 --- a/framework/testtools/config/seleniumXml.properties +++ b/framework/testtools/config/seleniumXml.properties @@ -1,5 +1,5 @@ serverHost=localhost proxyPort=4444 -browser=*firefox /usr/lib/firefox-3.0.14/firefox +browser=*firefox /usr/lib/firefox-3.0.8/firefox startUrl=http://localhost:8080/ log4jFile=./config/log4j.properties \ No newline at end of file diff --git a/framework/testtools/runSeleniumServer.bat b/framework/testtools/runSeleniumServer.bat index 4025d39f51..594526350c 100644 --- a/framework/testtools/runSeleniumServer.bat +++ b/framework/testtools/runSeleniumServer.bat @@ -1 +1 @@ -java -jar ../../framework/testtools/lib/selenium-server.jar -timeout 240 +java -jar ../../framework/testtools/lib/selenium-server.jar -firefoxProfileTemplate ./config/firefox_profile -timeout 240 diff --git a/framework/testtools/runSeleniumServer.sh b/framework/testtools/runSeleniumServer.sh index 50b5bc53b4..f59f1d720c 100755 --- a/framework/testtools/runSeleniumServer.sh +++ b/framework/testtools/runSeleniumServer.sh @@ -6,6 +6,5 @@ else JAVA=java fi -"$JAVA" -jar ../../framework/testtools/lib/selenium-server.jar -singleWindow -trustAllSSLCertificates -timeout 240 -exit 0 - +#"$JAVA" -jar ../../framework/testtools/lib/selenium-server.jar -firefoxProfileTemplate ./config/firefox_profile -singleWindow -trustAllSSLCertificates -timeout 240 +"$JAVA" -jar ../../framework/testtools/lib/selenium-server.jar -singleWindow -timeout 240 diff --git a/framework/testtools/runSeleniumXml.bat b/framework/testtools/runSeleniumXml.bat index ed4dc0e227..4508faac7f 100644 --- a/framework/testtools/runSeleniumXml.bat +++ b/framework/testtools/runSeleniumXml.bat @@ -8,6 +8,8 @@ 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 +set CP=%CP%;%OFBIZ_HOME%/framework/base/lib/javolution-5.2.3.jar +set CP=%CP%;%OFBIZ_HOME%/framework/base/build/lib/ofbiz-base.jar echo %CP% diff --git a/framework/testtools/runSeleniumXml.sh b/framework/testtools/runSeleniumXml.sh index a0e7adea96..70a0515ddc 100755 --- a/framework/testtools/runSeleniumXml.sh +++ b/framework/testtools/runSeleniumXml.sh @@ -10,6 +10,7 @@ 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 export CP=$CP:$OFBIZ_HOME/framework/base/lib/javolution-5.2.3.jar +export CP=$CP:$OFBIZ_HOME/framework/base/build/lib/ofbiz-base.jar echo $CP diff --git a/framework/testtools/src/org/ofbiz/testtools/VerifySeleniumSetups.java b/framework/testtools/src/org/ofbiz/testtools/VerifySeleniumSetups.java index 11019f6b8c..2101337336 100644 --- a/framework/testtools/src/org/ofbiz/testtools/VerifySeleniumSetups.java +++ b/framework/testtools/src/org/ofbiz/testtools/VerifySeleniumSetups.java @@ -30,150 +30,150 @@ import net.sf.json.JSONObject; public class VerifySeleniumSetups { - public static final String module = VerifySeleniumSetups.class.getName(); - private static int currentValue = 0; - private static int contentLength = 0; - private static Map josonMap = null; - private static String urlSite = "http://downloads.sourceforge.net/seleniumxml/selenium-server-1.0-SNAPSHOT-20081126.jar?use_mirror="; - private static String libPath = "framework/testtools/lib/selenium-server.jar"; + public static final String module = VerifySeleniumSetups.class.getName(); + private static int currentValue = 0; + private static int contentLength = 0; + private static Map josonMap = null; + private static String urlSite = "http://downloads.sourceforge.net/seleniumxml/selenium-server-1.0-SNAPSHOT-20081126.jar?use_mirror="; + private static String libPath = "framework/testtools/lib/selenium-server.jar"; - public VerifySeleniumSetups(){ + public VerifySeleniumSetups(){ - } + } - /* prepare lib for selenium test - * Check & download selenium-server.jar from http://downloads.sourceforge.net/seleniumxml/selenium-server-1.0-SNAPSHOT-20081126.jar?use_mirror= - * Check a change use HTTP as the default at file framework/webapp/config/url.properties - * Check correct the config/seleniumXml.properties and firefox path - */ + /* prepare lib for selenium test + * Check & download selenium-server.jar from http://downloads.sourceforge.net/seleniumxml/selenium-server-1.0-SNAPSHOT-20081126.jar?use_mirror= + * Check a change use HTTP as the default at file framework/webapp/config/url.properties + * Check correct the config/seleniumXml.properties and firefox path + */ - public static String verifyConfig(HttpServletRequest request, HttpServletResponse response){ - boolean lib = false; - boolean urlset = false; - Map msgMap = FastMap.newInstance(); - Properties urlProps = null; - try{ - /* Check and down load selenium-server.jar */ - File file = new File(libPath); - URL url = new URL(urlSite); - URLConnection connection = url.openConnection(); - contentLength = connection.getContentLength(); - if(contentLength == -1){ - request.setAttribute("_ERROR_MESSAGE_", "can not conect to the internet"); - } - Debug.log("file size. "+contentLength,module); - if(file.exists()){ - if(contentLength == file.length()){ - lib = true; - }else lib = false; - } - msgMap.put("LIBFLAG",lib); + public static String verifyConfig(HttpServletRequest request, HttpServletResponse response){ + boolean lib = false; + boolean urlset = false; + Map msgMap = FastMap.newInstance(); + Properties urlProps = null; + try{ + /* Check and down load selenium-server.jar */ + File file = new File(libPath); + URL url = new URL(urlSite); + URLConnection connection = url.openConnection(); + contentLength = connection.getContentLength(); + if (contentLength == -1) { + request.setAttribute("_ERROR_MESSAGE_", "can not conect to the internet"); + } + Debug.log("file size. "+contentLength,module); + if (file.exists()) { + if (contentLength == file.length()) { + lib = true; + } else lib = false; + } + msgMap.put("LIBFLAG",lib); - /* Check a change use HTTP as the default */ - String httpStatus = null; - URL urlProp = UtilURL.fromResource("url.properties"); - if (urlProps == null) { - urlProps = new Properties(); - if (urlProp == null) { - String errMsg = "variable with name " + urlProp.toString() + " is not set, cannot resolve location."; - throw new MalformedURLException(errMsg); - } - urlProps = UtilProperties.getProperties(urlProp); - if(urlProps != null){ - httpStatus = urlProps.getProperty("port.https.enabled"); - if(httpStatus != null && httpStatus.equals("N")){ - urlset = true; - } - } - } - msgMap.put("URLFLAG",urlset); - request.setAttribute("MSGMAP", msgMap); - }catch(Exception e){ - Debug.logError(e.getMessage(), module); - } - return "success"; - } + /* Check a change use HTTP as the default */ + String httpStatus = null; + URL urlProp = UtilURL.fromResource("url.properties"); + if (urlProps == null) { + urlProps = new Properties(); + if (urlProp == null) { + String errMsg = "variable with name " + urlProp.toString() + " is not set, cannot resolve location."; + throw new MalformedURLException(errMsg); + } + urlProps = UtilProperties.getProperties(urlProp); + if (urlProps != null) { + httpStatus = urlProps.getProperty("port.https.enabled"); + if (httpStatus != null && httpStatus.equals("N")) { + urlset = true; + } + } + } + msgMap.put("URLFLAG",urlset); + request.setAttribute("MSGMAP", msgMap); + }catch(Exception e){ + Debug.logError(e.getMessage(), module); + } + return "success"; + } - public static void doDownload( HttpServletRequest request, HttpServletResponse response){ - URL url = null; - long bytesRead= 0; - currentValue = 0; - contentLength = 0; - BufferedInputStream in = null; - BufferedOutputStream out = null; - try { - url = new URL(urlSite); + public static void doDownload( HttpServletRequest request, HttpServletResponse response){ + URL url = null; + long bytesRead= 0; + currentValue = 0; + contentLength = 0; + BufferedInputStream in = null; + BufferedOutputStream out = null; + try { + url = new URL(urlSite); - URLConnection connection = url.openConnection(); - contentLength = connection.getContentLength(); - InputStream stream = connection.getInputStream(); - Debug.log("getContentLength is :"+contentLength); + URLConnection connection = url.openConnection(); + contentLength = connection.getContentLength(); + InputStream stream = connection.getInputStream(); + Debug.log("getContentLength is :"+contentLength); - in = new BufferedInputStream(stream); + in = new BufferedInputStream(stream); - long totalBytes = in.available(); - Debug.log("totalBytes is : "+totalBytes); + long totalBytes = in.available(); + Debug.log("totalBytes is : "+totalBytes); - byte[] b = new byte[1024]; + byte[] b = new byte[1024]; - FileOutputStream file = new FileOutputStream(libPath); - out = new BufferedOutputStream(file); + FileOutputStream file = new FileOutputStream(libPath); + out = new BufferedOutputStream(file); - int r; - Debug.log("currentValue is : "+currentValue+" bytes"); - while ((r = in.read(b,0,b.length)) != -1) { - out.write(b,0,r); - bytesRead += r; - currentValue = (int)(bytesRead * 100 / contentLength); - // Debug.log("loading.. :"+bytesRead); - } - out.flush(); - } catch (IOException ex) { - Debug.logError("Error message :"+ex.getMessage(),module); - }finally { - try { - if (in != null) in.close(); - if (out != null) out.close(); - }catch (Exception ex) { - Debug.logError("Error message :"+ex.getMessage(),module); - } - } - } + int r; + Debug.log("currentValue is : "+currentValue+" bytes"); + while ((r = in.read(b,0,b.length)) != -1) { + out.write(b,0,r); + bytesRead += r; + currentValue = (int)(bytesRead * 100 / contentLength); + // Debug.log("loading.. :"+bytesRead); + } + out.flush(); + } catch (IOException ex) { + Debug.logError("Error message :"+ex.getMessage(),module); + }finally { + try { + if (in != null) in.close(); + if (out != null) out.close(); + }catch (Exception ex) { + Debug.logError("Error message :"+ex.getMessage(),module); + } + } + } - public static String checkProgressDownloadStatus(HttpServletRequest request, HttpServletResponse response){ - if(josonMap == null){ - josonMap = FastMap.newInstance(); - } + public static String checkProgressDownloadStatus(HttpServletRequest request, HttpServletResponse response){ + if(josonMap == null){ + josonMap = FastMap.newInstance(); + } - josonMap.put("loadPercent", currentValue); - josonMap.put("contentLength", contentLength); - toJsonObject(josonMap,response); + josonMap.put("loadPercent", currentValue); + josonMap.put("contentLength", contentLength); + toJsonObject(josonMap,response); - return "success"; - } + return "success"; + } - public static void toJsonObject(Map attrMap, HttpServletResponse response){ - JSONObject json = JSONObject.fromObject(attrMap); - String jsonStr = json.toString(); - if (jsonStr == null) { - Debug.logError("JSON Object was empty; fatal error!",module); - } - // set the X-JSON content type - response.setContentType("application/json"); - // jsonStr.length is not reliable for unicode characters - try { - response.setContentLength(jsonStr.getBytes("UTF8").length); - } catch (UnsupportedEncodingException e) { - Debug.logError("Problems with Json encoding",module); - } - // return the JSON String - Writer out; - try { - out = response.getWriter(); - out.write(jsonStr); - out.flush(); - } catch (IOException e) { - Debug.logError("Unable to get response writer",module); - } - } + public static void toJsonObject(Map attrMap, HttpServletResponse response){ + JSONObject json = JSONObject.fromObject(attrMap); + String jsonStr = json.toString(); + if (jsonStr == null) { + Debug.logError("JSON Object was empty; fatal error!",module); + } + // set the X-JSON content type + response.setContentType("application/json"); + // jsonStr.length is not reliable for unicode characters + try { + response.setContentLength(jsonStr.getBytes("UTF8").length); + } catch (UnsupportedEncodingException e) { + Debug.logError("Problems with Json encoding",module); + } + // return the JSON String + Writer out; + try { + out = response.getWriter(); + out.write(jsonStr); + out.flush(); + } catch (IOException e) { + Debug.logError("Unable to get response writer",module); + } + } } diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java index b62e183cc2..ed824bc3bf 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/DataLoader.java @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.ofbiz.testtools.seleniumxml; import java.util.List; @@ -29,6 +30,8 @@ import org.python.core.PyDictionary; import org.python.core.PyList; import org.python.core.PyObject; import org.python.util.PythonInterpreter; +import org.ofbiz.testtools.seleniumxml.InitJython; +import org.ofbiz.testtools.seleniumxml.SeleniumXml; public class DataLoader { @@ -37,18 +40,15 @@ public class DataLoader { 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; @@ -66,6 +66,7 @@ public class DataLoader { Map map = FastMap.newInstance(); map.put("file", this.file); interp.set("params", map); + interp.exec("from csvreader import CSVReader"); String cmd = "reader = CSVReader('" + this.file + "')"; interp.exec(cmd); @@ -74,21 +75,21 @@ public class DataLoader { 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() { + + public void runTest() throws TestCaseException { this.currentTest = new SeleniumXml(this.parent); + this.currentTest.setUserName(this.parent.getUserName()); + this.currentTest.setPassword(this.parent.getPassword()); Map dataMap = this.parent.getMap(); List> dataList = UtilGenerics.cast(dataMap.get(this.dataListName)); - for (Map mp: dataList) { + //for (Map mp: dataList) { // TODO, WARNING - these name could collide with names already in the test context - for (Map.Entry entry: mp.entrySet()) { - String name = entry.getKey(); - Object value = entry.getValue(); - dataMap.put(name, value); - } - currentTest.runCommands(this.children); + //for (Map.Entry entry: mp.entrySet()) { + //String name = entry.getKey(); + //Set eSet = mp.entrySet(); + Iterator iter2 = dataList.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); } -} +} \ No newline at end of file diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java index 7ebc84201e..4ca9758c36 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/GroovyRunner.java @@ -6,9 +6,9 @@ * 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 @@ -34,6 +34,7 @@ import java.util.Map; import org.codehaus.groovy.runtime.InvokerHelper; import org.jdom.Element; import org.ofbiz.testtools.seleniumxml.util.TestUtils; +import org.ofbiz.testtools.seleniumxml.SeleniumXml; public class GroovyRunner { @@ -63,9 +64,9 @@ public class GroovyRunner { binding.setVariable("context", map); binding.setVariable("seleniumXml", this.parent); InvokerHelper.createScript(scriptClass, binding).run(); - } catch (MalformedURLException e) { + } catch(MalformedURLException e) { System.out.println("Scriptrunner, runTest, MalformedURLException error: " + e.getMessage()); - } catch (IOException e) { + } 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 index d663ce0683..efd424c32e 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/InitJython.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/InitJython.java @@ -6,9 +6,9 @@ * 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 @@ -27,6 +27,7 @@ import org.apache.log4j.Logger; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; +import org.ofbiz.testtools.seleniumxml.InitJython; /** * @@ -45,7 +46,7 @@ public class InitJython { /** * getInterpreter initializes the Python environment the first time. It then issues a * new Interpreter for each request. - * @return PythonInterpreter + * @return PythonInterpreter */ public static PythonInterpreter getInterpreter() { @@ -56,7 +57,7 @@ public class InitJython { Properties pyProps = new Properties(); - if (props.getProperty("python.home") == null) { + if( props.getProperty("python.home") == null) { //pyProps.setProperty("python.home", "c:/devtools/jython2.2rc2"); pyProps.setProperty("python.home", "c:/devtools/Python24"); } diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java index d60d7a5183..9d0d3fe8b1 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/JythonRunner.java @@ -6,9 +6,9 @@ * 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 @@ -18,22 +18,11 @@ */ 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 { @@ -61,9 +50,9 @@ public class JythonRunner { String scriptText = TestUtils.readUrlText(this.urlName); interp.set("context", map); interp.exec(scriptText); - } catch (MalformedURLException e) { + } catch(MalformedURLException e) { System.out.println("Scriptrunner, runTest, MalformedURLException error: " + e.getMessage()); - } catch (IOException e) { + } 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 index 5d5698c592..00ddda0d2f 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/RemoteRequest.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/RemoteRequest.java @@ -6,9 +6,9 @@ * 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 @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.ofbiz.testtools.seleniumxml; import java.io.IOException; @@ -28,19 +29,17 @@ import java.util.Set; import javolution.util.FastMap; +import net.sf.json.JSONException; +import net.sf.json.JSONObject; + 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; @@ -53,18 +52,12 @@ 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 { @@ -92,6 +85,11 @@ public class RemoteRequest { private String requestUrl; private String host; private String responseHandlerMode; + + //Login-As parameters + private String loginAsUrl; + private String loginAsUserParam; + private String loginAsPasswordParam; private int currentRowIndx; @@ -113,6 +111,19 @@ public class RemoteRequest { defaultParameters = params; } + public RemoteRequest(SeleniumXml parent, List children, List loginAs, String requestUrl, String hostString, String responseHandlerMode) { + + this(parent, children, requestUrl, hostString, responseHandlerMode); + if(loginAs != null && !loginAs.isEmpty()) { + Element elem = loginAs.get(0); + + this.loginAsUserParam = elem.getAttributeValue("username-param"); + this.loginAsPasswordParam = elem.getAttributeValue("password-param"); + this.loginAsUrl = elem.getAttributeValue("url"); + + } + } + public RemoteRequest(SeleniumXml parent, List children, String requestUrl, String hostString, String responseHandlerMode) { super(); this.parent = parent; @@ -120,6 +131,8 @@ public class RemoteRequest { this.host = hostString; this.children = children; this.responseHandlerMode = (HttpHandleMode.equals(responseHandlerMode)) ? HttpHandleMode : JsonHandleMode; + System.out.println("RemoteRequest, requestUrl: " + this.requestUrl); + System.out.println("RemoteRequest, host: " + this.host); initData(); } @@ -133,6 +146,7 @@ public class RemoteRequest { if (nm.equals("param-in")) { name = elem.getAttributeValue("name"); value = this.parent.replaceParam(elem.getAttributeValue("value")); + System.out.println("RemoteRequest, param-in, name: " + name + ", value: " + value); this.inMap.put(name, value); } else if (nm.equals("param-out")) { name = elem.getAttributeValue("result-name"); @@ -155,8 +169,10 @@ public class RemoteRequest { DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters); client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); - //HttpContext clientContext = client. - //HttpHost target = new HttpHost(this.host, 80, "http"); + // + // We first try to login with the loginAs to set the session. + // Then we call the remote service. + // HttpEntity entity = null; ResponseHandler responseHandler = null; try { @@ -164,50 +180,92 @@ public class RemoteRequest { // 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)); - } + Header sessionHeader = null; + + if(this.loginAsUrl != null ) { + + String loginAsUri = this.host + this.loginAsUrl; + String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam; + + HttpGet req2 = new HttpGet ( loginAsUri + loginAsParamString ); + System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString); + + req2.setHeader("Connection","Keep-Alive"); + HttpResponse rsp = client.execute(req2, localContext); + + 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)); + } + } + //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 = null; + if(sessionHeader != null) { + String sessionHeaderValue = sessionHeader.getValue(); + int pos1 = sessionHeaderValue.indexOf("="); + int pos2 = sessionHeaderValue.indexOf(";"); + String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); + thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; + } else { + thisUri = this.host + this.requestUrl + "?" + paramString; + } + //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); + + HttpGet req = new HttpGet ( thisUri ); + if(sessionHeader != null) { + req.setHeader(sessionHeader); + } - String responseBody = client.execute(req, responseHandler, localContext); + String responseBody = client.execute( req, responseHandler, localContext); /* entity = rsp.getEntity(); @@ -223,9 +281,9 @@ public class RemoteRequest { System.out.println(EntityUtils.toString(rsp.getEntity())); } */ - } catch (HttpResponseException e) { + } catch(HttpResponseException e) { System.out.println(e.getMessage()); - } catch (IOException e) { + } catch(IOException e) { System.out.println(e.getMessage()); } finally { // If we could be sure that the stream of the entity has been @@ -236,7 +294,7 @@ public class RemoteRequest { try { if (entity != null) entity.consumeContent(); // release connection gracefully - } catch (IOException e) { + } catch(IOException e) { System.out.println("in 'finally' " + e.getMessage()); } @@ -249,7 +307,7 @@ public class RemoteRequest { String paramString = "USERNAME=" + this.parent.getUserName() + "&PASSWORD=" + this.parent.getPassword(); String thisUri = this.host + "/eng/control/login?" + paramString; - HttpGet req = new HttpGet (thisUri); + HttpGet req = new HttpGet ( thisUri ); req.setHeader("Connection","Keep-Alive"); client.execute(req, localContext); @@ -313,8 +371,8 @@ public class RemoteRequest { String bodyString = super.handleResponse(response); JSONObject jsonObject = null; try { - jsonObject = JSONObject.fromObject(bodyString); - } catch (JSONException e) { + jsonObject = JSONObject.fromObject( bodyString ); + } catch(JSONException e) { throw new HttpResponseException(0, e.getMessage()); } Set> paramSet = this.parentRemoteRequest.outMap.entrySet(); @@ -324,6 +382,7 @@ public class RemoteRequest { Map.Entry paramPair = paramIter.next(); if (jsonObject.containsKey(paramPair.getKey())) { Object obj = jsonObject.get(paramPair.getKey()); + System.out.println("RemoteRequest, param-out, name: " + paramPair.getKey() + ", value: " + obj); parentDataMap.put(paramPair.getKey(), obj); } } diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java index f8282c5d20..7f5b7fd586 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumIDEConverter.java @@ -16,13 +16,12 @@ * 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; @@ -32,12 +31,9 @@ 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; import org.ofbiz.base.util.UtilGenerics; @@ -49,18 +45,119 @@ public class SeleniumIDEConverter { 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()); + } + + } +*/ + + private void createSeleniumXml(String outputFile) { + + try { + FileOutputStream out = new FileOutputStream(outputFile); + XMLOutputter serializer = new XMLOutputter( Format.getPrettyFormat()); + serializer.output(this.xmlDestRoot, out); + out.flush(); + out.close(); + } catch (IOException e) { + System.err.println(e); + } + } + /** + * @param args + */ +/* public static void main(String[] args) { + // TODO Auto-generated method stub + if(args.length != 2) { + System.out.println("Please include the source and destination file paths."); + } else { + SeleniumIDEConverter sel = new SeleniumIDEConverter(); + try { + sel.convert(args[0], args[1]); + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } File xmlFile = new File(input); SAXBuilder builder = new SAXBuilder(); @@ -69,7 +166,7 @@ public class SeleniumIDEConverter { //this.root = new HashMap(); //this.root.put("doc", freemarker.ext.dom.NodeModel.parse(xmlFile)); } - +*/ private void convertIDECommands() throws JDOMException { @@ -151,18 +248,7 @@ public class SeleniumIDEConverter { } return newCmd; } - private void createSeleniumXml(String outputFile) { - try { - FileOutputStream out = new FileOutputStream(outputFile); - XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat()); - serializer.output(this.xmlDestRoot, out); - out.flush(); - out.close(); - } catch (IOException e) { - System.err.println(e); - } - } /** * @param args */ @@ -181,5 +267,4 @@ public class SeleniumIDEConverter { } } } - -} +} \ No newline at end of file diff --git a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumXml.java b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumXml.java index e9f1872d78..22638d75f0 100644 --- a/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumXml.java +++ b/framework/testtools/src/org/ofbiz/testtools/seleniumxml/SeleniumXml.java @@ -6,9 +6,9 @@ * 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 @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.ofbiz.testtools.seleniumxml; import java.io.BufferedInputStream; @@ -26,16 +27,17 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.List; -import java.util.ArrayList; import java.util.Map; import java.util.Properties; +import java.util.Set; +import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.lang.reflect.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -44,26 +46,29 @@ import junit.framework.Assert; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.lang.RandomStringUtils; +import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; -import org.apache.log4j.BasicConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.ofbiz.testtools.seleniumxml.util.TestUtils; - import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilHttp; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilURL; +import org.ofbiz.testtools.seleniumxml.DataLoader; +import org.ofbiz.testtools.seleniumxml.DataLoop; +import org.ofbiz.testtools.seleniumxml.GroovyRunner; +import org.ofbiz.testtools.seleniumxml.JythonRunner; +import org.ofbiz.testtools.seleniumxml.RemoteRequest; import com.thoughtworks.selenium.DefaultSelenium; -//import com.thoughtworks.selenium.SeleniumException; +import com.thoughtworks.selenium.SeleniumException; public class SeleniumXml { - //public static final String PROPS_NAME = "selenium.config"; public static String PROPS_NAME = "selenium.config"; Logger logger = Logger.getLogger(SeleniumXml.class.getName()); @@ -77,9 +82,10 @@ public class SeleniumXml { private String testSourcePath; private String username; private String password; + private String testCaseDirectory; - public static void main(String[] args) throws JDOMException, IOException{ - if (args.length == 0) { + public static void main(String[] args) throws JDOMException, IOException, TestCaseException{ + if(args.length == 0) { System.out.println("Please include a path for the selenium XML test file."); } else { SeleniumXml sel = new SeleniumXml(); @@ -92,37 +98,70 @@ public class SeleniumXml { sel.testSourcePath = arg; } } - sel.runTest(args[0]); + + File testFile = new File(args[0]); + if (testFile.exists()) { + System.err.println(" Argument : "+ args[0] ); + System.err.println(" Full absolute path of file : "+ testFile.getAbsolutePath() ); + System.err.println(" Full canonical path of file : "+ testFile.getCanonicalPath() ); + + sel.testCaseDirectory = sel.getFileDirectory(testFile.getAbsolutePath()); + System.err.println(" testCaseDirectory: "+ sel.testCaseDirectory ); + sel.runTest( testFile.getAbsolutePath() ); + } else { + System.err.println("Test File is not exist :"+args[0]); + } } } /* call run test suite from webtool selenium */ public static String runTestSuite(HttpServletRequest request, HttpServletResponse response){ - Map parameters = UtilHttp.getParameterMap(request); - String para = (String)parameters.get("testSuitePath"); - if(para == null){ - System.out.println("Error message : Test suite Path is null"); - return "success"; - } - if(para.length()==0){ - System.out.println("Error message : Test suite Path is null"); - return "success"; - } - try{ - URL url = UtilURL.fromResource("seleniumXml.properties"); - if (props == null) { - props = new Properties(); - initConfig(url); - } - SeleniumXml sel = new SeleniumXml(); - sel.runTest(para.trim()); + Map parameters = UtilHttp.getParameterMap(request); + String para = (String)parameters.get("testSuitePath"); + if(para == null){ + System.out.println("Error message : Test suite Path is null"); + return "success"; + } + if(para.length()==0){ + System.out.println("Error message : Test suite Path is null"); + return "success"; + } + try{ + URL url = UtilURL.fromResource("seleniumXml.properties"); + if (props == null) { + props = new Properties(); + initConfig(url); + } + SeleniumXml sel = new SeleniumXml(); + File testFile = new File(para.trim()); + if (testFile.exists()) { + System.err.println(" Argument : "+ para.trim() ); + System.err.println(" Full absolute path of file : "+ testFile.getAbsolutePath() ); + System.err.println(" Full canonical path of file : "+ testFile.getCanonicalPath() ); + + sel.testCaseDirectory = sel.getFileDirectory(testFile.getAbsolutePath()); + System.err.println(" testCaseDirectory: "+ sel.testCaseDirectory ); + sel.runTest( testFile.getAbsolutePath() ); + } else { + System.err.println("Test File is not exist :"+para.trim()); + } + //sel.runTest(para.trim()); }catch(JDOMException jdome){ - System.out.println(jdome.getMessage()); - }catch(IOException ioe){ - System.out.println("Error message : "+ioe.getMessage()); - }finally{ - return "success"; - } + System.out.println(jdome.getMessage()); + }catch(IOException ioe){ + System.out.println("Error message : "+ioe.getMessage()); + }finally{ + return "success"; + } + } + + private String getFileDirectory(String filePath){ + String directory = null; + if (filePath.indexOf(File.separatorChar) != -1 ) { + int lastIndexOf = filePath.lastIndexOf(File.separatorChar); + directory = filePath.substring(0, (lastIndexOf+1)); + } + return directory; } public SeleniumXml() throws IOException { @@ -136,12 +175,9 @@ public class SeleniumXml { private static void initConfig() throws IOException { try { - String configFile = ""; - if(System.getProperty(PROPS_NAME)==null){ - configFile = PROPS_NAME; - }else{ - configFile = System.getProperty(PROPS_NAME); - } + String configFile = System.getProperty(PROPS_NAME); + //System.out.println("Looking for " + PROPS_NAME); + //System.out.println("Found following config file: " + configFile); 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); @@ -151,12 +187,12 @@ public class SeleniumXml { props.load(in); in.close(); - } catch (IOException e) { e.printStackTrace(); throw e; } } + private static void initConfig(URL url) throws IOException { try { if (url == null) { @@ -179,6 +215,7 @@ public class SeleniumXml { public SeleniumXml(SeleniumXml selenium) { this.sel = selenium.getSelenium(); this.map = selenium.getParameterMap(); + this.testCaseDirectory = selenium.testCaseDirectory; } public DefaultSelenium getSelenium() { @@ -187,94 +224,113 @@ public class SeleniumXml { public Map getParameterMap() { return this.map; } - public void runTest(String fileName) throws JDOMException, IOException { + public void runTest(String fileName) throws JDOMException, IOException, TestCaseException { readFile(fileName); setupSelenium(); runCommands(); } - public void runCommands() { + public void runCommands() throws TestCaseException { Element root = this.doc.getRootElement(); //List nodes = UtilGenerics.cast(root.getChildren()); List nodes = root.getChildren(); runCommands(nodes); } - public void runCommands(List nodes) { + public void runCommands(List nodes) throws TestCaseException{ for(Element elem: nodes) { - if ("type" == elem.getName()) { + String thisName = elem.getName(); + if("type" == elem.getName()) { typeCmd(elem); - } else if ("clickAt" == elem.getName()) { + } else if("setParam" == thisName) { + setParam(elem); + } else if("clickAt" == thisName) { clickAt(elem); - } else if ("waitForValue" == elem.getName()) { + } else if("waitForValue" == thisName) { waitForValue(elem); - } else if ("waitForCondition" == elem.getName()) { + } else if("waitForCondition" == thisName) { waitForCondition(elem); - } else if ("loadData" == elem.getName()) { + } else if("loadData" == thisName) { loadData(elem); - } else if ("loadData" == elem.getName()) { - loadData(elem); - } else if ("jythonRunner" == elem.getName()) { + } else if("jythonRunner" == thisName) { jythonRunner(elem); - } else if ("groovyRunner" == elem.getName()) { + } else if("groovyRunner" == thisName) { groovyRunner(elem); - } else if ("dataLoop" == elem.getName()) { + } else if("dataLoop" == thisName) { dataLoop(elem); - } else if ("remoteRequest" == elem.getName()) { + } else if("remoteRequest" == thisName) { remoteRequest(elem); - } else if ("selectPopup" == elem.getName()) { + } else if("selectPopup" == thisName) { selectPopup(elem); - } else if ("getAllWindowIds" == elem.getName()) { + } else if("getAllWindowIds" == thisName) { getAllWindowIds(elem); - } else if ("captureTextInPage" == elem.getName()) { + } else if("captureTextInPage" == thisName) { captureTextInPageCmd(elem); - } else if ("getSelectedLabel" == elem.getName()) { + } else if("getSelectedLabel" == thisName) { getSelectedLabel(elem); - } else if ("getSelectedValue" == elem.getName()) { + } else if("getSelectedValue" == thisName) { getSelectedValue(elem); - } else if ("getSelectedId" == elem.getName()) { + } else if("getSelectedId" == thisName) { getSelectedId(elem); - } else if ("testcase" == elem.getName()) { + } else if("testcase" == thisName) { testcase(elem); - } else if ("assertContains" == elem.getName()) { + } else if("assertContains" == thisName) { assertContains(elem); - } else if ("getHtmlSource" == elem.getName()) { + } else if("getHtmlSource" == thisName) { getHtmlSource(elem); - } else if ("getBodyText" == elem.getName()) { + } else if("getBodyText" == thisName) { getBodyText(elem); - } else if ("setup" == elem.getName()) { + } else if("setup" == thisName) { continue; //setup is handled previously - } else if ("print" == elem.getName()) { + } else if("print" == thisName) { printCmd(elem); - } else if ("waitForPageToLoad" == elem.getName()) { + } else if("waitForPageToLoad" == thisName) { waitForPageToLoadCmd(elem); - } else if ("getSelectedIds" == elem.getName()) { + } else if("getSelectedIds" == thisName) { getSelectedIdsCmd(elem); - } else if ("copy" == elem.getName()) { + } else if("copy" == thisName) { copyCmd(elem); - } else if ("append" == elem.getName()) { + } else if("append" == thisName) { appendCmd(elem); - } else if ("open" == elem.getName()) { + } else if("loadParameter" == thisName) { + loadParameter(elem); + }else if("partialRunDependency" == thisName) { + partialRunDependency(elem); + }else if("if" == thisName) { + ifCmd(elem); + }else if("open" == thisName) { openCmd(elem); - } else if ("click" == elem.getName()) { + } else if("click" == thisName) { clickCmd(elem); - } else if ("select" == elem.getName()) { + } else if("check" == thisName) { + checkCmd(elem); + } else if("uncheck" == thisName) { + uncheckCmd(elem); + } else if("getValue" == thisName) { + getValueCmd(elem); + } else if("select" == thisName) { selectCmd(elem); - } else if ("uniqueId" == elem.getName()) { + } else if("uniqueId" == thisName) { uniqueIdCmd(elem); - } else if ("randomAlphaString" == elem.getName()) { + } else if("randomAlphaString" == thisName) { randomAlphaStringCmd(elem); - } else if ("randomString" == elem.getName()) { + } else if("randomString" == thisName) { randomStringCmd(elem); - } else if ("setSpeed" == elem.getName()) { + } else if("setSpeed" == thisName) { setSpeed(elem); + } else if("openWindow" == thisName) { + openWindow(elem); + } else if("selectWindow" == thisName) { + selectWindow(elem); + } else if("runScript" == thisName) { + runScript(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()); + logger.info("Undefined command calling by reflection for command: " + thisName); callByReflection(elem); } } @@ -290,12 +346,12 @@ public class SeleniumXml { Class[] paramTypes = null; Object[] args = null; - if ((param1 != null) && (param2 != null)) { + if( (param1 != null) && (param2 != null) ) { paramTypes = new Class[] {String.class, String.class}; - args = new Object[] {param1, param2}; + args = new Object[] {replaceParam(param1), replaceParam(param2)}; } else if (param1 != null) { paramTypes = new Class[] {String.class}; - args = new Object[] {param1}; + args = new Object[] {replaceParam(param1)}; } else { paramTypes = new Class[] {}; args = new Object[] {}; @@ -310,7 +366,7 @@ public class SeleniumXml { Object results = m.invoke(this.sel, args); //Add output parameter to common map - if ((out != null) && (results != null)) { + if( (out != null) && (results != null)) { addParam(out, results); } } catch (Exception e) { @@ -318,13 +374,11 @@ public class SeleniumXml { logger.error("Exception occurred when Unknown SeleniumXml command found:"+elem.getName()); e.printStackTrace(); } - - } public void waitForValue(Element elem) { - String locator = elem.getAttributeValue("locator"); + String locator = replaceParam(elem.getAttributeValue("locator")); String timeout = elem.getAttributeValue("timeout"); String outParam = elem.getAttributeValue("out"); @@ -334,31 +388,51 @@ public class SeleniumXml { //this.sel.waitForCondition(script, timeout); String foundValue = null; for(int second=0;; second++) { - if (second >= maxSeconds) { -// throw new SeleniumException("waitForValue exceeded timeout: " + maxTime); + if(second >= maxSeconds) { + throw new SeleniumException("waitForValue exceeded timeout: " + maxTime); } - try { + 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) { + if(outParam != null) { this.addParam(outParam, foundValue); } break; // - } catch (Exception e) { + } 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 setParam(Element elem) { + + String name = replaceParam(elem.getAttributeValue("name")); + String value = replaceParam(elem.getAttributeValue("value")); + + if( (name != null) && (value != null)) { + this.addParam(name, value); + } + } + public void getValueCmd(Element elem) { + + String locator = replaceParam(elem.getAttributeValue("locator")); + String outParam = elem.getAttributeValue("out"); + + logger.debug("getValueCmd: locator=" + locator); + String foundValue = sel.getValue(locator); + if(outParam != null) { + this.addParam(outParam, foundValue); + } + } + public void waitForCondition(Element elem) { String script = elem.getAttributeValue("script"); @@ -368,7 +442,35 @@ public class SeleniumXml { this.sel.waitForCondition(script, timeout); } - public void loadData(Element elem) { + public void openWindow(Element elem) { + + String url = elem.getAttributeValue("url"); + String windowId = replaceParam(elem.getAttributeValue("windowId")); + + logger.debug("openWindow: url=" + url + " windowId=" + windowId); + this.sel.openWindow(url, windowId); + return; + } + + public void selectWindow(Element elem) { + + String windowId = replaceParam(elem.getAttributeValue("windowId")); + + logger.debug("selectWindow: windowId=" + windowId); + this.sel.selectWindow(windowId); + return; + } + + public void runScript(Element elem) { + + String script = replaceParam(elem.getAttributeValue("script")); + + logger.debug("runScript: script=" + script); + this.sel.runScript(script); + return; + } + + public void loadData(Element elem) throws TestCaseException { String file = elem.getAttributeValue("file"); String iterations = elem.getAttributeValue("iterations"); @@ -392,7 +494,7 @@ public class SeleniumXml { runner.runTest(); } - public void dataLoop(Element elem) { + public void dataLoop(Element elem) throws TestCaseException { String dataListName = elem.getAttributeValue("dataListName"); List children = UtilGenerics.cast(elem.getChildren()); @@ -410,11 +512,32 @@ public class SeleniumXml { } String responseHandlerMode = elem.getAttributeValue("responseHandlerMode"); List children = UtilGenerics.cast(elem.getChildren()); - - RemoteRequest loader = new RemoteRequest(this, children, requestUrl, host, responseHandlerMode); + List loginAs = UtilGenerics.cast(elem.getChildren("login-as")); + logger.info("remoteRequest: children=" + children + " loginAs="+loginAs); + RemoteRequest loader = new RemoteRequest( this, children, loginAs, requestUrl, host, responseHandlerMode); loader.runTest(); } + + public void ifCmd(Element elem) throws TestCaseException { + String isRun = replaceParam(elem.getAttributeValue("condition")); + if (isRun != null && !isRun.equals("") && Boolean.valueOf(isRun)) { + List children = elem.getChildren(); + this.runCommands(children); + }else{ + Element child = elem.getChild("else"); + List children = child.getChildren(); + this.runCommands(children); + } + } + public void partialRunDependency(Element elem) throws TestCaseException { + String isRun = replaceParam(elem.getAttributeValue("isRun")); + if (isRun != null && Boolean.valueOf(isRun)) { + List children = elem.getChildren(); + this.runCommands(children); + } + } + public String getParamValue(String key) { return (String) this.map.get(key); } @@ -424,29 +547,30 @@ public class SeleniumXml { } public void addParam(String name, String value) { - //logger.info("addParam: name=" + name + " value="+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); + logger.info("addParam: name=" + name + " value="+value); this.map.put(name, value); } - private void assertContains(Element elem) { + private void assertContains(Element elem) throws TestCaseException { String src = replaceParam(elem.getAttributeValue("src")); String test = replaceParam(elem.getAttributeValue("test")); int indxSearch = src.indexOf(test); - if (indxSearch == -1) { + if(indxSearch == -1) { logger.info("assertContains didn't find " + test + " in the src"); + throw new TestCaseException("assertContains didn't find: " + test); + } else { logger.info("assertContains found " + test + " in the src"); } - Assert.assertTrue(indxSearch != -1); - //String text = this.sel.getHtmlSource(); - } + //TODO: implement JUnit TestCase - Assert.assertTrue(indxSearch != -1); + } - private void selectPopup(Element elem) { +/* private void selectPopup(Element elem) { String locator = elem.getAttributeValue("locator"); // String winId = elem.getAttributeValue("windowId"); String timeout = elem.getAttributeValue("timeout"); @@ -471,10 +595,33 @@ public class SeleniumXml { //this.sel.selectWindow("name=" + winNames[1]); //System.out.println("Did we select WindowName: " + winNames[1]); } - - private void getWindowPopup(Element elem) { +*/ + 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