Cross_Column

Monday, 23 December 2024

Selenium 4 features


Features in Selenium 4:


1. W3C WebDriver Protocol

1. Selenium 4 adopts the W3C WebDriver standard, ensuring better interoperability and reliability across different browsers.
2. Direct communication with the browser eliminates the need for encoding and decoding between JSON Wire Protocol and W3C, improving performance.

2. Relative Locators:

New relative locators simplify element location based on their relationship with other elements on the page.
Methods include:
above()
below()
toLeftOf()
toRightOf()
near()

Example :
WebElement element = driver.findElement(RelativeLocator.with(By.tagName("button")).below(By.id("username")));


Relative Locator Example:




public void relativeLocatorDemo()
{
try {
Thread.sleep(3000);
driver.navigate().to("https://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
WebElement element = driver.findElement(By.xpath(".//a[contains(text(), 'Usefull_things')]"));
highlight(driver, element);
Thread.sleep(3000);
WebElement elementabove = driver.findElement(RelativeLocator.with(By.tagName("td")).above(element));
highlight(driver, elementabove);
Thread.sleep(3000);
System.out.println("above==> " + elementabove.getText());
WebElement elementbelow = driver.findElement(RelativeLocator.with(By.tagName("td")).below(element));
highlight(driver, elementbelow);
Thread.sleep(3000);
System.out.println("below==> " +elementbelow.getText());
WebElement elementright = driver.findElement(RelativeLocator.with(By.tagName("td")).toLeftOf(element));
highlight(driver, elementright);
Thread.sleep(3000);
System.out.println("left==> " +elementright.getText());
WebElement elementleft = driver.findElement(RelativeLocator.with(By.tagName("td")).toRightOf(element));
highlight(driver, elementleft);
Thread.sleep(3000);
System.out.println("right==> " +elementleft.getText());
WebElement secondelement = driver.findElement(By.xpath("//*[@id=\"post-body-2064404811754288590\"]/form[2]/b[2]"));
WebElement elementnear = driver.findElement(RelativeLocator.with(By.tagName("input")).near(secondelement));
highlight(driver, elementnear);
Thread.sleep(3000);
elementnear.click();
}catch(Exception e) {
e.printStackTrace();
}
}

Output


3. Enhanced Selenium Grid

Grid 4 offers better scalability and reliability.
Features include:
Support for Docker to deploy and manage nodes.
Improved observability with built-in logging and monitoring.
New architecture using Hub-Node communication via messaging queues.
Support for both standalone and distributed modes.

4. Improved Browser Support

Selenium 4 adds support for modern browsers and features:
Native Chromium-based Edge support.
Enhanced DevTools Protocol for Chrome and Edge.

5. DevTools Protocol Integration

Selenium 4 integrates the Chrome DevTools Protocol (CDP), enabling access to advanced browser controls.
Capabilities include:
Network interception and monitoring.
Simulating geolocation and device settings.
Capturing console logs and exceptions.

Example :

DevTools devTools = ((HasDevTools) driver).getDevTools(); devTools.createSession(); devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty())); devTools.addListener(Network.requestWillBeSent(), request -> { System.out.println("Request URL: " + request.getRequest().getUrl()); });


6. Better Documentation

Selenium 4 provides updated and detailed documentation with examples for all APIs and features.

7. New Window/Tab Management

Simplified API to open and switch between new browser tabs or windows.
1. Open a New Tab
driver.switchTo().newWindow(WindowType.TAB);
2. Open a New Window
driver.switchTo().newWindow(WindowType.WINDOW);


8. Improved Actions API

The Actions class now supports finer control and more complex gestures for interactions like:
Multi-pointer input (for mobile testing).
Multi-touch gestures

9. Deprecations and Cleanups

Older methods and features have been deprecated, streamlining the API for easier usage.
Example: DesiredCapabilities replaced with Options.

10. Enhanced Screenshots

