Showing posts with label Test Automation. Show all posts
Showing posts with label Test Automation. Show all posts

Execute Playwright Script on Chrome Browser



When you execute a Playwright script on the Chrome browser, you are telling Playwright to launch tests on the real Chrome browser rather than the bundled Chromium. By default, Playwright uses Chromium, which is an open-source browser engine used by Chrome and Edge. However, if you specifically want to run on Google Chrome, Playwright allows you to configure it.


(1) Chromium vs Chrome

  • Chromium is the base project that Chrome is built on. Playwright ships with its own bundled version of Chromium.
  • Chrome is the actual browser installed on your system (with additional features, branding, and sometimes slight differences).

(2) How Playwright Handles Browsers

  • Playwright has built-in support for Chromium, Firefox, and WebKit.
  • For Chromium-based browsers, you can point Playwright to use either the bundled Chromium or your installed Chrome browser.
  • This is done by specifying the executable path of Chrome.

(3) Why Run Tests on Chrome?

  • Some projects or organizations require running automation scripts on the same browser version that end users use (i.e., Chrome instead of Playwright’s default Chromium).
  • This ensures compatibility testing with the actual Chrome build.
  • Running on Chrome may also be needed when browser policies, extensions, or enterprise configurations are involved.

(4) Process of Running on Chrome

  • Playwright launches Chrome using its Playwright API, but instead of the bundled Chromium, it points to the Chrome executable available on your machine.
  • Once launched, the script runs in the same way—navigating pages, finding locators, clicking elements, etc.—but all actions are now happening in the Google Chrome browser.

(5) Key Points

  • Execution on Chrome is nearly identical to execution on Chromium in terms of Playwright commands.
  • The main difference lies in specifying which browser binary to use.
  • After that, all locators, assertions, and interactions remain the same.


To execute a Playwright script in the Chrome browser using Java, you need to launch the browser in "Chrome" mode instead of the default "Chromium" (Playwright uses Chromium by default).









Steps to Run Playwright in Chrome (Java):

  • Install Chrome on your system (Playwright will launch the installed Chrome browser).
  • Set the executable path of Chrome.
  • Use launchPersistentContext with Chrome executable path to launch Chrome.
  • Write and run your Playwright Java test.


Maven Dependency

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.43.0</version> <!-- or latest -->
</dependency>




Java Code Example: Launch in Chrome

import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class PlaywrightChromeExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {

      // Path to the installed Chrome browser executable
      String chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"; // Adjust this path

      BrowserType.LaunchOptions options = new BrowserType.LaunchOptions()
        .setExecutablePath(Paths.get(chromePath))
        .setHeadless(false); // Show the browser window

      Browser browser = playwright.chromium().launch(options);
      Page page = browser.newPage();
      page.navigate("https://example.com");

      System.out.println("Page title: " + page.title());

      browser.close();
    }
  }
}



Code explanation:

(a) Create Playwright object
(b) Create Browser object
(c) Then, create Page object
(d) Navigate to webpage by page.navigate()
(e) Print page title on console

Overview of Playwright Framework

 



What is Playwright?

Playwright is an open-source end-to-end (E2E) automation testing framework developed by Microsoft. It is used to automate modern web applications across multiple browsers and platforms. Playwright provides APIs for automating Chromium (Chrome, Edge), Firefox, and WebKit (Safari) browsers using a single codebase.










Key Features of Playwright


FeatureDescription
Cross-browser testingSupports Chromium, Firefox, and WebKit with a unified API.
Cross-platformRuns on Windows, Linux, and macOS.
Auto-waitAutomatically waits for elements to be ready before performing actions.
Headless & Headful modesCan run in the background (headless) or visible mode (headful).
Multiple language supportOfficial support for JavaScript/TypeScript, Python, Java, and .NET.
Built-in test runnerIncludes its own Playwright Test runner for powerful parallel execution, retries, and test reporting.
Browser contextsIsolates test environments within the same browser instance to simulate multiple users.
Network & Geolocation mockingAllows simulation of network conditions and geolocation.
Visual comparisonsSupports screenshot and video capturing for visual regression testing.

Supported Browsers

  • Chromium (Google Chrome, Microsoft Edge)
  • Firefox
  • WebKit (Safari)

