ALL SLIPS CODE : Software Testing practical (Selenium), slip-wise

Each slip has: question, folder structure, then every file with its path and code.

CONTENTS

  Slip  1 : Download a file
  Slip  2 : Take a screenshot
  Slip  3 : Click Signup and verify the registration page
  Slip  4 : Verify title, Wikipedia icon and search button
  Slip  5 : Search three keyword combinations
  Slip  6 : TestNG parallel execution with JavaScript
  Slip  7 : Cross browser testing with TestNG
  Slip  8 : Page Object Model without Page Factory
  Slip  9 : Count and print hyperlinks
  Slip 10 : Find broken links
  Slip 11 : Count radio buttons with TestNG XML
  Slip 12 : TestNG invocationCount
  Slip 13 : Verify title and Wikipedia elements (no Java file)
  Slip 14 : Register on Demo Web Shop
  Slip 15 : Handle basic HTML controls
  Slip 16 : Count radio buttons with TestNG XML and assertion
  Slip 17 : Log in to Demo Web Shop
  Slip 18 : Download a file and verify it
  Slip 19 : Take a screenshot (replaces the old one)
  Slip 20 : Search three keyword combinations
  Slip 21 : Page Object Model with Page Factory

################################################################################
# SLIP 1 : Download a file
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL http://omayo.blogspot.com/p/page7.html
3. Download a file in the Selenium project.

FOLDER STRUCTURE

SeleniumSlip1/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- DownloadFile.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip1/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : DownloadFile.java
PATH : SeleniumSlip1/src/main/java/com/selenium/DownloadFile.java
--------------------------------------------------------------------------------
package com.selenium;

import java.util.HashMap;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class DownloadFile {

    public static void main(String[] args) throws Exception {

        String path = System.getProperty("user.dir");

        HashMap<String, Object> prefs = new HashMap<>();
        prefs.put("download.default_directory", path);

        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);

        WebDriver driver = new ChromeDriver(options);

        driver.manage().window().maximize();

        driver.get("http://omayo.blogspot.com/p/page7.html");

        driver.findElement(By.linkText("ZIP file")).click();

        Thread.sleep(5000);

        System.out.println("Check downloaded file in: " + path);

        driver.quit();
    }
}

################################################################################
# SLIP 2 : Take a screenshot
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://garwarecollege.mespune.in/
3. Take a screenshot using Selenium WebDriver.

FOLDER STRUCTURE

SeleniumSlip2/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- TakeScreenshot.java
`-- pom.xml

NOTES

- Delete screenshot.png before running again. Files.copy fails if the file already exists.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip2/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0"> 
 
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>com.selenium</groupId>
  <artifactId>SeleniumSlip2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  
  <properties>
  <maven.compiler.source>17</maven.compiler.source>
  <maven.compiler.target>17</maven.compiler.target>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>
    
  </dependencies>

  
</project>

--------------------------------------------------------------------------------
FILE : TakeScreenshot.java
PATH : SeleniumSlip2/src/main/java/com/selenium/TakeScreenshot.java
--------------------------------------------------------------------------------
package com.selenium;

import java.io.File;
import java.nio.file.Files;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;

public class TakeScreenshot {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://garwarecollege.mespune.in/");

        Thread.sleep(3000);

        TakesScreenshot ts = (TakesScreenshot) driver;

        File source = ts.getScreenshotAs(OutputType.FILE);

        File destination = new File("screenshot.png");

        Files.copy(source.toPath(), destination.toPath());

        System.out.println("Screenshot saved successfully");

        driver.quit();
    }
}

################################################################################
# SLIP 3 : Click Signup and verify the registration page
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.spicejet.com/
3. Click on the Signup button.
4. Verify the registration page.

FOLDER STRUCTURE

SeleniumSlip3/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- VerifyRegistration.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip3/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>
    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : VerifyRegistration.java
PATH : SeleniumSlip3/src/main/java/com/selenium/VerifyRegistration.java
--------------------------------------------------------------------------------
package com.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;



public class VerifyRegistration {

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		 WebDriver driver = new ChromeDriver();

	        driver.manage().window().maximize();

	        driver.get("https://www.spicejet.com/");

	        Thread.sleep(5000);

	        driver.findElement(By.xpath("//*[text()='Signup' or text()='Sign Up']")).click();

	        Thread.sleep(5000);

	        for (String window : driver.getWindowHandles()) {
	            driver.switchTo().window(window);
	        }

	        String url = driver.getCurrentUrl();

	        if (url.toLowerCase().contains("signup")) {
	            System.out.println("Registration Page Verified");
	        } else {
	            System.out.println("Registration Page Not Verified");
	        }

	        System.out.println("Current URL: " + url);

	        driver.quit();

	}

}

################################################################################
# SLIP 4 : Verify title, Wikipedia icon and search button
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://testautomationpractice.blogspot.com/
3. Verify the title of the web page.
4. Verify the presence of the Wikipedia icon on the web page.
5. Verify the presence of the Wikipedia search button on the web page.

FOLDER STRUCTURE

SeleniumSlip4/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- VerifyTitleAndIcon.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip4/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.selenium</groupId>
  <artifactId>SeleniumSlip4</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

<properties>
	<maven.compiler.source>17</maven.compiler.source>
	<maven.compiler.target>17</maven.compiler.target>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>

  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.54.0</version>
  
</dependency>
</dependencies>
</project>

--------------------------------------------------------------------------------
FILE : VerifyTitleAndIcon.java
PATH : SeleniumSlip4/src/main/java/com/selenium/VerifyTitleAndIcon.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class VerifyTitleAndIcon {

	public static void main(String[] args) throws Exception {
		
	WebDriver driver = new ChromeDriver();
	
	driver.manage().window().maximize();
	
	driver.get("https://testautomationpractice.blogspot.com/");
	
	Thread.sleep(3000);
	
	   // Verify Page Title
    String title = driver.getTitle();

    if (title.equals("Automation Testing Practice")) {
        System.out.println("Title Verified");
    } else {
        System.out.println("Title Not Verified");
    }

    // Verify Wikipedia Icon
    boolean icon = driver.findElement(
            By.className("wikipedia-icon")).isDisplayed();

    System.out.println("Wikipedia Icon Displayed: " + icon);

    // Verify Wikipedia Search Button
    boolean button = driver.findElement(
            By.className("wikipedia-search-button")).isDisplayed();

    System.out.println("Search Button Displayed: " + button);

    driver.quit();
}
}

################################################################################
# SLIP 5 : Search three keyword combinations
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Search the first keyword combination.
3. Repeat step 2 for the other 2 keyword combinations: India Qutub Minar, Agra Taj Mahal, Hyderabad Charminar.

FOLDER STRUCTURE

SeleniumSlip5/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- SearchKeywords.java
`-- pom.xml

