Select Page

Category Selected: Selenium Testing

47 results Found


People also read

E-Learning Testing

What is LMS Testing? Explore Effective Strategies

Software Development

Building RESTful APIs with Node.js and Express

Security Testing

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility
Selenium TextBox Actions & Validations

Selenium TextBox Actions & Validations

In Selenium, every HTML object is considered as WebElement. As an automation tester, you should be aware of what are all the applicable actions and validations for each HTML objects. In this blog article, you will learn all Selenium’s action and validation snippets for TextBox. As per W3C, a mutable HTML textbox should allow the user to edit value and it should not allow Line Feed & Carriage return characters.

Let’s start from some basics commands.

Enter Value

ChromeDriver driver = new ChromeDriver();
driver.get("URL");
WebElement txtBox = driver.findElement(By.id("txt2"));

//Entering using SendKeys
txtBox.sendKeys("codoid");

//Entering using JavaScript
executor.executeScript("arguments[0].value=arguments[1]",txtBox,"codoid");

Please note that the JavaScript snippet does not mimic user action the way how SendKeys does.

IsEnabled & ReadOnly

Before checking whether a textbox is enabled or readonly, you should know what is the difference between disabled and readonly textbox.

Readonly – If a textbox is readonly, you can still send the textbox’s content when a form is submitted and access the textbox using TAB key.

Disabled – If a textbox is disabled, the textbox’s content will not be sent when a form is submitted, you can’t access the textbox using TAB key, and the events like click, hover, & double click will not be triggered.

isReadOnly = txtBox.getAttribute("readonly");

isEnabled = txtBox.isEnabled();

Retrieve Value

Retrieving value from a textbox using Selenium is a cake walk for many. However, we, as an automation test company, would like to list it here. So that this blog article will be a quick reference guide for software testers who are learning Selenium.

value = txtBox.getAttribute("value");
Selenium 4 JavaScript Pinning Feature

Selenium 4 JavaScript Pinning Feature

In Selenium 4, we have another feature which is useful to pin the commonly used JavaScript snippets to a WebDriver session. In Selenium 4 alpha version 7, you can try the below snippets at your end to see how script pinning works. Once a script is pinned, you can use it until your WebDriver session is alive. Let’s say you want to run a series of JavaScript snippets multiple times. You need to store each of the snippets in a String variable and execute them one by one.

However, with the script pinning feature, you can store & run the commonly used snippets using the WebDriver session instead of storing in String variables.

WebDriver driver = new ChromeDriver();
JavascriptExecutor executor = (JavascriptExecutor) driver;

ScriptKey hello = executor.pin("return arguments[0]");
executor.executeScript(hello, "cheese");

You can also unpin the store script anytime.

executor.unpin(hello);

If you would like to store and retrieve multiple pins, you can use Set to save the pins.

Set<ScriptKey> expected = ImmutableSet.of(
      executor.pin("return arguments[0];"),
      executor.pin("return 'cheese';"),
      executor.pin("return 42;"));

Set<ScriptKey> pinned = executor.getPinnedScripts();
How to use Selenium’s Chrome DevTools Protocol?

How to use Selenium’s Chrome DevTools Protocol?

Chrome DevTools is a useful tool to grab vital information while testing a web application on Chrome browser. However, when the testing happens using automated test scripts, we can’t retrieve Chrome DevTools important details like console’s log messages, Network, Page Performance and etc.

In Selenium 4, we are going to get Chrome DevTools Protocol (CDP) which helps to get DevTools’ properties such as Application Cache, Fetch, Network, Performance, Profiler, Resource Timing, Security and Target CDP domains etc.

In this blog article, you will learn how to execute Chrome DevTools Protocol commands using Selenium 4.

Selenium 4 (Alpha) Maven Dependancy

Selenium 4 is yet to be released. However, we have 7 alpha versions. Use the below maven dependancy in POM xml.

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-5</version>
</dependency>

Setting Network Conditions

Sometimes you may have to test your website or web application in different network conditions. You can set custom upload and download throughput in Chrome DevTools manually to test a web application in a desired network condition.

In Selenium, you can do this using the below code.

ChromeDriver driver = new ChromeDriver();

CommandExecutor executor = driver.getCommandExecutor();
         
//Set the conditions
Map<String, Object> map = new HashMap<String, Object>();
map.put("offline", false);
map.put("latency", 5);
map.put("download_throughput", 5000);
map.put("upload_throughput", 5000);
 
Response response = executor.execute(new Command(driver.getSessionId(),"setNetworkConditions", ImmutableMap.of("network_conditions", ImmutableMap.copyOf(map))));
 