These are bundled with Playwright, so no need to install them manually.


Advanced Features

  • API Testing: Playwright can make HTTP requests and validate responses.
  • Mobile Emulation: Emulates mobile devices like iPhone, Pixel.
  • Component Testing: React, Angular, Vue component testing support.
  • CI/CD Integration: Jenkins, GitHub Actions, GitLab, Azure DevOps, etc.


Comparison: Playwright vs Selenium

FeaturePlaywrightSelenium
Modern web supportExcellentLimited in modern web features
SpeedFasterSlower
Auto-waitYesManual wait often required
Browser supportChromium, Firefox, WebKitAll major browsers
API TestingBuilt-inNeeds external tools
Built-in test runnerYesNo



Playwright generally used for:

  • Cross-browser UI Testing
  • Visual Regression Testing
  • API Testing
  • CI/CD pipeline automation
  • Mobile and geolocation testing
  • Real-time network condition simulation

You can go official website for more detail: 
https://playwright.dev/java/










Suggested Posts:

1. Handle Alerts in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright

How to Test Cookie based Authentication in API by Playwright




What are Cookies?

  • Cookies are small pieces of data stored by a web browser on the client side.
  • They are usually sent by the server in the HTTP response headers and stored by the browser.
  • On subsequent requests, the browser automatically attaches these cookies back to the server.
  • Cookies are used for:

        - Session management (login sessions, user preferences, shopping carts).

        - Personalization (themes, recommendations).

        - Tracking (analytics, advertising)


What is Cookie-Based Authentication?

  • Cookie-based authentication is a mechanism where the server authenticates a user and creates a session.
  • After successful login, the server generates a session ID and stores it in the server-side session storage.
  • This session ID is sent back to the client as a cookie.
  • For every subsequent request, the browser automatically sends this cookie back, allowing the server to recognize the authenticated user.

Steps in Cookie-Based Authentication:
  • User provides login credentials (username/password).
  • Server verifies credentials and creates a session on the backend.
  • Server sends a Set-Cookie header with a unique session ID to the client.
  • Browser stores the cookie.
  • For each new request, the browser includes the cookie in the Cookie header.
  • Server checks the cookie, validates the session, and grants access.


Handling Cookie-Based Authentication in Playwright (Java)

In Playwright automation, cookie-based authentication can be handled in two ways:

1. Manual Login Once & Reuse Cookies
  • Automate login once by filling in username/password and submitting.
  • After login, extract cookies from the browser context.
  • Save these cookies into a file (e.g., JSON format).
  • In subsequent tests, load these cookies into the browser context so you don’t need to log in again.
  • This makes tests faster and avoids hitting the login page repeatedly.
2. Programmatic Cookie Injection
  • If you already have valid cookies (from API calls or manual login), you can directly inject them into the browser context in Playwright.
  • This bypasses the UI login flow.
  • Once cookies are added, Playwright will automatically attach them to all requests, and the session will be authenticated.

Why This is Useful in Automation?
  • Efficiency: Skips repetitive login steps in test cases.
  • Stability: Reduces flakiness by avoiding multiple login UI interactions.
  • Scalability: Multiple test cases can reuse the same authenticated session.

To test cookie-based authentication in API using Playwright in Java, you need to simulate the process of login, capture the authentication cookies, reuse them for subsequent requests, and validate access to protected resources.









Concept: Cookie-Based Authentication

  • The user sends credentials via a login API (usually POST).
  • Server responds with a Set-Cookie header (usually a session or JWT cookie).
  • The browser stores this cookie and sends it with every subsequent request.
  • You can use Playwright to extract, reuse, and assert using these cookies.


Steps in Playwright Java

  • Launch browser.
  • Navigate to login API or page and perform login.
  • Extract cookies using context.cookies().
  • Store or reuse those cookies for a new context/page to access protected resources.

Example: Cookie-Based Login Simulation

Let’s use https://www.saucedemo.com/ for login.

You can use any backend which sets cookies, or mock a cookie manually for demonstration.







Java Code: Simulate Cookie Auth in Playwright

import com.microsoft.playwright.*;

import java.util.*;

