Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Sunday, July 17, 2022

Headless Browser Testing

 Headless Browser

a headless browser is a browser which doesn’t have a GUI. Headless browser is used to simulate programs even though there is no browser installed on your local system. You couldn’t see any browser in your system but you will get the same result in your console. Headless browser doesn’t have GUI means it’s just that it doesn’t have any GUI but the program runs in the background.

Headless browser testing using Selenium WebDriver is done to test the application without any visual interruption.

Two widely used headless drivers with practical examples.

  1. HtmlUnitDriver  WebDriver driver = new HtmlUnitDriver()
  2. PhantomJSDriver- WebDriver driver = new PhantomJSDriver ();

Advantages of Performing Headless Browser Testing In Selenium

  1. It’s faster. The performance is better compared to browser automation. Automated testing is to automate a browser to ensure that the application is running as expected. Running regression scripts take lots of time. With headless browsers, we could save time.
  2. It enables you to run the scripts on a system which doesn’t have a browser.
  3. Imagine you have a situation to run some tests on a version of google chrome and there is no such version of google chrome on your local system. In this case, you could use the headless browser, most of the headless browsers support browser versions.

Disadvantages of Headless Browsers Testing:

  1. Debugging is a bit difficult using headless browsers. Here browser is not visible, the only way is to capture a screenshot.

 

Selenium- method to input text value in text box

 Hi Foks,

Two ways to enter text in textbox. 

Input Text using WebDriver

WebDriver driver = new FirefoxDriver();

driver.get(https://www.gmail.com);

driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");

 

input text in the text box without calling the sendKeys()

// To initialize js object

JavascriptExecutor JS = (JavascriptExecutor)webdriver;

// To enter username

JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'");

// To enter password

JS.executeScript("document.getElementById('Pass').value='tester'");


Cheers,

TJ

Synchronization and Page Load ,Waits

 Implicit Waits:

Implicit waits tell to the WebDriver to wait for certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

Note: Implicit Wait is in place for the entire time the browser is open. Time taken to search all the elements are based on the time fixed for the implicit wait.

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

 first parameter will accept the time as an integer value, second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

 

Selenium FluentWait:

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

To say in effortless manner, it tries to find the web element repeatedly at regular intervals of time until the timeout or till the object gets found.

We use FluentWait commands mainly when we have web elements which sometimes visible in few seconds and some times take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on our requirement. We could ignore any exception while polling an element.

Wait wait = new FluentWait(WebDriver reference)

.withTimeout(timeout, SECONDS)

.pollingEvery(timeout, SECONDS)

.ignoring(Exception.class);

 

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {

public WebElement applyy(WebDriver driver) {

return driver.findElement(By.id("foo"));

}

});

 

Example:

Wait wait = new FluentWait<WebDriver>(driver)

.withTimeout(45, TimeUnit.SECONDS)

.pollingevery(5, TimeUnit.SECONDS)

.ignoring(NoSuchElementException.class);

 

WebDriverWait In Selenium:

It is applied on certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw exception when element is not found.

The following are the Expected Conditions that can be used in Explicit Wait

  1. alertIsPresent()
  2. elementSelectionStateToBe()
  3. elementToBeClickable()
  4. elementToBeSelected()
  5. frameToBeAvaliableAndSwitchToIt()
  6. invisibilityOfTheElementLocated()
  7. invisibilityOfElementWithText()
  8. presenceOfAllElementsLocatedBy()
  9. presenceOfElementLocated()
  10. textToBePresentInElement()
  11. textToBePresentInElementLocated()
  12. textToBePresentInElementValue()
  13. titleIs()
  14. titleContains()
  15. visibilityOf()
  16. visibilityOfAllElements()
  17. visibilityOfAllElementsLocatedBy()
  18. visibilityOfElementLocated()

//WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

WebDriverWait wait = new WebDriverWait (driver, 20);

wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(""//button[@value='Save Changes']"")));

 

What happen if you mix both implicit wait and explicit wait in a Selenium Script?

As per the official Selenium documentation, it is suggested not to mix both Implicit waits and Explicit Waits. Mixing both of them can cause unpredictable wait times. Implicit wait is defined only once in the code. It will remain same throughout the driver object instance. Explicit wait is defined whenever it is necessary in the code. This wait will call at the time of execution. It is a conditional wait.Explicit wait will overwrite the implicit wait where ever explicit wait is applied. So, Explicit Wait gets first preference then Implicit Wait.

 Cheers,

TJ

Taking Screenshots in automation

 Some of the scenarios we may need to capture a screenshot using Selenium WebDriver are

i. Application issues
ii. Assertion Failure
iii. Difficulty to find Webelements on the web page
iv. Timeout to find Webelements on the web page

Tosca

Take Screen Shot In Tosca Testsuite

A standard module is provided by tricentis to take screenshot. It is present in standard modules. TBox TakesScreenshot

Selenium

Selenium provides an interface called TakesScreenshot which has a method getScreenShotAs which can be used to take a screenshot of the application under test.

Syntax to capture and save the screenshot.
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Syntax to store it in our local drive

FileUtils.copyFile(screenshotFile, new File("filename_with_path"));

to capture full page screenshot using Selenium WebDriver:

What is aShot?
aShot is a WebDriver Screenshot utility. It takes a screenshot of the WebElement on different platforms (i.e. desktop browsers, iOS Simulator Mobile Safari, Android Emulator Browser).

aShot might be configured to handle browsers with the viewport problem. This gives a screenshot of the entire page even for Chrome, Mobile Safari, etc

Add this jar file in to your project. Note: Select Project and Right click on the Project – Go to ‘Build path’ – Go to ‘Configure build path’ – Click on ‘lib’ section – Add external jar

Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);

                  ImageIO.write(fpScreenshot.getImage(),"PNG",new File("D:///FullPageScreenshot.png"));

