Wednesday

Selenium - Framework with TestNG

<<>>

Ya so as promised the next post will be to create a basic framework on Automation for selenium. Please go thru the past two selenium post of blog before starting this post.

Overview
Framework is like the three following steps:

Driver : Testng.xml which will say which testcase need to run by enabled="true" property.

Testcases : These are the class file which will call the library function on demand.
The parameter it will take from Testng.xml to run them.

Library: Resusable function which will be invoked by the testcases and perform task or return the value.

Agree like other component like e-maling , reporting , exception handling etc should be added but as of now this basic architecture is suffice to embark our automation stuff.

Step by step framework designing

Part A : Create a basic Structure of test framework in Eclipse

Step 1:Make sure you have done installation of eclipse.
Step 2:Open eclipse and create a Java project ( eg ODP_main_automation)
Step 3:Right Click on project and go in properties and select java Build path to Add JRE of selenium testng mail etc
Step 4:Click on add external JRE and select testng-5.12.1.jar , selenium-server.jar,selenium-java-client-driver.jar,mail.jar and xmlwriter-2.0.jar ( this is javamail jre search on google for all this) and click on OK
Step 5:Create a pakage under Src folder (eg com.ca.ODP.Test )- FOr test Script
Step 6:Create another package undre same src folder (eg com.ca.ODP.utils) - For Library.

Step7: Create a BaseTests.Java class under pakage in step 5 (com.ca.ODP.Test )
Step8: Create a CreateTest.java class under pakage in step 5 (com.ca.ODP.Test )
Step9: Step8: Create a LoginTests.java class under pakage in step 5 (com.ca.ODP.Test )
Step10: Create a testng.xml undre under pakage in step 5 (com.ca.ODP.Test )

Now if u right click on this and go on run as u see that u are not getting option to 'RUN as TESTNG' so we need to make test which can run as testng

Step11: Go in windows > network host, here select network connection and check all http etc
Step 12 : click on help > Install new software and provide url http://beust.com/eclipse (dat of this post is 25 AUg-2010 so if u r seeing it much later than possible things went change so search on google that how to install TestNG with Eclipse)
Step 13: select version of testng and Click next ... it will install testng for that project. Restart Eclipse.

Now if u right click on this and go on run as u see that u are STILL STILL not getting option to 'RUN as TESTNG' so we need to make test which can run as testng

the reason is testng.xml is blank :-)

Step 14:
Double click on testng.xml and paste the following content we will discuss later about it . please replace ^ with <>
^suite name="ODP">


^parameter name="build" value="QA Build"/>
^parameter name="failureImagesPath" value="./logs"/>
^parameter name="url" value="http://rwcrh8.ca.com"/>
^parameter name="port" value="8080"/>
^parameter name="super_username" value="test@ca.com"/>
^parameter name="super_password" value="test"/>
^parameter name="service_username" value="shukr02@ca.com"/>
^parameter name="service_password" value="niku"/>
^parameter name="companyName" value="ca1"/>

^!-- Parameters to Automated test results Mail BEGIN -->
^parameter name="mail_smtpHost" value="mail.ca.com"/>
^parameter name="mail_from" value="Automation@aquila.ca.com"/>
^parameter name="mail_to" value="choba02@ca.com"/>
^parameter name="mail_subject" value="Automated Test Report -Aquila"/>
^parameter name="mail_body" value="this is automated test report"/>
^parameter name="mail_send_mail" value="false"/>
^!-- Parameters to Automated test results Mail END -->

^!-- test verbose="2" name="SDM Configure" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID125"/>
^parameter name="username" value="ODPadmin"/>
^parameter name="password" value="aquila"/>
^parameter name="sdmName" value="Service Desk"/>
^parameter name="wsdlUrl" value="http://itc-desra02022:8080/axis/services/USD_R11_WebService"/>
^parameter name="baseUrl" value="http://itc-desra02022:8080/"/>
^parameter name="sdmUser" value="ServiceDesk"/>
^parameter name="sdmPass" value="interOP@123"/>
^groups>
^run>
^include name="TCID125"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.tests.SDTests" />
^/classes>
^/test>
-->

^test verbose="2" name="Login104" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID104"/>
^parameter name="wPassword" value="wrongpassword"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase104"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>

^test verbose="2" name="LoginSuperAdmin_TCID100" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID100"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase100"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>


^test verbose="2" name="LoginServiceAdmin_TCID101" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID101"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase101"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>

^test verbose="2" name="LogintenantAdmin_TCID102" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID102"/>
^parameter name="tenant_username" value="admin@dell.com"/>
^parameter name="tenant_password" value="test"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase102"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>

^test verbose="2" name="LoginOrgUser_TCID103" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID103"/>
^parameter name="org_username" value="user@dell.com"/>
^parameter name="org_password" value="test"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase103"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>


^test verbose="2" name="CreatUser_TCID105" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID105"/>
^parameter name="org_user_email" value="Orgusr@ca.com"/>
^parameter name="org_user_password" value="test"/>
^parameter name="org_user_fname" value="Fname"/>
^parameter name="org_user_lname" value="Lname"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase105"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.CreateTest" />
^/classes>
^/test>


^test verbose="2" name="CreatOrgnization_TCID106" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID106"/>
^parameter name="org_name" value="Computer Associates"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase106"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.CreateTest" />
^/classes>
^/test>

^test verbose="2" name="assignUsertoOrg_TCID107" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID107"/>
^parameter name="org_name" value="Computer Associates"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase107"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.CreateTest" />
^/classes>
^/test>

^/suite>

