TESTEVERYTHING

Thursday, 17 January 2013

Jmeter bean shell script, create file, read jmeter variable value, store script variable value into jmeter variable

Hi All,

Some times in JMeter scripting we need to store the output value in file or wanna show the run time  variable value in console window. OR we need to get the current JMeter script directory path. This can be achieved via scripting in Bean Shell Pre/Post Processor.

Here I am using time and counter function of JMeter to create the file.In bean shell scripting we are reading the JMeter variables value and storing script variable value into JMeter variable or creating Jmeter variable

Here is the  Bean Shell script :

import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.services.FileServer;
import java.util.Date;
import java.text.SimpleDateFormat;

SimpleDateFormat formatter = new SimpleDateFormat( "yyyyMMddHHmmss" );  
String datetime = formatter.format( new java.util.Date() ); 

// Get current running counter value(C refrence name deifned in counter config element)

String counter= vars.get("C");

// Get Jmeter variable value in bean shell script by vars.get method

String timer= vars.get("JmeterTimerVariable");

// here JmeterTimerVariable defined in User Defined variable  config element


//  Display value in Console 

System.out.println("Current counter value = " + counter);

System.out.println("JmeterTimerVariable value = " + timer);


// Store beanshel script variable into Jmeter variable by using vars.put method and we will user this jmetervariable in Wikisearch http request

vars.put("JmeterSearchVariable",datetime+counter);

// get JmeterSearchVariable value in beanshell script

String SearchVariable = vars.get("JmeterSearchVariable");

System.out.println("SearchVariable value = " + SearchVariable);

// Here we can get the directory path of Jmeter script file

String DirPath = FileServer.getFileServer().getBaseDir();

// write into jmeter.log file under Jmeter/bin directory

log.info(DirPath);

System.out.println("Directory path of Jmeter script file = " + FileServer.getFileServer().getBaseDir());

// we will create a file under directory of jmeter script file with name JmeterReords using File system True file will be created if not and data will //append into the file False will create a new file with fresh data

f = new FileOutputStream(FileServer.getFileServer().getBaseDir()+"\\JmeterReords.txt", true); 
p = new PrintStream(f); 
// write data into file 
p.println("Current counter value = " + counter);
p.println("JmeterTimerVariable value = " + timer);
p.println("Directory path of Jmeter script file = " +DirPath);
p.close();
f.close();

// if you want to create unique file for each loop counter refer below script

String uniquefilename = timer+counter;
f = new FileOutputStream(FileServer.getFileServer().getBaseDir()+"\\"+uniquefilename+".log", true); 
p = new PrintStream(f); 
// write data into file 
p.println("Current counter value = " + counter);
p.println("JmeterTimerVariable value = " + timer);
p.println("Directory path of Jmeter script file = " +DirPath);
p.close();
f.close();





Here is the structure of JMeter script

Jmeter Bean Shell script
Jmeter bean Shell script


Wednesday, 9 January 2013

Perform Mouse, drag-and-drop, sliding, selecting multiple Action in Webdriver/Selenium 2

Perform Mouse, drag-and-drop, sliding, selecting multiple Actions in Web driver/Selenium 2 

Solution

The example code below shows some examples where we can use the Actions interface of Selenium WebDriver.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package selenium2.examples;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ActionExample {
    private static WebDriver driver;

    @BeforeClass
    public void setUp() {
        driver = new FirefoxDriver();
    }

    @AfterClass
    public void tearDown() {
        driver.close();
        driver.quit();
    }

    @Test
    public void draggable() {
        driver.get("http://jqueryui.com/demos/draggable/");

        WebElement draggable = driver.findElement(By.id("draggable"));
        new Actions(driver).dragAndDropBy(draggable, 120, 120).build()
                .perform();
    }

    @Test
    public void droppable() {
        driver.get("http://jqueryui.com/demos/droppable/");

        WebElement draggable = driver.findElement(By.id("draggable"));
        WebElement droppable = driver.findElement(By.id("droppable"));
        new Actions(driver).dragAndDrop(draggable, droppable).build().perform();
    }

    @Test
    public void selectMultiple() throws InterruptedException {
        driver.get("http://jqueryui.com/demos/selectable/");

        List<WebElement> listItems = driver.findElements(By
                .cssSelector("ol#selectable *"));

        Actions builder = new Actions(driver);
        builder.clickAndHold(listItems.get(1)).clickAndHold(listItems.get(2))
                .click();

        Action selectMultiple = builder.build();
        selectMultiple.perform();
    }

    @Test
    public void sliding() {
        driver.get("http://jqueryui.com/demos/slider/");

        WebElement draggable = driver.findElement(By
                .className("ui-slider-handle"));
        new Actions(driver).dragAndDropBy(draggable, 120, 0).build().perform();
    }
}

