Playwright
Q: What is the features of Playwright ?
Ans :
- open source
- multi browser/ multi language/ multi OS
- Easy setup
- Functional |API |Accessibility testing
- Built-in-Reporters | Custom report
- CI/CD |Docker support
- Recording/ Debugging
- Parallel testingAuto wait
- Built-in assertions
- Test retry ,logs ,screenshots ,video
- multi -tab and multi-window
- frame |Shadow DOM
- Emulate mobile devices
- test parameterization
- Fast
Q:How to create first script in Playwright ?
Ans :
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
Q:How to create locators in Playwright ?
Ans :
//single element
Locator button = page.locator("text=Get started");
button.click();
//mutiple element
Locator button = page.locator("text=Node.js");
button.first().click();
//with iterating
Locator list = page.locator("li");
List<String> a = list.allTextContents();
for(String s :a)
System.out.println(s);
//with lambda
a.foreach(e->System.out.println(e));
Q:What are different binaries in playwright ?
Ans :
Here are some common binaries associated with Playwright:
- Chromium: Playwright uses a specific version of Chromium, a project maintained by the Chromium team, as its default browser for testing. The Chromium binary provided by Playwright is optimized for automation and comes bundled with the Playwright installation.
- WebKit: Playwright supports automating WebKit, which is the rendering engine used by Safari. Similar to Chromium, Playwright includes a custom WebKit binary optimized for automation.
- Firefox: Playwright also allows automation of Firefox. For this, you'll need to download and specify the path to the Firefox executable on your machine.
Q:What are different selectors in playwright ?
Ans :
- Text selector
- CSS selector
- Selecting visible elements
- selecting elements that contains other elements
- selecting elements matching one of the conditions
- selecting element present in shadow DOM
- selecting element based on layout
- xpath selector
- N-th element selector
- React selector
- Vue selector
- id , data-testid
- chaining selector
Q:How can we get text of any element in playwright ?
Ans :
String str = page.locator("text=abc").textContent();
Q: How to use frames in playwright ?
Ans:
Page page = browser.newPage();
page.frameLocator(<can pass the xpath or css selector>).locator("").textContent();
page.frame("<name of the frame>")
Q: Can you explain the architecture of Playwright?
Ans:
- Playwright architecture is completely different from what Selenium architecture is. Both Selenium and Playwright use to send all browser automation commands and recieve responses in JSON format.
- Selenium uses separate HTTP requests for every command like launching the browser, opening the page, taking screenshots and so forth.
- However, sending a new HTTP request for every command requires sending and receiving a lot of redundant information such as HTTP headers. Such approach tends to be slower than using one permanent communication channel for all commands which is alive while browser is running.
- Playwright uses this approach and communicates with browser using one long-living web-socket connection. The web-socket connection gets established inside launch() method implementation which also automatically starts browser process for you.
n Playwright,
BrowserContext
is used to create isolated environments within a single browser instance. Each BrowserContext
can be thought of as a separate browser session, with its own cookies, cache, and storage. This allows you to run multiple, parallel, and isolated browser sessions within the same browser instanceQ: How to test GUI in Playwright ?
Ans:
package com.qa.app.tests;
import com.microsoft.playwright.*;
import org.testng.annotations.Test;
import java.awt.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class PlaywrightScriptUI {
//launching chromium /webkit/Firefox
@Test
public void test1() {
Playwright playwright = Playwright.create();
Browser browser = playwright.webkit().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
System.out.println(page.title());
page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example3.png")));
browser.close();
}
// launching simple browser
@Test
public void test2() {
Playwright playwright = Playwright.create();
/* BrowserType.LaunchOptions lo = new BrowserType.LaunchOptions();
lo.setChannel("chrome");
lo.setHeadless(false);
Browser browser = playwright.chromium().launch(lo);*/
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("msedge").setHeadless(false));
Page page = browser.newPage();
System.out.println(page.title());
page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example3.png")));
browser.close();
}
// creating locator =webelement and clicking
@Test
public void test3() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
BrowserContext bcontext = browser.newContext();
Page page = bcontext.newPage();
System.out.println(page.title());
page.navigate("https://playwright.dev/");
//single element
/*Locator button = page.locator("text=Get started");
button.click();*/
//mutiple element
Locator button = page.locator("text=Node.js");
button.first().click();
Locator list = page.locator("li");
List<String> a = list.allTextContents();
for(String s :a)
System.out.println(s);
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example3.png")));
browser.close();
}
//to capture the text
@Test
public void test4() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
Page page = browser.newPage();
System.out.println(page.title());
page.navigate("https://playwright.dev/");
String s1 = page.locator("//h1[@class='hero__title heroTitle_ohkl']").textContent();
System.out.println(s1);
browser.close();
}
//handling dynamic tables
@Test
public void test5() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
Page page = browser.newPage();
System.out.println(page.title());
page.navigate("https://datatables.net/extensions/select/examples/initialisation/checkbox.html");
Locator row = page.locator("//table[@id='example']//tr");
row.locator(":scope",new Locator.LocatorOptions().setHasText("Cedric Kelly"))
.locator("//td[@class=' select-checkbox']")
.click();
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example3.png")));
row.locator(":scope").allTextContents().forEach(e->System.out.println(e));
browser.close();
}
//handling dynamic tables 2
@Test
public void test6() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
Page page = browser.newPage();
System.out.println(page.title());
page.navigate("https://datatables.net/extensions/select/examples/initialisation/checkbox.html");
Locator row = page.locator("//table[@id='example']//tr");
row.locator(":scope",new Locator.LocatorOptions().setHasText("Cedric Kelly"))
.allInnerTexts().forEach(e->System.out.println(e));
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example3.png")));
browser.close();
}
//handling auto session login
@Test
public void test7() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext bcontext = browser.newContext();
Page page = bcontext.newPage();
page.navigate("https://www.demoblaze.com/index.html");
page.locator("//a[text()='Log in']").click();
page.locator("//input[@id='loginusername']").fill("test");
page.locator("//input[@id='loginpassword']").fill("test");
page.locator("//button[text()='Log in']").click();
System.out.println("Welcome...You are in...");
bcontext.storageState(new BrowserContext.StorageStateOptions()
.setPath(Paths.get("login.json")));
}
@Test
public void test8() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext br =
browser.newContext(new Browser.NewContextOptions()
.setStorageStatePath(Paths.get("login.json")));
Page page = br.newPage();
page.navigate("https://www.demoblaze.com/index.html");
browser.close();
}
//handling alert automatically by playwright
@Test
public void test9() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext bcontext = browser.newContext();
Page page = bcontext.newPage();
page.navigate("https://www.demoblaze.com/index.html");
page.locator("//a[text()='Log in']").click();
page.locator("//input[@id='loginusername']").fill("test");
page.locator("//input[@id='loginpassword']").fill("test");
page.locator("//button[text()='Log in']").click();
//capture alert message with playwright listener
page.onDialog(e -> {
System.out.println(e.message());
e.accept();
}
);
System.out.println("Welcome...You are in...");
List lo = page.locator("//a[@class='nav-link']").allTextContents();
System.out.println(lo.toString());
page.close();
browser.close();
playwright.close();
}
//upload file
@Test
public void test10() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext bcontext = browser.newContext();
Page page = bcontext.newPage();
page.navigate("https://davidwalsh.name/demo/multiple-file-upload.php");
// Select single files
page.locator("input#filesToUpload").setInputFiles(Paths.get("Sample.pdf"));
// Select multiple files
page.locator("input#filesToUpload").setInputFiles(new Path[] {Paths.get("Sample.pdf"), Paths.get("Sample1.pdf")});
// Remove all the selected files
page.locator("input#filesToUpload").setInputFiles(new Path[0]);
page.close();
browser.close();
playwright.close();
}
//select from dropdown
@Test
public void test11() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext bcontext = browser.newContext();
Page page = bcontext.newPage();
page.navigate("https://formstone.it/components/dropdown/demo/");
// Single selection matching the value
List lr = page.locator("select#demo_basic").selectOption("Two");
System.out.println(lr.toString());
/* // Single selection matching the label
page.getByLabel("Choose a color").selectOption(new SelectOption().setLabel("Blue"));
// Multiple selected items
page.getByLabel("Choose multiple colors").selectOption(new String[] {"red", "green", "blue"});*/
page.close();
browser.close();
playwright.close();
}
//download the file and save it to specific location
@Test
public void test12() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
BrowserContext bcontext = browser.newContext();
Page page = bcontext.newPage();
page.navigate("https://chromedriver.storage.googleapis.com/index.html?path=114.0.5735.90/");
// Wait for the download to start
Download download = page.waitForDownload(() -> {
// Perform the action that initiates download
//page.click("//a[text()='chromedriver_win32.zip']");
page.locator("//a[text()='chromedriver_win32.zip']").click();
});
// Save downloaded file somewhere
download.saveAs(Paths.get("C:\\Users\\dheer\\Desktop\\Personal\\chromedriver.zip"));
page.onDownload(d -> System.out.println(d.path()));
page.close();
browser.close();
playwright.close();
}
//launch browser in full size
@Test
public void test13() {
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
int width =(int)screensize.getWidth();
int height =(int)screensize.getHeight();
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
BrowserContext bcontext = browser.newContext(new Browser.NewContextOptions().setViewportSize(width,height));
Page page = bcontext.newPage();
page.navigate("https://www.amazon.com");
page.close();
browser.close();
playwright.close();
}
//recording videos
@Test
public void test14() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
BrowserContext bcontext = browser.newContext(new Browser.NewContextOptions()
.setRecordVideoDir(Paths.get("videos/test"))
.setRecordVideoSize(400, 480));
Page page = bcontext.newPage();
page.navigate("https://www.amazon.com");
page.close();
browser.close();
playwright.close();
}
//Handle browser window popup and new tab
@Test
public void test15() {
Playwright playwright = Playwright.create();
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setChannel("chrome").setHeadless(false));
BrowserContext bcontext =browser.newContext();
Page page = bcontext.newPage();
page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
// Get popup after a specific action (e.g., click)
Page popup = page.waitForPopup(() -> {
page.locator("//a[@href='https://twitter.com/orangehrm?lang=en']").click();
});
popup.waitForLoadState();
System.out.println(popup.title());
popup.locator("text=Create account").click();
popup.close();
page.locator("//a[@href='https://www.facebook.com/OrangeHRM/']").click();
page.close();
browser.close();
playwright.close();
}
}
Q: How to test API in Playwright ?
Ans:
package com.qa.app.tests;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.APIRequestContext;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.RequestOptions;
import com.qa.app.utilities.Userdetails;
import com.qa.app.utilities.UserswithLombok;
import org.testng.Assert;
import org.testng.annotations.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class PlaywrightAPI {
APIResponse responce;
APIRequestContext apireqContext;
Playwright playwright;
Random random;
@BeforeTest
public void setup()
{
playwright = Playwright.create();
APIRequest req = playwright.request();
apireqContext = req.newContext();
random = new Random();
}
//get request
@Test
public void APItest1() {
responce = apireqContext.get("https://gorest.co.in/public/v2/users");
System.out.println(responce.status());
Assert.assertEquals(responce.status(),200);
System.out.println(responce.text());
}
//setup query parameter
@Test
public void APItest2() {
responce = apireqContext.get("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setQueryParam("id",3944119)
.setQueryParam("status","inactive"));
System.out.println(responce.status());
Assert.assertEquals(responce.status(),200);
System.out.println(responce.text());
}
//get response in json format
@Test
public void APItest3() throws IOException {
responce = apireqContext.get("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setQueryParam("id",3944119)
.setQueryParam("status","inactive"));
System.out.println(responce.status());
ObjectMapper objtmap = new ObjectMapper();
JsonNode jsonparser =objtmap.readTree(responce.body());
System.out.println(jsonparser.toPrettyString());
}
// using dispose method
@Test
public void APItest4() throws IOException {
responce = apireqContext.get("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setQueryParam("id",3944119)
.setQueryParam("status","inactive"));
responce.dispose(); //dispose only the response body but status code, url , status text will be same
System.out.println(responce.status());
}
//capture the headers from the response
@Test
public void APItest5() throws IOException {
responce = apireqContext.get("https://gorest.co.in/public/v2/users");
responce.headers().forEach((e,v)->System.out.println(e+":"+v));
System.out.println("=====================================");
responce.headersArray().forEach((e)->System.out.println(e.name+": "+e.value));
}
//use post call with hashmap
@Test
public void APItest6() throws IOException {
Map<String,Object> data =new HashMap<>();
data.put("name","testngPW");
data.put("email","test"+random.nextInt(1000)+"@gmail.com");
data.put("gender","male");
data.put("status","active");
responce = apireqContext.post("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setHeader("Content-Type","application/json")
.setHeader("Authorization","Bearer e2c642609a587b4ef1f496ecf10b26fe8e3073e96977417f564cd4a1347da8c4")
.setData(data));
Assert.assertEquals(responce.status(),201);
System.out.println(responce.text());
Assert.assertEquals(responce.statusText(),"Created");
ObjectMapper objtmap = new ObjectMapper();
JsonNode jsonparser =objtmap.readTree(responce.body());
System.out.println(jsonparser.get("id").asText());
responce = apireqContext.get("https://gorest.co.in/public/v2/users/"+jsonparser.get("id").asText(), RequestOptions.create()
.setHeader("Authorization","Bearer e2c642609a587b4ef1f496ecf10b26fe8e3073e96977417f564cd4a1347da8c4"));
Assert.assertEquals(responce.status(),200);
Assert.assertEquals(responce.statusText(),"OK");
ObjectMapper objtmap1 = new ObjectMapper();
JsonNode jsonparser1 =objtmap.readTree(responce.body());
System.out.println(jsonparser1.get("email").asText());
}
//use post call with json File -> method 1
@Test
public void APItest7() throws IOException {
byte[] filebyte=null;
File file = new File("./src/test/Data/user.json");
filebyte = Files.readAllBytes(file.toPath());
responce = apireqContext.post("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setHeader("Content-Type","application/json")
.setHeader("Authorization","Bearer e2c642609a587b4ef1f496ecf10b26fe8e3073e96977417f564cd4a1347da8c4")
.setData(filebyte));
Assert.assertEquals(responce.status(),201);
System.out.println(responce.text());
Assert.assertEquals(responce.statusText(),"Created");
ObjectMapper objtmap = new ObjectMapper();
JsonNode jsonparser =objtmap.readTree(responce.body());
System.out.println(jsonparser.get("id").asText());
}
//use post call with POJO class -> method 1
//Deserialization - > JSON to POJO class
@Test
public void APItest8() throws IOException {
Userdetails user = new Userdetails("TestingAPIPOJo","test"+random.nextInt(1000)+"@gmail.com","active","male");
APIResponse responce1 = apireqContext.post("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setHeader("Content-Type","application/json")
.setHeader("Authorization","Bearer e2c642609a587b4ef1f496ecf10b26fe8e3073e96977417f564cd4a1347da8c4")
.setData(user));
Assert.assertEquals(responce1.status(),201);
System.out.println(responce1.text());
Assert.assertEquals(responce1.statusText(),"Created");
//convert response json to POJO
ObjectMapper objtmap1 = new ObjectMapper();
Userdetails actuser =objtmap1.readValue(responce1.text(),Userdetails.class);
System.out.println(actuser);
Assert.assertEquals(user.getEmail(),actuser.getEmail());
Assert.assertEquals(user.getGender(),actuser.getGender());
Assert.assertEquals(user.getStatus(),actuser.getStatus());
Assert.assertEquals(user.getStatus(),actuser.getStatus());
}
//use post call with POJO class -> method 1
//Deserialization - > JSON to POJO class using Lombok
@Test
public void APItest9() throws IOException {
UserswithLombok user = UserswithLombok.builder().name("TestingAPIPOJo")
.email("test"+random.nextInt(1000)+"@gmail.com")
.status("active")
.gender("male").build();
APIResponse responce1 = apireqContext.post("https://gorest.co.in/public/v2/users", RequestOptions.create()
.setHeader("Content-Type","application/json")
.setHeader("Authorization","Bearer e2c642609a587b4ef1f496ecf10b26fe8e3073e96977417f564cd4a1347da8c4")
.setData(user));
Assert.assertEquals(responce1.status(),201);
System.out.println(responce1.text());
Assert.assertEquals(responce1.statusText(),"Created");
//convert response json to POJO
ObjectMapper objtmap1 = new ObjectMapper();
Userdetails actuser =objtmap1.readValue(responce1.text(),Userdetails.class);
System.out.println(actuser);
Assert.assertEquals(user.getEmail(),actuser.getEmail());
Assert.assertEquals(user.getGender(),actuser.getGender());
Assert.assertEquals(user.getStatus(),actuser.getStatus());
Assert.assertEquals(user.getStatus(),actuser.getStatus());
}
@AfterTest
public void Finally() {
playwright.close();
}
}
Comments
Post a Comment