Tuesday, 16 July 2019

Different Types of Exceptions in Selenium + Java

Exceptions in Selenium WebDriver
Exception general meaning is a condition that is not common. Exceptions in Selenium WebDriver occurs many times in different scenarios. Following are few of them listed with example.

1. NoSuchElementException:
This exception occurs when WebDriver is unable to identify the elements during run time. Due to wrong selector or selector, which is, not exist.

Example:-
driver.findElement(By.id("invalidid")).sendKeys("Testing");

2. ElementNotVisibleException:
This Exception occurs when the element presence is in DOM, it is not visible.

Example:-
Hidden Elements, which has presence in DOM and it, is not visible. Visibility means the height and
width should be greater than zero. Hidden Elements are defined in HTML using of type=”hidden”.
driver.findElement(By.id("hiddenid")).sendKeys("Testing");

Reason 1- Duplicated XPATH
While writing xpath for your application, you might have taken xpath that is matching with more than 1 element, in this case, Selenium will throw Element, not the visible exception.

Solution: Try to write unique XPATH  that matches with a single element only.

Reason 2:
If you are trying to access some particular element on Webpage that is not currently visible, in this case also you will get the Element, not visible exception.

Solution: Use Explicit wait feature of Selenium and wait till the element is not visible. Once it is visible then you can perform your operations.
Syntax for Explicit wait
new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='index.html']")));

Reason 3 with solution:
This actually works for me a number of times. I was struggling with the OK button in my application. Even I was writing unique xpath but still I was facing Element Not Visible exception.  I have tried below code that solved my issue.

int ok_size=driver.findElements(By.xpath("//button[text()='OK']")).size();
driver.findElements(By.xpath("//button[text()='OK']")).get(ok_size-1).click();

3. NoSuchFrameException:
This Exception occurs when the driver is switching to an invalid frame, which is not available.
Example:-
driver.switchTo().frame(invalidindex);
(or)
driver.switchTo().frame("frame_z");

4. NoAlertPresentException:
This Exception occurs when the driver is switching to an invalid Alert, which is not available.
Example:-
driver.switchTo().alert().accept();
//Execute this command on browser without invoking the alert.

5. NoSuchWindowException:
This Exception occurs when the driver is switching to an invalid Window, which is not available.
Example:-
driver.switchTo().window("invalidwindowname");

6. WebDriverException:
This Exception occurs when the driver is performing the action after immediately closing the browser.
Example:-
driver.close();
driver.findElement(By.id("username")).sendKeys("Testing");

7. SessionNotFoundException:
This Exception occurs when the driver is performing the action after immediately quitting the browser.
Example:-
driver.quit();
driver.findElement(By.id("username")).sendKeys("Mukesh");

8. StaleElementReferenceException:
This Exception occurs when the Element belongs to a different frame than the current one. The user has navigated away to another page.
Example:-
WebElement element=driver.findElement(By.id("username"));// Element is available in parent window
driver.switchTo().window(Child_Window);//Switch to Child Window
element.sendKeys("Mukesh");//perform the action on the element which is not visible in the child window

9. InvalidElementStateException:
when element is in disabled mode, we can encounter this exception
WebDriver driver=new ChromeDriver();

driver.get("http://www.testing.com");

// This element is disable, so if we try to click on disable webelement then it will throw exception
// Using below code it will pass the data forcefully.

JavascriptExecutor jse = (JavascriptExecutor) driver;

jse.executeScript("document.getElementById('pass').value = 'Testing';");

10. ElementNotClickable:

// Scroll the browser to the element's Y position
((JavascriptExecutor)driver).executeScript("window.scrollTo(0,"+elementToClick.getLocation().y+")");

11. illegalstateexception:
  java.lang.illegalstateexception
 When we don't use system.setpropery method for Chrome, IE, Mozilla this exception comes
System.setProperty("webdriver.ie.driver","path of the chromedriver.exe");
WebDriver driver=new InternetExplorerDriver();

12. stateelementexception:
How to solve Stale Element Reference exception

