Skip to main content

Posts

Showing posts from 2011

Script Error while running selenium scripts on IE

While running the selenium scripts on IE, we might get this error sometimes: Script Error on IE Solutions:  Possible that your pop-up blocker is enabled which is stopping selenium from opening another window (multi-window mode) - so add an exception to your pop-up blocker - Use this link to add/remove popup exceptions You can disable script errors on IE by disabling MDM.  Machine Debug Manager  Windows service (not only stop it, but prevent it from starting after the computer restarts). Follow this link to Disable Sometimes running the tests/starting the server as an ADMIN resolves the issue

Selenium: How to verify a hidden div tag exists

Most of the times we do have hidden div tags which need to be verified.  In most of the test designs, the first step towards testing a particular application is to verify that all the elements exist on the application under test.  Example:  Lets say we have a login page which has two text-fields. One for username the other for password. On the page, we also have a hidden div tag which is used by the developer to pass on the login failure message.  Usually its hidden but is set to visible when there is a login failure.  In usual test designs we would want to do something like this at the first step.  1. test all the components exist:  verifyTrue(selenium.isElementExists(LoginPage.username));  verifyTrue(selenium.isElementExists(LoginPage.password)); 2. Then give an incorrect username and password  selenium.type("LoginPage.username","SomeUserName"); selenium.type("LoginPage.password","SomePassword"); 3. Now verify that the label fo

Creating Unique Values using Date

Many a times we are in need of a unique value. The best way to generate a unique value is to use the current date and time combination. We can add both the current date and time to generate a unique value but there are times when we need more precise data to get uniqueness. For instance, you have two jobs running in the same minute then your unique value fails, i.e. when one job is ran at 9.32 AM after 10 milli secs and another is ran at 9.32 AM after 20 milli secs. At this time our unique generator creates the values as: 20111102932 (2011 - 11 - 02 9:32) for both the orders. This is when we will need to include millisecs too. To get the milli secs you can use the following commands in Java: long ldtInMillis = new Date().getTime(); System.out.println("Date - "+ ldtInMillis); Calendar lCalDtMillis = Calendar.getInstance(); System.out.println("Calender - " + lCalDtMillis.getTimeInMillis());

TestNG Error: Reference testng-impl-classpath not found

When we are running testng ant tasks we might get this error:  "Reference testng-impl-classpath not found" You should look at the testng.xml file you are using for testng to pick up your classes from!!! Like mine has the following:                          Now you should check if your classes mentioned in the file are found at the exact path.. I have a mistake in the path. My classes are found under Panels.LeftPanels.Barrel.TestBookBox Thus the error. So solution: Check if you have any mistake in the class path you mentioned!!!!

ssh connection refused on port 22

When we are trying to access another linux box using ssh we might get this error: ssh error: connection refused on 22 Hit this command: ps aux | grep ssh If you get two entries which list sshd and ssh-agent then it means ssh is running on your machine Kill those connections Start your ssh again This should resolve the issue!!!! If you have resolved it in any other way, please leave a comment. Thanks!

Working with User Defined Properties using ANT

Its quite useful to work with user defined properties using ANT. Lets say you have a build.xml in which you want to run a target based on a user input...In my case I want to decide on which URL to pass to Selenium based on the user selection of the stage to run the tests against... Add the following to the build.xml:  Now you can access the property from your program as  String urlString = System.getProperty("url"); If you are using TestNG framework, then you should add the property to your ant task in the build.xml file as:          To send this property from command line, you should send the property as  -Durl=

Useful Linux Commands - I

Want to know your system name? /bin/uname -n Know where you are in your file system:  pwd  The command will print Present Working Directory How do you create a shortcut in linux? ln How to extract compressed files? tar Downloading from a link can't be faster on any other OS :)  wget Forgot which commands you ran? history Want to see whats your disk space usage? df  df -h gives human formatted listing Most important command to know more about the above commands - Need more help about the commands? man

Selenium n Safari

For all those who are stuck running Selenium tests on Safari... Here are a couple of tips: If you are using any version before 5 of Safari You can run your tests using any RC versions > 1.0 If you tests doesn't run then please verify the following:  Enable popup's on Safari - I know I sound silly but believe me thats the only issue sometimes Try running your tests using *safariproxy Verify the path given for the safari executable - it should be something like: C:\ProgramFiles\Safari\Safari.exe If you are using version 5.1  Then you have to run your tests on RC version 1.0.3 only Also change your tests to run using *safariproxy Don't forget enable pop ups :)  Even after doing all this - you'll still need an All the Best !!! And if you have a choice then pls run your tests on Safari Mac :) 