NOTES

- Google may show a CAPTCHA or a consent page. Check that the results really loaded.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip5/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip5</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>
    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : SearchKeywords.java
PATH : SeleniumSlip5/src/main/java/com/selenium/SearchKeywords.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class SearchKeywords {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        
        String[] keywords = {
                "India Qutub Minar",
                "Agra Taj Mahal",
                "Hyderabad Charminar"
            };
        
        for (String keyword : keywords) {

            driver.get("https://www.google.com/");

            driver.findElement(By.name("q"))
                  .sendKeys(keyword, Keys.ENTER);

            Thread.sleep(3000);

            System.out.println("Searched: " + keyword);
        }

        driver.quit();
	}

}

################################################################################
# SLIP 6 : TestNG parallel execution with JavaScript
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver. Write a JavaScript in Selenium WebDriver and execute the test case in TestNG using the parallel attribute.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.saucedemo.com/
3. Verify the page title.
4. Verify that the website logo is displayed.
5. Display the URL.

FOLDER STRUCTURE

SeleniumSlip6/
|-- src/
|   `-- test/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- ParallelTest.java
|-- pom.xml
`-- testng.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip6/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip6</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.11.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : ParallelTest.java
PATH : SeleniumSlip6/src/test/java/com/selenium/ParallelTest.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;


public class ParallelTest {

    @Test
    public void verifyTitle() {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.saucedemo.com/");
        
        Assert.assertEquals(driver.getTitle(), "Swag Labs");

        System.out.println("Title Verified");

        driver.quit();
    }
    
    @Test
    public void verifyLogo() {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.saucedemo.com/");

        boolean logo = driver.findElement(
                By.className("login_logo")).isDisplayed();

        Assert.assertTrue(logo);

        System.out.println("Logo Verified");

        driver.quit();
    } 
    
    @Test
    public void displayURL() {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        driver.get("https://www.saucedemo.com/");

        JavascriptExecutor js = (JavascriptExecutor) driver;

        String url = (String) js.executeScript(
                "return document.URL;");

        System.out.println("Current URL: " + url);

        driver.quit();
    }
}

--------------------------------------------------------------------------------
FILE : testng.xml
PATH : SeleniumSlip6/testng.xml
--------------------------------------------------------------------------------


<suite name="ParallelSuite" parallel="methods" thread-count="3">

    <test name="SauceDemoTest">

        <classes>
            <class name="com.selenium.ParallelTest"/>
        </classes>

    </test>