Solution 1:
You can refresh the page and again try for the same element.
Example- If you are trying to click on link and getting the exception then try in below format
Driver.navigate().refersh();
Driver.findElement(By.id(“ur element id”)).click();

Solution 2:

Sometimes it takes the time to attach element on Dom so you can retry using for loop and try catch.
for(int i=0i<=2;i++)
{
  try{
     Driver.findElement(By.id()).click();
    break;
}
catch(Exception e)
{
Sysout(e.getMessage());
}
}

Selenium - Different types of locators


Selenium identifies elements with locators. There are total 8 different types of locators available and those are mentioned in below with examples.

1. xpath
2. cssSelector
3. name
4. id
5. className
6. linkText
7. partialLinkText
8. tagName

There are different ways of finding xpath:

Using single attribute:
sintax: // tagname[@attribute-name=’value1’]

Example:
//a[@href=’http://www.google.com’]
//input[@id=’name’]
//input[@name=’username’]
//img[@alt=’sometext’]

Using multiple attributes:
Syntax: //tagname[@attribute1=’value1’][attribute2=’value2’]

Example:
//a[@id=’id1’][@name=’namevalue1’]
//img[@src=’’][@href=’’]
//a[@href='/log-in/link' and contains(text(),'Email me a login link')]
//a[contains(text(),'Get Started') and @id='hero-cta']
//bdi[contains(text(),'Description')]

Using Contains method:
Syntax with examples:
//tagname[contains(@attribute,’value1’)]
//input[contains(@id,’’)]
//input[contains(@name,’’)]
//a[contains(@href,’’)]
//img[contains(@src,’’)]
//div[contains(@id,’’)]
//a[@href='/log-in/link' and contains(text(),'Email me a login link')]
//a[contains(text(),'Get Started') and @id='hero-cta']
//bdi[contains(text(),'Company')]

Using Starts method:
//tagname[starts-with(@attribute-name,’’)]
//id[starts-with(@id,’’)]
//a[starts-with(@href=’’)]
//img[starts-with(@src=’’)]
//div[starts-with(@id=’’)]
//input[starts-with(@id=’’)]
//button[starts-with(@id,’’)]

Using Following node:
Xpath/following::again-ur-regular-path
//input[@id=’’]/following::input[1]
//a[@href=’’]/following::a[1]
//img[@src=’’]/following::img[1]
''from gmail login page example
//input[@name='identifier']/following::button[contains(text(),'Forgot email')]
//div[@class='card-body']/p[contains(text(),'First way to initialize all tooltips')]/following-sibling::div[@class='docs-clipboard']
//bdi[contains(text(),'Company')]/following::input[1]
//bdi[contains(text(),'Description')]/following::textarea
Using Preceding node (next node)
Xpath/preceding::again-ur-regular-path
//input[@id=’’]/ preceding::input[1]
//a[@href=’’]/ preceding::a[1]
//img[@src=’’]/ preceding::img[1]

Absolute XPath method:
If we give whole path to identify element and it is called as absolute xpath.
Example: /html/head/body/div/input

Text method in XPath:
Syntax- tagname[text()=’text which is visible on page’]
Note- While using text() method make sure you provide the exact text else it will not match
Example //b[text()=’Admin’]

Text method with contains:
Syntax- tagname[contains(text(),’partial text which you want to search ‘)]
Example – //*[contains(text(),’Employee Distribution by Subunit’)]

Relative and Absolute XPath method
//parent-xpath/absolute xpath
//input[@id=’section’]/div/input

Xpath Axes
Following
Proceeding
ancestor

// means searches through the page
/ means searches only after the following element

various methods available in xpath
using And & Or
Contains()
Start-with()
Text()
Following::
Preceding::
Ancestor
Absolute Vs Relative Path

cssSelector:
in terms of performance, CSS perform well as compared to XPATH and CSS will not change based on browsers, that is it will behave same in all browsers but xpath will behave differently in IE browser.