driver.get("http://google.com");

However, using Selenium’s Chrome DevTools Protocol, you can do it elegantly.

Refer the below code which uses Selenium 4 Chrome DevTools Protocol implementation.

DevTools devTools = driver.getDevTools();
devTools.createSessionIfThereIsNotOne();
devTools.clearListeners();

devTools.send(Network.emulateNetworkConditions(false, 5, 5000, 5000, Optional.of(ConnectionType.NONE)));

Clearing Browser Cookies and Cache

Cache creates temporary files and it eats RAM. If you want to clear browser cache using Chrome DevTools, you can try the below code.

DevTools devTools = driver.getDevTools();
devTools.send(Network.clearBrowserCache());

For clearing cookies:

devTools.send(Network.clearBrowserCookies());

Fetching Performance Metrics

In DevTools, you can analyse page’s runtime performance in Performance tab. Using CDP, you can fetch performance metrics in automation testing. Refer the below snippet.

devTools.send(Performance.setTimeDomain(Performance.SetTimeDomainTimeDomain.TIMETICKS));
devTools.send(Performance.enable());

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

List<Metric> metrics = devTools.send(Performance.getMetrics());


for (Metric metric:metrics) {
	System.out.println(metric.getName());
	System.out.println(metric.getValue());
}

devTools.send(Performance.disable());

Listening Console Log Entries

Monitoring Chrome console log entires while testing a web application manually is a cumbersome task. In Selenium 4, you can listen the log entires easily.

The below code listens 404 error.

devTools.send(Log.enable());

devTools.addListener(Log.entryAdded(), logEntry -> {
System.out.println(logEntry.getText().contains("404"));
        });

driver.get("https://codoid.com/fafafafsasf");

In Conclusion

We, as an automation testing services company, are happy to explore the new features of Selenium 4. Controlling and capturing Chrome DevTools is great value add for automation testing.

Running Selenium Scripts using Bazel

Running Selenium Scripts using Bazel

Bazel is one of the most widely used open source build tool these days, the rationale behind using Bazel is aplenty. Let’s say you want to compile Java and Python projects into one build file, then Bazel would be the ideal choice. As a QA company, we use Maven, Gradle, and Grunt to compile & kick-off automated test suites. Bazel is something new for us. In this blog article, you will learn how to run Selenium Scripts using Bazel.

Advantages of Bazel

1) Platform Independent: You can run your Selenium scripts on Linux, macOS, Windows.

2) Compiling Large Files: Bazel can handle large files easily.

3) Languages: You can build and test C/C++, Objective-C, Java, Python, and Bourne Shell scripts in one build file.

How to run Selenium Scripts using Bazel?

Bazel has its own build language. Using Bazel’s predefined test rule, you can set automated test scripts in the build file irrespective of the programming languages used. We, as a test automation company, explore new technologies with the intend to ease automation testing process. Bazel is so programmer friendly, even Selenium developers are using Bazel to test Selenium’s features before deploying. In this blog article, we have used Windows 10 and Python to show the code execution. Let’s start from installation.

Prerequisite – Visual C++ Redistributable for Visual Studio 2015

Visual C++ Redistributable for Visual Studio 2015 is a prerequisite if you are installing Bazel on Windows 10. Use the following link to install the package – Visual C++ Redistributable for Visual Studio 2015

Bazel Installation on Windows 10

Step #1 – Download bazel--windows-x86_64.exe from the following link – Download Bazel

Step #2 – Rename the downloaded file to bazel.exe

Step #3 – Copy and paste the bazel.exe wherever you want.

Step #4 – Set the bazel.exe path in PATH environment variable in Windows 10.

Step #5 – Restart your PC

Create a Python Project

Step #1 – Create a Python project

Step #2 – Create a directory called ‘scripts’

Step #3 – Create a directory called ‘drivers’

Step #4 – Download and paste the chromedriver.exe in drivers folder

Step #5 – Create a python file and name it as test-1.py inside the scripts folder

Step #6 – Paste the below snippet inside the test-1.py file

from selenium import webdriver
from bazel_tools.tools.python.runfiles import runfiles
r = runfiles.Create()
driver = webdriver.Chrome(executable_path=r.Rlocation("test_suite/drivers/chromedriver.exe"))
driver.get("https://codoid.com")
driver.quit()
  

Note: In line #4, the chromedriver executable path is set using Bazel’s runfiles module. Because all the supporting & testdata files for automated scripts need to be accessed using runfiles module. Maybe in future enhancements we will have a simple workaround instead of calling runfiles.