Issues Running Selenium Scripts Remotely

In real time we hardly have a simple setup like running on the same box which acts as a server and client :( So we might have to run the scripts remotely almost all the time...Well there might be issues while doing so...Here are some! Can't launch the browser at all: Check the host name you are using in your code first! There is a possibility that the DNS isn't able to map the hostname with the IP - so try running your tests specifying the IP instead of the hostname Check the path you provided to the executable of the browser - verify its found on the same path on your remote location Now the final check is to verify you can run the browser version on the RC version for ex: you can't run FF7 on RC1 :)  Browser Opens but tests aren't running This happens because the RC isn't able to talk to your browser - though it initiates the browser but can't talk to it anymore Solution: Upgrade your RC :)  Running on a Headless Box Selenium can't run u

Test Execution and Reporting - My Notes from a Seminar I attended!

TechGig Webinar by Ashu Chandra - Test Execution and Reporting Overview Test Bed Preparation Environment where to test - ensure we have the rite version or the app server/database/application (AUT - app under test) Execute Tests Analyze unexpected behavior - this is when we see a difference in the expected result and actual result How to drill down What to look for not every unexpected behavior is a bug report bugs When we get a bug we should report the bug in crisp and clear way to dev so that dev can recreate it quickly bug lifecycle What stages does a bug go through exit criteria (when to stop testing) how much should we test report test findings best practices Test Bed Preparation Ensure you have required hardware/operating system availability of qa environment of interface applications If there are intermediate systems we should check their requirements too setup environment as per supported platform (DB version, app server version etc)

Difference between isVisible() and isElementPresent()

Many a times I wondered what's the difference between the two functions. Here is what I have: isElementPresent() - This method basically tests if the element we are looking for is present somewhere on the page. isVisible() - looks for display: none style tag - this might throw a null pointer if we aren't careful...thus to see if an element is visible first check if the element is present using isElementPresent() method. Then try checking if the element is visible! Observe that isElementPresent() won't mind even if our element is not visible. For ex: lets say the below is the html code for a component on my test application: now if you test the above component with selenium.isElementPresent("testinput") - returns true! selenium.isVisible("testinput") - returns false!

Export Bookmarks

There are alot of times when we would have to move the bookmarks from one machine to another for various reasons - backup/system migrations etc So here is a one stop solution on various browsers: On IE: Go to View Menu on the browser --> Toolbars --> Check (click) the Favorites Toolbar if its not already checked - This will enable you to see the favorites toolbar on the browser Once you see the Favorites toolbar, click on the "Favorites" menu button on the favorites toolbar. This will enable you to see a sidebar on the browser with your favorites listed You will also see a "Add to Favorites" button with a side arrow. Click that side arrow to get a menu where you have an "Import and Export" option. Click the "Import and Export" option On Firefox : Go to Bookmarks Menu on the browser, then click "Organize Bookmarks" -- this will open a new window which has options to import/export bookmarks One change for Firefox 7

Failing to Run a single Testng Group

We all have various testng groups added/modified/deleted each time we update our test cases. Many a times we would want to run only a single testng group though! Failing tests? Pre Condition: My Test Automation Suite is based on Selenium-Ant-Testng When we want to run a single testng group lets say "sereUnitTests": If you don't have a beforemethod/beforetest/beforeclass annotation, then you should check your code...Its possible that something went wrong at the code level If you have a beforemethod/beforetest/beforeclass annotation, then you should check for the groups listed under each annotation For Ex: my beforemethod looks like this: @BeforeMethod(groups={"unit", "integration"}) public void openReader() throws SeleniumException { // Some functionality } But I see that the group which I wanted to run isn't listed thus testng notices that there is a before method to be initiated before your actual tests run but then doesn't

Linux Version Help

Want to know which version your linux box is? Simple question isn't it... Run the following commands: cat /etc/*-release - This will give the distro of your linux For Ex: for RHEL 5 it will give:  Red Hat Enterprise Linux Server release 5 (Tikanga) lsb_release -a - The lsb_release command displays certain LSB (Linux Standard Base) and distribution-specific information For Ex:    LSB Version: :core-3.1-ia32 Distributor ID: RedHatEnterpriseClient Description: Red Hat Enterprise Linux Client release 5.4 (Tikanga) Release: 5.4 Codename: Tikanga uname -mrs - this will give you your kernel version for ex: Linux 2.6.32-5-amd64 x86_64 where:  Linux - Kernel name 2.6.32-5-amd64 - Kernel version number x86_64 - Machine hardware name (64 bit)