symbol used while writing css selector in selenium
attribute symbol used
id #
className .
attribute tagname[attribute='value']
multiple attribute tagname[attribute1='value1'][attribute2='value2']
contains *
starts with ^
Ends with $

CSS Selector is the combination of an element selector and a selector value which identifies the web element within a web page. The composite of element selector and selector value is known as Selector Pattern.

CSS Selector: ID
Example:
css=input#Email

CSS Selector: Class
css=label.remember

CSS Selector: Attribute
css=input[type=’submit’]
css=input#Passwd[name='Passwd']

tagName[attributename=attributeValue]
Example 1: input[id=email]
Example 2: input[name=email][type=text]

WebElement ele1 = driver.findElement(By.cssSelector(".primary-btn"));
WebElement ele2 = driver.findElement(By.cssSelector(".btn.primary-btn"));
WebElement ele3 = driver.findElement(By.cssSelector(".submit.primary-btn"));

WebElement Email = driver.findElement(By.cssSelector("input[id=email]"));
Email.SendKeys("hello@sampleemail.com");

Monday, 3 December 2018

SAP GUI Scripting parameter - Automation Testing

By default SAP GUI doesn't allow automation test recording/playback due to security reasons. We have to explicitly enable following few parameters to allow these options.

SAP GUI Scripting contains the following 2 level of security mechanisms:

On the server:

Profile parameters whose setting determines whether SAP GUI Scripting should be allowed on the current application server

On the client:

Options in the SAP GUI setup program that make it possible to install SAP GUI without the scripting components.Registry keys that allow scripting to be disabled on the client.

Enabling and Disabling SAP GUI Scripting on the Server

SAP GUI Scripting can be switched on and off for a particular application server (or for dedicated users, see note 983990) using the profile parameter sapgui/user_scripting. By default, scripting is not enabled. To enable scripting, set the value of this profile parameter to TRUE. You do not have to restart the server, but you must log off and back on again, since the change does not affect sessions that are currently running. This setting overrides any client settings.

Additional Profile Parameters in Release 6.40 and higher

As well as sapgui/user_scripting, you can use the following profile parameters for more refined access control in Release 6.40. They are also included in Release 6.20 from support package 37, and in Release 4.6C from support package 47. SAPGUI Release 6.20 patch level 42 or higher is also required.

Profile Parameter                                      -   Description
sapgui/user_scripting_disable_recording  - If this parameter is set to TRUE, script playback is possible, but recording is not permitted.

sapgui/user_scripting_force_notification - If this parameter is set to TRUE, a notification is always displayed at the frontend, regardless of the client options described below under 'Warning Options on Client Side'.

sapgui/user_scripting_set_readonly - If this parameter is set to TRUE, scripts may only act on read-only user interface elements.

Enable scripting at client side:
The user can enable and disable scripting for their own use from path in SAP GUI via  Start of the navigation path: Options->Accessibility & Scripting -> Scripting

Notify when a script attaches to a running GUI: A message appears whenever a script attaches to the SAP GUI

Notify when a script opens a connection: A message appears whenever a script opens a new GUI connection.


Thursday, 13 September 2018

IE browser problems with Websites not showing the page content but it opens in Chrome and Mozilla

We might have come across some websites in IE browser doesn't open and page keeps loading without displaying the actual page, whereas other browser clients like Chrome and Mozilla opens the same websites without having any problems.

This is common problem in IE browser and when you are working in the tight project schedules and facing such issue will be challenging to cope up with work.

Following are 2 options we can use to fix such issues.

1. Add/Remove the URL from the compatibility mode. For cloud application this solves our purpose

2. Turn off SmartScreen Filter. When have Turned on this option. It would first verify the content being displayed with microsoft. Our project application server are placed under secured environment, having this option ON would be throws an error to send this information to microsoft. Hence we always have to Off this option


Friday, 15 June 2018

Micro Focus tooling - UFT, LoadRunner, ALM and support end dates for various version

Following are the dates declared by Micro Focus to end their support for various older versions of tools

QTP(QuickTest Professional) / UFT(Unified Functional Testing):