Friday, 12 October 2012

Count elements/links on page using webdriver

Sometimes we need to count links on page. Here we are counting the elements on page. We use the same method for any type of element like link, span,button just use html tag of that element in xpath.


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.
WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
   

Maximize window in selenium/webdriver

By using below methods you maximize window in selenium/webdriver
1.  selenium.windowMaximize();
2.  driver.manage().window().maximize();

3. If above 2 commands doesn't work try the below code.

Refer the below example

Sunday, 23 September 2012

Locating elements using DOM, Css and Xpath

 Refer the below example

Whole web page

xpath=/html
css=html
document.documentElement
Whole web page body
xpath=/html/body
css=body
document.body
All text nodes of web page
//text()
Element <E> by absolute reference
xpath=/html/body/.../.../.../E
css=body>…>…>…>E
document.body.childNodes[i]...childNodes[j]
Element <E> by relative reference
//E
css=E
document.gEBTN('E')[0]
Second <E> element anywhere on page
xpath=(//E)[2]
document.gEBTN('E')[1]
Image element
//img
css=img
document.images[0]
Element <E> with attribute A
//E[@A]
css=E[A]
dom=for each (e in document.gEBTN('E')) if (e.A) e Œ
Element <E> with attribute A containing text 't' exactly
//E[@A='t']
css=E[A='t'] 
Element <E> with attribute A containing text 't'
//E[contains(@A,'t')]

Element <E> whose attribute A begins with 't'
//E[starts-with(@A, 't')]

Element <E> whose attribute A ends with 't'
//E[substring(@A, string-length(@A) - string-length('t')+1)='t']

Element <E> with attribute A containing word 'w'
//E[contains(concat('⦿', @A, '⦿'), '⦿w⦿')
Element <E> with attribute A matching regex ‘r’
Element <E1> with id I1 or element <E2> with id I2
//E1[@id=I1] | //E2[@id=I2]
css=E1#I1,E2#I2
Element <E1> with id I1 or id I2
//E1[@id=I1 or @id=I2]
css=E1#I1,E1#I2
Attribute A of element <E>
//E/@A {Se: //E@A }
{Se: css=E@A }
document.gEBTN('E')[0].getAttribute('A')
{Se: document.gEBTN('E')[0]@A }
Attribute A of any element
//*/@A  {Se: //*@A }
{Se: css=*@A }
Attribute A1 of element <E> where attribute A2 is 't' exactly
//E[@A2='t']/@A1 {Se: //E[@A2='t']@A1 }
{Se: css=E[A2='t']@A1 }
Attribute A of element <E> where A contains 't'
//E[contains(@A,'t')]/@A {Se: //E[contains(@A,'t')]@A }
{Se: @A }
Element <E> with id I
//E[@id='I']
css=E#I
Element with id I
//*[@id='I']
css=#I
document.gEBI('I')
id=I

Friday, 10 August 2012

Selenium Webdriver 2 Wait /Sleep for time period/wait next step execution/ Set speed for next execution

Some times we have to wait while running the script like for next execution wait for specific duration.But in web driver 2, I did not find the simple way to wait for next step execution after that I have decided to use simplest way to wait in looping statement. I have created a method just call the method with waiting time in seconds.It will wait for given time period.


Thursday, 9 August 2012

Handling Security Cerificates(UntrustedSSLCertificates) using WebDriver(selenium2)

Handling Security Cerificates(UntrustedSSLCertificates) in Internet Explorer (IE) using WebDriver(selenium2)

driver = new InternetExplorerDriver();
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
// or using selenium rc
selenium.runScript("document.getElementById('overridelink').click()");

Handling Security Cerificates(UntrustedSSLCertificates) in Firefox using WebDriver(selenium2)


Thursday, 2 August 2012

Set cookies with domain using webdriver

using web driver I have created the script for adding the cookies using domain. Basically here is the things that you must know first open the URL then add the cookies after that again open the URL now it will add.

 ______________________________________________________
package webdriver;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class RuntestCase {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
       
        WebDriver driver;


        System.out.println("firefox");

        DesiredCapabilities capability = DesiredCapabilities.firefox();

        String appUrl = "http://beta.abc.com/mlb/sweepstakes/y2012/sd/alaska_form.jsp";

        capability.setBrowserName("firefox");
        capability.setPlatform(org.openqa.selenium.Platform.ANY);
        driver = new FirefoxDriver(capability);

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
       
        driver.get(appUrl);

        Calendar c = new GregorianCalendar();
        int year = 2014;
        int month = 6;
        int day = 7;
        int hour = 10;
        int minute = 26;
        int second = 47;
        c.set(year, month, day, hour, minute, second);
        Date expiry = c.getTime();
        String name = "betaaccess";
        String value = "true";
        String domain = ".abc.com";
        String path = "/";
        Cookie cookie = new Cookie(name, value, domain, path, expiry, false);
        driver.manage().addCookie(cookie);
        driver.get(appUrl);
               
            }
    }