Running Firefox with Firebug

Many a times our XPATH's would fail on test execution. This is when we would want to run the browser with the firebug extension. Just add this section of code in your code:  File file = new File("firebug-1.5.4.xpi"); FirefoxProfile firefoxProfile = new FirefoxProfile(); firefoxProfile.addExtension(file); WebDriver driver = new FirefoxDriver(firefoxProfile); 

Error while running selenium script on IE6

The following is the code:  1).selenium.click("css=img[alt=\"Search\"]"); // For clicking Search Button 2).selenium.waitForPopUp("winSLocation", "30000"); // Wait for popup 3).selenium.selectWindow("name=winSLocation"); // Popup window 4).selenium.type("id=sLocation", "dal"); // dal Value assigning to the text in Pop up 5).selenium.click("id=btnSearch"); // Then click on search button 6).selenium.waitForPageToLoad("30000"); // wait for popup to get all value from dal 7).selenium.click("id=r1c1"); // to selecting the dal value from required values After  Clicking the Search button (means 1st point )we are getting the following error in selenium RC Command history “file:///C:/DOCUME~1/yamunach/LOCALS~1/Temp/customProfileDir872f1cda4df44c588669558e67f77656/core/RemoteRunner.hta “  This Error is

Test Enabling/Disabling JavaScript on a browser

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverBackedSelenium; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import com.thoughtworks.selenium.Selenium; public class TestJS { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("javascript.enabled", false); WebDriver driver = new FirefoxDriver(profile); Selenium selenium = new WebDriverBackedSelenium(driver, "http://www.somedomain.com"); selenium.open("/dp/gotopage/"); driver.findElement(By.id("prodImage")).click(); boolean result = driver.findElement(By.className("imageWarningMessage")).isEnabled(); if (result) System.out.println("Result is: "+driver.

Remote Web Driver Program

Just a simple class depeciting the usage of a RemoteWebDriver which will be useful for any beginner... import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class TestRemote { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub DesiredCapabilities capability = DesiredCapabilities.firefox(); try { WebDriver driver = new RemoteWebDriver(new URL("http://computername:4444/wd/hub"), capability); driver.get("http://www.google.com"); } catch (MalformedURLException e) { } } } This will create a RemoteWebDriver which will run on a hub using firefox.

Java String Initialization - Null vs ""

In a code review, I got a comment which asked me why I initialized with a null instead of a "" Reason #1 When you use String s = null it will create variable "s" on stack only and no object will exists on heap,but as soon as you declare things as like String s=""; what it will does is like it will create "" object on heap.As we know that Strings are immutable so whenever u wil assign new value to string varible everytime it will create new Object on heap...So I think String s=null is efficient than String s = ""; Reason #2 When we initialize a string as "",we are actually supressing a possible exception that will be automatically raised when we have it initialized to null. Yes Java has inbuilt exception handler for treating nulls - remember NUllPointerException (the buggy exception)...So if we have used this string somewhere on our webpage and it doesn't get inialized properly at runtime, if we had it initialized

Set PATH

Whatever role you are into, this task comes to you eventually where you have to setup your environment! Setting up your classpath/path including... So here is how you can do it! Two ways: Method one - Setting up the path just for the particular session For LINUX: export PATH=$PATH:/home/gvsiri/apache-ant-1.8.2/bin For Windows: set PATH=%PATH%;.;C:\SirishaGV\Software\apache-ant-1.8.2\bin Method two - setting up the path for the profile For Linux: Modify the .bash_profile file For Windows: Change in the environment variables

Selenium2 - Read a Table

If I have a table which is designed in this manner: If you have an ID for the table its really good to catch the table else you will have to do alot of manipulation with the tables you find... // Here I try to identify the table using its ID. WebElement table = webdriver.findElement(By.id("tableID")); // Here I try to identify the table using a simple xpath WebElement table = webdriver.findElement(By.xpath("/html/body/table/tbody")); // Get all the rows of the table List rows = table.findElements(By.tagName("tr")); Iterator i = rows.iterator(); System.out.println("-----------------------------------------------"); // Iterate over the rows of the table while(i.hasNext()) { WebElement row = i.next(); // Find all the columns of the row List columns = row.findElements(By.tagName("td")); Iterator j = columns.iterator(); System.out.print(" | "); // Iterate over the columns of the

Selenium: Get DropDown Options

How to get the options of a dropdown list? Here are the ways to get it: Option 1: - There is a built in function in selenium getselectoptions() which can be called to get the list of options available for the select tag. For ex: string[] dropDownItems = selenium.GetSelectOptions("//select[@id='someid']"); Option 2: - If you want to get the text of the dropdown items which are in this format Option One Option Two then you can get the text for the options using: var iCount = (int) selenium.GetXpathCount("//select[@id='someid']/option"); var optionsList = new List (); for (int i = 1; i <= iCount; i++) { String option = selenium.GetText("//select[@id='someid']/option[" + i + "]"); optionsList.Add(option); } Option 3: To get the id for the select options. We need the following code: var iCount = (int) selenium.GetXpathCount("//select[@id='someid']/option"); var optionsList = new List (); for (int i = 1; i

Circular Reference Warning/Error message

In Excel when you refer the cell where the formula lies in, it is a circular reference as you get the workbook confused... For Ex: You are writing a formula in A1 and the formula you enter is =Sum(A1:A5) this is a circular reference as you have the formula in A1 and you want the sum to include A1 Now the frustrating part in the circular reference error message is that it doesn't point you to the location which has the error. Thankfully there is an easy way to figure out which cells have circular reference: To locate circular references: Go to Formulas --> Error Checking --> Circular Reference (Excel 2010) Once you hover over it, you will see all the cells which have circular references...you can then rectify the errors... there are resources which explain in good detail: Video or in excel help go to "Excel 2010 Home > Excel 2010 Help and How-to > Formulas > Correcting formulas"

"double" datatype doesn't accept null values

The application gets a double value from the database. Database has and allows "null" values for a double type variable but in my java code I can't assign null values to the variable type double. double var1 = null; -- this throws an error Double var2 = null; -- no error thrown here reason: double is a primitive datatype and thus can't initialize it to a null but we can assign a null to Double as it takes the input as an object which encapsulates a primitive datatype. its like a wrapper to the primitive datatype thus can be initiated to null we can read the null value into our code as double var1 = resultset.getDouble(columnIndex); if the column has null it will return a zero thus saving your variable from the null pointer exception!

Java Out of Memory Error

If we get an outofmemory error on java you can do the following: 1. If you are running your java program using eclipse a. right click on project --> Run As --> Java Application --> Select Run Configurations b. Give -Xms1024m in Arguments Tab --> VM arguments: This sets the virtual memory to 1 GB for jvm to run

Profile Error on Chrome - "Your profile can not be used because..."

After upgrading/reinstalling Chrome we get this error when we open Chrome: "Your profile can not be used because it is from a newer version of Google Chrome. Some features may be unavailable. Please specify a different profile directory or use a newer version of Chrome." Solution Posted here: http://www.groovypost.com/howto/how-to/fix-chrome-error-message-profile-can-not-be-used-a-newer-version/

Clipboard Hack

A simple script has it all: var content = clipboardData.getData("Text"); alert(content); put this in the script tag! Didn't know it was that easy! Solution for IE: Go to internet options->security Press custom level In the security settings, select disable under Allow paste operations via script Not every browser seems to be allowing such easy way of protection ;) Solution for Chrome: Go to browser "Options" Choose Under the Hood Tab --> Content Settings Select Javascript -- Don't allow any site to run JavaScript I haven't tested this yet though! Let me know if you know better ways :) and also how to do it on various browsers :) Thanks!

Cron Job

Excellent Post @ http://www.markus-gattol.name/ws/time.html#cron Once we get to know what a cron job is, we can go on an get going on our linux box. This link will help you create your own cronjob: http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/

XHR Issue with Selenium - Firefox

When we try executing our suite on Firefox, there is an issue with the new Selenium 1.0.3 server: Got result: XHR ERROR: URL = http://www.____.com/ Response_Code = 503 Error_Message = Serrvice Temporarily Unavailable on session b882a11224b7____ This doesn't occur with the older selenium server jar but just the new one. Root Cause: This occurs mainly due to Open command If we alter the open command to have its second argument as TRUE...it works! Reference: Reference2 Also suggest  that you might want to use the latest version of Selenium RC...RC's 2 and above don't throw the XHR error... Get the latest RC here .

Selenium throws an exception when running on Firefox

we get this error when we are trying to run a testng annotated java selenium code on firefox: "[testng] com.thoughtworks.selenium.SeleniumException: this.getCurrentWindow is not a function" Then all the other annotations are SKIPPED. A workaround for such an error would be to put the line of code which gives this error under a try block. In my case it was openReader() I changed the code as below: try{ openReader()} catch(Exception e){System.out.println(e.toString());} The class should throw the Exception too! This solved the problem and after the exception is printed, the execution continues!