QC(Quality Center) / ALM(Application LifeCycle Management):


LoadRunner / Performance Center:











** these dates may change by Micro Focus later point of time, we may have to keep looking information from Micro Focus for latest dates. 

Thursday, 24 May 2018

How to download test cases from ALM/QC TestLab folder

There is no direct option to download all the test cases from ALM under specific folder from Test Lab. Though we can download single test case at a time from export option available in TestLab, it is time consuming if we want to download 100's of test cases in a short span of time.

Writing SQL query in the ALM under "Dashboard->Analysis View" with Excel report would solve our problem and can download all test cases in seconds/minutes

Following SQL queries needs to be added in excel report, and upon executing these queries would generate excel file with relevant information we are looking for.

It is basically 2 way approach as there is no option to provide the folder path in the SQL query

1. Find out the absolute path of required folder path in TestLab

''Finding actual folder path from the absolute path
select in_cf.AL_ITEM_ID, sys_connect_by_path( in_cf.AL_DESCRIPTION, '\') PTH, in_cf.AL_ABSOLUTE_PATH as "ABS Path"
     from ALL_LISTS in_cf connect by prior in_cf.AL_ITEM_ID = in_cf.AL_FATHER_ID
     start with in_cf.AL_FATHER_ID = 0

''Finding absolute path from Test Lab
SELECT  AL_DESCRIPTION, /* Level3 Folder Name */ AL_ABSOLUTE_PATH
FROM All_Lists

2. Pick up the absolute path from the above query and pass that in the following query and execute the report to generate excel file with the test cases.
You can pass required fields though in the query, in below I have only provided basic fields which are required in test case.

'''Downloading testcases from Test Lab with absolute path
SELECT
ALL_LISTS.AL_DESCRIPTION as "Folder Name" /*Test Plan Folder.Name*/,
TEST.TS_TEST_ID as "Test ID" /*Test.Test ID*/,
TEST.TS_NAME as "Test Name" /*Test.Test Name*/,
TEST.TS_STATUS as "Status" /*Test.Status*/,
TEST.TS_TYPE as "Test Case Type" /*Test.Status*/,
TEST.TS_RESPONSIBLE as "Tester" /*Test.Designer*/,
TEST.TS_DESCRIPTION as "Test Description"/*Test.Description*/,
DESSTEPS.DS_STEP_NAME as "Test Step Name" /*Test Step.Step Name*/,
DESSTEPS.DS_DESCRIPTION as "Step Description"/*Test Step.Description*/,
DESSTEPS.DS_EXPECTED as "Expected Results" /*Test Step.Expected*/
From TEST
Join ALL_LISTS On TEST.TS_SUBJECT = ALL_LISTS.AL_ITEM_ID
Join DESSTEPS On TEST.TS_TEST_ID=DESSTEPS.DS_TEST_ID
Where All_Lists.AL_ABSOLUTE_PATH like'AAAAAPAAMAAIAAHAAD%'
ORDER BY TEST.TS_TEST_ID, DESSTEPS.DS_STEP_ORDER

Tuesday, 8 May 2018

Enable "Connections" tab in IE browser to change the proxy

Issue:
Due to corporate policies or accidentally sometimes in IE browser "Connections" tab would be disabled.

If you enable the policy, users are prevented from seeing and changing connection and proxy settings.

If you disable this policy or do not configure it, users can see and change these settings.

When you set this policy, you do not need to set the following policies for the Content tab, because this policy removes the Connections tab from the interface:

"Disable Internet Connection Wizard"
"Disable changing connection settings"
"Prevent changing proxy settings"
"Disable changing Automatic Configuration settings"

Path: IE browser Tools->Internet Options->Connections

Solution:
Navigate to "Registry Editor" window and follow the path to change values.

Registry Hive HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER
Registry Path Software\Policies\Microsoft\Internet Explorer\Control Panel
Value Name ConnectionsTab
Value Type REG_DWORD
Enabled Value 1
Disabled Value 0