To Capture Screenshot of Failed Test Cases Using Selenium WebDriver

If a script fails, we need to know where was the error in script. Solution for this is to capture a screenshot of webpage when the test case fails. We could easily identify where exactly the script got failed by seeing the screenshot.

To achieve this, we could place the entire code in try-catch block. Which means placing the test steps in try block and screen capture statement in catch block. If a test step fails in the try block then it goes to the catch block and capture a screenshot of the web page.

 

UFT/QTP 

Dim ScreenName

  On Error Resume Next

  ScreenName = " "
  
  CurrentTime = "_Test_Case"&"_"& Day(Now)&"_"& Month(Now)&"_"& Year(Now)&"_"&

   Hour(Now)&"_"& Minute(Now)&"_"& Second(Now)

  ScreenShotName = "Name_of_the_Screen" &  CurrentTime & ".png"

  ScreenName ="Path where the Screenshot needs to be stored"&"\"&ScreenShotName

  Desktop.CaptureBitmap ScreenName,True

 

 

Monday, March 29, 2021

BDD Cucumber -resequencing the feature file and scenarios

 Hey Folks,

There may be a situation while you need to call your scenario outline of one feature needs to call in particular sequence based on application flow, this can be achieved by adding the tags to scenario outline with priority will work.

However, what happens when you need to sequence your scenario outline with different feature files? 

By default, BDD cucumber takes feature names alphabetically during the execution and then based on your tag sequences. So, if you want to resequencing your scenario in different features file, then you need to give your feature names in sequence of alphabet or append some numbering. if it still doesn't work then rename the feature file name itself and it will work. for example,

Feature file name : 01Feature1.feature, 02Feature2.feature

Feature Name: 01Feature1, 02 Feature2

Cheers,

TJ


Tuesday, October 20, 2020

Steps to implement Allure Reporting in Selenium java

 Hey Guys,

Steps to implement Allure reporting in selenium java framework.

Allure is an open-source framework designed to create interactive and comprehensive test report.

Each time when we run automation tests, we will have test results to view details about no. of tests passed, failed and failure details etc. And few reports also include test failure screenshots.

Allure report works

When we run our tests, every popular test framework generates junit-style xml report which will be used by Allure to generate HTML report. Allure reports has provided adapters for Java, PHP, Ruby, Python, Scala and C# test frameworks.

Steps to Generate Allure Reports

Install and configuration

  • Install Allure report command line application
  • do this manually by downloading the latest version as a zip archive from bintray.
    • Unpack the archive to allure-command line directory
    • Navigate to bin directory
    • Add allure to system PATH.

Implementation in code

  •            Create Maven project
  •             Add allure maven dependencies in pom.xml file and also add  AspectJ Weaver dependency along with allure.
  •             Create two test file in src/test/java folder and append the allure features in it for writing reports
  •             Create Testng.xml file
  •             We can add environment details in allure report by adding following
      •   Environment.properties
      •   Environment.xml
  •              We can categories the failed cases/defects using categories.json file
  • append the features of allure report to code like @step, @feature etc

 Run the code and generate the allure report

  •  Go to command prompt and in project directory and run the command
    • Mvn clean test
  • Or run the code through eclipse/intelij
  • Go to command prompt and generate the allure report in temporary folder using command
    • Allure serve <path of allure report>  (Generate report in temporary folder)
    • Allure generate <path of allure report> (Generate report in c:/user directory with allure folder)
    • Allure open <path of allure report>
    • Allure generate <path of allure report> --clean (will overwrite the existing report)

You can find more information on Allure documentation.

 Cheers.

TJ

Wednesday, September 16, 2020

Rest Assured Automation - API

Hello All,

 

Try to put some information around Rest Assured API testing using eClipse, TestNG. in subsequent blog, will provide some technical view.

 

API testing using RestAssured

  • RestAssured itself is API designed for automating Rest services/ Rest APIs.
  • Implemented using java classes
  • Available in jar files
  • Multiple request, get response from apis, validate data etc
  • Restassured only support Rest services, it not support SOAP services 

Setting up

  • Java
  • Eclipse
  • Test NG
  • Maven (specify dependencies)  

Steps:

  1. Create Maven project in eclipse
  2. Need to update POM.xml file
    1. RestAssured (https://mvnrepository.com/artifact/io.rest-assured/rest-assured/4.3.1)
    2. TestNG (https://mvnrepository.com/artifact/org.testng/testng/7.3.0)
    3. JSON – simple (https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1)
    4. Apache poi (https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml/4.1.2, https://mvnrepository.com/artifact/org.apache.poi/poi/4.1.2)

 

Validations:

Status Code

Status Line

Request body n parameters

Success code

Validate Header

Json contains

Print headers

 

Data driven testing

1 prepare test data in excel

2 add apache poi dependency in pom.xml  or download apache poi & attach jars to your build path

3 XL utility file(java class file) which will read data from excel

4 write TestNG with data provider method

Cheers,

TJ