Take screenshots of specific web elements or the entire page, improving test debugging.
Example :
WebElement element = driver.findElement(By.id("example"));
File screenshot = element.getScreenshotAs(OutputType.FILE);

11. WebDriverManager No Longer Required

Selenium 4 handles driver binaries automatically through the WebDriverManager class.

Sunday, 3 November 2024

Java Script Tutorial 3 Data Types in Java Scripts




Data Types in Java Script:

JavaScript, as a dynamically-typed language, provides several data types that help developers define the nature of variables and manipulate data within their programs. These data types include:

1. Primitive Data Types:


Number: Represents both integer and floating-point numbers.
String: Represents a sequence of characters, enclosed in single (' ') or double (" ") quotes.
Boolean: Represents a logical value of either true or false.
Null: Represents the intentional absence of any object value.
Undefined: Represents a variable that has been declared but not assigned any value.
Symbol: Represents unique and immutable values and is often used as object property keys.

Example :

let a = 10;
let b = 15.50;
console.log(a+b);
let str = "chandan";
let str2 = 'singh';
console.log(str + " " +str2);
let str3 = `str ${a*10}`;
console.log(str3);
let bo = true;
if(bo){
console.log("its true")
}




2. Composite Data Types/Non-primitive data type:


Object: Represents a collection of key-value pairs where keys are strings (or Symbols) and values can be of any data type, including functions, other objects, etc.

Array: A special type of object used to store a collection of elements. Arrays can contain any data type, and elements are accessed by their numeric indices. JavaScript also supports special data structures and object types like Map, Set, Date, RegExp, etc., each with its own unique characteristics and functionalities.The dynamic nature of JavaScript allows variables to adapt to different data types as needed during runtime, which gives developers flexibility but also requires careful consideration to avoid unexpected behaviors due to type coercion or implicit type conversions.

ex : let arrayName = [element1, element2, element3, ...];

Objects in Java Script

In JavaScript, objects are a fundamental data type that allows for the creation of collections of key-value pairs. Objects are used to store data in the form of properties and methods. They are versatile and can represent complex entities by grouping related data and functionalities together.

Objects in JavaScript are defined using curly braces {} and contain zero or more key-value pairs. Keys (also known as property names) are strings or Symbols, and values can be of any data type, including other objects, arrays, functions, etc.

Here's an example of creating an object in JavaScript:



Array in Java Script


In JavaScript, an array is a collection of elements, which can include numbers, strings, objects, other arrays, and more. Arrays are particularly useful for storing lists of items and are zero-indexed, meaning the first element has an index of 0.
Key Features of Arrays in JavaScript
Flexible Data Types: Arrays can hold any data type, including strings, numbers, objects, and even other arrays (making it possible to create multidimensional arrays).
Example :
let mixedArray = [42, "hello", true, { name: "Alice" }, [1, 2, 3]];

Dynamic Length: The length of an array can change dynamically. You can add or remove elements as needed.
Accessing Elements: Elements are accessed by their index, starting from 0
Example :
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]); // Output: "banana"

Array Properties and Methods:
length: Returns the number of elements in the array.
Example :
console.log(fruits.length); // Output: 3

push(element): Adds one or more elements to the end of the array.
Example :
fruits.push("orange"); // ["apple", "banana", "cherry", "orange"]

pop(): Removes the last element from the array and returns it
Example :
let lastFruit = fruits.pop(); // "orange"

unshift(element): Adds one or more elements to the beginning of the array
Example :
fruits.unshift("kiwi"); // ["kiwi", "apple", "banana", "cherry"]

shift(): Removes the first element from the array and returns it.
Example :
let firstFruit = fruits.shift(); // "kiwi"

splice(start, deleteCount, ...items): Adds/removes elements from a specific position in the array.
Example :
fruits.splice(1, 1, "grape"); // Replaces "apple" with "grape"

slice(start, end): Returns a shallow copy of a portion of an array
Example :
let newFruits = fruits.slice(1, 3); // ["banana", "cherry"]

