Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
## Testing
This module contains articles about test libraries.
### Relevant articles
- [Introduction to Serenity BDD](https://www.baeldung.com/serenity-bdd)
- [Introduction to JSONassert](https://www.baeldung.com/jsonassert)
- [Serenity BDD and Screenplay](https://www.baeldung.com/serenity-screenplay)
- [Serenity BDD with Spring and JBehave](https://www.baeldung.com/serenity-spring-jbehave)
- [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing)
- [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly)
- [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide)
+5
View File
@@ -0,0 +1,5 @@
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
+171
View File
@@ -0,0 +1,171 @@
<?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>
<artifactId>libraries-testing</artifactId>
<name>libraries-testing</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-core</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-junit</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jbehave</artifactId>
<version>${serenity.jbehave.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-rest-assured</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-jira-requirements-provider</artifactId>
<version>${serenity.jira.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-spring</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-screenplay-webdriver</artifactId>
<version>${serenity.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>${jsonassert.version}</version>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility-proxy</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.specto</groupId>
<artifactId>hoverfly-java</artifactId>
<version>${hoverfly-java.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>${spring-mock-mvc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.7.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
<version>${serenity.plugin.version}</version>
<executions>
<execution>
<id>serenity-reports</id>
<phase>post-integration-test</phase>
<goals>
<goal>aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<serenity.version>1.9.9</serenity.version>
<serenity.jbehave.version>1.9.0</serenity.jbehave.version>
<serenity.jira.version>1.9.0</serenity.jira.version>
<serenity.plugin.version>1.9.27</serenity.plugin.version>
<jsonassert.version>1.5.0</jsonassert.version>
<awaitility.version>3.0.0</awaitility.version>
<hoverfly-java.version>0.8.1</hoverfly-java.version>
<spring.version>4.3.8.RELEASE</spring.version>
<spring-mock-mvc.version>4.1.1</spring-mock-mvc.version>
<assertj.version>3.6.2</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties>
</project>
+4
View File
@@ -0,0 +1,4 @@
jira.url=<jira-url>
jira.project=<jira-project>
jira.username=<jira-username>
jira.password=<jira-password>
@@ -0,0 +1,52 @@
package com.baeldung.awaitility;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public class AsyncService {
private final int DELAY = 1000;
private final int INIT_DELAY = 2000;
private final AtomicLong value = new AtomicLong(0);
private final Executor executor = Executors.newFixedThreadPool(4);
private volatile boolean initialized = false;
void initialize() {
executor.execute(() -> {
sleep(INIT_DELAY);
initialized = true;
});
}
boolean isInitialized() {
return initialized;
}
void addValue(long val) {
throwIfNotInitialized();
executor.execute(() -> {
sleep(DELAY);
value.addAndGet(val);
});
}
public long getValue() {
throwIfNotInitialized();
return value.longValue();
}
private void sleep(int delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void throwIfNotInitialized() {
if (!initialized) {
throw new IllegalStateException("Service is not initialized");
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.serenity.github;
public class GitHubUser {
private String login;
public GitHubUser() {
super();
}
public String getLogin() {
return login;
}
public void setLogin(final String login) {
this.login = login;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.serenity.membership;
/**
* @author aiet
*/
public enum Commodity {
MacBookPro(1499), GoProHero5(400);
public final int price;
Commodity(int price) {
this.price = price;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.serenity.membership;
import static com.baeldung.serenity.membership.MemberGrade.Bronze;
import static com.baeldung.serenity.membership.MemberGrade.Gold;
import static com.baeldung.serenity.membership.MemberGrade.Silver;
/**
* @author aiet
*/
public class Member {
private int points;
private Member(int points) {
if (points < 0)
throw new IllegalArgumentException("points must not be negative!");
this.points = points;
}
public static Member withInitialPoints(int initialPoints) {
return new Member(initialPoints);
}
public MemberGrade getGrade() {
if (points < 1000)
return Bronze;
else if (points >= 1000 && points < 5000)
return Silver;
else
return Gold;
}
public void spend(int moneySpent) {
points += moneySpent / 10;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.serenity.membership;
/**
* @author aiet
*/
public enum MemberGrade {
Bronze, Silver, Gold;
}
@@ -0,0 +1,29 @@
package com.baeldung.serenity.spring;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/adder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class AdderController {
private AdderService adderService;
public AdderController(AdderService adderService) {
this.adderService = adderService;
}
@GetMapping("/current")
public int currentNum() {
return adderService.currentBase();
}
@PostMapping
public int add(@RequestParam int num) {
return adderService.add(num);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.serenity.spring;
import org.springframework.stereotype.Service;
@Service
public class AdderService {
private int num;
public void baseNum(int base) {
this.num = base;
}
public int currentBase() {
return num;
}
public int add(int adder) {
return this.num + adder;
}
public int accumulate(int adder) {
return this.num += adder;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.serenity.spring;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/adder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class PlainAdderController {
private final int currentNumber = RandomUtils.nextInt();
@GetMapping("/current")
public int currentNum() {
return currentNumber;
}
@PostMapping
public int add(@RequestParam int num) {
return currentNumber + num;
}
}
@@ -0,0 +1,77 @@
package com.baeldung.awaitility;
import org.awaitility.Duration;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.awaitility.Awaitility.fieldIn;
import static org.awaitility.Awaitility.given;
import static org.awaitility.Awaitility.setDefaultPollDelay;
import static org.awaitility.Awaitility.setDefaultPollInterval;
import static org.awaitility.Awaitility.setDefaultTimeout;
import static org.awaitility.proxy.AwaitilityClassProxy.to;
import static org.hamcrest.Matchers.equalTo;
public class AsyncServiceLongRunningManualTest {
private AsyncService asyncService;
@Before
public void setUp() {
asyncService = new AsyncService();
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs1() {
asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized;
await().until(isInitialized);
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize();
Callable<Boolean> isInitialized = asyncService::isInitialized;
await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized);
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() {
setDefaultPollInterval(10, TimeUnit.MILLISECONDS);
setDefaultPollDelay(Duration.ZERO);
setDefaultTimeout(Duration.ONE_MINUTE);
asyncService.initialize();
await().until(asyncService::isInitialized);
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs_withProxy() {
asyncService.initialize();
await().untilCall(to(asyncService).isInitialized(), equalTo(true));
}
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize();
await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true));
}
@Test
public void givenValue_whenAddValue_thenValueAdded() {
asyncService.initialize();
await().until(asyncService::isInitialized);
long value = 5;
asyncService.addValue(value);
await().until(asyncService::getValue, equalTo(value));
}
@Test
public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize();
given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L));
}
}
@@ -0,0 +1,33 @@
package com.baeldung.hamcrest;
public class Animal {
String name;
boolean wild;
String sound;
public Animal(String name, boolean wild, String sound) {
super();
this.name = name;
this.wild = wild;
this.sound = sound;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isWild() {
return wild;
}
public void setWild(boolean wild) {
this.wild = wild;
}
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.hamcrest;
public class Cat extends Animal {
public Cat() {
super("cat", false, "meow");
}
public String makeSound() {
return getSound();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.hamcrest;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
public class IsPositiveInteger extends TypeSafeMatcher<Integer> {
public void describeTo(Description description) {
description.appendText("a positive integer");
}
@Factory
public static Matcher<Integer> isAPositiveInteger() {
return new IsPositiveInteger();
}
@Override
protected boolean matchesSafely(Integer integer) {
return integer > 0;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.hamcrest;
public class Person {
String name;
String address;
public Person(String personName, String personAddress) {
name = personName;
address = personAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
String str="[address:"+address+",name:"+name+"]";
return str;
}
}
@@ -0,0 +1,112 @@
package com.baeldung.hoverfly;
import static io.specto.hoverfly.junit.core.SimulationSource.dsl;
import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service;
import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes;
import static io.specto.hoverfly.junit.dsl.ResponseCreators.success;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiLiveTest {
private static final SimulationSource source = dsl(service("http://www.baeldung.com").get("/api/courses/1").willReturn(success().body(jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
.post("/api/courses").willReturn(success())
.andDelay(3, TimeUnit.SECONDS).forMethod("POST"),
service(matches("www.*dung.com")).get(startsWith("/api/student")).queryParam("page", any()).willReturn(success())
.post(equalsTo("/api/student")).body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))).willReturn(success())
.put("/api/student/1").body(matchesJsonPath("$.name")).willReturn(success())
.post("/api/student").body(equalsToXml("<student><id>2</id><name>John</name></student>")).willReturn(success())
.put("/api/student/2").body(matchesXPath("/student/name")).willReturn(success()));
@ClassRule
public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source);
private final RestTemplate restTemplate = new RestTemplate();
@Test
public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<String> courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
}
@Test
public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/courses", null, Void.class);
stopWatch.stop();
long postTime = stopWatch.getTime();
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime));
}
@Test
public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<Void> courseResponse = restTemplate.getForEntity("http://www.baeldung.com/api/student?page=3", Void.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/1")).body("{\"id\":\"1\",\"name\":\"Trevor\"}");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity("http://www.baeldung.com/api/student", "<student><id>2</id><name>John</name></student>", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity.put(new URI("http://www.baeldung.com/api/student/2")).body("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<student><id>2</id><name>Monica</name></student>");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
}
@@ -0,0 +1,113 @@
package com.baeldung.jsonassert;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.skyscreamer.jsonassert.Customization;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.RegularExpressionValueMatcher;
import org.skyscreamer.jsonassert.comparator.ArraySizeComparator;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import static org.assertj.core.api.Assertions.assertThat;
public class JsonAssertUnitTest {
@Test
public void givenLenientode_whenAssertEqualsSameJsonString_thenPass() throws JSONException {
String actual = "{id:123,name:\"John\"}";
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
actual = "{id:123,name:\"John\",zip:\"33025\"}";
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
}
@Test
public void givenStrictMode_whenAssertNotEqualsExtendedJsonString_thenPass() throws JSONException {
String actual = "{id:123,name:\"John\"}";
JSONAssert.assertNotEquals("{name:\"John\"}", actual, JSONCompareMode.STRICT);
}
@Test
public void whenUsingCompareModeOrBoolean_thenBothAreSame() throws JSONException {
String actual = "{id:123,name:\"John\",zip:\"33025\"}";
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
JSONAssert.assertEquals("{id:123,name:\"John\"}", actual, false);
actual = "{id:123,name:\"John\"}";
JSONAssert.assertNotEquals("{name:\"John\"}", actual, JSONCompareMode.STRICT);
JSONAssert.assertNotEquals("{name:\"John\"}", actual, true);
}
@Test
public void givenDifferentOrderForJsonObject_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"John\"}";
JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.STRICT);
JSONAssert.assertEquals("{name:\"John\",id:1}", result, JSONCompareMode.LENIENT);
}
@Test
public void givenDifferentTypes_whenAssertEqualsSameValue_thenPass() throws JSONException {
JSONObject expected = new JSONObject();
JSONObject actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12345));
JSONAssert.assertEquals(expected, actual, false);
JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT);
}
@Test
public void givenNestedObjects_whenAssertEquals_thenPass() throws JSONException {
String result = "{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}";
JSONAssert.assertEquals("{id:1,name:\"Juergen\", address:{city:\"Hollywood\", " + "state:\"LA\", zip:91601}}", result, false);
}
@Test
public void whenMessageUsedInAssertion_thenDisplayMessageOnFailure() throws JSONException {
String actual = "{id:123,name:\"John\"}";
String failureMessage = "Only one field is expected: name";
try {
JSONAssert.assertEquals(failureMessage, "{name:\"John\"}", actual, JSONCompareMode.STRICT);
} catch (AssertionError ae) {
assertThat(ae.getMessage()).containsIgnoringCase(failureMessage);
}
}
@Test
public void givenArray_whenComparing_thenOrderMustMatchForStrict() throws JSONException {
String result = "[Alex, Barbera, Charlie, Xavier]";
JSONAssert.assertEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.LENIENT);
JSONAssert.assertEquals("[Alex, Barbera, Charlie, Xavier]", result, JSONCompareMode.STRICT);
JSONAssert.assertNotEquals("[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.STRICT);
}
@Test
public void givenArray_whenComparingExtended_thenNotEqual() throws JSONException {
String result = "[1,2,3,4,5]";
JSONAssert.assertEquals("[1,2,3,4,5]", result, JSONCompareMode.LENIENT);
JSONAssert.assertNotEquals("[1,2,3]", result, JSONCompareMode.LENIENT);
JSONAssert.assertNotEquals("[1,2,3,4,5,6]", result, JSONCompareMode.LENIENT);
}
@Test
public void whenComparingSizeOfArray_thenPass() throws JSONException {
String names = "{names:[Alex, Barbera, Charlie, Xavier]}";
JSONAssert.assertEquals("{names:[4]}", names, new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void whenComparingContentsOfArray_thenPass() throws JSONException {
String ratings = "{ratings:[3.2,3.5,4.1,5,1]}";
JSONAssert.assertEquals("{ratings:[1,5]}", ratings, new ArraySizeComparator(JSONCompareMode.LENIENT));
}
@Test
public void givenValueMatcher_whenComparingUsingRegex_thenPass() throws IllegalArgumentException, JSONException {
JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher<Object>("\\d"))));
JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", new CustomComparator(JSONCompareMode.STRICT, new Customization("entry.id", new RegularExpressionValueMatcher<Object>("\\d"))));
}
}
@@ -0,0 +1,7 @@
package com.baeldung.serenity;
import net.serenitybdd.jbehave.SerenityStory;
public class GithubUserProfilePayloadIntegrationTest extends SerenityStory {
}
@@ -0,0 +1,33 @@
package com.baeldung.serenity;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
@RunWith(SerenityRunner.class)
public class GoogleSearchLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
browser.get("https://www.google.com/ncr");
browser.findElement(By.name("q")).sendKeys("baeldung", Keys.ENTER);
new WebDriverWait(browser, 5).until(visibilityOfElementLocated(By.cssSelector("._ksh")));
assertThat(browser.findElement(By.cssSelector("._ksh")).getText(), containsString("Eugen (Baeldung)"));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.serenity;
import com.baeldung.serenity.pageobjects.GoogleSearchPageObject;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Managed;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
@RunWith(SerenityRunner.class)
public class GoogleSearchPageObjectLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
private GoogleSearchPageObject googleSearch;
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
googleSearch.open();
googleSearch.searchFor("baeldung");
googleSearch.resultMatches("Eugen (Baeldung)");
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serenity;
import com.baeldung.serenity.screenplay.GoogleSearchResults;
import com.baeldung.serenity.screenplay.SearchForKeyword;
import com.baeldung.serenity.screenplay.StartWith;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.thucydides.core.annotations.Managed;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import static net.serenitybdd.screenplay.GivenWhenThen.givenThat;
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;
import static net.serenitybdd.screenplay.GivenWhenThen.then;
import static net.serenitybdd.screenplay.GivenWhenThen.when;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.hasItem;
@RunWith(SerenityRunner.class)
public class GoogleSearchScreenplayLiveTest {
@Managed(driver = "chrome")
private WebDriver browser;
private Actor kitty = Actor.named("kitty");
@Before
public void setup() {
kitty.can(BrowseTheWeb.with(browser));
}
@Test
public void whenGoogleBaeldungThenShouldSeeEugen() {
givenThat(kitty).wasAbleTo(StartWith.googleSearchPage());
when(kitty).attemptsTo(SearchForKeyword.of("baeldung"));
then(kitty).should(seeThat(GoogleSearchResults.displayed(), hasItem(containsString("Eugen (Baeldung)"))));
}
}
@@ -0,0 +1,73 @@
package com.baeldung.serenity;
import com.baeldung.serenity.membership.MemberStatusSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.baeldung.serenity.membership.Commodity.MacBookPro;
import static com.baeldung.serenity.membership.MemberGrade.Bronze;
import static com.baeldung.serenity.membership.MemberGrade.Gold;
import static com.baeldung.serenity.membership.MemberGrade.Silver;
@RunWith(SerenityRunner.class)
public class MemberStatusIntegrationTest {
@Steps
private MemberStatusSteps memberSteps;
@Test
public void membersShouldStartWithBronzeStatus() {
memberSteps.aClientJoinsTheMemberProgram();
memberSteps.theMemberShouldHaveAStatusOf(Bronze);
}
@Test
@Title("Members earn Silver grade after 1000 points ($10,000)")
public void earnsSilverAfterSpends$10000() {
memberSteps.aClientJoinsTheMemberProgram();
memberSteps.theMemberSpends(10_000);
memberSteps.theMemberShouldHaveAStatusOf(Silver);
}
@Test
@Title("Members with 2,000 points should earn Gold grade when added 3,000 points ($30,000)")
public void memberWith2000PointsEarnsGoldAfterSpends$30000() {
memberSteps.aMemberHasPointsOf(2000);
memberSteps.theMemberSpends(30_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
}
@Test
@Title("Members with 50,000 points can exchange a MacBook Pro")
public void memberWith50000PointsCanExchangeAMacbookpro() {
memberSteps.aMemberHasPointsOf(50_000);
memberSteps.aMemberExchangeA(MacBookPro);
memberSteps.memberShouldHavePointsLeft();
}
/**
* This test should fail, comment out <code>@Ignore</code> to see how failed test can be reflected in Serenity report. <br/>
*/
@Test
@Ignore
@Title("Members with 500 points should have a Gold status when added 4,000 points ($40,000)")
public void memberWith500PointsEarnsGoldAfterSpends$40000() {
memberSteps.aMemberHasPointsOf(500);
memberSteps.theMemberSpends(40_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
}
@Test
@Ignore
@Title("Members with 100 points would have a Gold status when added 10,000 points ($100,000)")
public void memberWith100EarnsGoldAfterSpends$100000() {
memberSteps.aMemberHasPointsOf(100);
memberSteps.theMemberSpends(100_000);
memberSteps.theMemberShouldHaveAStatusOf(Gold);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.serenity.github;
import net.thucydides.core.annotations.Step;
import org.hamcrest.Matchers;
import java.io.IOException;
import static net.serenitybdd.rest.SerenityRest.rest;
import static net.serenitybdd.rest.SerenityRest.then;
class GithubRestAssuredUserAPISteps {
private String api;
@Step("Given the github REST API for user profile")
void withUserProfileAPIEndpoint() {
api = "https://api.github.com/users/{username}";
}
@Step("When looking for {0} via the api")
void getProfileOfUser(String username) throws IOException {
rest().get(api, username);
}
@Step("Then there should be a login field with value {0} in payload of user {0}")
void profilePayloadShouldContainLoginValue(String username) {
then().body("login", Matchers.equalTo(username));
}
}
@@ -0,0 +1,48 @@
package com.baeldung.serenity.github;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.thucydides.core.annotations.Step;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.hamcrest.Matchers;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
public class GithubRestUserAPISteps {
private String api;
private GitHubUser resource;
@Step("Given the github REST API for user profile")
public void withUserProfileAPIEndpoint() {
api = "https://api.github.com/users/%s";
}
@Step("When looking for {0} via the api")
public void getProfileOfUser(String username) throws IOException {
HttpResponse httpResponse = getGithubUserProfile(api, username);
resource = retrieveResourceFromResponse(httpResponse, GitHubUser.class);
}
@Step("Then there should be a login field with value {0} in payload of user {0}")
public void profilePayloadShouldContainLoginValue(String username) {
assertThat(username, Matchers.is(resource.getLogin()));
}
private static <T> T retrieveResourceFromResponse(final HttpResponse response, final Class<T> clazz) throws IOException {
final String jsonFromResponse = EntityUtils.toString(response.getEntity());
final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(jsonFromResponse, clazz);
}
private static HttpResponse getGithubUserProfile(String api, String username) throws IOException {
HttpUriRequest request = new HttpGet(String.format(api, username));
return HttpClientBuilder.create().build().execute(request);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.serenity.github;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
public class GithubUserProfilePayloadStepDefinitions {
@Steps
private GithubRestAssuredUserAPISteps userAPISteps;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
userAPISteps.withUserProfileAPIEndpoint();
}
@When("looking for $user via the api")
public void whenLookingForProfileOf(String user) throws IOException {
userAPISteps.getProfileOfUser(user);
}
@Then("github's response contains a 'login' payload same as $user")
public void thenGithubsResponseContainsAloginPayloadSameAs(String user) {
userAPISteps.profilePayloadShouldContainLoginValue(user);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.serenity.membership;
import net.thucydides.core.annotations.Pending;
import net.thucydides.core.annotations.Step;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class MemberStatusSteps {
private Member member;
@Step("Given a member has {0} points")
public void aMemberHasPointsOf(int points) {
member = Member.withInitialPoints(points);
}
@Step("Then the member grade should be {0}")
public void theMemberShouldHaveAStatusOf(MemberGrade grade) {
assertThat(member.getGrade(), equalTo(grade));
}
@Step("When the member spends ${0} ")
public void theMemberSpends(int moneySpent) {
member.spend(moneySpent);
}
@Step("Given client joins membership program")
public void aClientJoinsTheMemberProgram() {
member = Member.withInitialPoints(0);
}
@Pending
@Step("When the member exchange {}")
public void aMemberExchangeA(Commodity commodity) {
// TODO
}
@Pending
@Step("Then the member should have points left")
public void memberShouldHavePointsLeft() {
}
}
@@ -0,0 +1,31 @@
package com.baeldung.serenity.pageobjects;
import net.thucydides.core.annotations.DefaultUrl;
import net.thucydides.core.pages.PageObject;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
@DefaultUrl("https://www.google.com/ncr")
public class GoogleSearchPageObject extends PageObject {
@FindBy(name = "q")
private WebElement search;
@FindBy(css = "._ksh")
private WebElement result;
public void searchFor(String keyword) {
search.sendKeys(keyword, Keys.ENTER);
}
public void resultMatches(String expected) {
withTimeoutOf(5, SECONDS).waitFor(result).waitUntilVisible();
assertThat(result.getText(), containsString(expected));
}
}

Some files were not shown because too many files have changed in this diff Show More