</suite>

################################################################################
# SLIP 7 : Cross browser testing with TestNG
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.google.com/
3. Get the URL https://firebox.com/
4. Handle cross browser testing in Selenium TestNG.

FOLDER STRUCTURE

SeleniumSlip7/
|-- src/
|   `-- test/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- CrossBrowserTest.java
|-- pom.xml
`-- testng.xml

NOTES

- Firefox must be installed.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip7/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0"> 

<modelVersion>4.0.0</modelVersion>

  <groupId>com.selenium</groupId>
  <artifactId>SeleniumSlip7</artifactId>
  <version>0.0.1-SNAPSHOT</version> 
  <packaging>jar</packaging>
  
  <properties>
  
  <maven.compiler.source>17</maven.compiler.source>
  <maven.compiler.target>17</maven.compiler.target>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  
  </properties>

<dependencies>

 <dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.54.0</version> 

</dependency>

 <dependency>
  <groupId>org.testng</groupId>
  <artifactId>testng</artifactId>
  <version>7.11.0</version>
  <scope>test</scope> 
 
 </dependency>


</dependencies>

</project>

--------------------------------------------------------------------------------
FILE : CrossBrowserTest.java
PATH : SeleniumSlip7/src/test/java/com/selenium/CrossBrowserTest.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.Parameters;

public class CrossBrowserTest {

    @Test
    @Parameters("browser")
    public void crossBrowser(String browser) throws Exception {

        WebDriver driver;

        if (browser.equals("chrome")) {
            driver = new ChromeDriver();
        } else {
            driver = new FirefoxDriver();
        }

        driver.manage().window().maximize();

        driver.get("https://www.google.com/");
        Thread.sleep(3000);

        System.out.println(browser + " : " + driver.getTitle());

        driver.get("https://firebox.com/");
        Thread.sleep(3000);

        System.out.println(browser + " : " + driver.getTitle());

        driver.quit();
    }
}

--------------------------------------------------------------------------------
FILE : testng.xml
PATH : SeleniumSlip7/testng.xml
--------------------------------------------------------------------------------
<suite name="CrossBrowserSuite">

    <test name="ChromeTest">
        <parameter name="browser" value="chrome"/>

        <classes>
            <class name="com.selenium.CrossBrowserTest"/>
        </classes>
    </test>

    <test name="FirefoxTest">
        <parameter name="browser" value="firefox"/>

        <classes>
            <class name="com.selenium.CrossBrowserTest"/>
        </classes>
    </test>

</suite>

################################################################################
# SLIP 8 : Page Object Model without Page Factory
################################################################################

QUESTION

Create a Maven project using the Page Object Model (POM).

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.saucedemo.com/
3. Log in to the saucedemo page without Page Factory (use By and findElement).

FOLDER STRUCTURE