Wednesday, 16 May 2012

String Reverse in VB Script Without using any function

Dim yourstr,r,letter,result
yourstr="pro1gr3a6m"

Set r=new regexp
r.pattern="[a-z 0-9 A-Z]"
r.global=true
set s=r.execute(yourstr)

For each letter in s
result= letter.value&result
Next

print result

Wednesday, 15 February 2012

Tips to Optimize QTP Scripts to Yield Better Performance



Tips to Optimize QTP Scripts to Yield Better Performance


We use Automated-testing tools to optimize our manual testing processes. But in order to reap full benefits of any automated testing tool, we must know the complete ins and outs of the tool otherwise it would be a huge waste of money spent on automation. We have to learn the automation tool very thoroughly. We also need to learn the language of the automation tool to do coding more effectively and efficiently. I believe that a software testing tool is as good as the person who is actually using it.
I have been getting so many emails from my esteemed readers asking about HP QuickTest Professional tutorials, QTP tips and tricks etc. Some readers even complain that their QTP scripts are too slow to execute. This time I decided to write a post on how to use QTP more effectively which means how to make our QTP scripts perform better. In order words, this post will throw light on some points, which will optimize your QTP scripts.
Some of the QTP optimization tips can be:  
Tip – 1: You should not use hard coded wait statement until absolutely necessary. Instead of the wait statement, you should use either exist or synchronization (sync) statements. The wait statement waits for the number of seconds, which have been provided. For example using wait(5) will wait for 5 seconds even if the browser gets into a ready state even after 2 seconds which means a waste of 3 seconds. Imagine how much time would be wasted if you have say 10 wait statements per script and you are running a batch of 500 scripts. A better alternative is using sync or exist statements for example:
 
Browser("").Page("").Sync
var=Browser("").Page("").Exist(2)
 

Never use the exist statement without a value as it will take the default object synchronization timeout value from QTP settings. You can navigate to these settings from File->Settings and then go to Run tab. So use Exist(0) instead of Exist(10). Moreover, I will suggest to set the global object synchronization timeout to 1 second. 
 Tip – 2: Use declared variables instead of using variables on the fly. In order to enforce this in your scripts, use Option Explicit statement which forces the variable declaration. Moreover, using declared variables, scripts perform a bit faster. Also if you are using Option Explicit, it has to be the very first line of the code otherwise you will get an error.
