Friday, 2 June 2023

Playwright: get the locator by label text

Using 'page.getByLabel()' method, we can interact with an element using label text.

 

For example, we can use this method to fill the text field data, to locate a radio button by associated label text etc.,

 

Example

page.getByLabel("Java").click();

 

Above snippet click on the element associated with given label. For example, if the label is associated with the radio button, the it select it.

 

Find the below working application.

 

labelDemo.html

<!DOCTYPE html>
<html>

<body>

	<h1>User favorite language form</h1>

	<p>Select one of your favorite language and click on submit button</p>

	<form onsubmit="return false;">
		  <input type="radio" id="java" name="my_fav_language" value="Java">
		  <label for="java">Java</label><br>

		  <input type="radio" id="go" name="my_fav_language" value="Go">
		  <label for="go">Go</label><br>

		  <input type="radio" id="python" name="my_fav_language" value="Python">
		  <label for="python">Python</label><br><br>

		<input type="submit" value="submit" onclick="display()">
	</form>

	<p id="result"></p>

	<script>
		function display() {
			let result = document.getElementById("result");
			let selectedValue = document.querySelector('input[name="my_fav_language"]:checked').value;
			result.innerHTML = `<b>Your favourite language is :  ${selectedValue}</b>`
		}
	</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();
		}

	}
}

GetByLabel.java

package com.sample.app.locators;

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.Playwright;
import com.sample.app.util.FileUtil;

public class GetByLabel {

	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("locators" + File.separator + "labelDemo.html");

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

			page.getByLabel("Java").click();
			page.locator("input[type=\"submit\"]").click();

			String textContent = page.locator("id=result").textContent();
			System.out.println(textContent);
		}
	}

}

Output

Your favourite language is :  Java


 

Previous                                                 Next                                                 Home

PlantUML: Draw many to many relationship in class diagram

To model many to many relationship, you can use double-quotes "" on each side of the relation.

 

Example

Student "0..*" -- "1..*" Course

 


manyToMany.txt

@startuml

title "Class Composition"

class Student
class Course

Student "0..*" -- "1..*" Course

@enduml

 


 

Previous                                                    Next                                                    Home

Thursday, 1 June 2023

PlantUML: Draw one to many relationship in class diagram

To model one to many relationship, you can use double-quotes "" on each side of the relation.

 

Example

Human "1" -- "many" BodyParts
Human "1" -- "1..*" BodyParts

Above one specifies that one human has many body parts.

 

oneToMany.txt

@startuml

title "Class Composition"

class Human

class BodyParts

Class Brain
class Lungs
class Liver
class Heart
class Stomach
class Kidney
class Bladder

class Frontal
class Parietal
class Temporal
class Occipital

Human "1" -- "many" BodyParts

BodyParts <|-- Brain : contains
BodyParts <|-- Lungs : contains
BodyParts <|-- Liver : contains
BodyParts <|-- Heart : contains
BodyParts <|-- Stomach : contains
BodyParts <|-- Kidney : contains
BodyParts <|-- Bladder : contains

Brain *-- Frontal : contains
Brain *-- Parietal : contains
Brain *-- Temporal : contains
Brain *-- Occipital : contains

@enduml

Above snippet generate below diagram.





 

Previous                                                    Next                                                    Home

Playwright: Locate the element by text content

Using page.getByText() method, we can locate the elements by text content.

 

Signature

Locator getByText(String text)
Locator getByText(String text, GetByTextOptions options)
Locator getByText(Pattern text)
Locator getByText(Pattern text, GetByTextOptions options)

 

Example

page.getByText("Hello there!!!").allTextContents();

Pattern helloPattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
page.getByText(helloPattern).allTextContents();

page.getByText("hello", new Page.GetByTextOptions().setExact(true)).allTextContents()

Find the below working application.

 

locatorByTextContent.html

<!DOCTYPE html>
<html>

<body>

	<h1>Page text content demo</h1>

	<p>hello world!!!!</p>
	<p>Hello there!!!</p>
	<p>>Hey buddy</p>
	<p>say hello</p>
	<p>hello</p>
	<p>HELlo</p>
	
</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();
		}

	}
}

GetLocatorByTextContent.java

package com.sample.app.locators;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

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

public class GetLocatorByTextContent {
	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("locators" + File.separator + "locatorByTextContent.html");

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

			System.out.println("All the locators match to the text 'Hello there!!!'");
			List<String> textContent = page.getByText("Hello there!!!").allTextContents();
			for (String str : textContent) {
				System.out.println(str);
			}