SeleniumSlip8/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   |-- LoginPage.java
|                   `-- LoginTest.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip8/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

  <groupId>com.selenium</groupId>
  <artifactId>SeleniumSlip8</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  
  <properties>

  <maven.compiler.source>17</maven.compiler.source>
  <maven.compiler.target>17</maven.compiler.target>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>
  
  <dependencies>
 
  <dependency>
  
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.54.0</version>
 
  </dependency>  
  </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : LoginPage.java
PATH : SeleniumSlip8/src/main/java/com/selenium/LoginPage.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {

    WebDriver driver;

    // Locators
    By username = By.id("user-name");
    By password = By.id("password");
    By loginButton = By.id("login-button");

    // Constructor
    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    // Login Method
    public void login(String user, String pass) {

        driver.findElement(username).sendKeys(user);

        driver.findElement(password).sendKeys(pass);

        driver.findElement(loginButton).click();
    }
}

--------------------------------------------------------------------------------
FILE : LoginTest.java
PATH : SeleniumSlip8/src/main/java/com/selenium/LoginTest.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class LoginTest {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://www.saucedemo.com/");

        LoginPage page = new LoginPage(driver);

        page.login("standard_user", "secret_sauce");

        Thread.sleep(3000);

        if (driver.getCurrentUrl().contains("inventory")) {
            System.out.println("Login Successful");
        } else {
            System.out.println("Login Failed");
        }

        driver.quit();
    }
}

################################################################################
# SLIP 9 : Count and print hyperlinks
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.calculator.net/
3. Count and print the hyperlinks on the web page.

FOLDER STRUCTURE

SeleniumSlip9/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- CountHyperlinks.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip9/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip9</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>
    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : CountHyperlinks.java
PATH : SeleniumSlip9/src/main/java/com/selenium/CountHyperlinks.java
--------------------------------------------------------------------------------
package com.selenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class CountHyperlinks {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://www.calculator.net/");

        List<WebElement> links = driver.findElements(By.tagName("a"));

        System.out.println("Total Hyperlinks: " + links.size());

        for (WebElement link : links) {

            System.out.println(link.getDomAttribute("href"));
        }

        driver.quit();
    }
}

################################################################################
# SLIP 10 : Find broken links
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL http://www.deadlinkcity.com/
3. Find the broken (dead) links on the web page.

FOLDER STRUCTURE

SeleniumSlip10/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- BrokenLinks.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip10/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip10</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>
    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : BrokenLinks.java
PATH : SeleniumSlip10/src/main/java/com/selenium/BrokenLinks.java
--------------------------------------------------------------------------------
package com.selenium;

import java.net.HttpURLConnection;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class BrokenLinks {

    public static void main(String[] args) {

        ChromeOptions options = new ChromeOptions();

        Map<String, Object> prefs = new HashMap<>();

        prefs.put("https_only_mode_enabled", false);
        prefs.put("https_first_balanced_mode_enabled", false);
        prefs.put("https_only_mode_auto_enabled", false);

        options.setExperimentalOption("prefs", prefs);

        WebDriver driver = new ChromeDriver(options);

        try {

            driver.manage().window().maximize();

            driver.get("http://deadlinkcity.com/");

            WebDriverWait wait =
                new WebDriverWait(driver, Duration.ofSeconds(30));

            wait.until(ExpectedConditions
                .presenceOfElementLocated(By.tagName("a")));

            System.out.println("Page Title: " + driver.getTitle());

            List<WebElement> links =
                driver.findElements(By.tagName("a"));

            System.out.println("Total Links: " + links.size());

            int valid = 0;
            int broken = 0;
            int unchecked = 0;

            for (WebElement link : links) {

                String url = link.getDomProperty("href");

                if (url == null || !url.startsWith("http")) {
                    unchecked++;
                    continue;
                }

                HttpURLConnection connection = null;

                try {

                    connection = (HttpURLConnection)
                        URI.create(url).toURL().openConnection();

                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);

                    int code = connection.getResponseCode();

                    if (code >= 400) {

                        System.out.println(url +
                            " - Broken Link - " + code);

                        broken++;

                    } else {

                        System.out.println(url +
                            " - Valid Link - " + code);

                        valid++;
                    }

                } catch (Exception e) {

                    System.out.println(url + " - Unable to check");
                    unchecked++;

                } finally {

                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }

            System.out.println("-------------------------");
            System.out.println("Total Links: " + links.size());
            System.out.println("Valid Links: " + valid);
            System.out.println("Broken Links: " + broken);
            System.out.println("Unchecked Links: " + unchecked);

        } finally {

            driver.quit();
        }
    }
}

################################################################################
# SLIP 11 : Count radio buttons with TestNG XML
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.techlistic.com/p/selenium-practice-form.html
3. Count the number of radio buttons on the web page and create a TestNG XML file.

FOLDER STRUCTURE

SeleniumSlip11/
|-- src/
|   `-- test/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- RadioButtonTest.java
|-- pom.xml
`-- testng.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip11/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.selenium</groupId>
  <artifactId>SeleniumSlip11</artifactId>
  <version>0.0.1-SNAPSHOT</version> 
  <packaging>jar</packaging>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

</properties>
  <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>
 <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.11.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>


</project>

--------------------------------------------------------------------------------
FILE : RadioButtonTest.java
PATH : SeleniumSlip11/src/test/java/com/selenium/RadioButtonTest.java
--------------------------------------------------------------------------------
package com.selenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class RadioButtonTest {

    @Test
    public void countRadioButtons() throws InterruptedException {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://www.techlistic.com/p/selenium-practice-form.html");

        Thread.sleep(3000);

        List<WebElement> radioButtons =
                driver.findElements(By.cssSelector("input[type='radio']"));

        System.out.println("Total Radio Buttons: " + radioButtons.size());

        driver.quit();
    }
}

--------------------------------------------------------------------------------
FILE : testng.xml
PATH : SeleniumSlip11/testng.xml
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<suite name="RadioButtonSuite">

    <test name="RadioButtonCount">

        <classes>

            <class name="com.selenium.RadioButtonTest"/>

        </classes>

    </test>

</suite>

################################################################################
# SLIP 12 : TestNG invocationCount
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver. Write a JavaScript in Selenium WebDriver and execute the test case in TestNG using the invocationCount attribute, which runs a single test case multiple times.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.google.com/
3. Verify the page title.
4. Verify that the website logo is displayed.
5. Display the URL.
6. Close all windows.

FOLDER STRUCTURE

SeleniumSlip12/
|-- src/
|   `-- test/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- InvocationCountTest.java
|-- pom.xml
`-- testng.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip12/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip12</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.11.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : InvocationCountTest.java
PATH : SeleniumSlip12/src/test/java/com/selenium/InvocationCountTest.java
--------------------------------------------------------------------------------
package com.selenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;
import org.testng.annotations.Test;

public class InvocationCountTest {

    @Test(invocationCount = 3)
    public void testGoogle() throws InterruptedException {

        WebDriver driver = new ChromeDriver();

        try {

            driver.manage().window().maximize();

            driver.get("https://www.google.com/webhp?hl=en");

            Thread.sleep(5000);

            // Verify Title
            String title = driver.getTitle();

            Assert.assertEquals(title, "Google");

            System.out.println("Title Verified: " + title);

            // Verify Google Logo
            List<WebElement> logos = driver.findElements(
                By.cssSelector(
                    "img[alt='Google'], img.lnXdpd, " +
                    "img[src*='googlelogo'], img[src*='doodle'], " +
                    "#hplogo, svg[aria-label='Google']"
                )
            );

            boolean logoDisplayed = false;

            for (WebElement logo : logos) {

                if (logo.isDisplayed()) {

                    logoDisplayed = true;
                    break;
                }
            }

            System.out.println("Logo Displayed: " + logoDisplayed);

            // Display URL using JavaScript
            JavascriptExecutor js = (JavascriptExecutor) driver;

            String url = (String) js.executeScript(
                "return document.URL;"
            );

            System.out.println("Current URL: " + url);

            Assert.assertTrue(logoDisplayed,
                "Google Logo Not Found");

            System.out.println("Google Logo Verified");

        } finally {

            driver.quit();
        }

        System.out.println("-------------------------");
    }
}

--------------------------------------------------------------------------------
FILE : testng.xml
PATH : SeleniumSlip12/testng.xml
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<suite name="InvocationCountSuite">

    <test name="GoogleTest">

        <classes>

            <class name="com.selenium.InvocationCountTest"/>

        </classes>

    </test>

</suite>

################################################################################
# SLIP 13 : Verify title and Wikipedia elements (no Java file)
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://testautomationpractice.blogspot.com/
3. Verify the title of the web page.
4. Verify the presence of the Wikipedia icon on the web page.
5. Verify the presence of the Wikipedia search button on the web page.

FOLDER STRUCTURE

SeleniumSlip13/
`-- pom.xml