Creating WORKSPACE file

Bazel identifies a directory as Bazel Workspace when it contains WORKSPACE file.

Step #1 – Create WORKSPACE file without any extension

Step #2 – Paste the below line to name the workspace

workspace(name = "test_suite")
  

Creating BUILD file

Bazel build file is being used to compile and run your test code. We, as a software testing company, use Maven POM.xml files to compile and run test code for Java projects. If you have test code base in different programming languages, then you can opt for Bazel to compile & execute test code of different languages into a single build file. Let’s see how to create a build file.

Step #1: Inside the root directory, create a BUILD file without any extension.

Step #2: Copy and paste the below snippet in BUILD file.

py_binary(
    name = "test-1",
    srcs = ["scripts/test-1.py"],
    srcs_version = "PY2AND3",
    data = [":drivers/chromedriver.exe"],
    deps = ["@bazel_tools//tools/python/runfiles"],
)
  
Code Explanation

Line #1: py_binary is one of the Bazel’s rules. For Python, Bazel has two more rules – py_library & py_test. Any Python related tasks can be defined using these three rules in the build file.

Line #2: You can name your tasks using ‘name’ attribute.

Line #3: ‘srcs’ attribute is used to mention source files inside the rule. You can also mention multiple source files.

Line #5: To launch the chrome browser, we need chromedriver.exe file. So we are copying the file inside the runfiles folder which can be found in bazel-out folder. Use ‘data’ attribute to copy all the supporting files.

Line #6: To access runfiles in Python code, you need runfiles module from bazel_tools. Refer Line#2 in test-1.py file, you can understand why we are mentioning this dependency here.

Bazel Run

Now it is the time to run the script. You can run the rules from command prompt. Let’s see how to run our test-1 task.

Clean – bazel clean

Run – bazel run :test-1

That’s it. You can see browser launch after running the above commands. We have uploaded the Python project in Github. Please refer it if you face any issues. Full Code Download Link

In Conclusion

As a test automation company, we manage and maintain automation test scripts in multiple programming languages. However, managing single build file for compiling test code from different programming languages is a daunting task and eventually a great value add for QA companies. In our subsequent blog articles, we will be publishing more about nuances of Python automation testing.

Selenium Plugins

Selenium Plugins

This article throws light on available Selenium plugins and its features. There are umpteen number of plugins available in the market, we will see the most popular ones which are widely used.

Selenium IDE

Selenium IDE brings the benefit of functional test automation to many testers and frontend developers. It came as a record and playback tool for Firefox browser back in 2006, Selenium IDE is now cross-browser, and it is available as Google chrome extension and Firefox Add-on.

Applitools for Selenium IDE

While speaking about new plugins, Applitools is a great visual AI tool, which introduces a new Selenium IDE plugin to add AI powered visual validations. Visual checkpoints are a great way to ensure whether a UI renders correctly or not. It lets you to visually test your webpages on Applitools Visual Grid which enables you to test across a combination of browsers, and devices. It would be painful to maintain a bunch of assert statements on all the UI elements for one visual checkpoint Applitools address this.

BlazeMeter Chrome Extension

You can run a performance test using this chrome browser extension – BlazeMeter. It records the Selenium test scripts for your load testing by recording all the HTTP/S requests that your browser sends. The multi test feature in BlazeMeter allows you to aggregate and run both Selenium and JMeter tests, run them in parallel and synchronize them.

ChroPath

ChroPath is a top rated XPath tool, which comes as a Chrome plugin. It is a great tool to edit, inspect XPath and CSS Selectors. ChroPath generates a unique relative XPath and CSS Selector for the elements selected.

Ranorex Selocity

Ranorex auto-generates robust XPath, link text, RanoreXPath, and CSS selectors to use with Selenium. You can obtain selectors with one click, and copy them into your locators in Selenium. If you choose to modify a selector, Ranorex Selocity provides instant feedback to check whether the selector is valid or not. In addition to the selector definition, Ranorex Selocity displays the number of matching elements for the selector, along with action buttons to copy and modify the selector. If you hover over the selectors, you can see the matched elements on the website.

Selenium Page Object Generator

This chrome extension helps in creating the page object class for Selenium WebDriver with locators for all available elements and methods to access them. It generates a Page Object Model on the active Chrome tab with a single click, provided all the options and template are configured. The generated Page Object Model can be saved to the pre-configured Chrome download folder. By using this plugin, you can generate Page Object classes for Java, C#, and Robot Framework.