			System.out.println("\nAll the locators contains the text 'hello' and case insensitive");
			Pattern helloPattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
			textContent = page.getByText(helloPattern).allTextContents();
			for (String str : textContent) {
				System.out.println(str);
			}

			System.out.println("\nAll the locators contains the text 'hello' only");
			textContent = page.getByText("hello", new Page.GetByTextOptions().setExact(true)).allTextContents();
			for (String str : textContent) {
				System.out.println(str);
			}

		}
	}
}

Output

All the locators match to the text 'Hello there!!!'
Hello there!!!

All the locators contains the text 'hello' case insensitive
hello world!!!!
Hello there!!!
say hello
hello
HELlo

All the locators contains the text 'hello' case insensitive
hello




Previous                                                 Next                                                 Home

Micronaut rest: test the hello world application

This is continution to my previous post. In this post, I am going to explain how to test the rest api.

 

API details are given below:

 

url: /welcome

method: GET

expectedMessage: Welcome to Micronaut app!!!!

 

Following snippet test the rest api /welcome.

@MicronautTest
public class WelcomeControllerTest {
	@Inject
	EmbeddedServer embeddedServer;

	@Inject
	@Client("/")
	HttpClient httpClient;

	@Test
	void testHelloWorldResponse() {
		String response = httpClient.toBlocking().retrieve(HttpRequest.GET("/welcome"));
		assertEquals("Welcome to Micronaut app!!!!", response);
	}
}

 

a. @MicronautTest can be applied to any JUnit 5 test to make it a Micronaut test.

b. EmbeddedServer is a general abstraction to manage the lifecycle of any server implementation within a running Micronaut application. Embedded server runs on a randomly available port.

c. HttpClient used to make the calls and the retrieve method returns the response of the controller as a String.

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-rest-hello-world-test’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-rest-hello-world-test</artifactId>
	<version>0.1</version>
	<packaging>jar</packaging>

	<parent>
		<groupId>io.micronaut</groupId>
		<artifactId>micronaut-parent</artifactId>
		<version>3.7.3</version>
	</parent>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>11</jdk.version>
		<release.version>11</release.version>
		<micronaut.version>3.7.3</micronaut.version>
		<micronaut.runtime>netty</micronaut.runtime>
		<exec.mainClass>com.sample.app.App</exec.mainClass>
	</properties>

	<repositories>
		<repository>
			<id>central</id>
			<url>https://repo.maven.apache.org/maven2</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-validation</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-client</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-server-netty</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-jackson-databind</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>jakarta.annotation</groupId>
			<artifactId>jakarta.annotation-api</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut.test</groupId>
			<artifactId>micronaut-test-junit5</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>io.micronaut.build</groupId>
				<artifactId>micronaut-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<!-- Uncomment to enable incremental compilation -->
					<!-- <useIncrementalCompilation>false</useIncrementalCompilation> -->

					<annotationProcessorPaths
						combine.children="append">
						<path>
							<groupId>io.micronaut</groupId>
							<artifactId>micronaut-http-validation</artifactId>
							<version>${micronaut.version}</version>
						</path>
					</annotationProcessorPaths>

				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

 

Step 3: Define WelcomeController class.

 

WelcomeController.java
package com.sample.app.controller;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/welcome")
public class WelcomeController {

	@Get(produces = MediaType.TEXT_PLAIN)
	public String index() {
		return "Welcome to Micronaut app!!!!";
	}
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import io.micronaut.runtime.Micronaut;

public class App {

	public static void main(String[] args) {
		Micronaut.run(App.class);
	}
}

Define WelcomeControllerTest class under src/test/java.

 

WelcomeControllerTest.java

package com.sample.app.controller;

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

import org.junit.jupiter.api.Test;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.runtime.server.EmbeddedServer;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;

@MicronautTest
public class WelcomeControllerTest {
	@Inject
	EmbeddedServer embeddedServer;

	@Inject
	@Client("/")
	HttpClient httpClient;

	@Test
	void testHelloWorldResponse() {
		String response = httpClient.toBlocking().retrieve(HttpRequest.GET("/welcome"));
		assertEquals("Welcome to Micronaut app!!!!", response);
	}
}

Total project structure looks like below.





How to run the test cases?

Navigate to the folder, where pom.xml is located and execute below command.

 

mvn test

 

You will see test results in the console.

[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  6.272 s
[INFO] Finished at: 2022-11-22T13:52:51+05:30
[INFO] ------------------------------------------------------------------------

 

You can download this application from this link.


 


 

Previous                                                    Next                                                    Home