NOTES

- This project has only pom.xml. It has no Java file yet.
- The question is the same as Slip 4. See stpythons code 4. Add the selenium-java dependency from the Slip 4 pom.xml before using that code here.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip13/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.selenium</groupId>
  <artifactId>SeleniumSlip13</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SeleniumSlip13</name>
  <description>Verify Title and Wikipedia Elements</description>
</project>

################################################################################
# SLIP 14 : Register on Demo Web Shop
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Navigate to the URL https://demowebshop.tricentis.com/
3. Click on the Register link.
4. Enter valid personal details and password.
5. Click the Register button.

FOLDER STRUCTURE

SeleniumSlip14/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- RegisterTest.java
`-- pom.xml

NOTES

- The email in the code is fixed (ststudent1234@example.com), so registration fails once that address is taken. Replace 1234 with System.currentTimeMillis() to get a new email on every run.
- Use demo details only, never real passwords.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip14/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip14</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : RegisterTest.java
PATH : SeleniumSlip14/src/main/java/com/selenium/RegisterTest.java
--------------------------------------------------------------------------------
package com.selenium;

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class RegisterTest {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));

        // A unique email prevents duplicate registration on repeat runs.
        String email = "ststudent" +1234 + "@example.com";
        String password = "DemoTest@123";

        try {
            driver.manage().window().maximize();
            driver.get("https://demowebshop.tricentis.com/");

            wait.until(ExpectedConditions.elementToBeClickable(
                    By.linkText("Register"))).click();

            wait.until(ExpectedConditions.elementToBeClickable(
                    By.id("gender-male"))).click();
            driver.findElement(By.id("FirstName")).sendKeys("Demo");
            driver.findElement(By.id("LastName")).sendKeys("Student");
            driver.findElement(By.id("Email")).sendKeys(email);
            driver.findElement(By.id("Password")).sendKeys(password);
            driver.findElement(By.id("ConfirmPassword")).sendKeys(password);
            driver.findElement(By.id("register-button")).click();

            wait.until(ExpectedConditions.textToBePresentInElementLocated(
                    By.className("result"), "Your registration completed"));

            System.out.println("Registration Successful");
            System.out.println("Registered Email: " + email);

            // Save only the generated practice account for Slip 17.
            Properties account = new Properties();
            account.setProperty("email", email);
            account.setProperty("password", password);
            try (OutputStream out = Files.newOutputStream(
                    Path.of("demo-account.properties"))) {
                account.store(out, "Demo Web Shop practice account only");
            }
            System.out.println("Demo account saved for Slip 17");
        } finally {
            driver.quit();
        }
    }
}

################################################################################
# SLIP 15 : Handle basic HTML controls
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.hyrtutorials.com/p/basic-controls.html
3. Handle the basic HTML controls in Selenium WebDriver.

FOLDER STRUCTURE

SeleniumSlip15/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- BasicControls.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip15/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip15</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : BasicControls.java
PATH : SeleniumSlip15/src/main/java/com/selenium/BasicControls.java
--------------------------------------------------------------------------------
package com.selenium;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class BasicControls {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));

        try {
            driver.manage().window().maximize();
            driver.get("https://www.hyrtutorials.com/p/basic-controls.html");

            // Text boxes
            WebElement firstName = wait.until(ExpectedConditions
                    .visibilityOfElementLocated(By.id("firstName")));
            firstName.sendKeys("Demo");
            driver.findElement(By.id("lastName")).sendKeys("Student");
            System.out.println("First Name: " + firstName.getDomProperty("value"));

            // Radio button
            WebElement male = driver.findElement(By.id("malerb"));
            male.click();
            System.out.println("Male Selected: " + male.isSelected());

            // Check boxes
            WebElement english = driver.findElement(By.id("englishchbx"));
            WebElement hindi = driver.findElement(By.id("hindichbx"));
            if (!english.isSelected()) english.click();
            if (!hindi.isSelected()) hindi.click();
            System.out.println("English Selected: " + english.isSelected());
            System.out.println("Hindi Selected: " + hindi.isSelected());
            hindi.click();
            System.out.println("Hindi After Uncheck: " + hindi.isSelected());

            driver.findElement(By.id("email")).sendKeys("student@example.com");
            driver.findElement(By.id("password")).sendKeys("DemoTest@123");

            // Button and result label
            driver.findElement(By.id("registerbtn")).click();
            WebElement message = wait.until(ExpectedConditions
                    .visibilityOfElementLocated(By.id("msg")));
            System.out.println("Registration Message: " + message.getText());

            // Clear button
            driver.findElement(By.id("clearbtn")).click();
            System.out.println("First Name Cleared: " + firstName.getDomProperty("value").isEmpty());

            // Hyperlink
            WebElement homeLink = driver.findElement(By.partialLinkText("Click here"));
            System.out.println("Home Link Displayed: " + homeLink.isDisplayed());
            homeLink.click();
            System.out.println("Current URL: " + driver.getCurrentUrl());
        } finally {
            driver.quit();
        }
    }
}

################################################################################
# SLIP 16 : Count radio buttons with TestNG XML and assertion
################################################################################

QUESTION

Create a Maven project and add all dependencies in the pom.xml file.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.techlistic.com/p/selenium-practice-form.html
3. Count the number of radio buttons on the web page and create a TestNG XML file.

FOLDER STRUCTURE

SeleniumSlip16/
|-- src/
|   `-- test/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- RadioButtonTest.java
|-- pom.xml
`-- testng.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip16/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip16</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.11.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : RadioButtonTest.java
PATH : SeleniumSlip16/src/test/java/com/selenium/RadioButtonTest.java
--------------------------------------------------------------------------------
package com.selenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.Assert;

public class RadioButtonTest {

    @Test
    public void countRadioButtons() throws InterruptedException {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://www.techlistic.com/p/selenium-practice-form.html");

        Thread.sleep(3000);

        List<WebElement> radioButtons =
                driver.findElements(By.cssSelector("input[type='radio']"));

        System.out.println("Total Radio Buttons: " + radioButtons.size());

        driver.quit();

        Assert.assertTrue(radioButtons.size() > 0, "No radio buttons found");
    }
}

--------------------------------------------------------------------------------
FILE : testng.xml
PATH : SeleniumSlip16/testng.xml
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>

<suite name="RadioButtonSuite">

    <test name="RadioButtonCount">

        <classes>

            <class name="com.selenium.RadioButtonTest"/>

        </classes>

    </test>

</suite>

################################################################################
# SLIP 17 : Log in to Demo Web Shop
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://demowebshop.tricentis.com/
3. Click on the Log in link.
4. Enter a valid registered email address.
5. Enter the corresponding password.
6. Click the Log in button.
7. Verify that the user is successfully logged in.
8. Verify that the Log out link is displayed.

FOLDER STRUCTURE

SeleniumSlip17/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- LoginTest.java
`-- pom.xml

