Switch tabs in Selenium

                                 Switch tabs in Selenium




  • We have to get all the set of tabs present in the browser.
  • When switching you might need to wait for 5 to 10 seconds for the types of browser windows to get generated.

2 Tabs:

You can switch between the tabs usingdriver.switchTo().window("handle")

String parentID = driver.getWindowHandle();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
if(parentID.equals(tabs2.get(0))) {
  driver.switchTo().window(tabs2.get(1));
}else {
  driver.switchTo().window(tabs2.get(0));
}
// perform your tasks on the newly created window



More than 2 tabs:

You need to bring the loop once you find the target window

String parentID = driver.getWindowHandle();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());

for (String handle : tabs2) {
  driver.switchTo().window(handle);
  if(driver.getTitle().equals("your wish")) {
	  break;
  }
}
// perform your tasks on the newly created window


CSV Files in Selenium

    CSV Files with selenium





    I. Concept CSV file

    It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV

    It is a common format for data interchange as it is simple, compact, and used everywhere. It will open into Excel with a double click, and nearly all databases have a tool to allow import from CSV

    We can handle the CSV file using the below packages :

    • Apache Commons CSV
    • Open CV

    II. Dependency CSV Integration

    First of all, you need to add an apache-commons-csv dependency in your project. If you use maven, then add the following dependency to your pom.xml file.
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-csv</artifactId>
        <version>1.5</version>
    </dependency>

    Link: https://commons.apache.org/proper/commons-csv/download_csv.cgi

    III. Reading a CSV file by Column Index

    Ex:

    import org.testng.annotations.Test;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVParser;
    import org.apache.commons.csv.CSVRecord;
    import java.io.IOException;
    import java.io.Reader;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    public class ApacheCommonsCSV {
    	@Test
    	public void readCSV() throws IOException {
    		String CSV_File_Path = "C:UsersuserDesktopq.csv";
    		// read the file
    		Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
    		// parse the file into csv values
    		CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
    
            for (CSVRecord csvRecord : csvParser) {
                // Accessing Values by Column Index
    			String name = csvRecord.get(0);
    			String product = csvRecord.get(1);
    			String description = csvRecord.get(2);
    			// print the value to console
    			System.out.println("Record No - " + csvRecord.getRecordNumber());
    			System.out.println("---------------");
    			System.out.println("Name : " + name);
    			System.out.println("Product : " + product);
    			System.out.println("Description : " + description);
    			System.out.println("---------------
    
    ");
            }
    	}
    }

    IV. Reading a CSV file with Column Name

    Ex:

    public class ReadWithColumnName {
    	@Test
    	public void readCSV() throws IOException {
    		String CSV_File_Path = "C:UsersuserDesktopq.csv";
    		// read the file
    		Reader reader = Files.newBufferedReader(Paths.get(CSV_File_Path));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
                    .withHeader("Name", "Product", "Description")
                    .withIgnoreHeaderCase()
                    .withTrim());
    
            for (CSVRecord csvRecord : csvParser) {
                // Accessing values by the names assigned to each column
                String name = csvRecord.get("Name");
                String product = csvRecord.get("Product");
                String description = csvRecord.get("Description");
                System.out.println("Record No - " + csvRecord.getRecordNumber());
                System.out.println("---------------");
                System.out.println("Name : " + name);
                System.out.println("Product : " + product);
                System.out.println("Description : " + description);
                System.out.println("---------------
    
    ");
            }
    	}
    }





    Basic Form

    XPath Tip and Trick
    Hello World! (Ignore Me) @04:45 PM
    I'm a Hacker - 18 years old - living in Viet Nam - 15/03/2020
    Michael Jackson
    Michael Jackson
    Michael Jackson
    Michael Jackson
    Michael Jackson
    Michael Jackson
    Michael Jackson
    Michael Jackson

    Mail Personal or Business Check, Cashier's Check or money order to:


    NOP SOLUTIONS
    your address here,
    New York, NY 10001 
    USA

    Notice that if you pay by Personal or Business Check, your order may be held for up to 10 days after we receive your check to allow enough time for the check to clear.  If you want us to ship faster upon receipt of your payment, then we recommend your send a money order or Cashier's check.

    P.S. You can edit this text from admin panel.

    Hello "John", What's happened?
    Many of the estimates are acknowledged to be rough and out of date, as follows:
    Afghanistan: 100-200
    Bhutan: 100-200
    China: 2,000-2,500
    India: 200-600
    Kazakhstan: 180-200
    Kyrgyzstan: 150-500
    Mongolia: 500-1,000
    Nepal: 300-500
    Pakistan: 200-420
    Russia: 150-200
    Tajikistan: 180-220
    Uzbekistan: 20-50
    1. Your basic info











    2. Your profile



































    Tooltips can be attached to any element. When you hover the element with your mouse, the title attribute is displayed in a little box next to the element, just like a native tooltip.

    But as it's not a native tooltip, it can be styled. Any themes built with ThemeRoller will also style tooltips accordingly.

    Tooltips are also useful for form elements, to show some additional information in the context of each field.

    Hover the field to see the tooltip.

    Test Scenarios for Image Upload Functionality

     

    Test Scenarios for Image Upload Functionality





    1. Check for the uploaded image path.

    2. Check image upload and change functionality.

    3. Check image upload functionality with image files of different extensions (For Example, JPEG, PNG, BMP, etc.)

    4. Check image upload functionality with images that have space or any other allowed special character in the file name.

    5. Check for duplicate name image upload.

    6. Check the image upload with an image size greater than the max allowed size. Proper error messages should be displayed.

    7. Check image upload functionality with file types other than images (For Example, txt, doc, pdf, exe, etc.). A proper error message should be displayed.

    8. Check if images of specified height and width (if defined) are accepted or otherwise rejected.

    9. The image upload progress bar should appear for large size images.

    10. Check if the cancel button functionality is working in between the upload process.

    11. Check if the file selection dialog only shows the supported files listed.

    12. Check the multiple images upload functionality.

    13. Check image quality after upload. Image quality should not be changed after upload.

    14. Check if the user is able to use/view the uploaded images.


    Test Cases for Error Message

      Test Cases for Error Message



      1. Check the spelling of the error message is correct or not.

      2. Verify the grammar for the error messages is correct.

      3. Verify error message for empty field will be displayed.

      4. Verify the error message uploading an empty file is displayed.

      5. Verify an error message will be displayed for files that are not supported by the system.

      6. Verify message when confirming email/phone registration is duplicated or locked

      7. Verify an error message will be displayed in case characters out of range.

      8. Check the error message that will be displayed for the invalid URL.

      9. An error message will be displayed when a captcha is not valid.

      10. Verify and check error message will be displayed if captcha is not uploaded (may be affected by network)

      11. Verify where the error message should be aligned.

      12. A 500 error message page will be displayed to the user. (when affected by Server)

      13. Verify the time period for the error message to be displayed.

      14. Verify the Alert error messages are not overlapping.


      Explict Wait in Selenium

         I. Explicit Wait in selenium



        ExplicitWait does not have any effect on findElement and findElements. ExplicitWait also called WebdriverWait.

        WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.

        Syntax : WebDriverWait wait=new WebDriverWait( driver, timeoutInSeconds);

        II. alertIsPresent()

        Ex:

        public class A
        {
        	public static void main(String[] args) throws InterruptedException
        	{
        		//open firefox
        		WebDriver driver=new FirefoxDriver();
        		//open google.com
        		driver.get("https://abc.com");
        		driver.findElement(BY.xpath("//button[@class='alert']")).click();
        		WebDriverWait wait = new WebDriverWait(driver, 30 /*timeout in seconds*/);
        		//throws TimeoutException if no alert is present
        		wait.until(ExpectedConditions.alertIsPresent());
        		driver.switchTo().alert().dismiss();
        	}
        }


        III. elementToBeClickable()

        Ex:

        public class A
        {
          public static void main(String[] args) throws InterruptedException
          {
              //open firefox
              WebDriver driver=new FirefoxDriver();
              //open google.com
              driver.get("https:abc.com");
              driver.findElement(By.xpath("//button[@id='btn1']")).click();
        
          }
        }


        IV. elementToBeSelected()

        Ex:

        public class A
        {
          public static void main(String[] args) throws InterruptedException
          {
              //open firefox
              WebDriver driver=new FirefoxDriver();
              //open google.com
              driver.get("https//:abc.com");
        driver.findElement(BY.xpath("//button[@class='alert']")).click(); WebDriverWait wait = new WebDriverWait(driver, 30 /*timeout in seconds*/); //throws TimeoutException if element is not selected in given time wait.until(ExpectedConditions.elementToBeSelected(By.xpath("//input[@id='hidden]")))); } }


        V. textToBePresentInElement()

        Ex:

        public class A
        {
          public static void main(String[] args) throws InterruptedException
          {
              //open firefox
              WebDriver driver=new FirefoxDriver();
              //open google.com
              driver.get("https//:abc.com");
        driver.findElement(BY.xpath("//button[@class='alert']")).click(); WebDriverWait wait = new WebDriverWait(driver, 30 /*timeout in seconds*/); //throws TimeoutException if some text is not present in he webpage wait.until(ExpectedConditions.textToBePresentInElement(By.xpath("//input[@id='h2]")))); } }


        Implicit Wait in Selenium


          Implicitly Wait in Selenium


          Implicitly wait is one of the ways to request selenium not throw any exception until provided time. The default wait time of the selenium is 500 milliseconds, implicitly wait overrides the default wait time of the selenium.

          If the element is found before implicitly wait time, selenium moves to the next commands in the program without waiting to complete the implicitly wait time; this wait is also called dynamic wait.

          Implicit wait tries to find the element in the first go if the element is not present implicit wait tries to find the element after 500ms of first polling, if the element is not available on the second time also then implicit wait tries the third time after 500 ms of the second try and it goes on till the time reaches the 30 seconds.

          If the driver still does not find the element, then it throws an exception. Implicit wait does the same for all the elements in your program, so you just have to set it once.


          WebDriver driver = new ChromeDriver();
          // set implicit wait tme as 30 Seconds
          driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


          Ex:

          public class MultiValueDropdownSelectByValue {
          	public static void main(String[] args) throws Exception {
          		// set the geckodriver.exe property
          		System.setProperty("webdriver.gecko.driver", "C:/~/geckodriver.exe");
          		// open firefox
          		WebDriver driver = new FirefoxDriver();
          		// set implicitly wait time for 1 Minute
          		driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
          		// open webpage
          		driver.get("https://chercher.tech/practice/practice-dropdowns");
          		// find the dropdown using xpath
          		WebElement dropdownElement = driver.findElement(By.xpath("//select[@id='second']"));
          		// create object for Select class
          		Select dropdown = new Select(dropdownElement);
          		// select options from the dropdown options which have value as 'donut', 'burger'
          		dropdown.selectByValue("donut");
          	}
          }


           Timeunits with Implicit Wait

          • TimeUnit.NANOSECONDS : represents nano seconds (10pow-9 of a second is nanosecond)
          • TimeUnit.MICROSECONDS : represents microseconds (10pow-6 of a second is microsecond)
          • TimeUnit.MILLISECONDS : represents mill seconds (10pow-3 of a second is microsecond, i.e. 1000 milliseconds is a second)
          • TimeUnit.SECONDS : represent a second
          • TimeUnit.MINUTES : represent minutes, a minute is 60 seconds
          • TimeUnit.HOURS : represent the hour, an hour is 60 minutes
          • TimeUnit.DAYS : represents the day, a day is 24 hours