i want to automate onpresskey event in selenium how can i automate - selenium

i have one form and i want to test invalid credential(for ex.test #) and in my code i passed text when i run the code it take test not # )
.
#Then("user enter invalid credentials")
public void user_enter_invalid_credentials() throws InterruptedException {
WebElement text=driver.findElement(By.xpath("//*[#id=\"rule-name\"]"));
//enter text
text.sendKeys("Testing# ");
// get value attribute with getAttribute()
String val = text.getAttribute("value");
System.out.println("Entered text is: " + val);
Thread.sleep(3000);
}
how can i validate onpressevent using selenium

Related

Testng assert with DataProvider object values

i create a function test false login test but i want to assert with those loop test
here is my sample data
#DataProvider(name = "Lgindataprovides")
public Object[][] getData(){
Object[][] data= {
{"abcd#mail.com","12345666"}#email and password wrong (asset text = enter email is not available please register)
{"xyz#mail.com","12345666"},#email correct password wrong (assert text = password is wrong)
return data;
}
here is my test
#Test(dataProvider = "Lgindataprovides", dependsOnMethods = "boofoo")
public void logintest(String email, String passowrd) {
driver.get("https://dummyurl/login");
driver.findElement(By.id("email")).sendKeys(email);
driver.findElement(By.id("password")).sendKeys(passowrd);
driver.findElement(By.cssSelector("button[type='submit']"));
Assert.assertEquals(get1stdatatest, "enter email is not available please register")
Assert.assertEquals(get2nderrordatatest, "password is wrong")
}
buts it fails this test case how can I handle this?
what I want is
when this data"abcd#mail.com","12345666" is passed to the login test its should assert with this "enter email is not available please register"
when this dataxyz#mail.com","12345666 is passed to the login test its should assert with this "enter email is not available please register"
I see, you wand to check a unique error message per test data pair.
Add the 3rd item to data-provider with the error message text you expecting. So, each email/password will be linked with the error message.
#DataProvider(name = "Lgindataprovides")
public Object[][] getData(){
Object[][] data= {
{"abcd#mail.com","12345666", "error-message-1"},
{"xyz#mail.com","12345666", "error-message-2"}
}
return data;
}
Add 3rd arg to your test and assert that actual error matches the expected.
#Test(dataProvider = "Lgindataprovides", dependsOnMethods = "boofoo")
public void logintest(String email, String passowrd, String expectedError) {
driver.get("https://dummyurl/login");
driver.findElement(By.id("email")).sendKeys(email);
driver.findElement(By.id("password")).sendKeys(passowrd);
driver.findElement(By.cssSelector("button[type='submit']"));
Assert.assertEquals(getActualErrorMessage(driver), expectedError)
}
Adjust the method which getting the actual error message text. Your locator for driver.findElement sould find both password or email error messages. You might try to use xpath and search by some class //*[contains(#class, 'some-error-class']. So, you'll get any error message text on the form and it should work.
private String getActualErrorMessage(WebDriver driver) {
driver.findElement(By.xpath("...")).getText();
}
You might also do it inline without creating a new method. Also add some waits/timeouts if you need.

Selenium After sendkey, do some validation

I'm new to Selenium, TestNG and Stackoverflow.
After sendkeys, I want to do some validation. If the validation is true, then the assert is true. I know this is not the right way to write the Assert method.
WebDriver driver;
#DataProvider(name= "testdata")
public static Object[][] loginData(){
return new Object[][]{{"username1", "123"}, {"username2", "4211"}};
}
#BeforeTest
public void configure(){
....
}
#Test(dataProvider = "testdata")
public void testmethod(String uname, String password){
WebElement usernameTextbox = driver.findElement(By.id("username"));
usernameTextbox.sendKeys(uname);
WebElement passwordTextbox = driver.findElement(By.id("username"));
passwordTextbox.sendKeys(uname);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MICROSECONDS);
Assert.assertTrue(if(usernameTextbox.contains("[a-zA-Z0-9]+") && passwordTextbox.contains("[0-9]+") == true));
PS: Any inputs will be appreciated.
Try implementing explicit wait in Your code. What that mean, is that You wait for some condition to be set, here is example how to manage this:
But my suggestion is that You assert if there are some error messages (labels, span, or whatever that appears saying something is wrong with email or pass)
So here is how I would do it:
WebDriver driver;
#DataProvider(name= "testdata")
public static Object[][] loginData(){
return new Object[][]{{"username1", "123"}, {"username2", "4211"}};
}
#BeforeTest
public void configure(){
driver = new WebDriver();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); //this is wait which will wait until driver throws exception (that is not found eg."NoSuchElementException")
}
#Test(dataProvider = "testdata")
public void testmethod(String uname, String password){
WebElement usernameTextbox = driver.findElement(By.id("usernameID"));
usernameTextbox.sendKeys(uname);
WebElement passwordTextbox = driver.findElement(By.id("passwordID"));
passwordTextbox.sendKeys(password); //here is where You've sent wrong param
// if You know You will get error label or something use this
WebDriverWait wait = new WebDriverWait(driver, 10); //wait for max 10 sec, and wait for error element defined bellow
WebElement errorElement = wait.until(ExpectedConditions. presenceOfElementLocated(By.id("someErrorElementId"))); //(or ExpectedConditions.textToBePresentInElement(..)), see what better suites You
// If You're expecting error than use this assert
Assert.assertTrue(errorElement.isDisplayed(),"There should be error message!")
// but If You're expecting that there should not be any error than use this assert
Assert.assertFalse(errorElement.isDisplayed(),"There shouldn't be no error messages!")
}
tweak this code, but basicaly this is the logic.
So to try to answer the original question your code could look like below:
1. Using the getAttribute("value")
2. Building the assertion - you don't need to wrap the condition in an if as the contains() function will return true or false for you:
WebDriver driver;
#DataProvider(name= "testdata")
public static Object[][] loginData(){
return new Object[][]{{"username1", "123"}, {"username2", "4211"}};
}
#BeforeTest
public void configure(){
....
}
#Test(dataProvider = "testdata")
public void testmethod(String uname, String password){
WebElement usernameTextbox = driver.findElement(By.id("username"));
usernameTextbox.sendKeys(uname);
WebElement passwordTextbox = driver.findElement(By.id("username"));
passwordTextbox.sendKeys(uname);
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MICROSECONDS);
Assert.assertTrue(usernameTextbox.getAttribute("value").contains("[a-zA-Z0-9]+") && passwordTextbox.getAttribute("value").contains("[0-9]+"));
HTH
As per your question just after invoking sendKeys() you want to do some assertions.
At this point it is worth to mention that when you invoke sendKeys() on a <input> node/tag/field the HTML DOM is not immediately updated with the value / characters which you have just entered in majority of the cases (of-coarse there are exceptional cases). Moving forward when you invoke click() or submit()on a <button> or similar <input> element, the associated onclick event of this <input> element updates the HTML DOM and the value / characters previously sent through sendKeys() are adjusted within the HTML DOM.
Unless the value / characters are not accommodated within the DOM Tree Selenium won't be able to interact with them.
As per your code block, you have populated the passwordTextbox field with the String value of uname as follows :
passwordTextbox.sendKeys(uname);
This value / characterset is still volatile and editable (can be overwritten/cleared/deleted) as follows :
passwordTextbox.clear();
passwordTextbox.sendKeys("Emma E");
Essentially, Assert methods can be invoked on text those are part of the HTML DOM. As an example you can use the following Assert for a Page Heading, Table Heading, etc :
Assert.assertTrue(if(pageHeaderElement.contains("[a-zA-Z0-9]+") && tableHeaderElement.contains("[0-9]+") == true));

In Moneycontrol's Login page , Selenium is unable to find the Webelementes

In Moneycontrol's website, I am unable to enter the username and password while trying to log in. Selenium is unable to find the Webelements.
public void setUrl() throws IOException {
driver = new FirefoxDriver()
driver.get("http://www.moneycontrol.com/");
}
public void Login() {
driver.findElement(By.xpath("//a[#title='Log In']")).click();
//enter user name and password
driver.findElement(By.xpath("//div[#class='formbox']/div[1]/form/div[1]")).sendKeys("xyz#gmail.com");
driver.findElement(By.xpath("//input[#id='pwd']")).sendKeys("Abc#92");
screenshot
The Email or User ID field is within an <iframe>, so to invoke sendKeys() at Email or User ID and Password field you have to switch to the respective <iframe> as follows :
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#src='https://accounts.moneycontrol.com/mclogin/?d=2']")));
driver.findElement(By.xpath("//form[#id='login_form']//input[#class='textfield' and #id='email']")).sendKeys("xyz#gmail.com");
driver.findElement(By.xpath("//form[#id='login_form']//input[#class='textfield' and #id='pwd']")).sendKeys("Abc#92");
**Selenium with C#**
You need to switch to frames and in your case id of your frame is "myframe". Below is the working code for selenium with C#
[TestMethod]
public void moneyControl()
{
IWebDriver driver = new ChromeDriver(#"C:\Users\Akash\Downloads\chromedriver_win32\");
driver.Navigate().GoToUrl("http://www.moneycontrol.com/");
driver.Manage().Window.Maximize();
driver.FindElement(By.XPath("//a[#title='Log In']")).Click();
driver.SwitchTo().Frame("myframe");
driver.FindElement(By.Id("email")).SendKeys("xyz#gmail.com");
driver.FindElement(By.Id("pwd")).SendKeys("abc");
}

Not able to identify element on the screen- how to use tab

Screenshot of the element I want to click:
I automating my website(new to automation). once i login i get to another page where selenium web driver is not able to find any of the elements(I tried all possibilities even sso related).
Only solution i could find was using tabs and enter.
So when i enter that page i need to click 9 time "TAB" key from the keyboard and then enter so that my login is verified. since i don't have any element using which i can perform the tab and enter actions. is there a way where once i get to that page the web driver starts pressing "TAB" key 9 times and then "Enter" on 10 time.
Please help I have been working on this over a week now and not getting
anywhere.
optimist_creeper-main class:
package Modules;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import Modules.HomePage;
public class MainClass {
String appUrl = "als-stg-1.mtvn.ad.viacom.com/webqa/";
#Test public void MainTest() {
System.setProperty("webdriver.gecko.driver", "C:\\Shayni Coding\\Automation\\Gecko\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(appUrl);
HomePage home = new HomePage();
home.HomePageTest(driver);
}
}
Home Page class:
public class HomePage {
#BeforeClass public void beforeClass() {
System.out.println("before class");
}
public void HomePageTest(WebDriver driver) {
driver.manage().window().maximize();
WebElement email = driver.findElement(By.id("cred_userid_inputtext"));
email.sendKeys("shayni#outlook.com");
WebElement pass = driiver.findElement(By.id("cred_password_inputtext"));
pass.sendKeys(Keys.ENTER);
pass.click();
String expectedTitle = "VMS Web";
String actualTitle = driver.getTitle();
Assert.assertEquals(expectedTitle,actualTitle);
}
}
Thanks.
Just get a random object like the body tag and use that to send your key presses.
e.g.
WebElement dummyElement = driver.findElement(By.xpath("/html/body"));
for (int i = 0; i < 9; ++i) {
dummyElement.sendKeys(keys.TAB);
}
dummyElement.sendKeys(keys.ENTER);
The above code finds the body take and sets it as an element. It then presses the tab key 9 times and then presses the enter key. Which is what you asked for. Hope that helps.

Getting error while running selenium code

I am getting below error while running selenium code while everything is right in code. Please help
Exception in thread "main" com.thoughtworks.selenium.SeleniumException: ERROR: Element .//*[#id='content']/p[2] not found
at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:109)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:103)
at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:272)
at com.thoughtworks.selenium.DefaultSelenium.getText(DefaultSelenium.java:471)
at selrcdemo.RCDemo.main(RCDemo.java:35)
package selrcdemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class RCDemo {
public static void main(String[] args) throws InterruptedException
{
Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();
// Click on Link Math Calculator
selenium.click("xpath=.//*[#id='menu']/div[3]/a");
Thread.sleep(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath=.//*[#id='menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load
// Focus on text Box
selenium.focus("name=cpar1");
// enter a value in Text box 1
selenium.type("css=input[name=\"cpar1\"]", "10");
// enter a value in Text box 2
selenium.focus("name=cpar2");
selenium.type("css=input[name=\"cpar2\"]", "50");
// Click Calculate button
selenium.click("xpath=.//*[#id='content']/table/tbody/tr/td[2]/input");
Thread.sleep(4000);
// verify if the result is 5
String result = selenium.getText(".//*[#id='content']/p[2]");
if (result == "5")
{
System.out.println("Pass");
}else
{
System.out.println("Fail");
}
}
}
If you open this site, you'll find that the output is not getting stored in the third text box, rather it is getting displayed above, just under where "Result" is written.
You'll have to make some changes in the code(the xpath for click button and that for the third text box, i.e. from where the value is getting picked). The following codes works perfectly:
package seleniumrcdemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
#SuppressWarnings("deprecation")
public class rcdemo {
public static void main(String[] args) throws InterruptedException {
// Instatiate the RC Server
Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();
// Click on Link Math Calculator
selenium.click("xpath=.//*[#id='menu']/div[3]/a");
Thread.sleep(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath=.//*[#id='menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load
// Focus on text Box
selenium.focus("name=cpar1");
// enter a value in Text box 1
selenium.type("css=input[name=\"cpar1\"]", "10");
// enter a value in Text box 2
selenium.focus("name=cpar2");
selenium.type("css=input[name=\"cpar2\"]", "50");
// Click Calculate button
selenium.click("xpath=.//*[#id='content']/table[1]/tbody/tr[2]/td/input[2]");
// verify if the result is 5
Thread.sleep(4000);
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/font/b");
//String result = selenium.getValue("xpath=.//*[#id='cpar3']");
System.out.println("result"+result);
if (result.equals("5")/*== "5"*/){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}
Pretty sure you need to add xpath= inside your quotes. Or do:
String result = selenium.findElement(By.xpath('path')).getText();
Your answer (result) doesn't exist in the second p. After closer inspect the xpath is:
/html/body/table[2]/tbody/tr/td[1]/div[1]/p[2]/span
The statement
String result = selenium.getText(".//*[#id='content']/p[2]");
missing the "xpath=".
The correct statement
String result = selenium.getText("xpath=.//*[#id='content']/p[2]");
But this will return the result "10% of 50 = 5", which of course != "5". The exact xpath is for the element "5" is "xpath=.//*[#id='content']/p[2]/span/font/b". So the statement should be
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/span/font/b");
You'll still get "Fail" in comparing the String literals. Suggest to use equals() or compareTo() method when comparing strings:
if (result.equals("5"))
{
System.out.println("Pass");
}else
{
System.out.println("Fail");
}
Hope this helps.
Thread.sleep(2000);
// verify if the result is 5
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/span/font/b");
if (result.equals("5")){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
correct me if I am wrong
the % calculation module in calculator web application is failed to pass test case, may be the application code requires a bug fix , the result is not displaying on the rhs(cpar3) side
xpath=.//*[#id='cpar3']==>RHS xpath
here is the selenium code which works fine for me if i manually enter the result value to 5
package selRcDemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class RcDemo {
/**
* #param args
*/
public static void main(String[] args) throws InterruptedException {
// Instatiate the RC Server
Selenium selenium = new DefaultSelenium("localhost", 4444, "firefox",
"http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();
// Click on Link Math Calculator
selenium.click("xpath=.//*[#id='menu']/div[3]/a");
Thread.sleep(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath=.//*[#id='menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load
// Focus on text Box
selenium.focus("name=cpar1");
// enter a value in Text box 1
selenium.type("css=input[name=\"cpar1\"]", "10");
// enter a value in Text box 2
selenium.focus("name=cpar2");
selenium.type("css=input[name=\"cpar2\"]", "50");
// Click Calculate button
selenium.click("xpath=.//*[#id='content']/table[1]/tbody/tr[2]/td/input[2]");
Thread.sleep(2500);
// verify if the result is 5
String result = selenium.getText("xpath=.//*[#id='cpar3']");
// result="5";
System.out.println(result);
// result is not equal to 5 due to bug in application code its returning
// "" (no value)
if (result.equals("5")) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}