Selenium web driver and csv file - selenium

I have data in csv file and also integrate with Selenium.
The test scenario is Search the name of product and verify that the Product name, category, Brand and sub-category according to the document or not? Please Help if it is possible.
Here is my code
public class ProductVerification {
public String baseurl="https://souqofqatar.com/admin";
String driverPath="C:\\Users\\Novatore\\Desktop\\Selenium-Drivers\\chromedriver.exe";
String CSV_file="CSVdatafile\\Cat-Home Appliances and SubCat-Home Comfort (1).csv";
static WebDriver driver;
String line="";
#BeforeMethod
public void launchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",driverPath);
driver =new ChromeDriver();
driver.get(baseurl);
driver.manage().window().maximize(); driver.findElement(By.xpath("//[#id=\"admin_user_email\"]")).sendKeys("admin#example.com");
driver.findElement(By.xpath("//*[#id=\"admin_user_password\"]")).sendKeys("password");
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div/form/fieldset[2]/ol/li/input")).click();
driver.findElement(By.xpath("/html/body/div[1]/div[1]/ul[1]/li[5]/a")).click();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(450,0)", "");
Thread.sleep(3000);
}
#Test
public void search() throws InterruptedException, IOException, CsvException {
File file = new File(CSV_file);
if(file.exists()){
System.out.println("File Exists");
}
try {
BufferedReader br=new BufferedReader(new FileReader(file));
while((line=br.readLine()) !=null){
while((line=br.readLine()) !=null) {
String[] values = line.split(",");
String row= (values[1]);
for (int i=0; row!=null;i++) {
driver.findElement(By.xpath("//*[#id=\"q_name\"]")).sendKeys(""+row);
Thread.sleep(5000);
driver.findElement(By.xpath("/html/body/div[1]/div[4]/div[2]/div/div/form/div[9]/input[1]")).click();
Thread.sleep(3000);
String name=driver.findElement(By.xpath("//td[#class='col col-name']")).getText();
System.out.println(name);
if(name!=row) {
System.out.println(name+" Not find");
}
}
}
}}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}
#AfterMethod
public void CloseBrowser() {
driver.close();
}
}

Related

getting NullPointerException for inline code. I have defined the WebDriver globally, call browser method is working fine What i am doing wrong here