public class CookieAuthTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Step 1: Navigate to website and simulate login
            page.navigate("https://www.saucedemo.com/");

            //Save cookies + localStorage/sessionStorage
            context.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get(storageStatePath)));
             

            // Simulate login (replace with actual selectors)
            page.locator("[name='user-name']").fill("standard_user");
            page.locator("[name='password']").fill("secret_sauce");
            page.locator("[name='login-button']").click();

            // Wait for navigation or successful login indication
            page.waitForURL("**/inventory.html");

            // Step 2: Extract cookies after login
            List<BrowserContext.Cookie> cookies = context.cookies();
            System.out.println("Extracted Cookies:");
            for (BrowserContext.Cookie cookie : cookies) {
                System.out.println(cookie.name + " = " + cookie.value);
            }

            // Step 3: Create new context with saved cookies (simulate another session)
            BrowserContext authContext = browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get(storageStatePath)));
            authContext.addCookies(cookies);

            Page authPage = authContext.newPage();
            authPage.navigate("https://www.saucedemo.com/inventory.html"); // Protected resource

            // Step 4: Verify protected content is accessible
            if (authPage.locator(".header_label>div").isVisible()) {
                System.out.println("Authentication successful using cookie!");
            } else {
                System.out.println("Authentication failed.");
            }

            browser.close();
        }
    }
}


Code Steps:

(a) Create Playwright, Browser, BrowserContext and Page object
(b) Save cookies + localStorage/sessionStorage
(c) Navigate to website and simulate login
(d) Simulate login (replace with actual selectors)
(e) Wait for navigation or successful login indication
(f) Extract cookies after login
(g) Create new context with saved cookies (simulate another session)
(h) Verify protected content is accessible



Explanation:

  • page.locator().fill() – Simulates user entering credentials.
  • context.cookies() – Gets all cookies after login.
  • authContext.addCookies(cookies) – Applies saved cookies to new context.
  • authPage.navigate() – Navigates to protected resource using cookie-based session.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright

How to Test Token based Authentication in API by Playwright




What is Token-based Authentication?

Token-based authentication is a method used to verify the identity of a user or system trying to access a protected resource (like an API or web application). Instead of repeatedly sending a username and password, the system issues a token (a unique string, often in the form of a JWT – JSON Web Token) after a successful login.


How it generally works:

  • Login: The user sends their credentials (username & password) to the authentication server.
  • Token Issuance: If valid, the server generates a token and sends it back to the client.
  • Token Usage: The client includes this token in the Authorization header (usually as Bearer <token>) for all subsequent requests.
  • Validation: The server validates the token and grants or denies access to protected resources.
  • Expiry & Refresh: Tokens often expire after some time, so refresh tokens may be used to obtain a new one without re-login.


How to Handle Token-based Authentication in Playwright Java

When automating scenarios with Playwright, token handling is key to bypass login screens or test APIs securely. Here’s how it is conceptually managed:


(1) Obtain Token Programmatically or Manually:
  • You can call the authentication API endpoint (using Java HTTP client or Playwright’s request context) with credentials and capture the token.
  • Alternatively, use a pre-generated token provided by the developer or QA team.
(2) Store Token in Test Context:
  • Keep the token in a variable or configuration file so it can be reused across requests and sessions.
(3) Attach Token to Requests:
  • Use Playwright’s APIRequestContext in Java to send API requests with headers that include the token (Authorization: Bearer <token>).
  • For browser-based flows, inject the token into browser storage:
       LocalStorage/SessionStorage: Save the token where the application expects it.
       Cookies: If the app stores the token in cookies, set them before navigating.

(4) Re-use Authenticated State:
  • Once the browser is authenticated with the token, Playwright allows saving that state (cookies, local storage).
  • This state can then be reused in subsequent tests to skip login repeatedly.
(5) Token Expiry Handling:
  • If the token expires, the automation should either:
        Request a new token before test execution, or
        Use a refresh token flow if supported.


To test token-based authentication in an API using Playwright in Java, you typically perform the following steps:











Workflow Explanation

  • Get the Authentication Token
    Send a POST (or appropriate) request to the authentication endpoint with credentials to get a token.
  • Use the Token in Headers
    For subsequent API calls, include the token in the Authorization header as a Bearer token.
  • Validate Response
    Use assertions to verify the status code and content of the protected endpoint's response.