Tip – 3: Using QTP for a longer period of time has a direct impact on the performance. It has been observed that a lot of Random Access Memory(RAM) gets consumed by QTP if QTP is running scripts for prolonged time. QTP starts eating system memory(memory leak) and sooner or later it will get hanged and we will be required to kill the qtpro.exe process and restart QTP all over again. In such a case, I will suggest you is to use QTP on computers with particular good amount of RAM and equally good clock speed.
Tip – 4: Do not load all addins while opening QTP. Use only the addins, which are required. This directly impacts QTP performance.
Tip – 5: I have personally experienced that opening QTP through a vbs file is faster than loading QTP through the icon.

Tuesday, 10 January 2012

Jmeter: pass a value between threads


Synopsis: 

Find out ways to pass a value between threads (i.e. capturing a value in one of the thread and passing it to the other thread in the same test plan).

Tool Used:     JMeter: Performance testing tool.


Solution:       Sharing Variables





1)      Used Sampler : BSF Sampler
1)      Screenshot displaying the use of the BSF Sampler using  ${__setProperty(storeid, ${storeid})}; for capturing the time. The website used is http://www.mail-archive.com/jmeter-user@jakarta.apache.org/info.html for displaying the value captured in one thread to the other thread.
Screenshot 1: Displaying the BSF Sampler capturing the time value using ${__setProperty(storetime, ${__time(HMS)})};





Screenshot 2: Displaying the time captured using ${__property(storetime)} in the other thread.

Screenshot3: Successful execution of the script displaying the time value captured in Thread2




QTP : object is Visible OR Not on Web Page

Hi All,
Some times we have to  check that a object(WebElement) is  exist on page or not. For this we use object exist = False  property but when we run the script it gets failed While object is not showing in the Page. We think that there is  something  wrong.
The reason behind why QTP  is giving this because object is present in the page but not visible means it not displaying while it exist in HTML code.
So for this we have to be understand the object property( object.currentstyle.display) there will be case some time object inherit the property from its parent or another parent element property to display in page. First we have to identify that object when it not showing/displaying in page.We have to check its display property
Display property value we can get through like this 

rem disvalue

disvalue =Browser(“Google”).Page(“Google”).Image(“Happy Holidays from Google!”).Object.currentStyle.display
if disvalue =”block” then
print ” object not displaying”
else
print ” object displaying”
end if
like this(incase if object using display property from its  parent object )  we have to check by which element my object showing on page

Friday, 2 December 2011

Selenium disable add-ons pop-up for Custom firefox profile

Here is the way to disable add-ons window which appears every time when selenium scripts are run on Custom Firefox Profile.


Close all instances of Firefox browser and delete the following files from the Custom Profile folder, this should reset Extension Manager and disable add-ons pop-up:
  • extensions.cache
  • extensions.ini
  • extensions.rdf
  • compatibility.ini
This Add-ons pop-up will not displayed the next time you run selenium scripts.

To find the Firefox profile,  type in cmd run prompt "%APPDATA%\Mozilla\Firefox\Profiles\"  press enter

Thursday, 1 December 2011

Tips to Decide What Test Cases to Automate

It is impossible to automate all testing; the first step to successful automation is to determine what test cases should be automated first.

The benefit of automated testing is correlated with how many times a given test can be repeated. Tests that are only performed a few times are better left for manual testing. Good test cases for automation are those that are run frequently and require large amounts of data to perform the same action.


You can get the most benefit out of your automated testing efforts by automating:

  •       Repetitive tests that run for multiple builds
  •    Tests that are highly subject to human error
  •      Tests that require multiple data sets
  •        Frequently-used functionality that introduces high risk conditions
  •        Tests that run on several different hardware or software platforms and configurations
  •        Tests that take a lot of effort and time when doing manual testing

Saturday, 15 October 2011

Vi - Linux Editor Commands

Common vi Commands
Have a look at this list of common vi commands (there are many more, but these will at least allow you to get some basic work done). Then we'll do one more exercise before moving on.
Note: As with all of Linux, vi commands are case sensitive.
Positioning the Cursor
Move cursor one space right.
Move cursor one space left.
Move cursor up one line.
Move cursor down one line.
ctrl-F Move forward one screen.
ctrl-B Move backward one screen.
$ Move cursor to end of line.
^ Move cursor to beginning of line.
:1 Move to first line of file
:$ Move to last line of file
/ Search for a character string.
? Reverse search for a character string.
x Delete the character at the cursor position.
dd Delete the current line.
p Paste data that was cut with x or dd commands.
u Undo.

