I tried the following solutions to Verify that the button is not displayed for a particular user-group.None of the solutions work. I get a no such element exception with the codes.
Please let me know if there is anything else i can try.
try {
boolean btnPresence = driver.findElement(By.linkText("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed();
}
catch (org.openqa.selenium.NoSuchElementException e)
{
return;
}
}
Assert.assertTrue(driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed());
if (driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed()) {
System.out.println("Fail! Submit button is displayed for a CMS Admin on the ORC TA Form.");}
else {
System.out.println("Pass!!- Submit Button is not displayed for CMS Admin on the ORC TA Form");
}
boolean elePresent = driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed();
boolean elePresent = driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed();
boolean exist = driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).size() == 0;
You can check if the element exists or not:
public boolean existsElement_byXpath(String xpath) {
try {
driver.findElement(By.xpath(xpath));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
Related
In my UI java test framework I have lots of methods that are doing try catch around element actions like click, send keys etc and return true when action is successful and false when any exception occurs. I was wondering is there any smarter way to pass the method as parameter and in that one method surround that code with try catch statement. So that code could be simpler and cleaner to read (may be Java 8 functional interfaces).
public boolean expandPanel(String panelHeading) {
boolean panelFound = false;
try {
getElement(PanelHeadings.fromString(panelHeading)).click();
panelFound = true;
} catch (Exception e) {
panelFound = false;
}
return panelFound;
}
I did try creating an actions class and defining different methods for click, sendKeys etc. But is there a way if i can just have one try catch method and pass code or behaviour to that method.
public boolean expandPanel(String panelHeading) {
return actions.click(getElement(PanelHeadings.fromString(panelHeading)));
}
public class WebElementActions {
public Boolean click(WebElement element) {
try {
element.click();
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
}
You could do something like
public boolean executeSafely(Runnable action) {
try {
action.run();
return true;
} catch (Exception x) {
return false;
}
}
And then call it with return executeSafely(element::click).
the problem is simple: To add Context Sensitive Help i followed the standard steps, but once i try to link the BLOCKS to the CONTEXT IDs with SetHelp() from IWorkbenchHelpSystem. The frist argument should be either a Control(swt) or IAction.
void setHelp(Control control, String helpContextId);. How can i refer to Control from a damos.dml.Block object type ?
org.eclipselabs.damos.dml.blockTypes
FYI
I've tried and visited all the content of these sites
http://rajakannappan.blogspot.com/2009/05/context-sensitive-help-in-eclipse.html
https://help.eclipse.org/2019-03/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fua_help_context.htm&cp=2_0_19_1_2
https://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fextension-points%2Forg_eclipse_ui_commands.html
The display and search methods are working correctly but I just need to set the help and not display it so that only upon calling Help (F1 or ctrl+F1) the context help is shown.
Thanks.
After trying I thought maybe this workaround would get me the same result but NADA.
private Block getBlock() {
EObject semanticElement = resolveSemanticElement();
if (semanticElement instanceof Block) {
Block block = (Block) semanticElement;
PlatformUI.getWorkbench().getHelpSystem().search(block.getType().getName());
//PlatformUI.getWorkbench().getHelpSystem().setHelp(?, Activator.HELP_VIEW); Cannot cast block directly to Control
PlatformUI.getWorkbench().getHelpSystem().displayHelp(Activator.HELP_VIEW);
return block;
} else {
return null;
}
}
#Override
protected NodeFigure createMainFigure() {
blockFigure = new BlockFigure();
// OB: java.awt.event.KeyEvent.VK_F1 is wrong, use SWT.F1
blockFigure.setFocusTraversable(true);
blockFigure.setRequestFocusEnabled(true);
blockFigure.addMouseListener(new MouseListener.Stub() {
#Override
public void mousePressed(final MouseEvent me) {
blockFigure.requestFocus();
}
});
blockFigure.addKeyListener(new KeyListener.Stub() {
#Override
public void keyReleased(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
if (ke.keycode == SWT.F1) {
PlatformUI.getWorkbench().getHelpSystem().search(getBlock().getType().getName());
PlatformUI.getWorkbench().getHelpSystem().displayHelp(Activator.HELP_VIEW);
}
}
});
return blockFigure;
}
Any help is appreciated!
public String getSelection() {
String blockName = "SelectBlock";
EObject element = null;
EditPart part = getDiagramEditPart();
EditPartViewer viewer = part.getViewer();
List selectedList = viewer.getSelectedEditParts();
try {
GraphicalEditPart editPart = (GraphicalEditPart) selectedList.get(0);
BlockEditPart blockPart = (BlockEditPart) editPart;
viewer.getProperty("BlockFigure");
NodeImpl node = (NodeImpl) blockPart.getModel();
element = node.getElement();
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
e.printStackTrace();
}
ISelection selection1 = viewer.getSelection();// EURêKA
if (element instanceof Block) {
Control control2 = getGraphicalViewer().getControl();
blockName = ((Block) element).getType().getName();
return blockName;
// return part.getParent().getSelected();
}
return "SelectBlock";
}
i have the possiblity to select a block type CTRL+F1 and voila the Help Definition of said Block is shown.
I was with a element is not attached to the page document in my Java script for automation using SeleniumWebDriver.
I searched the internet and found the script below that solved the error element is not attached to the page document.
boolean breakIt = true;
while (true) {
breakIt = true;
try {
Select acao = new Select(driver.findElement(By.id("cboSubMotivo")));
acao.selectByValue("519");
} catch (Exception e) {
if (e.getMessage().contains("element is not attached")) {
breakIt = false;
}
}
}
I continued the automation process and right after the above script, I added the code below to select an option within a DropDown List.
Select status = new Select(driver.findElement(By.id("cboStatus")));
At this point Eclipse displays the error message: Unreachable code.
I searched the internet but did not find anything about the error message regarding SeleniumWebDriver.
Here is the complete code and error message displayed by Eclipse.
public class validarStatus {
static WebDriver driver;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver.exe");
}
#Test
public void logarBkoMais() throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("http://10.5.9.45/BKOMais_S86825EstrategiaBackOfficeClaroFixo");
driver.manage().window().maximize();
// Logar BkoMais
driver.findElement(By.id("matricula_I")).sendKeys("844502");
driver.findElement(By.id("senha_I")).sendKeys("Pw34Jdt#*");
driver.findElement(By.id("bt_entrar")).click();
// Logar na Estratégia
driver.findElement(By.id("mn_backoffice")).click();
driver.findElement(By.id("mn_bkoffice_prod_203")).click();// Produto
driver.findElement(By.id("mn_bkoffice_est_57")).click();// Estratégia
// Selecionado a atividade
Select atividade = new Select(driver.findElement(By.id("cboAtividade")));
atividade.selectByIndex(3);
// Registro >> Novo
Thread.sleep(500);
driver.findElement(By.id("mn_registro")).click();
driver.findElement(By.id("mn_novo_caso")).click();
// Cod Os Estratégia VREL
String CodOs = driver.findElement(By.xpath("//*[#id=\"content\"]/div[1]/fieldset[1]/div[2]/div[3]/span"))
.getText();
System.out.println(CodOs);
// Campo Análise de Contrato
Select analiseContrato = new Select(driver.findElement(By.id("cboMotivo")));
analiseContrato.selectByIndex(5);
// Campo Ação
boolean breakIt = true;
while (true) {
breakIt = true;
try {
Select acao = new Select(driver.findElement(By.id("cboSubMotivo")));
acao.selectByValue("519");
} catch (Exception e) {
if (e.getMessage().contains("element is not attached")) {
breakIt = false;
}
}
}
Select status = new Select(driver.findElement(By.id("cboStatus")));
}
#After
public void tearDown() throws Exception {
}}
As I am understand correct, there's no guarantee for compiler that code above while statement will run. It will run only when there would be exception thrown and the while-loop breaks. Moreover your breakIt isn't changing at all. As I think right this code will be work right:
while (breakIt) {
breakIt = true;
try {
Select acao = new Select(driver.findElement(By.id("cboSubMotivo")));
acao.selectByValue("519");
} catch (Exception e) {
if (e.getMessage().contains("element is not attached")) {
breakIt = false;
}
}
}
I want to write a reusable method to identify whether the web Element is Present or not.
This method needs to accept e different locators like xpath, id, class name.
Here is the code snipped I tried, but not worked for the line.
if(Obj.isDisplayed())
public static boolean isElementPresent(WebDriver driver, WebElement Obj)
{
boolean result = false;
try
{
// if(Obj.isDisplayed())
if(driver.findElement(By.id("username")) != null)
{
System.out.println("WEBELEMENT Username FOUND");
result = true;
}
else
{
result = false;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
Below method returns true in case element present.
public boolean isElementPresent(WebDriver driver,By locator){
if(driver.findElements(locator).size()!=0){
//Element present
return true;
}
else{
//Element not present
return false;
}
}
Example:
isElementPresent(By.id("test"));
isElementPresent(By.xpath("//test1"));
For your case solution will be Try/Catch:
public boolean isElementPresent(WebElement element) {
try {
element.getText();
return true;
} catch (NoSuchElementException e) {
return false;
}
If element not exists on the page then element.getText() will throw NosuchElementException, method will catch this exception and returns false.
Try it and let me know if it works for you.
Every Java code export from selenium ide will have this method..But it is the same with method for iselementpresent because I cant figured out how to use it:
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
What need to be put exactly in the try code?
The above method is not same as isElementPresent(). The closeAlertAndGetItsText() method is for handling alert boxes in your web application.
Where ever you need to handle the alert boxes in your web application, you can simply make a call to this closeAlertAndGetItsText() method. closeAlertAndGetItsText() method will click OK on the alert box and alert.getText() will provide you the text that was present in the alert box.
isElementPresent() is a method, which you will call when you need to find whether a particular element is present in the webpage or not. There are many implementations of isElementPresent() Find below some of them.
private boolean isElementPresent(WebDriver driver, String id) {
try {
driver.getWrappedDriver().findElement(By.id(id));
return true;
} catch (Exception e) {
return false;
}
}
private boolean isElementPresent(WebDriver driver, String classname) {
try {
driver.findElements(By.className("someclass")).size() > 0;
return true;
} catch (Exception e) {
return false;
}
}