indexOf(element): Returns the index of the first occurrence of the specified element, or -1 if it does not exist.
Example :
console.log(fruits.indexOf("cherry")); // Output: 2

Java Script Tutorial 2 Variables in Java Script




Variables in JavaScript

1) Variable names are case sensitive means “way2testing” and “WAY2TESTING” are different.

2) Space is not allowed only letter, digit, underscore and $ is allowed in variable name.

3) Reserved words cannot be used as variable name like “log, break, case, catch etc”.

4) Variable name’s first character must be only a letter, underscore or $.

Note : In general variable name should be in camel case.

Variable name can be used with three keywords

var : Variable can be re-declared and updated. A global Scope variable.
let : Variable can’t be re-declared but can be updated. A block scope variable.
Const: Variable can’t be re-declared or updated. A block space variable.

Note : const variable generally defined in capital letter.





JavaScript Tutorials

Java Script Topics Java Script Topics
1.

Java Script Tutorial 1 Introduction

2.

Java Script Tutorial 2 Variables in JavaScript

3.

Java Script Tutorial 3 Data Types, Object, Array in Java Script

4.

Java Script Tutorial 4

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

Java Script Tutorial 1 -- Introduction of java script, Syntax of Java Script




JavaScript Introduction 1:

JavaScript is a high-level, versatile programming language primarily used to create interactive effects within web browsers. Developed by Netscape, it was initially named LiveScript before being renamed JavaScript.

Key aspects of JavaScript include:

Client-Side Scripting: JavaScript is primarily used for client-side web development, allowing developers to create dynamic content that interacts with users, modifies the content of web pages, and responds to events triggered by users' actions (like clicks, form submissions, etc.).

Object-Based Language: JavaScript is object-based, meaning it uses objects and their properties to build scripts and functionalities. Objects in JavaScript can be predefined (like Date, Math, etc.) or custom-defined by developers.

Versatility: Originally created for web browsers, JavaScript has expanded its scope and can now be used for server-side development (Node.js), mobile app development (React Native, NativeScript), game development (using frameworks like Phaser, Three.js), and more.

Syntax: The syntax of JavaScript is similar to other programming languages like Java and C, making it relatively easy to learn for those familiar with programming concepts.

Interactivity and Dynamic Content: JavaScript allows for the creation of interactive elements on web pages, such as form validation, animations, dynamic updates without reloading the page (AJAX), and more.

Libraries and Frameworks:There are numerous libraries and frameworks built on top of JavaScript (e.g., jQuery, React.js, Angular.js, Vue.js) that simplify and streamline the development process, providing reusable components and enhancing the functionality of JavaScript.

Cross-Browser Compatibility: JavaScript is supported by all major web browsers like Chrome, Firefox, Safari, and Edge, ensuring cross-browser compatibility for web applications.

JavaScript plays a crucial role in modern web development, allowing developers to create rich, interactive, and user-friendly web experiences. Its versatility and widespread adoption have made it an integral part of web development ecosystems.




JavaScript Syntax :


0. Use the curly braces ({}) to create a block that groups one or more simple statements.

1.Javascript ignore the white spaces

2.In javascript (“;” ) used to end a statement and it is optional

3.Single line comment like “//”

4. Multiple line comment should be like “/* …… */”

For Example :

console.log("chandan");
let a = 10;
let b = 20;
//console.log(a+b);
console.log(a+b+30);
/*console.log("comment me)
console.log("comment me")
console.log("comment me")*/



Saturday, 12 October 2024

Generics in Java with Example




Hello Friends,

Generics , This concept, introduced in JDK 5.0

Generics in Java are a powerful feature that allows you to define classes, interfaces, and methods with type parameters. This means that you can write flexible and reusable code while maintaining type safety, as it helps prevent runtime type casting errors by catching them at compile time.


Advantages of Generics:

Type Safety: Compile-time type checks prevent runtime ClassCastException.
Code Reusability: You can write a generic class or method once and use it for different data types.
Elimination of Casts: When retrieving elements from a generic collection, there's no need to cast the result.