NOTES

- If the saved account no longer works, delete demo-account.properties and run again.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip17/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip17</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : LoginTest.java
PATH : SeleniumSlip17/src/main/java/com/selenium/LoginTest.java
--------------------------------------------------------------------------------
package com.selenium;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class LoginTest {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));

        try {
            driver.manage().window().maximize();
            driver.get("https://demowebshop.tricentis.com/");

            // Reuse Slip 14 account if available; otherwise register a demo account.
            Properties account = getAccount(driver, wait);
            String email = account.getProperty("email");
            String password = account.getProperty("password");

            // Actual Slip 17 login test starts here.
            wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log in"))).click();
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Email"))).sendKeys(email);
            driver.findElement(By.id("Password")).sendKeys(password);
            driver.findElement(By.cssSelector("input.login-button")).click();

            WebElement logout = wait.until(ExpectedConditions
                    .visibilityOfElementLocated(By.linkText("Log out")));
            WebElement user = driver.findElement(By.cssSelector("a.account"));

            if (!email.equalsIgnoreCase(user.getText().trim()) || !logout.isDisplayed()) {
                throw new IllegalStateException("Login verification failed");
            }
            System.out.println("Login Successful");
            System.out.println("Logged in User: " + user.getText());
            System.out.println("Log out Link Displayed: " + logout.isDisplayed());
        } finally {
            driver.quit();
        }
    }

    // Test data setup only. Does not bypass the login test.
    private static Properties getAccount(WebDriver driver, WebDriverWait wait) throws Exception {
        Path local = Path.of("demo-account.properties");
        Path slip14 = Path.of("..", "SeleniumSlip14", "demo-account.properties");
        Path existing = Files.exists(local) ? local : slip14;
        Properties account = new Properties();

        if (Files.exists(existing)) {
            try (InputStream in = Files.newInputStream(existing)) {
                account.load(in);
            }
            if (account.getProperty("email", "").isBlank() ||
                    account.getProperty("password", "").isBlank()) {
                throw new IllegalStateException("Demo account file is missing email/password");
            }
            return account;
        }

        String email = "ststudent" + System.currentTimeMillis() + "@example.com";
        String password = "DemoTest@123";
        wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Register"))).click();
        wait.until(ExpectedConditions.elementToBeClickable(By.id("gender-male"))).click();
        driver.findElement(By.id("FirstName")).sendKeys("Demo");
        driver.findElement(By.id("LastName")).sendKeys("Student");
        driver.findElement(By.id("Email")).sendKeys(email);
        driver.findElement(By.id("Password")).sendKeys(password);
        driver.findElement(By.id("ConfirmPassword")).sendKeys(password);
        driver.findElement(By.id("register-button")).click();
        wait.until(ExpectedConditions.textToBePresentInElementLocated(
                By.className("result"), "Your registration completed"));

        // Registration signs in the user; log out before testing login.
        wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log out"))).click();
        account.setProperty("email", email);
        account.setProperty("password", password);
        try (OutputStream out = Files.newOutputStream(local)) {
            account.store(out, "Generated demo account only");
        }
        System.out.println("Demo account created for login test");
        return account;
    }
}