public class Test{
static WebDriver driver;
public static void main(String[] arg) throws IOException, InterruptedException {
Test2();
}
public static void CallBrowserChrome() {
try {
System.setProperty("webdriver.chrome.driver", "G:\\Chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void Test2() throws IOException, InterruptedException {
CallBrowserChrome();
FileInputStream fis = new FileInputStream("G:\\Book1.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getLastRowNum();
System.out.println(rows);
for (int i = 1; i <= rows; i++) {
String value = sheet.getRow(i).getCell(0).getStringCellValue();
System.out.println(value);
**driver.findElement(By.xpath("//*[#id='js-main-container']"))
.sendKeys(value);**
}
}
}
//The Error is at this line Highlighted(driver in 2nd Class); I have tried giving the WebDriver inside the body of the method but that also does not work
[1]: https://i.stack.imgur.com/0GzeA.png
This line: WebDriver driver = new ChromeDriver(); declares the driver local to CallBrowserChrome and ignores your other declaration.
Change your first method to this:
public static void CallBrowserChrome() {
try {
System.setProperty("webdriver.chrome.driver", "G:\\Chrome\\chromedriver.exe");
driver = new ChromeDriver();// update this line
driver.get("https://google.com");
//...etc

Cannot pass from login popup page to password popup page in Selenium

I am trying to create a Selenium test for the account login. Each time when a 'continue' button is clicked it says:
no such element: Unable to locate element:
{"method":"xpath","selector":"//INPUT[#id='password']"}
and remains on the email page, doesn't move to the password page. Though xpath of 'password' textbox is correct. My code is below.
login class
public class login {
WebDriver driver;
public login(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//LI[#data-cy='account']")
WebElement CreateorLoginButtonXpath;
#FindBy(xpath="//INPUT[#id='username']")
WebElement EmailTextBoxXpath ;
#FindBy(xpath="//BUTTON[#class='capText font16']")
WebElement ContinueButtonXpath;
#FindBy(xpath="//INPUT[#id='password']")
WebElement PasswordTextBoxXpath;
#FindBy(xpath="//BUTTON[#data-cy='login']")
WebElement LoginButtonXpath;
public void clickCreateorLoginButtonXpath()
{
CreateorLoginButtonXpath.click();
System.out.println("login or create button is clicked");
}
public void TypeEmailTextBoxXpath(String email)
{
EmailTextBoxXpath.sendKeys(email);
System.out.println("email is typed");
}
public void clickContinueButtonXpath()
{
ContinueButtonXpath.click();
System.out.println("Continue Button is clicked");
}
public void TypePasswordTextBoxXpath(String password)
{
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(PasswordTextBoxXpath)).sendKeys(password);
System.out.println("Password is given");
}
public void clickLoginButtonXpath()
{
LoginButtonXpath.click();
System.out.println("Login Button is clicked");
}
}
main class
public class RunloginTestCase {
WebDriver driver = new ChromeDriver();
login lg = new login(driver);
#BeforeTest
public void openBrowser() throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.makemytrip.com/");
System.out.println("Broweser opened");
}
#Test
public void loginTestPositive() throws InterruptedException
{
lg.clickCreateorLoginButtonXpath();
lg.TypeEmailTextBoxXpath("test1992#test.com");
Thread.sleep(2000L);
lg.clickContinueButtonXpath();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS) ;
lg.TypePasswordTextBoxXpath("!Qwerqwer1");
lg.clickLoginButtonXpath();
Thread.sleep(3000L);
lg.clickSkipVerificationPopupPageButtonXpath();
}
}
I think you provided a wrong formatted email address. Please try with a valid sample email like "test#test.test" ...
public class RunloginTestCase {
WebDriver driver = new ChromeDriver();
#BeforeTest
public void openBrowser() throws InterruptedException
{
driver.get("https://www.makemytrip.com/");
System.out.println("Broweser opened");
Thread.sleep(3000L);
}
#Test
public void loginTestPositive() throws InterruptedException{
login lg = new login(driver);
lg.clickCreateorLoginButtonXpath();
lg.TypeEmailTextBoxXpath("email");
Thread.sleep(5000L);
lg.clickContinueButtonXpath();
Thread.sleep(5000L);
lg.TypePasswordTextBoxXpath("password");
lg.clickLoginButtonXpath();
}
}
Please try with this one

Unable to load chrome/gecko driver after using Cucumber Driver Factory

This is my first question ever asked here, so I hope I ask it the right way:
I'm working on a multimodule maven project to test a software that is still in a development. I've been using Cucumber, Selenium, JUnit for some time and doing online courses to improve my skills. In one of the tutorials was explained how to use Driver Factory and configuration files so I applied it to my project, but after that was unable to run any of the drivers (gecko/chrome/ie). Here is a big part of the code, so I hope someone can help :)
I catch the exception from the DriverFactory.class:
"Unable to load browser: null"
config.properties file has only one line:
browser=chrome
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
//Read Config
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (driver == null) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
FirefoxOptions options = new FirefoxOptions();
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
break;
case "chrome":
if (driver == null) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
/*case "ie":
if (driver == null) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", Constant.IE_DRIVER_DIRECTORY);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
}
*/
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
} finally {
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
return driver;
}
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch(IOException e) {
e.printStackTrace();
}
}
public String getBrowser() {
if(prop.getProperty("browser") == null) {
return "";
}
return prop.getProperty("browser");
}
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\geckodriver.exe";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\chromedriver.exe";
public class CreateCaseSteps extends DriverFactory {
//Background Steps
#Given("^user accesses the login page$")
public void userAccessesTheLoginPage() throws Throwable {
getDriver().get("http://localhost:8080/");
}
#When("^user enters a valid username")
public void userEntersAValidUsername(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='username']")).sendKeys(data.get(0).get(0));
}
#When("^user enters a valid password")
public void userEntersAValidPassword(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='password']")).sendKeys(data.get(0).get(0));
}
#And("^user clicks on the login button$")
public void userClicksOnTheLoginButton() throws Throwable {
getDriver().findElement(By.xpath("//input[#value='Login']")).click();
}
#Then("^user should be taken successfully to the login page$")
public void userShouldBeTakenSuccessfullyToTheLoginPage() throws Throwable {
Thread.sleep(3000);
WebElement logoutMenu = getDriver().findElement(By.xpath("//i[#class='glyphicon glyphicon-user']"));
Assert.assertEquals(true, logoutMenu.isDisplayed());
}

Extent Reports tests always reporting Pass

