Showing posts with label playwright. Show all posts
Showing posts with label playwright. Show all posts

Tuesday, 8 August 2023

Writing API tests in Playwright

Step 1: Define APIRequestContext.

APIRequestContext request = playwright
.request()
.newContext(new APIRequest
          .NewContextOptions()
          .setBaseURL("https://self-learning-java-tutorial.blogspot.com"));

 

Step 2: Get the APIResponse from the request object.

APIResponse apiResponse = request.get("/2015/10/gson-convert-json-to-hashmap.html");

Step 3: Now, you can apply assertion on the apiResponse object content.

int status = apiResponse.status();
assertEquals(200, status);

Find the below working application.

 

ApiTest.java

package com.sampe.app;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.APIRequestContext;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class ApiTest {

  private static Playwright playwright;
  private static Browser browser;

  // Get new instances for each call
  private BrowserContext context;
  private Page page;

  @BeforeAll
  static void launchBrowser() {
    playwright = Playwright.create();
    browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
  }

  @AfterAll
  static void closeBrowser() {
    playwright.close();
  }

  @BeforeEach
  void createContextAndPage() {
    context = browser.newContext();
    page = context.newPage();
  }

  @Test
  public void testAPI() {

    APIRequestContext request = playwright.request().newContext(
        new APIRequest.NewContextOptions().setBaseURL("https://self-learning-java-tutorial.blogspot.com"));

    APIResponse apiResponse = request.get("/2015/10/gson-convert-json-to-hashmap.html");

    int status = apiResponse.status();
    assertEquals(200, status);

    byte[] body = apiResponse.body();
    String str = new String(body);

    page.setContent(str);

    String title = page.locator("title").textContent();

    assertEquals("Programming for beginners: Gson: Convert Json to a HashMap", title.trim());

  }

}

 

Previous                                                 Next                                                 Home

Tuesday, 1 August 2023

How to Write Accessibility Tests in Playwright?

We can identify many type of accessibility issues in the web application using Playwright. You need to add below dependency to find accessibility issues.

<dependency>
  <groupId>com.deque.html.axe-core</groupId>
  <artifactId>playwright</artifactId>
  <version>4.5.1</version>
</dependency>

To scan entire webpage

page.navigate("https://self-learning-java-tutorial.blogspot.com/");
AxeResults accessibilityScanResults = new AxeBuilder(page).analyze();
List<Rule> violations = accessibilityScanResults.getViolations();

Find the below working application.

 

ScanEntirePage.java

package com.sample.app.accessibility;

import java.util.List;

import com.deque.html.axecore.playwright.AxeBuilder;
import com.deque.html.axecore.results.AxeResults;
import com.deque.html.axecore.results.Rule;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class ScanEntirePage {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium()
          .launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
      BrowserContext context = browser.newContext();
      Page page = context.newPage();

      page.navigate("https://self-learning-java-tutorial.blogspot.com/");
      AxeResults accessibilityScanResults = new AxeBuilder(page).analyze();

      List<Rule> violations = accessibilityScanResults.getViolations();
      for (Rule violation : violations) {
        System.out.println("impact : " + violation.getImpact());
        System.out.println("description : " + violation.getDescription());
      }

    }
  }
}

To scan specific part of a page

AxeResults accessibilityScanResults = new AxeBuilder(page)
  .include(Arrays.asList("#navbar-iframe-container"))
  .analyze();

ScanSpecificPartOfAPage.java

package com.sample.app.accessibility;

import java.util.Arrays;
import java.util.List;

import com.deque.html.axecore.playwright.AxeBuilder;
import com.deque.html.axecore.results.AxeResults;
import com.deque.html.axecore.results.Rule;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class ScanSpecificPartOfAPage {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium()
          .launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
      BrowserContext context = browser.newContext();
      Page page = context.newPage();

      page.navigate("https://self-learning-java-tutorial.blogspot.com/2014/11/pretty-print-json-format.html");
      AxeResults accessibilityScanResults = new AxeBuilder(page)
          .include(Arrays.asList("#navbar-iframe-container")).analyze();

      List<Rule> violations = accessibilityScanResults.getViolations();
      for (Rule violation : violations) {
        System.out.println("impact : " + violation.getImpact());
        System.out.println("description : " + violation.getDescription());
      }

    }
  }
}

Scanning for WCAG violations

AxeResults accessibilityScanResults = new AxeBuilder(page)
  .withTags(Arrays.asList("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))
  .analyze();

ScanWcagViolations.java

package com.sample.app.accessibility;

import java.util.Arrays;
import java.util.List;

import com.deque.html.axecore.playwright.AxeBuilder;
import com.deque.html.axecore.results.AxeResults;
import com.deque.html.axecore.results.Rule;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class ScanWcagViolations {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium()
          .launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
      BrowserContext context = browser.newContext();
      Page page = context.newPage();

      page.navigate("https://self-learning-java-tutorial.blogspot.com/2014/11/pretty-print-json-format.html");
      AxeResults accessibilityScanResults = new AxeBuilder(page)
          .withTags(Arrays.asList("wcag2a", "wcag2aa", "wcag21a", "wcag21aa")).analyze();

      List<Rule> violations = accessibilityScanResults.getViolations();
      for (Rule violation : violations) {
        System.out.println("impact : " + violation.getImpact());
        System.out.println("description : " + violation.getDescription());
        System.out.println("description : " + violation.getTags() + "\n");
      }

    }
  }
}