Generic Class Example:




import java.util.*;

class A<T>{
private T item;
public A(T item){
this.item=item;
}
public void set(T item){
this.item = item;
}
public T get(){
return item;
}
}

public class GenericDemo {
public static void main(String[] args){
ArrayList list = new ArrayList();
list.add(24);
// list.add("www.way2testing.com");
// list.add(new HashSet());
int x = list.get(0);
System.out.println(x);
A obj = new A("csc");
// obj.set("way2testing");
System.out.println(obj.get());
}
}

Output:


Generic Methods:

In Java, generic methods are methods that are written with a parameterized type, enabling them to operate on objects of various types while still being type-safe. The key feature of generics is that they allow you to write a method or class that can handle any data type, without sacrificing compile-time type checking.

Advantages of Generic Methods:

Type Safety: You get compile-time type checking and avoid ClassCastException. Code Reusability: A single generic method can be used for different data types, avoiding duplication.

Generic Methods Example:



public class GenericMethod {
public static <T> void gtest(T[] arr){
for(T a:arr){
System.out.println(a);
}
System.out.println("Generic Methods");
}

public static void main(String[] args){
Integer[] ia = {1,2,3,4,5};
gtest(ia);
String[] sa = {"csc", "way2testing", "datastop", "dbshop"};
gtest(sa);
}
}







Generic Interface:


In Java, a generic interface is an interface that can work with any type of data using type parameters. This allows the interface to be type-safe and reusable for different types, similar to generic classes and methods.



Generic Interface Example:



interface genricEngine<T>{
void set(T item);
T get();
}
class car implements genricEngine<String>{
private String accessories;
public void set(String accessories){
this.accessories = accessories;
}
@Override
public String get() {
return accessories;
}
}
class suv implements genricEngine<Integer>{
private Integer gear;
public void set(Integer gear){
this.gear = gear;
}
@Override
public Integer get() {
return gear;
}
}
public class InterfaceGeneric {
public static void main(String[] args){
car a = new car();
a.set("nitrogen");
System.out.println(a.get());
suv b = new suv();
b.set(5);
System.out.println(b.get());
}
}






What does Generics mean in Selenium?

In automation, we often use Collections with WebElement — like List<WebElement>. This is nothing but Generics.
Example : List<WebElement> elements = driver.findElements(By.xpath("//button")); Meaning of List<WebElement>
List = a collection that stores multiple values
<WebElement> = allows only WebElement type to be stored inside
Some Common Generics in Selenium
Syntax Meaning
List<WebElement> List of WebElements only
List<String> List of only String values
Map<String, String> Key–Value pair map
Set<WebElement> No duplicate WebElements
List<Map<String, String>> Table-like dynamic test data structure

Friday, 11 October 2024

Comparable and Comparator Interface in Java




Hello Friends,

In java, when we want to sort a collection, we use Class “Collections” and static method “sort()”
For example : List list = new ArraysList();
Collections.sort(list);
Now all the elements of the list will be sorted as per alphabetic order or numeric order.
But what if a list has objects then list items will be compared and which one will go first in list??
So , to sort the objects, we need to specify a rule based on that object should be sorted.
The “Comparator” and “Comparable” interface allow us to specify what rule is used to sort the objects.

FeatureComparableComparator
Interfacejava.lang.Comparablejava.util.Comparator
MethodcompareTo(T o)compare(T o1, T o2)
Natural OrderDefines natural ordering within the classDefines custom ordering outside the class
Single/MultipleCan only have one natural orderCan define multiple comparison methods
UsageUsed when you have one "natural" way to compareUsed for custom sorting logic or multiple comparisons


1. Comparable Interface

Purpose: Used to define a natural ordering of objects.
Method: Requires implementation of the method compareTo(Object o).
Usage: A class implements Comparable when its objects are supposed to be ordered in a natural way (e.g., alphabetical for strings, numerical for numbers).
Modification: This affects the class itself, meaning the comparison logic is part of the class definition.