################################################################################
# SLIP 18 : Download a file and verify it
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL http://omayo.blogspot.com/p/page7.html
3. Download a file in the Selenium project.

FOLDER STRUCTURE

SeleniumSlip18/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- DownloadFile.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip18/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip18</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : DownloadFile.java
PATH : SeleniumSlip18/src/main/java/com/selenium/DownloadFile.java
--------------------------------------------------------------------------------
package com.selenium;

import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class DownloadFile {

    public static void main(String[] args) throws Exception {

        String path = System.getProperty("user.dir");
        HashMap<String, Object> prefs = new HashMap<>();
        prefs.put("download.default_directory", path);
        prefs.put("download.prompt_for_download", false);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
        WebDriver driver = new ChromeDriver(options);

        // Only remove the previous file produced by this practice exercise.
        Path file = Path.of(path, "DownloadDemo-master.zip");

        try {
            Files.deleteIfExists(file);
            driver.manage().window().maximize();
            driver.get("https://omayo.blogspot.com/p/page7.html");
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
            wait.until(ExpectedConditions.elementToBeClickable(By.linkText("ZIP file"))).click();

            // Wait up to 30 seconds for the actual ZIP file, not a partial download.
            for (int i = 0; i < 30 && !Files.exists(file); i++) {
                Thread.sleep(1000);
            }
            if (!Files.exists(file) || Files.size(file) == 0) {
                throw new IllegalStateException("Download not completed; check Chrome downloads");
            }
            System.out.println("File Downloaded Successfully");
            System.out.println("Downloaded File: " + file);
        } finally {
            driver.quit();
        }
    }
}