To exclude known elements from the scan

AxeResults accessibilityScanResults = new AxeBuilder(page)
  .exclude(Arrays.asList("#element-with-known-issue"))
  .analyze();

References

https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#axe-core-tags

https://playwright.dev/java/docs/accessibility-testing#example-accessibility-tests


 

Previous                                                 Next                                                 Home

Monday, 31 July 2023

Skelton for unit tests in PlayWright

HelloWorldTest.java

package com.sampe.app;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class HelloWorldTest {
  private static Playwright playwright;
  private static Browser browser;

  // Get new instances for each call
  private BrowserContext context;
  private Page page;

  @BeforeAll
  static void launchBrowser() {
    playwright = Playwright.create();
    browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
  }

  @AfterAll
  static void closeBrowser() {
    playwright.close();
  }

  @BeforeEach
  void createContextAndPage() {
    context = browser.newContext();
    page = context.newPage();
  }

  @Test
  public void testTitle() {
    page.navigate("https://self-learning-java-tutorial.blogspot.com/");
    assertEquals("Programming for beginners", page.title());
  }
}

 


Previous                                                 Next                                                 Home

Sunday, 30 July 2023

Playwright: resize the page

page.setViewportSize() method, we can set the page widht and height.

Signature

void setViewportSize(int width, int height)

 

Find the below working application.

 

PageResize.java
package com.sample.app.miscellaneous;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.concurrent.TimeUnit;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class PageResize {

  public static void main(String[] args) throws InterruptedException {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium()
          .launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
      Page page = browser.newPage();
      page.navigate("https://self-learning-java-tutorial.blogspot.com/");
      TimeUnit.SECONDS.sleep(3);

      System.out.println("Resizing the page");
      Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
      int screenWidth = dimension.width;
      int screenHeight = dimension.height;
      page.setViewportSize((screenWidth / 2), (screenHeight / 2));

      TimeUnit.SECONDS.sleep(3);
    }
  }

}

 

 

 

  

Previous                                                 Next                                                 Home

Friday, 28 July 2023

Playwright: wait for an element

Using page.waitForSelector() method, we can wait for the selector certain amount of time.

Example

page.waitForSelector("#result", waitForSelectorOptions)

Find the below working application.

 

waitForElement.html

<!DOCTYPE html>
<html>

<head> </head>

<body>


	See the result here

	<script>

		setTimeout(() => {
			const para = document.createElement("p");
			para.setAttribute("id", "result");
			document.body.appendChild(para);
			document.getElementById("result").innerHTML = "<b>Hello World</b>";
		}, 3000);

	</script>

</body>

</html>

FileUtil.java

package com.sample.app.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {
	
	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = FileUtil.class.getClassLoader();
		URL url = classLoader.getResource(resourceName);
		if (url == null) {
			return null;
		}

		URLConnection urlConnection = url.openConnection();

		urlConnection.setUseCaches(false);

		try (InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream())) {
			char[] buffer = new char[1048];
			StringBuilder builder = new StringBuilder();

			int count = -1;
			while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
				builder.append(buffer, 0, count);
			}

			return builder.toString();
		}

	}
}

WaitForAnElement.java

package com.sample.app.miscellaneous;

import java.io.File;
import java.io.IOException;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Page.WaitForSelectorOptions;
import com.microsoft.playwright.Playwright;
import com.sample.app.util.FileUtil;

public class WaitForAnElement {

	public static void main(String[] args) throws IOException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
			final String content = FileUtil.resourceAsString("miscellaneous" + File.separator + "waitForElement.html");

			Page page = browser.newPage();
			page.setContent(content);

			WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
			waitForSelectorOptions.setTimeout(5000);

			String resultData = page.waitForSelector("#result", waitForSelectorOptions).textContent();
			System.out.println(resultData);

		}
	}

}

Output

Hello World


 

Previous                                                 Next                                                 Home

Tuesday, 25 July 2023

Playwright: wait for the request and validate the response

Using 'page.waitForResponse()' method, we can wait until we receive a matching response.

Example

page.waitForResponse(response -> {
	String url = response.url();
	System.out.println("processed url : " + url);

	boolean isMatched = url.contains("google.com");

	if (isMatched) {
		System.out.println("Received matching response");
	}
	return isMatched;
}, () -> {
	page.navigate("https://self-learning-java-tutorial.blogspot.com/");
});

 

Above snippet wait until we process a response url that contains the string "google.com" in it.

 

Find the below working application.

 

WaitForResponse.java
package com.sample.app.miscellaneous;

import java.io.IOException;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class WaitForResponse {

	public static void main(String[] args) throws IOException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));

			Page page = browser.newPage();

			page.waitForResponse(response -> {
				String url = response.url();
				System.out.println("processed url : " + url);

				boolean isMatched = url.contains("google.com");

				if (isMatched) {
					System.out.println("Received matching response");
				}
				return isMatched;
			}, () -> {
				page.navigate("https://self-learning-java-tutorial.blogspot.com/");
			});

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

		}
	}

}

 

Output

processed url : https://self-learning-java-tutorial.blogspot.com/
processed url : https://self-learning-java-tutorial.blogspot.com/2014/02/blog-post.html
processed url : https://www.blogger.com/static/v1/widgets/2975350028-css_bundle_v2.css
processed url : https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js
processed url : https://apis.google.com/js/platform.js
Received matching response
title : Programming for beginners

 

 

Previous                                                 Next                                                 Home