Example Scenario

Let’s take an example of https://reqres.in/api/login which gives a token on successful login, and then use that token to call another API like https://reqres.in/api/users

https://reqres.in/api/login
















https://reqres.in/api/users














Maven Dependencies

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version> <!-- Use latest -->
</dependency>




Java Code: Token-based API Testing Using Playwright

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;

import java.util.*;

public class TokenBasedAuthTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            APIRequest request = playwright.request().newContext();

            // Step 1: Login to get the token
            APIResponse loginResponse = request.post("https://reqres.in/api/login", 
                RequestOptions.create()
                    .setHeader("Content-Type", "application/json")
                    .setData("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
            );

            if (loginResponse.status() != 200) {
                System.out.println("Login failed! Status: " + loginResponse.status());
                return;
            }

            // Extract token from response JSON
            String token = loginResponse.json().get("token").toString();
            System.out.println("Token received: " + token);

            // Step 2: Use token in Authorization header to call protected resource
            APIResponse userResponse = request.get("https://reqres.in/api/users/2", 
                RequestOptions.create()
                    .setHeader("Authorization", "Bearer " + token)
            );

            System.out.println("User API Status Code: " + userResponse.status());
            System.out.println("User API Response: " + userResponse.text());

            if (userResponse.status() == 200) {
                System.out.println("Token-based API access successful.");
            } else {
                System.out.println("Access failed.");
            }
        }
    }
}



Code Steps:

(a) Login to get the token
(b) Extract token from response JSON
(c) Use token in Authorization header to call protected resource


Explanation

  • playwright.request().newContext() → Creates a new API context.
  • loginResponse.json().get("token") → Extracts token from login response.
  • "Authorization": "Bearer " + token → Adds the token to the headers for authentication.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Cookie Based Authentication in Playwright
5. Basic Authentication in Playwright

Test Basic Authentication in API by Playwright




What is Basic authentication?

Basic Authentication is the process to verify a user by means of user's login credentials, it can be username and password. 


How Playwright Java Handles basic authentication?

Playwright provides a straightforward way to handle Basic Authentication by passing credentials when creating a BrowserContext.

  • A BrowserContext is like an isolated browser profile.
  • While creating the context, Playwright allows you to define HTTP credentials (username and password).
  • Once configured, every request made within that context automatically includes the necessary Authorization header, so you don’t need to manually handle it on each request.

Advantages of This Approach

  • No need to manually add headers for each request.
  • Works across all pages, frames, and API calls within the same context.
  • Ensures a secure and centralized way of handling credentials.















Steps:

  • Set up Playwright.
  • Create a new browser context with HTTP credentials.
  • Navigate to a website that requires basic authentication.
  • Assert the successful authentication.

We’ll use the website:
https://httpbin.org/basic-auth/user/passwd











It requires basic auth with:

  • Username: user

  • Password: passwd




Playwright Java Code Example:

import com.microsoft.playwright.*;

public class BasicAuthTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            // Create a browser
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Set up HTTP Basic Auth credentials
            Browser.NewContextOptions contextOptions = new Browser.NewContextOptions()
                    .setHttpCredentials("user", "passwd");  // username: user, password: passwd

            // Create browser context with credentials
            BrowserContext context = browser.newContext(contextOptions);

            // Open a new page
            Page page = context.newPage();

            // Navigate to the Basic Auth test URL
            page.navigate("https://httpbin.org/basic-auth/user/passwd");

            // Verify if authentication is successful
            String bodyText = page.textContent("body");
            if (bodyText.contains("\"authenticated\": true")) {
                System.out.println("Basic authentication successful!");
            } else {
                System.out.println("Basic authentication failed.");
            }

            // Close browser
            browser.close();
        }
    }
}



Code explanation:

(a) After creating Browser object, we have to setup HTTP basic auth credentials by setHttpCredentials()
(b) Create browser context with credentials
(c) Create Page object
(d) Navigate to the URL
(e) Verify if authentication is successful



Output:


Basic authentication successful!




Maven Dependencies:

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.44.0</version>
</dependency>