Selenium Java : stale excpetion for dropdown - selenium-webdriver

I am doing below steps in my test case
1.Open main page
2.Click on one link which opens a new page(tab)
3.Query data (Click on Query button. Page gets reloaded)
4.Select one drop down – “request” , fill some text data and click save
5.Close this tab
6.From Main page , again click on the link to open this page (tab)
7.Query some data ( Click on Query button . page gets reloaded)
8.Select one drop down - “response” , fill some data and click save
I am getting error at Step-8 while selecting drop-down "Response". The same drop-down while selecting “request” worked fine. Also, I am able to select “response” if I open the page only once (exclude steps- 3,4,5). What is happening here? I am new to selenium and tried almost every solution available for stale exception.
The same code is working fine in my colleagues system without any issues . ( same chrome version)
I also tried by giving sleep time . Also while execution it is expanding the drop-down and I could see the “response” , but still it is not selecting the response.
These are my code snippets. Using chrome browser.
************************ Testcase ******************************
public class TC_004 extends BaseClass{
#Test
public void TNRangeConfirm() throws InterruptedException{
driver.get(baseURL);
LoginUS login=new LoginUS();
login.loginTest();
Thread.sleep(10000);
logger.info("Starting Multiline Creation");
PageActions icp=new PageActions();
logger.info("Sending request");
icp.PortReq();
logger.info("Sending response");
Thread.sleep(5000);
icp.PortRes();
LogoutUS logout=new LogoutUS();
logger.info("Logging out");
logout.logoutTest();
}
}
*********************************************************
**********************Reusable Action***********************
public class PageActions extends BaseClass{
String currentWindow = driver.getWindowHandle();
MainMenuPage mmp=new MainMenuPage(driver);
ActionsPage ipdP=new ActionsPage(driver);
public void PortReq() throws InterruptedException{
System.out.println(" Creation Multi Line : Started");
System.out.println(" Click on Actions page");
mmp.clickPRRADM(); // It expands the link
Thread.sleep(1000);
mmp.clickIPD(); // Opens the page
Thread.sleep(60000);
//Switch tab
//ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//driver.switchTo().window(tabs.get(1));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(currentWindow)) {
driver.switchTo().window(handle);
}
}
//Read Data from Excel
//objExcelFile
MngTestData mtd=new MngTestData();
try {
TN1 = mtd.readExcel(filePath, fileName, sheetName, "New_TN");
TN2 = mtd.readExcel(filePath, fileName, sheetName, "TN1");
TN3 = mtd.readExcel(filePath, fileName, sheetName, "TN2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("TN : "+TN);
ipdP.selectPortType("Request");
ipdP.setPortNo(TN);
ipdP.selectOwner(TN1);
Thread.sleep(10000);
ipdP.clickQuery();
Thread.sleep(10000);
Boolean isPresent = driver.findElements(By.id("INFO_MSD_ID_0")).size() >0 ;
if((isPresent) && (ipdP.isExist("NO RECORDS FOUND"))){ */
System.out.println("Multi Line Creation Started");
ipdP.selectPortAction("Request");
Thread.sleep(10000);
ipdP.selectNNSP(TN1);
Thread.sleep(6000);
ipdP.selectONSP(TN2);
Thread.sleep(10000);
ipdP.clickSave();
Thread.sleep(30000);
driver.close();
driver.switchTo().window(currentWindow);
Thread.sleep(10000);
}
public void PortRes() throws InterruptedException{
String currentWindow = driver.getWindowHandle();
mmp.clickPRRADM();
Thread.sleep(1000);
mmp.clickPRRADM();
Thread.sleep(5000);
mmp.clickIPD(); // opens page
Thread.sleep(30000);
//Read Data from Excel
//objExcelFile
MngTestData mtd=new MngTestData();
try {
TN = mtd.readExcel(filePath, fileName, sheetName, "New_TN");
onsp = mtd.readExcel(filePath, fileName, sheetName,"Old_Network");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create Response
System.out.println("Response Started");
//Switch tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
waitUntil wt= new waitUntil();
boolean isFound=wt.waitForElement(driver, By.id("select-REC_TYPE_ID"));
System.out.println("isFound"+isFound);
wt.waitTillDropdownElementLoads(By.id("select-REC_TYPE_ID"), "Request");
wt.waitTillListOfElementsVisibility(By.id("QRY_NUM_ID"));
Thread.sleep(40000);
ipdP.setPortNo(TN);
wt.waitTillDropdownElementLoads(By.id("select-QRY_OWNER_ID"), owner);
ipdP.selectOwner(owner);
Thread.sleep(10000);
ipdP.clickQuery();
Thread.sleep(40000);
ipdP.selectMultiPortAction("Response"); // My code fails at this point stale excecption.
Thread.sleep(10000);
driver.close();
driver.switchTo().window(currentWindow);
Thread.sleep(10000);
}
}
************************************************************************************
***********************************PageObject class ********************************
public class ActionsPage {
WebDriver ldriver;
public ActionsPage (WebDriver rdriver){
ldriver=rdriver;
PageFactory.initElements(rdriver,this);
}
#FindBy(id="select-DETAILS_ACTION_ID")
#CacheLookup
WebElement selAction;
public void selectPortAction(String action){
Select portAction = new Select(selAction);
portAction.selectByValue(action);
}
******************************************************************************************

I commented out #CacheLookup and it started working without any issues. But I dont know what is the reason behind this.
In PageObject class comment out #CacheLookup and this resolved my error.
#FindBy(id="select-DETAILS_ACTION_ID")
//#CacheLookup
WebElement selAction;

Related

While clicking every link and first level sublink on website, unhandled popup appears

I have written a selenium test that clicks all links on a page. But my popup close code does not handle the popup and the test is discontinued.
I am on Selenium Java V2.53.1, TestNG and backend is browserstack.
This is the call stack, after the last page the popup appears and is not dismissed!
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
link: /
link2: /
link2: /articles
link: /articles
link2: /
This is my test method:
#Test
public void test_click_all_links() throws Exception {
String base_url = "https://infinite-taiga-25466.herokuapp.com";
driver.get(base_url);
//get all links with href that start with /
ArrayList<String> links = (ArrayList) ((JavascriptExecutor) driver).executeScript("return [...document.querySelectorAll(\"a[href^='/']\")].map(e=>e.getAttribute('href'))");
links.forEach(link->{
driver.get(base_url + link);
System.out.println("link: " + link);
//check here
try {
WebDriverWait wait = new WebDriverWait(driver, 5, 100);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
// Prints text and closes alert
//System.out.println(alert.getText());
alert.dismiss();
} catch (NoAlertPresentException | TimeoutException ex) {
//do nothing
};
Assert.assertNotEquals(title(), "The page you were looking for doesn't exist.");
//get all sublinks with href that start with /
ArrayList<String> sublinks = (ArrayList) ((JavascriptExecutor) driver).executeScript("return [...document.querySelectorAll(\"a[href^='/']\")].map(e=>e.getAttribute('href'))");
sublinks.forEach(link2->{
driver.get(base_url + link2);
System.out.println("link2: " + link2);
//check here
try {
WebDriverWait wait = new WebDriverWait(driver, 5, 100);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
// Prints text and closes alert
//System.out.println(alert.getText());
alert.dismiss();
} catch (NoAlertPresentException | TimeoutException ex) {
//do nothing
};
Assert.assertNotEquals(title(), "The page you were looking for doesn't exist.");
});
});
}
Without no clear understand how you're going pass authentication without username/password, page will not open in this case, code below will cancel authentication using page load timeout.
How to use basic authentication you can find here.
private WebDriver driver;
private WebDriverWait wait;
private JavascriptExecutor js;
private String baseUrl = "https://infinite-taiga-25466.herokuapp.com";
#BeforeMethod
public void setUp() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver, 5, 100);
js = (JavascriptExecutor) driver;
}
public void closeAlert() {
try {
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.dismiss();
} catch (NoAlertPresentException | TimeoutException ignored) { }
}
#SuppressWarnings("unchecked")
public ArrayList<String> getLinks() {
return (ArrayList<String>) js.
executeScript("return [...document.querySelectorAll(\"a[href^='/']:not([href='/'])\")].map(e=>e.getAttribute('href'))");
}
#Test
public void clickAllLinks() {
driver.get(baseUrl);
ArrayList<String> links = getLinks();
links.forEach(link -> {
System.out.println("link: " + link);
driver.get(baseUrl + link);
closeAlert();
Assert.assertNotEquals(driver.getTitle(), "The page you were looking for doesn't exist.");
ArrayList<String> subLinks = getLinks();
subLinks.forEach(link2 -> {
System.out.println("link2: " + link2);
try {
driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
driver.get(baseUrl + link2);
} catch (Exception ignore) {
System.out.println("Cancel authorization popup");
} finally {
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
}
// On page loading timeout, authentication closed automatically.
// No need
//closeAlert();
Assert.assertNotEquals(driver.getTitle(), "The page you were looking for doesn't exist.");
});
});
}

How to Implement Conditionally Running of Tests in TestNG?

I am stuck in a scenario, where user is allowed to rate the movie only once a day with same user credentials.
If user tried to rate the same movie or contract, error pop_up seen.
I want to Implement in a way, that if once any movie/contract is rated. The rating functionality should be skipped and Error pop should be Handled.
I am using Selenium eclipse 2017, Chrome browser 61.0 and Test-Ng
Please help in the same.
Thanks.
public class Ratings {
String driverPath = "F:/ChromeDriver/chromedriver.exe";
public WebDriver driver;
public Alert alert;
#BeforeTest
public void LaunchBrowser () throws InterruptedException {
System.out.println("WebBrowser open");
System.setProperty("webdriver.chrome.driver","F:/ChromeDriver/chromedriver.e
xe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
#Test (priority = 1, alwaysRun = true)
public void HomePageUSA() throws InterruptedException {
driver.navigate().to("Https://us.justdial.com");
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
AssertJUnit.assertEquals(expectedTitle, actualTitle);
System.out.println("Test Passed");
}
catch (Throwable e)
{
System.out.println("Test Failed");
}
Thread.sleep(3000);
}
#Test (priority = 2, dependsOnMethods = {"HomePageUSA"})
public void Login() throws Exception{
Thread.sleep(3000);
driver.findElement(By.xpath("/html/body/div/div[1]/div[1]/div[1]/div/div/div
/div[4]/aside/div/span/a[1]")).click();
driver.findElement(By.id("inputPassword3")).clear();
driver.findElement(By.id("inputPassword3")).sendKeys("testing.testjd#gmail.c
om");
driver.findElement(By.id("exampleInputPassword1")).clear();
driver.findElement(By.id("exampleInputPassword1")).sendKeys("justdial");
driver.findElement(By.xpath("/html/body/div[4]/div[2]/div[1]/section/div/div
[1]/div/form/div[3]/div/button")).click();
Thread.sleep(1000);
String expectedTitle = "Justdial US";
String actualTitle = driver.getTitle();
try
{
Assert.assertEquals(expectedTitle, actualTitle);
System.out.println("Login Successful");
}
catch (Throwable e)
{
System.out.println("Login Failed");
}
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div[1]/div/header/div/div[1]/a[2]")).click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void Movies_Rating_page() throws Exception {
driver.findElement(By.xpath(".//*[#id='hotkeylnk106']/div[2]")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[3]/div[2]/div/div[1]/div[1]/div/a/span/img")).click();
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='main-
wrapper']/div/div/div[2]/div[1]/ul/li[2]/span/a[2]/span[1]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(".//*
[#id='AlreadyRated']/div/div/div/section/div/a")).click();
System.out.println("Rating Page Redirection Successful");
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[2]/span[2]/span[10]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[3]/textarea")).sendKeys("Very nice
movie, Must watch.");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='us-jdnew-
wrapper']/div/form/div/div/div/div[3]/div[4]/button[2]")).click();
Thread.sleep(3000);
System.out.println("Rating Successfully Submitted");
You can create a method and tag that method in your test method as dependsOnMethods . You can achieve it like below (i tried to answer to the best based on the info provided)
The idea here is that when your rated condition is met isMovieRated should throw exception so that Movies_Rating_page() will be skipped by testNG ,otherwise isMovieRated just returns true and nothing should be skip.
#Test
public static boolean isMovieRated(String locator) {
//check in "if" below that element has already clicked or is equal to something. I used 'AlreadyClicked' just to
give an idea as I dont have your application information.
if (driver.findElement(By.xpath(locator).getText()=="AlreadyClicked"){
throw new RuntimeException();
}
else {
return true;
}
}
Now your Movies_Rating_page() will look like this
#Test (priority = 3,dependsOnMethods = { "isMovieRated" })
public void Movies_Rating_page() throws Exception {
public static String YourLocator = "/html/body/...."
Ratings.isMovieRated(YourLocator);
..
}
here is a link for more info on testNG dependsOnMethods
Note:
The code above is not tested.
If you are doing things other than checking rating in Movies_Rating_page() then you should separate those things because everything will be skipped when an exception is thrown.
Hope this helps.

connection and Toastbar not displaying issue

1)ConnectionRequest using actionListener as parameter
ArrayList<Map<String, Object>> responses;
public void groupConnection(StateMachine sm, ActionListener al) {
ConnectionRequest connectionRequest = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jSONParser = new JSONParser();
Map<String, Object> parsedData = jSONParser.parseJSON(new InputStreamReader(input));
responses = (ArrayList<Map<String, Object>>) parsedData.get("root");
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
al.actionPerformed(null);
}
});
}
#Override
protected void handleException(Exception err) {
//System.out.println("handleException " + err);
}
#Override
protected void handleIOException(IOException err) {
//toastbar doesnt work here but dialogBox works, if showForm("Groups") is used, toastbar is also shown along with dialogbox
//ToastBar.showErrorMessage("Please check your network connection", 4000);
//sm.showForm("Groups", null);
Dialog.show("", "Please check your network connection", "ok", null);
}
};
AllUrl allUrl = new AllUrl();
connectionRequest.setUrl(allUrl.groupsMenu);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
connectionRequest.setDisposeOnCompletion(d);
NetworkManager.getInstance().addToQueue(connectionRequest);
}
In connectionRequest code above, if there is no network connection, it gives IoException: unreachable which is handled by handleIOException method below but if i use dialogBox there, it works. Instead toastbar doesnt work there, why is that? If I use showForm("Form",null) along with dialogBox and toastbar, the same form is called repeatedly and toastbar is also seen with dialog box appearing multiple times.
2)postForm(Form f) method
connectionGroup = new GroupConnection();
connectionGroup.groupConnection(StateMachine.this, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//checking connectionGroup.responses == null doesnt work since the connectionRequest gives IOException if no network.So Toastbar doesnt work here.
if (connectionGroup.responses == null) {
ToastBar.showErrorMessage("Please check your network connection", 4000);
}
if (connectionGroup.responses != null) {
for (Map<String, Object> element : connectionGroup.responses) {
String tableName = (String) element.get("name");
TextArea nameLabel = new TextArea(tableName.toUpperCase());
f.add(singleRowContainerr);
}
}
}
}
In postForm method above, I used to check if there is network connection or not by checking: if (connectionGroup.responses == null) { do smth...}, it doesnt work here since the connectionRequest gives IoException & doesnt run code inside connectionRequest.
How to solve this problem? I have to show "check connection" in toastBar and a label with text "no connection" as well. PS I need to put all my components & connectionRequest in postForm since I need to go to the form before connectionRequest is called.
ToastBar is bound to a specific Form whereas Dialog will block any form to show itself.
You've set the ToastBar to one form then transitioned to another Form.

Get title of window without switching in selenium webdriver

Is there any way to get window title without making any switch in selenium?
presently I'm using below code:
public boolean switchToWindowByTitle(String title){
String currentWindow = driver.getWindowHandle();
Set<String> availableWindows = driver.getWindowHandles();
if (!availableWindows.isEmpty()) {
for (String windowId : availableWindows) {
String switchedWindowTitle=driver.switchTo().window(windowId).getTitle();
if ((switchedWindowTitle.equals(title))||(switchedWindowTitle.contains(title))){
return true;
} else {
driver.switchTo().window(currentWindow);
}
}
}
return false;
}
Page Title is the <title> tag and appears at the top of a browser window which is part of the HTML DOM within the <header> section of the <html>.
So Selenium driven WebDriver needs to have the focus on the specific Browsing Context to extract the Page Title.
Where as Window Handle is a unique identifier that holds the address of all the windows and can return the string value. All the browser will have a unique window handle. This getWindowHandles() function helps to retrieve the handles of all windows.
So Selenium driven WebDriver can collect the Window Handles from the Browsing Context even without having individual focus on them.
Conclusion
So it is not possible to get the title of window/tab without switching to the specific Window / TAB.
This Code will do the purpose. Call this function as follows
swithToWindow("window Name");
public static Boolean switchToWindow(String title) {
String Parent_window = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String handle : handles) {
driver.switchTo().window(handle);
if (driver.getTitle().equalsIgnoreCase(title)) {
return true;
}
}
driver.switchTo().window(Parent_window);
return false;
}
ArrayList<String> tabs = new ArrayList<String> driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
String parentWindow=driver.getWindowHandle();
Set<String> windows= driver.getWindowHandles();
for(String child:windows){
try{
if(!child.equalsIgnoreCase(parentWindow)){
driver.switchTo().window(child);
String windowTitle=driver.getTitle();
if(windowTitle.equals("book My Show")){
System.out.println("Window found");
}
else{
System.out.println("no windows found");
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println("");
}
}
driver.switchTo().window(parentWindow);
}
}

How do I get Codenameone to capture video?

I am using the following code to try to capture video with codenameone 2.0
tProperty.setHint("name the property that is a media");
final CheckBox cbVideo = new CheckBox("Video");
final Button bCapture = new Button("Capture Media");
final MediaPlayer mpPlayer = new MediaPlayer();
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect){
try {
if (cbVideo.isSelected()) {
String value = Capture.captureVideo();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}else {
String value = Capture.captureAudio();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}
}catch (Exception e){
}
}
});
cM.addComponent(tProperty);
cM.addComponent(cbVideo);
cM.addComponent(bCapture);
cM.addComponent(mpPlayer);
Command [] cmds = new Command[1];
cmds[0] = new Command("Done") {
public void actionPerformed(ActionEvent evt) {
//do Option1
}
};
Dialog.show(editType, cM, cmds);
When running in the simulator, clicking on the CaptureMedia button, it will present the file chooser interface. But then I am unable to choose any file at all whether audio or video because the choose file button is diabled.
How do I get to test the video capture in the simulator?
I think it's a layout problem, you are adding the MediaPlayer component before the video was created, so it's preferred size is 0.
Try to place the video in the border layout center so it's preferred size is ignored and the player will have enough space to display.
Try this:
final Form hi = new Form("Hi World");
hi.setLayout(new BorderLayout());
final Button bCapture = new Button("Capture Media");
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect) {
try {
final MediaPlayer mpPlayer = new MediaPlayer();
String value = Capture.captureVideo();
System.out.println("Captured Video " + value);
if (value != null) {
System.out.println("Playing Video");
InputStream is = FileSystemStorage.getInstance().openInputStream(value);
String strMime = "video/mp4";
System.out.println("Input Stream" + is.available());
mpPlayer.setName("bla");
mpPlayer.setDataSource(is, strMime, new Runnable() {
public void run() {
System.out.println("reset the clip for playback");
}
});
hi.addComponent(BorderLayout.CENTER, mpPlayer);
hi.revalidate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
hi.addComponent(BorderLayout.NORTH, bCapture);
hi.show();
There is a regression in playing local videos in the Codename One simulator although it should work on the device. The next update of Codename One will fix it but for now you can workaround it by playing from a stream which should work just fine.
Just use the FileSystemStorage class to get an InputStream to the video and invoke the appropriate playback code. Note that this is less efficient than the play via URL API so when the regression is fixed you should probably return to the URL based API.

Resources