2. Comparator Interface

Purpose: Used to define a custom or multiple orderings for objects.
Method: Requires implementation of the method compare(Object o1, Object o2).
Usage: Comparator is typically used when you want to define multiple ways of comparing objects or when you want to compare objects of a class that you do not control (e.g., a library class).
Modification: The comparison logic is external to the class being compared.

Comparable with example :




public class Vehicle implements Comparable<Vehicle>{
private int vehiclenumber;
private String vehiclename;
private int vehicleyear;
public Vehicle(int vehiclenumber, String vehiclename, int vehicleyear){
this.vehiclenumber = vehiclenumber;
this.vehiclename = vehiclename;
this.vehicleyear = vehicleyear;
}
public String toString(){
return "vehicle{"+
"vehiclenumber='" + vehiclenumber+ '\''+
", vehiclename='" + vehiclename+ '\''+
", vehicleyear=" + vehicleyear+
'}';
}

@Override
public int compareTo(@NotNull Vehicle o) {
return this.vehiclenumber - o.vehiclenumber;
}
}

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class comparatordemoa {
public static void main(String[] args){
List list = new ArrayList();
list.add(10);
list.add(20);
list.add(9);
list.add(15);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List list2 = new ArrayList();
list2.add(new vehical(2345, "ford", 2024));
list2.add(new vehical(3456, "kia", 2023));
list2.add(new vehical(5678, "suzuki", 2025));
System.out.println(list2);
Collections.sort(list2);
System.out.println(list2);
}
}

Comparator with example :

public class Vehicle2 {
public int getVehiclenumber() {
return vehiclenumber;
}
public void setVehiclenumber(int vehiclenumber) {
this.vehiclenumber = vehiclenumber;
}
public String getVehiclename() {
return vehiclename;
}
public void setVehiclename(String vehiclename) {
this.vehiclename = vehiclename;
}
public int getVehicleyear() {
return vehicleyear;
}

public void setVehicleyear(int vehicleyear) {
this.vehicleyear = vehicleyear;
}

private int vehiclenumber;
private String vehiclename;
private int vehicleyear;

public Vehicle2(int vehiclenumber, String vehiclename, int vehicleyear){
this.vehiclenumber = vehiclenumber;
this.vehiclename = vehiclename;
this.vehicleyear = vehicleyear;
}

public String toString(){
return "vehicle{"+
"vehiclenumber='" + vehiclenumber+ '\''+
", vehiclename='" + vehiclename+ '\''+
", vehicleyear=" + vehicleyear+
'}';
}
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableDemo {
public static void main(String[] args){
List list = new ArrayList();
list.add("Amit");
list.add("Baji");
list.add("Nishant");
list.add("Diraaj");
list.add("Chandan");
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List list1 = new ArrayList();
list1.add(new Vehicle(10,"ford", 2022));
list1.add(new Vehicle(15,"Hundai", 2023));
list1.add(new Vehicle(5,"Honda", 2026));
System.out.println(list1);
Collections.sort(list1);
System.out.println(list1);
List list2 = new ArrayList();
list2.add(new Vehicle2(10,"City", 2022));
list2.add(new Vehicle2(15,"Baleno", 2023));
list2.add(new Vehicle2(5,"Accent", 2026));
System.out.println(list2);
Collections.sort(list2, new CompratorDemo());
System.out.println(list2);
}
}

public class CompratorDemo implements Comparator<Vehicle2> {

@Override
public int compare(Vehicle2 o1, Vehicle2 o2) {
return o1.getVehiclename().compareTo(o2.getVehiclename());
}
}

Example :


Tags:

Example of Comparable interface in java

Example of Comparator interface in java

Comparable vs comparator in java

Adavntage of Comparator over Comparable interface in java

Few More

Encapsulation in Python

Encapsulation in Python: A Complete Guide with Examples and Diagrams Encapsul...

Popular Posts