Basic UNIX Commands

Directory
::
Show current directory
pwd
Show content of directory
ls -al
Changing directory
cd <newdir>
Creating directory
mkdir <dir>
Deleting directory if empty
rmdir <dir>
Deleting directory if full
rm -r <dir>
Moving directory
mv <olddir> <newdir>
Copy directory
cp -r <olddir> <newdir>
Files
::
Show file entry
ls -al <file>
Delete file
rm -i <file>
Move file
mv <file> <path>
Copy file
cp <file> <newfile>
Rename file
mv <oldfile> <newfile>
Show file content at once
cat <file>
Show file content page wise
more <file>
Show file with long lines
cat <file> | fold
Show first 20 lines of file
head -20 <file>
Show last 20 lines of file
tail -20 <file>
Edit file
<editorname> <file>
Edit file with vi
vi <file>
Give all file permissions to yourself
chmod 700 <file>
The above even into subdirectories
chmod -R 700 <dir>
Open file for reading and executing for all
chmod 644 <file>
Starting file as program
<filneame> <arguments>
Find word in file
grep <word> <file>
Find all files which contain a word
grep -l <word> *
Find abstract pattern: ab 2 digits cd
grep 'ab[0-9][0-9]cd' <file>
Comparing two files
diff <file1> <file2>
Updating the date of a file
touch <file>
Giving a specific date to a file
touch 0101010199 <file>
Help
::
Getting help about a command
man <command>
Find command related to a term
man -k <term>
Where is a particular program if it is in the path
which <commandname>
Is a <name> a unix command or an alias in ksh
whence <commandname>
Aliases
::
Making an alias in csh/tcsh
alias <aliasname> '<long_command>'
Making an alias where the arguments go in the middle
alias <aliasneme> '<command> \!* <other>'
Making an alias in sh/bash/ksh
alias <aliasname>='<long_command>'
Using an alias
<aliasname> <arguments>
Use command instead of it's alias
\<command>
Showing all aliases
alias
Remove an alias
unalias <aliasname>
Adjustments
::
See environment variables
env
Setting the term variable if vi doesn't work
setenv term vt100
Opening the X-server for X-clients
xhost +
Setting the display for X-clients
setenv display <computer>:0.0
Internet
::
Telnet to another computer
telnet <computername>
Rlogin to another computer
rlogin -l <username_there> <computername>
Browsing the net with netscape
netscape
Check whether someone is logged in somwhere
finger user@host.domain
Check for all people on another computer
finger @host.domain
Talk to another person on another computer
talk user@host.domain
Ftp building up connection
ftp <computername>
Ftp adjusting for binary transfer
>bin
Ftp showing directory
>dir
Ftp changing directory
>cd /<path>/<path>
Ftp getting a file
>get <file>
Ftp getting multiple files
>mget <filenamecommon>*
Ftp searching for a file
>quote site find <filename>
Get the ip number of a computer
nslookup <computername>
Check whether another computer is up
ping <computername>
Check the pathway to another computer
traceroute <computername>
Info about Unix System
::
See who is logged on
who ... w ... what
Get the date
date
See who logged in lately
last -20
See what operating system is there
uname -a
See who you are
whoami
Get the name of your computer
hostname
See the disk space used
df -k
See you quota usage
quota -v
See how much space all your files need
du -k
Mail
::
Check for mail
from
Read mail
Mail
Compose mail
Mail -s <subject> <mailaddress>
Mail a whole file ( one "<" is real )
Mail -s <subject> <mailaddr> < <file>
Compressing Files
::
Compress 50%
compress <file>
Uncomress the above file.Z
uncompress <file>.Z
Compress 70%
gzip <file>
Uncompress the above file.gz
gzip -d <file>.gz

Which one is right ?

Translate







Tweet