I am having an issue where if I run a test that has 6 steps, 3 pass, 1 fail, 2 skipped. It will always report as Passed in my extent reports. I am using Klov. Is it possible that I have not correctly configured the report? and if so does anyone have suggestions to fix this issue.
public class MyRunner {
#BeforeClass
public static void initialize(){
d = new Date();
ExtentProperties extentProperties = ExtentProperties.INSTANCE;
extentProperties.setKlovServerUrl("http://localhost");
extentProperties.setKlovProjectName("Test Project");
extentProperties.setKlovReportName("Test Report: " + d);
extentProperties.setMongodbHost("localhost");
extentProperties.setMongodbPort(27017);
extentProperties.setMongodbDatabase("klov");
}
}
#AfterClass
public static void teardown(ITestResult result){
extent.flush();
}
}
And here is my test, it is just a simple test that opens googles login page, just to make sure the extent reports will do everything I need it to
public class Google {
WebDriver driver;
#Given("^that I am on the webpage Google$")
public void thatIAmOnTheWebpageGoogle() throws Throwable {
System.setProperty("webdriver.chrome.driver","\\\\hiscox.nonprod\\profiles\\Citrix\\XDRedirect\\CaseyG\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://accounts.google.com/signin/v2/identifier?hl=en&passive=true&continue=https%3A%2F%2Fwww.google.com%2F&flowName=GlifWebSignIn&flowEntry=ServiceLogin");
driver.manage().window().maximize();
MyRunner.logger.log(Status.INFO, "Opened Google login page")
//throw new PendingException();
//extent.createTest("Step 1").pass("log");
}
#When("^I try to login$")
public void i_try_to_login() throws Throwable {
// find the username field and enters the username, then clicks next
WebElement username = driver.findElement(By.xpath("//input[#id='identifierId']"));
username.sendKeys("********");
driver.findElement(By.id("identifierNext")).click();
//finds the password field and enters the password
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
password.sendKeys("**********");
Assert.assertFalse(true);
driver.findElement(By.id("passwordNext")).click();
//throw new PendingException();
//extent.createTest("Step 2").pass("log");
}
#Then("^I will be successfully logged into Google$")
public void i_will_be_successfully_logged_into_Google() throws Throwable {
String account = "Google Account: greg casey \n" + "(klovtest#gmail.com)";
//WebElement loggedInUser = driver.findElement(By.xpath("//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]"))
//*[#id="gbw"]/div/div/div[2]/div[4]/div[1]/a
//extent.createTest("Step 3").pass("log");
throw new PendingException();
}
}
You should use ITestListener Interface on your Listener class where extent report's test is created
OnTestStart and do other things alos as descriobed below (I have used Thread for parallel device testing so you can ignore, rest is useful)
public class Listeners extends Utilities implements ITestListener {
ExtentReports extent = ExtentReporterTool.getReport();enter code here
ExtentTest test;
ThreadLocal<ExtentTest> testObjects = new ThreadLocal<ExtentTest>();
#Override
public void onTestStart(ITestResult result) {
test = extent.createTest(result.getMethod().getMethodName());
testObjects.set(test);
}
#Override
public void onTestSuccess(ITestResult result) {
testObjects.get().log(Status.PASS, "Test Case passed");
}
#Override
public void onTestFailure(ITestResult result) {
testObjects.get().fail(result.getThrowable());
WebDriver driver;
try {
driver = (WebDriver) result.getTestClass().getRealClass().getSuperclass().getField("driver")
.get(result.getInstance()); testObjects.get().addScreenCaptureFromPath(takeScreenshot(result.getMethod().getMethodName(), driver),
result.getMethod().getMethodName());
} catch (IOException | IllegalArgumentException | SecurityException | IllegalAccessException
| NoSuchFieldException e) {
e.printStackTrace();
}
}
#Override
public void onTestSkipped(ITestResult result) {
testObjects.get().log(Status.SKIP, "Test Case skipped");
}
#Override
public void onFinish(ITestContext context) {
extent.flush();
}
}

Configuring ExtentReports to provide accurate test statuses and screenshot on failure