'''
15:
Now if u right click on this and go on run as u see that u are getting option to 'RUN as TESTNG'



Step16: Create a Base64.Java class under pakage in step 6 (com.ca.ODP.utils)
Step17: Create a GenericFunction.java class under pakage in step 6 (com.ca.ODP.utils)
Step18: Step8: Create a Globals.java class under pakage in step 6 (com.ca.ODP.utils)
Step19: Step8: Create a LoginUtil.java class under pakage in step 6 (com.ca.ODP.utils )

Step20: Step8: Create a UserUtil.java class under pakage in step 6 (com.ca.ODP.utils )

So now our basic Structure Done

PART B : Creating the test and library code for simple login utility

we will build all testcase what i did in my project



Step 1: Start the Selenium server

go to command prompt > go to path where selenium-server.jar reside
eg cd C:\silenuim\selenium-server-1.0.3
provide command java -jar selenium-server.jar and enter
{if you are new please read the http://seleniumhq.org/docs/05_selenium_rc.html first it will help , It may be bouncer first but it will help later.}


check your server start , if not chk java is there , if it is there shout F1 F1 ;-)

Step 2:

Now just copy paste all the code .... hmmm

File 1: BaseTest.java

package com.ca.ODP.Test;
import java.io.File;
import java.io.IOException;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Parameters;
//import com.ca.ODP.utils.Globals_old;
//import com.ca.frontoffice.utils.OnboardingUtil;
//import com.ca.frontoffice.utils.common.EmailUtil;
//import com.ca.ODP.utils.common.EmailUtil;
import com.ca.ODP.utils.Globals;
import com.thoughtworks.selenium.*;


public class BaseTests {
@BeforeSuite (alwaysRun=true)
protected void doSetup(){
Globals.selenium = new DefaultSelenium("localhost", 4444, "*iexplore","https://rwcrh8.ca.com/");


//google code should like this

/*Globals.selenium = new DefaultSelenium("localhost", 4444, "*firefox","http://google.co.uk/");
Globals.selenium.start();
Globals.selenium.windowMaximize();
Globals.selenium.open("/");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.click("css=#gb_2 > span.gbts");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.click("id=lst-ib");
Globals.selenium.type("id=lst-ib", "hi");
Globals.selenium.keyPress("id=lst-ib", "13");

System.out.println("hi");
Globals.selenium.waitForPageToLoad("30000");
System.out.println("bye");*/ 

Globals.selenium.start();


Globals.selenium.open("https://rwcrh8.ca.com//web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");

while(Globals.selenium.isElementPresent("Id=overridelink")!= false)

{
Globals.selenium.click("Id=overridelink");
Globals.selenium.waitForPageToLoad("10000");
System.out.println("It is not safe to continue link found");
}
}

@AfterSuite (alwaysRun=true)
protected void doTearDown(){
Globals.selenium.close();
Globals.selenium.stop();
System.out.println("Completed execution of test suite");

}

}


File 2: CreateTest.java
package com.ca.ODP.Test;

import org.testng.Reporter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.ca.ODP.Test.BaseTests;
import com.ca.ODP.utils.Globals;
import com.ca.ODP.utils.LoginUtil;
import com.ca.ODP.utils.UserUtil;

public class CreateTest extends BaseTests {


@Parameters( {"org_user_email","org_user_password","org_user_fname","org_user_lname","super_username","super_password" })
@Test(groups = {"TestCase105"})

public void createOrgUser_TCID105(String org_user_email,String org_user_password,String org_user_fname,String org_user_lname,String super_username,String super_password) {

String orgUser;
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();
LoginUtil.login(super_username, super_password);

orgUser= UserUtil.createOrgUser(org_user_email, org_user_password, org_user_fname, org_user_lname);

System.out.println(orgUser);


// Reporter.log("Ending Invalid Password.");

LoginUtil.logout();



}

@Parameters( {"org_name","super_username","super_password" })
@Test(groups = {"TestCase106"})
public void createOrgnization_TCID106(String org_name,String super_username,String super_password) {

String orgname;
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();
LoginUtil.login(super_username, super_password);

orgname=UserUtil.createOrg(org_name);
LoginUtil.logout();
// Reporter.log("Ending Invalid Password.");

System.out.println(orgname);

}


// @Parameters( {"org_user_email","org_user_password","org_user_fname","org_user_lname","super_username","super_password","org_name" })
// @Test(groups = {"TestCase107"})
// public void assignUsertoOrg_TCID107(String org_user_email,String org_user_password,String org_user_fname,String org_user_lname,String super_username,String super_password,String org_name){
//
// LoginUtil.logout();
// LoginUtil.login(super_username, super_password);
//
//
// UserUtil.createOrgUser(org_user_email, org_user_password, org_user_fname, org_user_lname);
// UserUtil.createOrg(org_name);
//
//// this.createOrgUser_TCID105(org_user_email, org_user_password, org_user_fname, org_user_lname, super_username, super_password);
//// this.createOrgnization_TCID106(org_name, super_username, super_password);
//
// }
//


@Parameters( {"super_username","super_password","org_name" })
@Test(groups = {"TestCase107"})
public void addUsertoOrg_TCID107(String super_username,String super_password,String org_name){
String orgname;
LoginUtil.logout();
LoginUtil.login(super_username, super_password);

orgname=UserUtil.createOrg(org_name);

UserUtil.addOrgMember(orgname);

LoginUtil.logout();

// this.createOrgUser_TCID105(org_user_email, org_user_password, org_user_fname, org_user_lname, super_username, super_password);
// this.createOrgnization_TCID106(org_name, super_username, super_password);

}
}

File 3 : LoginTest.java
package com.ca.ODP.Test;

import org.testng.Reporter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import com.ca.ODP.Test.BaseTests;
import com.ca.ODP.utils.Globals;
import com.ca.ODP.utils.LoginUtil;

public class LoginTests extends BaseTests {

@Parameters( { "testcase", "super_username", "super_password", "wPassword" })
@Test(groups = {"TestCase104"})
public void CheckInvalidPassword_TCID104(String testcase,String super_username, String super_password,String wPassword) {
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();
LoginUtil.checkInvalidLogin(super_username, wPassword);

// Reporter.log("Ending Invalid Password.");
}

@Parameters({"testcase", "super_username", "super_password",})
@Test(groups = {"TestCase100"})
public void Login_SuperAdmin_TCID100(String testcase,String super_username, String super_password) {
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();

LoginUtil.login(super_username, super_password);
Globals.selenium.waitForPageToLoad("40000");
LoginUtil.logout();

// Reporter.log("Ending Invalid Password.");
}

@Parameters({"testcase", "service_username", "service_password",})
@Test(groups = {"TestCase101"})
public void Login_ServiceAdmin_TCID101(String testcase,String service_username, String service_password) {
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();

LoginUtil.login(service_username, service_password);
Globals.selenium.waitForPageToLoad("40000");
LoginUtil.logout();

// Reporter.log("Ending Invalid Password.");
}

@Parameters({"testcase", "tenant_username", "tenant_password",})
@Test(groups = {"TestCase102"})
public void Login_TenantAdmin_TCID102(String testcase,String tenant_username, String tenant_password) {
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();

LoginUtil.login(tenant_username, tenant_password);
Globals.selenium.waitForPageToLoad("40000");
LoginUtil.logout();

// Reporter.log("Ending Invalid Password.");
}

@Parameters({"testcase", "org_username", "org_password",})
@Test(groups = {"TestCase103"})
public void Login_OrgUser_TCID103(String testcase,String org_username, String org_password) {
//Reporter.log("Starting Invalid Password...");
LoginUtil.logout();

LoginUtil.login(org_username, org_password);
Globals.selenium.waitForPageToLoad("40000");
LoginUtil.logout();

// Reporter.log("Ending Invalid Password.");
}


}
File 4: testng.xml. Please remove
Double click on testng.xml and paste the following content we will discuss later about it . please replace ^ with < name="ODP">
''
'
'
'
'
' ^!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
^suite name="ODP">


^parameter name="build" value="QA Build"/>
^parameter name="failureImagesPath" value="./logs"/>
^parameter name="url" value="http://rwcrh8.ca.com"/>
^parameter name="port" value="8080"/>
^parameter name="super_username" value="test@ca.com"/>
^parameter name="super_password" value="test"/>
^parameter name="service_username" value="shukr02@ca.com"/>
^parameter name="service_password" value="niku"/>
^parameter name="companyName" value="ca1"/>

^!-- Parameters to Automated test results Mail BEGIN -->
^parameter name="mail_smtpHost" value="mail.ca.com"/>
^parameter name="mail_from" value="Automation@aquila.ca.com"/>
^parameter name="mail_to" value="choba02@ca.com"/>
^parameter name="mail_subject" value="Automated Test Report -Aquila"/>
^parameter name="mail_body" value="this is automated test report"/>
^parameter name="mail_send_mail" value="false"/>
^!-- Parameters to Automated test results Mail END -->

^!-- test verbose="2" name="SDM Configure" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID125"/>
^parameter name="username" value="ODPadmin"/>
^parameter name="password" value="aquila"/>
^parameter name="sdmName" value="Service Desk"/>
^parameter name="wsdlUrl" value="http://itc-desra02022:8080/axis/services/USD_R11_WebService"/>
^parameter name="baseUrl" value="http://itc-desra02022:8080/"/>
^parameter name="sdmUser" value="ServiceDesk"/>
^parameter name="sdmPass" value="interOP@123"/>
^groups>
^run>
^include name="TCID125"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.tests.SDTests" />
^/classes>
^/test>
-->

^test verbose="2" name="Login104" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID104"/>
^parameter name="wPassword" value="wrongpassword"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase104"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>

^test verbose="2" name="LoginSuperAdmin_TCID100" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID100"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase100"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>


^test verbose="2" name="LoginServiceAdmin_TCID101" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID101"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase101"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>

^test verbose="2" name="LogintenantAdmin_TCID102" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID102"/>
^parameter name="tenant_username" value="admin@dell.com"/>
^parameter name="tenant_password" value="test"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase102"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>

^test verbose="2" name="LoginOrgUser_TCID103" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID103"/>
^parameter name="org_username" value="user@dell.com"/>
^parameter name="org_password" value="test"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase103"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.LoginTests" />
^/classes>
^/test>


^test verbose="2" name="CreatUser_TCID105" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID105"/>
^parameter name="org_user_email" value="Orgusr@ca.com"/>
^parameter name="org_user_password" value="test"/>
^parameter name="org_user_fname" value="Fname"/>
^parameter name="org_user_lname" value="Lname"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase105"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.CreateTest" />
^/classes>
^/test>


^test verbose="2" name="CreatOrgnization_TCID106" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID106"/>
^parameter name="org_name" value="Computer Associates"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase106"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.CreateTest" />
^/classes>
^/test>

^test verbose="2" name="assignUsertoOrg_TCID107" annotations="JDK" enabled="true">
^parameter name="testcase" value="TCID107"/>
^parameter name="org_name" value="Computer Associates"/>
^groups>
^run>
^!-- L002 Invalid password. -->
^include name="TestCase107"/>
^/run>
^/groups>
^classes>
^class name="com.ca.ODP.Test.CreateTest" />
^/classes>
^/test>

^/suite>



File 5: Base64.java - DOWNLOAD THIS CLASS FROM GOOGLE, THIS CODE IS CORRUPT


//DOWNLOAD THIS CLASS FROM GOOGLE, THIS CODE IS CORRUPT/*
 * Java Base64 - A pure Java library for reading and writing Base64
 *               encoded streams.
 *
 * Copyright (C) 2007-2009 Carlo Pelliccia (www.sauronsoftware.it)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version
 * 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License version 2.1 along with this program.
 * If not, see .
 */
package com.ca.ODP.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 *
 * Base64 encoding and decoding utility methods, both for binary and textual
 * informations.
 *
 *
 * @author Carlo Pelliccia
 * @since 1.1
 * @version 1.3
 */
public class Base64 {

/**
*
* Encodes a string.
*
*
* Before the string is encoded in Base64, it is converted in a binary
* sequence using the system default charset.
*
*
* @param str
*            The source string.
* @return The encoded string.
* @throws RuntimeException
*             If an unexpected error occurs.
*/
public static String encode(String str) throws RuntimeException {
byte[] bytes = str.getBytes();
byte[] encoded = encode(bytes);
try {
return new String(encoded, "ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("ASCII is not supported!", e);
}
}

/**
*
* Encodes a string.
*
*
* Before the string is encoded in Base64, it is converted in a binary
* sequence using the supplied charset.
*
*
* @param str
*            The source string
* @param charset
*            The charset name.
* @return The encoded string.
* @throws RuntimeException
*             If an unexpected error occurs.
* @since 1.2
*/
public static String encode(String str, String charset)
throws RuntimeException {
byte[] bytes;
try {
bytes = str.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported charset: " + charset, e);
}
byte[] encoded = encode(bytes);
try {
return new String(encoded, "ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("ASCII is not supported!", e);
}
}

/**
*
* Decodes the supplied string.
*
*
* The supplied string is decoded into a binary sequence, and then the
* sequence is encoded with the system default charset and returned.
*
*
* @param str
*            The encoded string.
* @return The decoded string.
* @throws RuntimeException
*             If an unexpected error occurs.
*/
public static String decode(String str) throws RuntimeException {
byte[] bytes;
try {
bytes = str.getBytes("ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("ASCII is not supported!", e);
}
byte[] decoded = decode(bytes);
return new String(decoded);
}

/**
*
* Decodes the supplied string.
*
*
* The supplied string is decoded into a binary sequence, and then the
* sequence is encoded with the supplied charset and returned.
*
*
* @param str
*            The encoded string.
* @param charset
*            The charset name.
* @return The decoded string.
* @throws RuntimeException
*             If an unexpected error occurs.
* @since 1.2
*/
public static String decode(String str, String charset)
throws RuntimeException {
byte[] bytes;
try {
bytes = str.getBytes("ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("ASCII is not supported!", e);
}
byte[] decoded = decode(bytes);
try {
return new String(decoded, charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported charset: " + charset, e);
}
}

/**
*
* Encodes a binary sequence.
*
*
* If data are large, i.e. if you are working with large binary files,
* consider to use a {@link Base64OutputStream} instead of loading too much
* data in memory.
*
*
* @param bytes
*            The source sequence.
* @return The encoded sequence.
* @throws RuntimeException
*             If an unexpected error occurs.
* @since 1.2
*/
public static byte[] encode(byte[] bytes) throws RuntimeException {
return encode(bytes, 0);
}

/**
*
* Encodes a binary sequence, wrapping every encoded line every
* wrapAt characters. A wrapAt value less than 1 disables
* wrapping.
*
*
* If data are large, i.e. if you are working with large binary files,
* consider to use a {@link Base64OutputStream} instead of loading too much
* data in memory.
*
*
* @param bytes
*            The source sequence.
* @param wrapAt
*            The max line length for encoded data. If less than 1 no wrap
*            is applied.
* @return The encoded sequence.
* @throws RuntimeException
*             If an unexpected error occurs.
* @since 1.2
*/
public static byte[] encode(byte[] bytes, int wrapAt)
throws RuntimeException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
encode(inputStream, outputStream, wrapAt);
} catch (IOException e) {
throw new RuntimeException("Unexpected I/O error", e);
} finally {
try {
inputStream.close();
} catch (Throwable t) {
;
}
try {
outputStream.close();
} catch (Throwable t) {
;
}
}
return outputStream.toByteArray();
}

/**
*
* Decodes a binary sequence.
*
*
* If data are large, i.e. if you are working with large binary files,
* consider to use a {@link Base64InputStream} instead of loading too much
* data in memory.
*
*
* @param bytes
*            The encoded sequence.
* @return The decoded sequence.
* @throws RuntimeException
*             If an unexpected error occurs.
* @since 1.2
*/
public static byte[] decode(byte[] bytes) throws RuntimeException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
decode(inputStream, outputStream);
} catch (IOException e) {
throw new RuntimeException("Unexpected I/O error", e);
} finally {
try {
inputStream.close();
} catch (Throwable t) {
;
}
try {
outputStream.close();
} catch (Throwable t) {
;
}
}
return outputStream.toByteArray();
}

/**
*
* Encodes data from the given input stream and writes them in the given
* output stream.
*
*
* The supplied input stream is read until its end is reached, but it's not
* closed by this method.
*
*
* The supplied output stream is nor flushed neither closed by this method.
*
*
* @param inputStream
*            The input stream.
* @param outputStream
*            The output stream.
* @throws IOException
*             If an I/O error occurs.
*/
public static void encode(InputStream inputStream, OutputStream outputStream)
throws IOException {
encode(inputStream, outputStream, 0);
}

/**
*
* Encodes data from the given input stream and writes them in the given
* output stream, wrapping every encoded line every wrapAt
* characters. A wrapAt value less than 1 disables wrapping.
*
*
* The supplied input stream is read until its end is reached, but it's not
* closed by this method.
*
*
* The supplied output stream is nor flushed neither closed by this method.
*
*
* @param inputStream
*            The input stream from which clear data are read.
* @param outputStream
*            The output stream in which encoded data are written.
* @param wrapAt
*            The max line length for encoded data. If less than 1 no wrap
*            is applied.
* @throws IOException
*             If an I/O error occurs.
*/
public static void encode(InputStream inputStream,
OutputStream outputStream, int wrapAt) throws IOException {
// Base64OutputStream aux = new Base64OutputStream(outputStream, wrapAt);
// copy(inputStream, aux);
// aux.commit();
}

/**
*
* Decodes data from the given input stream and writes them in the given
* output stream.
*
*
* The supplied input stream is read until its end is reached, but it's not
* closed by this method.
*
*
* The supplied output stream is nor flushed neither closed by this method.
*
*
* @param inputStream
*            The input stream from which encoded data are read.
* @param outputStream
*            The output stream in which decoded data are written.
* @throws IOException
*             If an I/O error occurs.
*/
public static void decode(InputStream inputStream, OutputStream outputStream)
throws IOException {
// copy(new Base64InputStream(inputStream), outputStream);
}

/**
*
* Encodes data from the given source file contents and writes them in the
* given target file, wrapping every encoded line every wrapAt
* characters. A wrapAt value less than 1 disables wrapping.
*
*
* @param source
*            The source file, from which decoded data are read.
* @param target
*            The target file, in which encoded data are written.
* @param wrapAt
*            The max line length for encoded data. If less than 1 no wrap
*            is applied.
* @throws IOException
*             If an I/O error occurs.
* @since 1.3
*/
public static void encode(File source, File target, int wrapAt)
throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(target);
Base64.encode(inputStream, outputStream, wrapAt);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable t) {
;
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Throwable t) {
;
}
}
}
}

/**
*
* Encodes data from the given source file contents and writes them in the
* given target file.
*
*
* @param source
*            The source file, from which decoded data are read.
* @param target
*            The target file, in which encoded data are written.
* @throws IOException
*             If an I/O error occurs.
* @since 1.3
*/
public static void encode(File source, File target) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(target);
Base64.encode(inputStream, outputStream);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable t) {
;
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Throwable t) {
;
}
}
}
}

/**
*
* Decodes data from the given source file contents and writes them in the
* given target file.
*
*
* @param source
*            The source file, from which encoded data are read.
* @param target
*            The target file, in which decoded data are written.
* @throws IOException
*             If an I/O error occurs.
* @since 1.3
*/
public static void decode(File source, File target) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(target);
decode(inputStream, outputStream);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Throwable t) {
;
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Throwable t) {
;
}
}
}
}

/**
* Copies data from a stream to another.
*
* @param inputStream
*            The input stream.
* @param outputStream
*            The output stream.
* @throws IOException
*             If a unexpected I/O error occurs.
*/
private static void copy(InputStream inputStream, OutputStream outputStream)
throws IOException {
// 1KB buffer
byte[] b = new byte[1024];
int len;
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
}
}

}
 // end class Base64


File 6: GenericFunction.java

package com.ca.ODP.utils;


import java.util.Random;
import java.io.*;
public class GenericFunction {



public int getRandomNumber(int num)
{
Random rand = new Random();
int randNum1=rand.nextInt(num);
System.out.println(randNum1);
return randNum1;

}


}

File 7: Globals.java

package com.ca.ODP.utils;
import static org.testng.Assert.fail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;

import com.ca.ODP.utils.Base64;
import com.ca.ODP.utils.Globals;
import com.generationjava.io.xml.XmlWriter;
import com.thoughtworks.selenium.*;


public class Globals {

public static Selenium selenium;
public static DefaultSelenium Onboard_selenium;
public static String browser;
public static String Ousername;
public static String Opassword;
public static String username;
public static String password;
public static String companyname;
public static String failureImagesFolder;
public static Writer writer = new java.io.StringWriter();
public static XmlWriter xmlWriter=null;
public static long timestamp=new Date().getTime();


public static int passed=0;
public static int failed=0;
public static int skipped=0;

public static void markTestAsFailed(String testcase,Throwable cause)
{
captureScreenShotAfter(failureImagesFolder+"/"+Globals.timestamp+"/"+browser+"/"+testcase+"-FAILED.png");
fail(testcase,cause);
}


protected static void captureScreenShotAfter(String path) {
try {
String base64Screenshot = Globals.selenium.captureEntirePageScreenshotToString("");
byte[] decodedScreenshot = Base64.decode(base64Screenshot.getBytes());
FileOutputStream fos = new FileOutputStream(new File(path));
FileChannel outChannel = fos.getChannel();
outChannel.write(ByteBuffer.wrap(decodedScreenshot));
fos.close();

} catch (Exception e) {
e.printStackTrace();
}
}

public static void markTestAsOK(String testcase)
{
long randomTime=new Date().getTime();
captureScreenShotAfter(failureImagesFolder+"/"+Globals.timestamp+"/"+browser+"/"+testcase+"-"+randomTime+"-OK.png");
}



public static String getPageLoadTimeOut() {
return String.valueOf(30000);
}

public static String getPageLoadTimeOut(int seconds) {
return String.valueOf(seconds * 1000);
}



}

File 8: LoginUtil.Java

package com.ca.ODP.utils;

//import com.ca.ODP.Log_inOut;

import org.testng.Reporter;

import com.ca.ODP.Test.BaseTests;
import com.ca.ODP.utils.Globals;
//import com.ca.frontoffice.utils.LoginUtil;
//import org.testng.Reporter;
import static org.testng.Assert.assertTrue;

public class LoginUtil {

//public static DefaultSelenium selenium;

public static void login(String username,String password){


if(!LoginUtil.isLoggedIn())
{

try
{

// Globals.selenium.open("https://rwcrh8.ca.com//web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");
// Globals.selenium.waitForPageToLoad("30000");
// Globals.markTestAsOK(testcase);
while(Globals.selenium.isElementPresent("Id=overridelink")!= false)

{
Globals.selenium.click("Id=overridelink");
Globals.selenium.waitForPageToLoad("10000");
System.out.println("It is not safe to continue link found");
}

Globals.selenium.type("_58_login", username);
//selenium.waitForPageToLoad("10000");

Globals.selenium.type("_58_password", password);
Globals.selenium.click("//input[@value='Sign In']");
Globals.selenium.waitForPageToLoad("20000");
}
catch(Throwable cause)
{
System.out.println("this is login function error");

}

}
} //login end


public static void logout(){

if(LoginUtil.isLoggedIn()){
try{
Globals.selenium.click("link=Sign Out");

Globals.selenium.waitForPageToLoad("20000");
System.out.println("logging out");
}
catch(Throwable cause)
{

System.out.println("this is logout function error");

}

}
else{

System.out.println("System is already logged out1");

}

}
public static boolean isLoggedIn()
{
return Globals.selenium.isTextPresent("Sign Out");
//return CreateUser.selenium.isTextPresent("Sign Out");
}

public static void checkInvalidLogin(String username,String password){

if(!LoginUtil.isLoggedIn())
{

//Globals.selenium.open("/web/frontoffice/login");
Globals.selenium.type("_58_login", username+"@"+"ca"+".com");
Globals.selenium.type("_58_password", password);
Globals.selenium.click("//input[@type='submit']");
Globals.selenium.waitForPageToLoad("40000");

assertTrue(Globals.selenium.isTextPresent("You have entered invalid data. Please try again."));
assertTrue(Globals.selenium.isTextPresent("Authentication failed. Please try again."));

}
else
{
System.out.println("Already logged in");
LoginUtil.logout();

}

}

}


File9: User Util.java

package com.ca.ODP.utils;
import org.testng.Reporter;
import com.ca.ODP.Test.BaseTests;
import com.ca.ODP.utils.Globals;
//import com.ca.frontoffice.utils.LoginUtil;
//import org.testng.Reporter;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertEquals;
import com.ca.ODP.utils.GenericFunction;

public class UserUtil {

public static String createOrg(String org_name){

int randnum;
String orgnization_name;

GenericFunction randnumber = new GenericFunction();
randnum=randnumber.getRandomNumber(10000);


orgnization_name=randnum+org_name;
System.out.println("Creating an orgnization");

Globals.selenium.click("link=My Account");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.click("link=Organizations");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.click("link=Add");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.type("_126_name", orgnization_name);
Globals.selenium.click("//input[@value='Save']");
// Globals.selenium.waitForPageToLoad("30000");
// Globals.selenium.click("link=Sign Out");

return orgnization_name;

}

public static String createOrgUser(String org_user_email,String org_user_password,String org_user_fname,String org_user_lname){

System.out.println("Creating an user");
int randnum;String fname,lname;

String emailid=new String();

GenericFunction randnumber = new GenericFunction();

randnum=randnumber.getRandomNumber(10000);

Globals.selenium.click("link=My Account");
//Globals.selenium.waitForPageToLoad("30000");

// System.out.println(Globals.selenium.getAllWindowNames());
// selectWindow("Security Warning" );

////pop-up code and it is not working
////assertEquals("Security Warning", Globals.selenium.getAlert());
//Globals.selenium.waitForPopUp("Security Warning", "30000");
//Globals.selenium.selectWindow("Security Warning");
////assertEquals("Security Warning", Globals.selenium.getAlert());
//Globals.selenium.windowFocus();
//Globals.selenium.click("Yes");
//Globals.selenium.waitForPageToLoad("30000");


Globals.selenium.click("link=Users");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.click("link=Add");
Globals.selenium.waitForPageToLoad("30000");

emailid=randnum+org_user_email;
fname=randnum+org_user_fname;
lname=randnum+ org_user_lname;



System.out.println("Created new Org user email id is: "+ emailid);

Globals.selenium.type("_125_emailAddress",emailid);
Globals.selenium.type("_125_firstName", fname);
Globals.selenium.type("_125_lastName", lname);
Globals.selenium.click("//input[@value='Save']");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.click("passwordLink");
Globals.selenium.waitForPageToLoad("30000");
Globals.selenium.type("_125_password1", org_user_password);
Globals.selenium.type("_125_password2", org_user_password);
Globals.selenium.click("//input[@value='Save']");
//Globals.selenium.waitForPageToLoad("30000");
//Globals.selenium.click("link=Sign Out");

return emailid;

}
protected static void selectWindow(String windowIndenifer ) {
if (windowIndenifer==null ||windowIndenifer.length() <= 1) windowIndenifer = Globals.selenium.getEval("{var windowId; for(var xWindow in selenium.browserbot.openedWindows ) {windowId=xWindow;} }"); if(windowIndenifer == null || windowIndenifer.length() <=1) System.out.println("There is no popupWindow in current AUT"); else{ Globals.selenium.selectWindow(windowIndenifer); System.out.println("Selenium found a popup Window : " + windowIndenifer); } } public static void addOrgMember(String orgname){ int randnum2; String fname1,lname1; String emailid1=new String(); GenericFunction randnumber = new GenericFunction(); randnum2=randnumber.getRandomNumber(10000); emailid1=randnum2+"user@ca.com"; fname1=randnum2+"fname"; lname1=randnum2+ "lname"; Globals.selenium.click("link=My Account"); Globals.selenium.waitForPageToLoad("30000"); Globals.selenium.click("link=Organizations"); Globals.selenium.waitForPageToLoad("30000"); Globals.selenium.type("toggle_id_enterprise_admin_organization_searchkeywords", orgname); Globals.selenium.click("//input[@value='Search']"); Globals.selenium.waitForPageToLoad("40000"); Globals.selenium.click("//div[@id='portlet-wrapper-126']/div[2]/div/div/form/div[6]/table/tbody/tr[3]/td[8]/ul/li/strong/span"); // Globals.selenium.click("//a[contains(@href, 'https://rwcrh8.ca.com/group/control_panel/manage?p_p_id=126&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&refererPlid=11067&_126_struts_action=%2Fenterprise_admin_organizations%2Fedit_user&_126_redirect=https%3A%2F%2Frwcrh8.ca.com%2Fgroup%2Fcontrol_panel%2Fmanage%3Fp_p_id%3D126%26p_p_lifecycle%3D0%26p_p_state%3Dmaximized%26p_p_mode%3Dview%26refererPlid%3D11067%26_126_struts_action%3D%252Fenterprise_admin_organizations%252Fview%26_126_tabs1%3Dorganizations%26_126_tabs2%3D%26_126_tabs3%3D%26_126_cur%3D1%26_126_delta%3D20%26_126_keywords%3D3975Computer%2BAssociates%26_126_advancedSearch%3Dfalse%26_126_andOperator%3Dtrue%26_126_name%3D%26_126_street%3D%26_126_city%3D%26_126_zip%3D%26_126_countryId%3D0%26_126_regionId%3D0%26_126_parentOrganizationId%3D0%26_126_orderByCol%3Dtype%26_126_orderByType%3Dasc&_126_organizationsSearchContainerPrimaryKeys=26472')]"); Globals.selenium.click("alt=Add User"); Globals.selenium.waitForPageToLoad("30000"); Globals.selenium.type("_126_emailAddress", emailid1); Globals.selenium.type("_126_firstName", fname1); Globals.selenium.type("_126_middleName", "mname"); Globals.selenium.type("_126_lastName", lname1); Globals.selenium.click("//input[@value='Save']"); // Globals.selenium.waitForPageToLoad("30000"); // Globals.selenium.click("link=Sign Out"); } } Step 3:So the above code is working for my project ....
but in this section we see what things need to change for any project and also understand the small concepts

Thursday

Selenium - Designing First Test case in Selenium

After installing Eclipse , testng plug-in , Selenium RC server. I am starting with creating first testcase Login and Logout

1. OPen Mozilla
2. Tool > Selenium IDE
3. Record the Script
4. Stop recording
5. Export The file as Testng from File > Export
6. Now open Eclipse ( which having testng , EC server running)
7. Create a Project type JAVA
and Create a new class name Log_inOut init.

8. paste the recorded script in that:

package com.example.tests;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.regex.Pattern;

public class Log_inOut extends SeleneseTestNgHelper {
@Test public void testLog_inOut() throws Exception {
selenium.open("/web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");
selenium.type("_58_password", "test");
selenium.click("//input[@value='Sign In']");
selenium.waitForPageToLoad("30000");
selenium.click("link=Sign Out");
}
}

9. Now remove
package com.example.tests;
extends SeleneseTestNgHelper
throws Exception

So It becomes:

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
//import java.util.regex.Pattern;

public class Log_inOut {
@Test public void testLog_inOut(){
selenium.open("/web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");
selenium.type("_58_password", "test");
selenium.click("//input[@value='Sign In']");
selenium.waitForPageToLoad("30000");
selenium.click("link=Sign Out");
}
}


10. Save
11. Run the class As testng.

12. ITS FAILED :) and now I spend 2-3 hour to understand what happened:

13. First of all a) there is no browser mentioned b)there is no refernce of selenium
public Selenium selenium; after the class declaration.

so I added piece of code

import com.thoughtworks.selenium.*;import org.testng.annotations.*;
public class Log_inOut {

public Selenium selenium;

@BeforeClass
public void setup()
{
selenium = new DefaultSelenium("localhost", 4444, "*iexplore","http://rwcrh8.ca.com/");
selenium.start();

}

it will tell IE to open the following url

14. Then I also wrote @Aftertest which will close Selenium

@AfterClass
public void StopTest()
{
selenium.stop();
}

15. Now I run the test and IT AGAIN FAILED ..... I found that my url is redirecting to https and Selenium is unable to pick the whole string

16. so in @Test section I gave full URL
selenium.open("https://rwcrh8.ca.com//web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");

17. but some time it run some time it fails. I found that page loading is creating problem

so I put selenium.waitForPageToLoad("30000"); whenever I am feeling the page load is taking time. But be sure that it is not inbetween the two input field like

selenium.type("_58_login", "test@ca.com");
//selenium.waitForPageToLoad("10000"); For this I got error and It took time to get that if it is not there than I am able to fill both of fields.

selenium.type("_58_password", "test");

18. And I ran script . IT AGAIN FAILED
I realize that I am getting a IE error that page is unsafe and do you want to proceed ....

IN Ineternet explorer I did Tool > devlopment and get the ID of that link and clicked it
in FF I use Firebug to get the ID of that .and add this code in script.

selenium.click("Id=overridelink");


19. Now I ran and YEAH IT RAN


So here is my first script :-)


//package com.example.tests;

import com.thoughtworks.selenium.*;

import org.testng.annotations.*;

public class Log_inOut {

public Selenium selenium;

@BeforeClass
public void setup()
{
selenium = new DefaultSelenium("localhost", 4444, "*iexplore","http://rwcrh8.ca.com/");
selenium.start();

}

@Test
public void testLog_inOut() {



selenium.open("https://rwcrh8.ca.com//web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");
selenium.waitForPageToLoad("30000");

//< id="overridelink" href="http://rwcrh8.ca.com/web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f">
selenium.click("Id=overridelink");
//selenium.open("/web/portal/login?TYPE=33554433&REALMOID=06-0003637f-cceb-1ba3-8e98-fa5682c8c044&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-Lv3PYArtpFEOxfQZFPHmNauhn5NYebq9auIeK%2fNS2KxEB3P9bprxh3XDZlbLhNS47%2fKK00%2fHVfFG6UHhEfNWMITnNbU4XRY1&TARGET=-SM-http%3a%2f%2frwcrh8%2eca%2ecom%2f");

selenium.waitForPageToLoad("30000");

selenium.type("_58_login", "test@ca.com");
//selenium.waitForPageToLoad("10000");

selenium.type("_58_password", "test");
selenium.click("//input[@value='Sign In']");
selenium.waitForPageToLoad("40000");
selenium.click("link=Sign Out");

// selenium.waitForPageToLoad("10000");


}

@AfterClass
public void StopTest()
{
selenium.stop();
}

}


20 . Now I created a package in eclipse and put 2 classes (same cut copy paste of first for second) and ran.
Suite ran successfully.

Now next post is to build basic Automation framework....

Selenium - Starting Selenium - First Step

Always thought selenium was magic , too dificult to start .... but it is a 2 hour learning which make you to start you automation:


The best thing to start Selenium is read first the following 10 minute article.
http://epyramid.wordpress.com/2008/11/26/setting-up-selenium-rc-testng-using-eclipse/

Also Install selenium IDE plug in for Mozilla. (5 minute)
For installing Selenium First read
http://seleniumhq.org/docs/05_selenium_rc.html

you can download IDE and RC from here In installation section (20 Minute)
http://seleniumhq.org/download/


First Script:
import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
public class GoogleTest1
{
public Selenium selenium;
@BeforeClass
public void setup()
{
selenium = new DefaultSelenium("localhost", 4444, "*iexplore","http://www.google.com");
selenium.start();
}

@Test
public void Googlesearch()
{
selenium.open("http://www.Google.com/webhp");
assertEquals("Google", selenium.getTitle());
selenium.type("q", "Selenium OpenQA");
assertEquals("Selenium OpenQA", selenium.getValue("q"));
selenium.click("btnG");
selenium.waitForPageToLoad("50000");

}

@AfterClass
public void StopTest()
{
selenium.stop();
}

}

simple Login setting UID PWD based on URL in Global sheet

startURL = Cstr(DataTable.Value("url", dtGlobalSheet))
set InternetExplorer = CreateObject("InternetExplorer.Application")
InternetExplorer.Visible = true
InternetExplorer.Navigate startURL

If DataTable("username",dtGlobalSheet)<>"" and DataTable("LoginIndicator",dtGlobalSheet)=2 Then

If Browser("Browser").Dialog("XYZ").Exist Then

Browser("Browser").Dialog("XYZ").Activate
Browser("Browser").Dialog("XYZ").WinEdit("User name").Set Datatable("username",dtGlobalSheet)
wait(4)
Browser("Browser").Dialog("XYZ").WinEdit("Password").Set Datatable("password",dtGlobalSheet)
Browser("Browser").Dialog("UAT_Login_Pop_Up").WinButton("OK").Click
Environment.Value("TransactionStratTime")=Timer
Environment.Value("SecondTransactionStratTime")=Timer
End If

'windprop=Browser("Browser").GetROProperty("hwnd")
'Window("hwnd:="& windprop).Maximize
'
End If

Tuesday

SilkPerformer - Opening stopping firewall on unix

For completely stopping the firewall, use these steps.
• Login as root
• On prompt give this command “service iptables stop”
• To check the status of firewall use command below
o service iptables status
o It normally gives output as follows “Firewall is stopped”

For opening specific ports run following commands as root
• Edit the iptables as follows (Note the port number decision may vary)
vi /etc/sysconfig/iptables
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 4155 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8443 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 9443 -j ACCEPT
• Now restart the iptables as follows
/etc/init.d/iptables restart

Monday

SilkPerformer - Linux - counters analysis

Linux - counters, symptoms and Resolution

Virtual Memory Statistics ( vmstat )
vmstat – vmstat reports virtual memory statistics of process, virtual memory, disk, trap, and CPU activity.

example% vmstat 5
procs memory page disk faults cpu
r b w swap free re mf pi p fr de sr s0 s1 s2 s3 in sy cs us sy id
0 0 0 11456 4120 1 41 19 1 3 0 2 0 4 0 0 48 112 130 4 14 82
0 0 1 10132 4280 0 4 44 0 0 0 0 0 23 0 0 211 230 144 3 35 62

Following columns has to be watched to determine if there is any cpu issue
1. Processes in the run queue (procs r)
2. User time (cpu us)
3. System time (cpu sy)
4. Idle time (cpu id)
procs cpu
r b w us sy id
0 0 0 4 14 82
0 0 1 3 35 62
0 0 1 3 33 64
0 0 1 1 21 78
Problem symptoms

A. CPU issues
1.) Number of processes in run queue
1.) If the number of processes in run queue (procs r) are consistently greater than the number of CPUs on the system it will slow down system as there are more processes then available CPUs .
2.) if this number is more than four times the number of available CPUs in the system then system is facing shortage of cpu power and will greatly slow down the processess on the system.
3.) If the idle time (cpu id) is consistently 0 and if the system time (cpu sy) is double the user time (cpu us) system is facing shortage of CPU resources.
Resolution
Resolution to these kind of issues involves tuning of application procedures to make efficient use of cpu and as a last resort increasing the cpu power or adding more cpu to the system.

B. Memory Issues
Memory bottlenecks are determined by the scan rate (sr) . The scan rate is the pages scanned by the clock algorithm per second. If the scan rate (sr) is continuously over 200 pages per second then there is a memory shortage.
Resolution
1. Tune the applications & servers to make efficient use of memory and cache.
2. Increase system memory .
3. Implement priority paging in s in pre solaris 8 versions by adding line “set priority paging=1″ in
/etc/system. Remove this line if upgrading from Solaris 7 to 8 & retaining old /etc/system file.

The top Command

The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of tasks currently being managed by the Linux kernel.
The top command monitors CPU utilization, process statistics, and memory utilization. The top section contains information related to overall system status - uptime, load average, process counts, CPU status, and utilization statistics for both memory and swap space.
[root@bigboy tmp]# top
3:04pm up 25 days, 23:23, 2 users, load average: 0.00, 0.02, 0.00
78 processes: 76 sleeping, 2 running, 0 zombie, 0 stopped
CPU states: 0.9% user, 0.5% system, 0.0% nice, 0.8% idle
Mem: 384716K av, 327180K used, 57536K free, 0K shrd, 101544K buff
Swap: 779112K av, 0K used, 779112K free 130776K cached

PID USER PRI NI SIZE RSS SHARE STAT %CPU %MEM TIME COMMAND
27191 root 15 0 1012 1012 780 R 5.6 0.2 0:00 top
4545 root 16 0 5892 5888 4956 S 0.9 1.5 169:26 magicdev
1 root 15 0 476 476 432 S 0.0 0.1 0:05 init
2 root 15 0 0 0 0 SW 0.0 0.0 0:00 keventd
5 root 15 0 0 0 0 SW 0.0 0.0 0:41 kswapd
6 root 25 0 0 0 0 SW 0.0 0.0 0:00 bdflush

Find out who is monopolizing or eating the CPUs

Finally, you need to determine which process is monopolizing or eating the CPUs. Following command will displays the top 10 CPU users on the Linux system.
# ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
OR
# ps -eo pcpu,pid,user,args | sort -r -k1 | less
Output:
%CPU PID USER COMMAND
96 2148 vivek /usr/lib/vmware/bin/vmware-vmx -C /var/lib/vmware/Virtual Machines/Ubuntu 64-bit/Ubuntu 64-bit.vmx -@ ""
0.7 3358 mysql /usr/libexec/mysqld --defaults-file=/etc/my.cnf --basedir=/usr --datadir=/var/lib/mysql --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --skip-locking --socket=/var/lib/mysql/mysql.sock
0.4 29129 lighttpd /usr/bin/php
0.4 29126 lighttpd /usr/bin/php
0.2 2177 vivek [vmware-rtc]
0.0 9 root [kacpid]
0.0 8 root [khelper]
Now you know vmware-vmx process is eating up lots of CPU power. ps command displays every process (-e) with a user-defined format (-o pcpu). First field is pcpu (cpu utilization). It is sorted in reverse order to display top 10 CPU eating process.

Input Output statistics ( iostat )

iostat reports terminal and disk I/O activity and CPU utilization. The first line of output is for the time period since boot & each subsequent line is for the prior interval . Kernel maintains a number of counters to keep track of the values.

Basic synctax is iostat interval count
option – let you specify the device for which information is needed like disk , cpu or terminal. (-d , -c , -t or -tdc ) . x options gives the extended statistics .

To run iostat , sysstat package should be installed.
iostat -xtc 5 2
extended disk statistics tty cpu
disk r/s w/s Kr/s Kw/s wait actv svc_t %w %b tin tout us sy wt id
sd0 2.6 3.0 20.7 22.7 0.1 0.2 59.2 6 19 0 84 3 85 11 0
sd1 4.2 1.0 33.5 8.0 0.0 0.2 47.2 2 23
sd2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 0
The fields have the following meanings:
disk name of the disk
r/s reads per second
w/s writes per second
Kr/s kilobytes read per second
Kw/s kilobytes written per second
wait average number of transactions waiting for service (Q length)
actv average number of transactions actively being serviced
(removed from the queue but not yet completed)
%w percent of time there are transactions waiting
for service (queue non-empty)
%b percent of time the disk is busy (transactions
in progress)

The values to look from the iostat output are:
* Reads/writes per second (r/s , w/s)
* Percentage busy (%b)
* Service time (svc_t)
If a disk shows consistently high reads/writes along with , the percentage busy (%b) of the disks is greater than 5 percent, and the average service time (svc_t) is greater than 30 milliseconds, then one of the following action needs to be taken
1.) Tune the application to use disk i/o more efficiently by modifying the disk queries and using available cache facilities of application servers .
2.) Spread the file system of the disk on to two or more disk using disk striping feature of volume manager /disksuite etc.
3.) Increase the system parameter values for inode cache , ufs_ninode , which is Number of inodes to be held in memory. Inodes are cached globally (for UFS), not on a per-file system basis
4.) Move the file system to another faster disk /controller or replace existing disk/controller to a faster one.

Network Statistics (netstat)

netstat displays the contents of various network-related data structures in depending on the options selected.

Example 1:
Network Response
$ netstat -i
Name Mtu Net/Dest Address Ipkts Ierrs Opkts Oerrs Collis Queue
lo0 8232 loopback localhost 77814 0 77814 0 0 0
hme0 1500 server1 server1 10658 3 48325 0 279257 0

This option is used to diagnose the network problems when the connectivity is there but it is slow in response .
Values to look at:
1. Collisions (Collis)
2. Output packets (Opkts)
3. Input errors (Ierrs)
4. Input packets (Ipkts)

The above values will give information to workout
i. Network collision rate as follows :
Network collision rate = Output collision counts / Output packets
Network-wide collision rate greater than 10 percent will indicate
* Overloaded network,
* Poorly configured network,
* Hardware problems.
ii. Input packet error rate as follows :
Input Packet Error Rate = Ierrs / Ipkts.
If the input error rate is high (over 0.25 percent), the host is dropping packets. Hub/switch cables etc needs to be checked for potential problems.

Example 2:
#netstat -a
Local Address Remote Address Swind Send-Q Rwind Recv-Q State
*.* *.* 0 0 24576 0 IDLE
*.22 *.* 0 0 24576 0 LISTEN
if you see a lots of connections in FIN_WAIT state tcp/ip parameters have to be tuned because the
connections are not being closed and they gets accumulating . After some time system may run out of
resource . TCP parameter can be tuned to define a time out so that connections can be released and used by new connection.


sar command
The command is run by typing in:
sar -options int #samples
where valid options generally are:
-g or -p Paging
-q Average Q length
-u CPU Usage
-w Swapping and Paging
-y Terminal activity
-v State of kernel tables

The free Utility

The free utility can determine the amount of free RAM on your system. The output is easier to understand than vmstat's. Here's a sample.

[root@bigboy tmp]# free
total used free shared buffers cached
Mem: 126060 119096 6964 0 58972 40028
-/+ buffers/cache: 20096 105964
Swap: 522072 15496 506576
[root@bigboy tmp]#

You should generally try to make your system run with at least 20% free memory on average, which should allow it to handle moderate spikes in usage caused by running memory-intensive cron batch jobs or tape backups. If you cannot achieve this, consider running more efficient versions of programs, offloading some applications to servers with less load, and, of course, upgrading the capacity of your RAM.

Silk Performance Explorer - Server Monitor option for Linux gives NULL (zero) value for all the counters

Performance Explorer executes a set of commands against the REXEC daemon running on the Linux server, so the first thing to do would be to ensure the rexec daemon is running on the Linux box.

You will find the default measures under PRE-DEFINED DATA SOURCES | CUSTOM DATA | REXEC DATA
*********

QUESTION
----------------------------------
In SilkPerformer"s Server Analysis Module, how can I use the Rexec command to get performance data of a Unix Server ?

The easiest way to do this would be to obtain a MIB file for the device or server you wish to monitor.
Some vendors supply a MIB with their products.

If you do not have a MIB file then you can make use of the Rexec command.


ANSWER
----------------------------------
Open a command prompt from Windows and get information on the device - the command will be:
Rexec "netstat -i " (include the " marks)
You will need an admin level login and password

This will return values for all of the devices on the unix box, normally something like :-

Name MTU Net/Dest Address IPkts IErrors Opkts Oerrs Collis Queue
lo0 8232 loopback locahost 39112 0 22333 0 0 0
hme0 1500 293813 0 333332 0 0 0

The hme0 is the Network Card of the Unix machine which should provide us with the information we require.
Let"s say for example we are interested in the number of InPackets (InPkts) and OutPackets (Opkts) during the loadtest.

We now need to incorporate this Rexec command into SilkPerformer"s SAM, so that we can retrieve this information and either write it to a report or create a graphical representation of it.

Open SilkPerformer
Go to RESULTS | MONITOR SERVER
Performance Explorer will open.
Click MONITOR | ADD DATA SOURCE
Choose Custom Data from the list
Then choose Rexec Data from the Custom Data tree
Choose Next
Enter the Unix server name and the port you are connecting to.
Enter an administrator"s username and password

The Rexec Measures dialog opens.

1)Enter a Measure Type " My Unix"
2)Enter a Measure Name " In Pkts"
3)Enter a Command netstat - I hme0 // please ensure you use a capital letter I for this netstat command
4)Enter a Field Index (looking at the table above it is column 5 for Inpkts - so enter 5)
5)Enter a Line to Skip - 1 //this skips the table headers and choose the hme0 data only

Although the table above shows that you would need to skip 2 rows to get to hme0, however in our command (step 3) we are specifying the name of the device explicitly therefore this will be the only one listed

Click Add when done.
Now follow steps 1 - 5 to add Opkts to our custom measures, you will need to change the Field Index
(Step 4) to a value of 7

Click Add when done.

You should now be able to obtain these measures from your server.