Katalon Recorder

It will let you capture the web elements and record the actions performed on the web app. It allows you to create new test cases, edit existing test cases and play automated test cases. You can record and export Selenium scripts in Katalon Studio easily. In Katalon recorder, you use all Selenese commands, control statements, and import test data from a CSV file.

WebDriver Scripting Assistant

It is a Chrome plugin from AppDynamics. Application Performance Monitoring needs to locate web objects in order to track end-user actions like Tap, Click, and Swipe. You can use WebDriver Scripting Assistant plugin to identify any element on the web page via their CSS selector.

Page Modeller

It is an excellent plugin for automation testing engineers as it supports multiple languages to write the test scripts. It saves a lot of time when developing WebDriver based automation using a best Page Object model approach in a range of languages. It enables the developers to scan a web page and generate page object style code for various tools, languages and frameworks and test the UI locators in the browser.

Chromedriver Jenkins Plugin

It is essential to integrate selenium testing into a continuous integration servers like Jenkins. It can be done using Jenkins plugin which downloads and installs ChromeDriver binary automatically in every slave.

AutoAction

AutoAction plugin opens real browser and execute the actions, so the browser is required to be installed at the machine hosting Jenkins server. This is a simple Jenkins plugin which allows you to write Selenium steps in Build section. If you have a requirement to write Selenium script in a Jenkins job instead of configuring from a Java or Python file, then this is the ideal choice for you. You can write the scripts using flat lines format. Refer the sample code script below.

Open https://accounts.google.com/SignUp?lp=1&hl=en
Input Auto First Name
Input Action Last Name
Input autoaction2019 Username
Input autoaction123 Password
Input autoaction123 Confirm
Click Next

Conclusion

As an expert Selenium Testing Services provider, we believe that this article throws light on how plugins can extend Selenium’s default behaviour, by adding additional commands and locators, bootstrapping setup before and after a test runs. We recommend you install and use each of them, so that you can arrive at a conclusion that which plug-in suits you the most. We hope you enjoyed reading this article, happy reading!

Selenium Keys & Sendkeys Examples

Selenium Keys & Sendkeys Examples

A major proportion of automation testers are familiar with Selenium Keys feature. You can use Selenium Keys and SendKeys in WebElement class, Action Class, and Keyboard class. In this blog article, you will learn the nuances between these methods.

WebElement SendKeys

Everyone is well aware of the fact that SendKeys method is mostly used to enter value in a textbox or file path in File inputbox. Take for instance if you wish to paste the value which is available in clipboard using CTRL + V in a textbox.

txtBox = driver.find_element_by_id("txt1")

#Pastes the clipboard value in the textbox
txtBox.send_keys(Keys.LEFT_CONTROL, 'v')
  

The above snippet pastes the value in the textbox. Now, you want to enter a string after pasting the clipboard.

txtBox.send_keys(Keys.LEFT_CONTROL, 'v', 'Codoid')
  

When you execute the above code, it won’t accept the string (i.e. Codoid). Because the modifiers keys (i.e. CTRL/ALT/SHIFT/etc) will not be released until SendKeys call is complete.

To understand the above precisely, pass the third argument text as ‘value’ and rerun the snippet.

txtBox.send_keys(Keys.LEFT_CONTROL, 'v', 'value')

If you notice the execution, the snippet has pasted the clipboard text twice. The reason is CTRL key is released only after the SendKeys method call.

CTRL key is not released yet and the third argument (‘value’) string’s starting letter is ‘v’. So again CTRL + V is pressed. That’s why the clipboard text is pasted twice in the textbox.

Then how to enter the argument text in the textbox? Just use KEYS.NULL after CTRL + V. Refer the below snippet.

txtBox.send_keys(Keys.LEFT_CONTROL, 'v', Keys.NULL, 'value')
  

As soon as Keys.NULL is used all the modifier keys will be released.

Action Class Sendkeys

Using Action class’ SendKeys methods, you can’t press modifier keys. Try the below code, it won’t paste the clipboard content as we tried using WebElement’s Sendkeys method.

action = ActionChains(driver)

action.send_keys_to_element(txtBox, Keys.LEFT_CONTROL, "v").perform()
  

You need to use KeyDown to press modifiers keys. Try with the below code, it will paste the text in the textbox.

action.key_down(Keys.LEFT_CONTROL).send_keys_to_element(txtBox, "v").perform()
  

In conclusion

We as an automation testing company, have mitigated several unsuccessful automation testing projects. Gaining enduring technical know-how of selenium basics to advanced level is a key to test automation success.