################################################################################
# SLIP 19 : Take a screenshot (replaces the old one)
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://garwarecollege.mespune.in/
3. Take a screenshot using Selenium WebDriver.

FOLDER STRUCTURE

SeleniumSlip19/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- TakeScreenshot.java
`-- pom.xml

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip19/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip19</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : TakeScreenshot.java
PATH : SeleniumSlip19/src/main/java/com/selenium/TakeScreenshot.java
--------------------------------------------------------------------------------
package com.selenium;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;

public class TakeScreenshot {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://garwarecollege.mespune.in/");

        Thread.sleep(3000);

        TakesScreenshot ts = (TakesScreenshot) driver;

        File source = ts.getScreenshotAs(OutputType.FILE);

        File destination = new File("screenshot.png");

        Files.copy(source.toPath(), destination.toPath(),
                StandardCopyOption.REPLACE_EXISTING);

        System.out.println("Screenshot saved successfully");

        driver.quit();
    }
}

################################################################################
# SLIP 20 : Search three keyword combinations
################################################################################

QUESTION

Create a Maven project using Selenium WebDriver.

Test steps:

1. Launch the Chrome browser.
2. Search the first keyword combination.
3. Repeat step 2 for the other 2 keyword combinations: India Qutub Minar, Agra Taj Mahal, Hyderabad Charminar.

FOLDER STRUCTURE

SeleniumSlip20/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   `-- SearchKeywords.java
`-- pom.xml

NOTES

- Google may show a CAPTCHA or a consent page. Check that the results really loaded.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip20/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip20</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : SearchKeywords.java
PATH : SeleniumSlip20/src/main/java/com/selenium/SearchKeywords.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class SearchKeywords {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();
        
        String[] keywords = {
                "India Qutub Minar",
                "Agra Taj Mahal",
                "Hyderabad Charminar"
            };
        
        for (String keyword : keywords) {

            driver.get("https://www.google.com/");

            driver.findElement(By.name("q"))
                  .sendKeys(keyword, Keys.ENTER);

            Thread.sleep(3000);

            System.out.println("Searched: " + keyword);
        }

        driver.quit();
	}

}

################################################################################
# SLIP 21 : Page Object Model with Page Factory
################################################################################

QUESTION

Create a Maven project using the Page Object Model (POM).

Test steps:

1. Launch the Chrome browser.
2. Get the URL https://www.saucedemo.com/
3. Log in to the saucedemo page with Page Factory (use the @FindBy annotation and PageFactory.initElements).

FOLDER STRUCTURE

SeleniumSlip21/
|-- src/
|   `-- main/
|       `-- java/
|           `-- com/
|               `-- selenium/
|                   |-- LoginPage.java
|                   `-- LoginTest.java
`-- pom.xml

NOTES

- The method name is initElements (plural). Run LoginTest, not LoginPage.

--------------------------------------------------------------------------------
FILE : pom.xml
PATH : SeleniumSlip21/pom.xml
--------------------------------------------------------------------------------
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>SeleniumSlip21</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.54.0</version>
        </dependency>

    </dependencies>

</project>

--------------------------------------------------------------------------------
FILE : LoginPage.java
PATH : SeleniumSlip21/src/main/java/com/selenium/LoginPage.java
--------------------------------------------------------------------------------
package com.selenium;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {

    @FindBy(id = "user-name")
    WebElement username;

    @FindBy(id = "password")
    WebElement password;

    @FindBy(id = "login-button")
    WebElement loginButton;

    public LoginPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }

    public void login(String user, String pass) {
        username.sendKeys(user);
        password.sendKeys(pass);
        loginButton.click();
    }
}

--------------------------------------------------------------------------------
FILE : LoginTest.java
PATH : SeleniumSlip21/src/main/java/com/selenium/LoginTest.java
--------------------------------------------------------------------------------
package com.selenium;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class LoginTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

        try {
            driver.manage().window().maximize();
            driver.get("https://www.saucedemo.com/");
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("user-name")));

            LoginPage page = new LoginPage(driver);
            page.login("standard_user", "secret_sauce");

            wait.until(ExpectedConditions.urlContains("inventory.html"));
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("inventory_list")));
            System.out.println("Login Successful");
            System.out.println("Current URL: " + driver.getCurrentUrl());
        } finally {
            driver.quit();
        }
    }
}