I am having some difficulty tweaking ExtentReports to provide the desired output.
I have a simple test framework with TestNG, using a TestBase class to do the heavy lifting to keep tests simple. I wish to implement ExtentReports in a simple fashion, using the TestNG ITestResult interface to report Pass, Fail and Unknown.
Here are example tests, 1 pass and 1 deliberate fail:
public class BBCTest extends TestBase{
#Test
public void bbcHomepagePass() throws MalformedURLException {
assertThat(driver.getTitle(), (equalTo("BBC - Home")));
}
#Test
public void bbcHomePageFail() throws MalformedURLException {
assertThat(driver.getTitle(), (equalTo("BBC - Fail")));
}
And here is the relevant section in TestBase:
public class TestBase implements Config {
protected WebDriver driver = null;
private Logger APPLICATION_LOGS = LoggerFactory.getLogger(getClass());
private static ExtentReports extent;
private static ExtentTest test;
private static ITestContext context;
private static String webSessionId;
#BeforeSuite
#Parameters({"env", "browser"})
public void beforeSuite(String env, String browser) {
String f = System.getProperty("user.dir") + "\\test-output\\FabrixExtentReport.html";
ExtentHtmlReporter h = new ExtentHtmlReporter(f);
extent = new ExtentReports();
extent.attachReporter(h);
extent.setSystemInfo("browser: ", browser);
extent.setSystemInfo("env: ", env);
}
#BeforeClass
#Parameters({"env", "browser", "login", "mode"})
public void initialiseTests(String env, String browser, String login, String mode) throws MalformedURLException {
EnvironmentConfiguration.populate(env);
WebDriverConfigBean webDriverConfig = aWebDriverConfig()
.withBrowser(browser)
.withDeploymentEnvironment(env)
.withSeleniumMode(mode);
driver = WebDriverManager.openBrowser(webDriverConfig, getClass());
String baseURL = EnvironmentConfiguration.getBaseURL();
String loginURL = EnvironmentConfiguration.getLoginURL();
APPLICATION_LOGS.debug("Will use baseURL " + baseURL);
switch (login) {
case "true":
visit(baseURL + loginURL);
break;
default:
visit(baseURL);
break;
}
driver.manage().deleteAllCookies();
}
#BeforeMethod
public final void beforeTests(Method method) throws InterruptedException {
test = extent.createTest(method.getName());
try {
waitForPageToLoad();
webSessionId = getWebSessionId();
} catch (NullPointerException e) {
APPLICATION_LOGS.error("could not get SessionID");
}
}
#AfterMethod
public void runAfterTest(ITestResult result) throws IOException {
switch (result.getStatus()) {
case ITestResult.FAILURE:
test.fail(result.getThrowable());
test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));
test.fail("WebSessionId: " + webSessionId);
break;
case ITestResult.SKIP:
test.skip(result.getThrowable());
break;
case ITestResult.SUCCESS:
test.pass("Passed");
break;
default:
break;
}
}
private String takeScreenShot(String methodName) {
String path = System.getProperty("user.dir") + "\\test-output\\" + methodName + ".jpg";
try {
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(path));
} catch (Exception e) {
APPLICATION_LOGS.error("Could not write screenshot" + e);
}
return path;
}
#AfterClass
public void tearDown() {
driver.quit();
}
#AfterSuite()
public void afterSuite() {
extent.flush();
}
Here is the report:
The issues are:
The name of the failed test is not recorded at left hand menu
The screenshot is not displayed despite correctly being taken
It is reporting both a Pass and Unexpected for the passed test
Version 3.0
Most of code is provided by person created this library, i just modified to your needs.
public class TestBase {
private static ExtentReports extent;
private static ExtentTest test;
#BeforeSuite
public void runBeforeEverything() {
String f = System.getProperty("user.dir")+ "/test-output/MyExtentReport.html";
ExtentHtmlReporter h = new ExtentHtmlReporter(f);
extent = new ExtentReports();
extent.attachReporter(h);
}
#BeforeMethod
public void runBeforeTest(Method method) {
test = extent.createTest(method.getName());
}
#AfterMethod
public void runAfterTest(ITestResult result) {
switch (result.getStatus()) {
case ITestResult.FAILURE:
test.fail(result.getThrowable());
test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));
break;
case ITestResult.SKIP:
test.skip(result.getThrowable());
break;
case ITestResult.SUCCESS:
test.pass("Passed");
break;
default:
break;
}
extent.flush();
}
protected String takeScreenShot(String methodName) {
String path = "./screenshots/" + methodName + ".png";
try {
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(path));
} catch (Exception e) {
APPLICATION_LOGS.error("Could not write screenshot" + e);
}
return path;
}
}
You need several changes to make. Instantiate the ExtentReport & add configuration information in any of the configuration methods except BeforeClass.
#BeforeTest
#Parameters({"env", "browser"})
public void initialiseTests(String env, String browser, String emulatorMode, String mode) {
EnvironmentConfiguration.populate(env);
WebDriverConfigBean webDriverConfig = aWebDriverConfig()
.withBrowser(browser)
.withDeploymentEnvironment(env)
.withSeleniumMode(mode);
driver = WebDriverManager.openBrowser(webDriverConfig, getClass());
APPLICATION_LOGS.debug("Will use baseURL " + EnvironmentConfiguration.getBaseURL());
try {
visit(EnvironmentConfiguration.getBaseURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().deleteAllCookies();
}
Initailize test = extent.startTest(testName); in the #BeforeMethod section.
#BeforeMethod
public void beforeM(Method m) {
test = extent.startTest(m.getName());
}
And, you may call extent.endTest(test); in the #AfterTest method.
#AfterTest
public void afterTests() {
extent.endTest(test);
extent.close();
}
}
And, to log your step info call test.log(LogStatus, "your info to show"); with appropirate status.