Spark graphx moved to a new project due to a incompatibility of scala compiler

This commit is contained in:
Norberto Ritzmann Jr
2019-10-06 21:57:54 +02:00
parent db85c8f275
commit 45be61376e
20299 changed files with 1635696 additions and 0 deletions
@@ -0,0 +1,13 @@
package com.baeldung.restassured;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,100 @@
package com.baeldung.restassured.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.restassured.model.Movie;
import com.baeldung.restassured.service.AppService;
@RestController
public class AppController {
@Autowired
AppService appService;
@GetMapping("/movies")
public ResponseEntity<?> getMovies() {
Set<Movie> result = appService.getAll();
return ResponseEntity.ok()
.body(result);
}
@PostMapping("/movie")
@ResponseStatus(HttpStatus.CREATED)
public Movie addMovie(@RequestBody Movie movie) {
appService.add(movie);
return movie;
}
@GetMapping("/movie/{id}")
public ResponseEntity<?> getMovie(@PathVariable int id) {
Movie movie = appService.findMovie(id);
if (movie == null) {
return ResponseEntity.badRequest()
.body("Invalid movie id");
}
return ResponseEntity.ok(movie);
}
@GetMapping("/welcome")
public ResponseEntity<?> welcome(HttpServletResponse response) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
headers.add("sessionId", UUID.randomUUID()
.toString());
Cookie cookie = new Cookie("token", "some-token");
cookie.setDomain("localhost");
response.addCookie(cookie);
return ResponseEntity.noContent()
.headers(headers)
.build();
}
@GetMapping("/download/{id}")
public ResponseEntity<Resource> getFile(@PathVariable int id) throws FileNotFoundException {
File file = appService.getFile(id);
if (file == null) {
return ResponseEntity.notFound()
.build();
}
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.restassured.learner;
class Course {
private String code;
public Course() {
}
Course(String code) {
this.code = code;
}
String getCode() {
return code;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.restassured.learner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping(path = "/courses")
public class CourseController {
private final CourseService courseService;
public CourseController(CourseService courseService) {
this.courseService = courseService;
}
@GetMapping(produces = APPLICATION_JSON_UTF8_VALUE)
public Collection<Course> getCourses() {
return courseService.getCourses();
}
@GetMapping(path = "/{code}", produces = APPLICATION_JSON_UTF8_VALUE)
public Course getCourse(@PathVariable String code) {
return courseService.getCourse(code);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.restassured.learner;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice(assignableTypes = CourseController.class)
public class CourseControllerExceptionHandler extends ResponseEntityExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(CourseNotFoundException.class)
@SuppressWarnings("ThrowablePrintedToSystemOut")
public void handleCourseNotFoundException(CourseNotFoundException cnfe) {
System.out.println(cnfe);
}
}
@@ -0,0 +1,8 @@
package com.baeldung.restassured.learner;
class CourseNotFoundException extends RuntimeException {
CourseNotFoundException(String code) {
super(code);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.restassured.learner;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
@Service
class CourseService {
private static final Map<String, Course> COURSE_MAP = new ConcurrentHashMap<>();
static {
Course wizardry = new Course("Wizardry");
COURSE_MAP.put(wizardry.getCode(), wizardry);
}
Collection<Course> getCourses() {
return COURSE_MAP.values();
}
Course getCourse(String code) {
return Optional.ofNullable(COURSE_MAP.get(code)).orElseThrow(() -> new CourseNotFoundException(code));
}
}
@@ -0,0 +1,58 @@
package com.baeldung.restassured.model;
public class Movie {
private Integer id;
private String name;
private String synopsis;
public Movie() {
}
public Movie(Integer id, String name, String synopsis) {
super();
this.id = id;
this.name = name;
this.synopsis = synopsis;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getSynopsis() {
return synopsis;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
@@ -0,0 +1,45 @@
package com.baeldung.restassured.service;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import com.baeldung.restassured.model.Movie;
@Service
public class AppService {
private Set<Movie> movieSet = new HashSet<>();
public Set<Movie> getAll() {
return movieSet;
}
public void add(Movie movie) {
movieSet.add(movie);
}
public Movie findMovie(int id) {
return movieSet.stream()
.filter(movie -> movie.getId()
.equals(id))
.findFirst()
.orElse(null);
}
public File getFile(int id) {
File file = null;
try {
file = new ClassPathResource(String.valueOf(id)).getFile();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
@@ -0,0 +1 @@
File 1
@@ -0,0 +1 @@
File 2
@@ -0,0 +1,49 @@
package com.baeldung.restassured;
public class Odd {
float price;
int status;
float ck;
String name;
Odd(float price, int status, float ck, String name) {
this.price = price;
this.status = status;
this.ck = ck;
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public float getCk() {
return ck;
}
public void setCk(float ck) {
this.ck = ck;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,67 @@
package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.with;
import static org.hamcrest.Matchers.hasItems;
public class RestAssured2IntegrationTest {
private static final int PORT = 8084;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String EVENTS_PATH = "/odds";
private static final String APPLICATION_JSON = "application/json";
private static final String ODDS = getJson();
@BeforeClass
public static void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
configureFor("localhost", PORT);
RestAssured.port = PORT;
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody(ODDS)));
stubFor(post(urlEqualTo("/odds/new"))
.withRequestBody(containing("{\"price\":5.25,\"status\":1,\"ck\":13.1,\"name\":\"X\"}"))
.willReturn(aResponse().withStatus(201)));
}
@Test
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
hasItems(5.25f, 1.2f));
}
@Test
public void whenRequestedPost_thenCreated() {
with().body(new Odd(5.25f, 1, 13.1f, "X"))
.when()
.request("POST", "/odds/new")
.then()
.statusCode(201);
}
private static String getJson() {
return Util.inputStreamToString(RestAssured2IntegrationTest.class
.getResourceAsStream("/odds.json"));
}
@AfterClass
public static void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
}
@@ -0,0 +1,139 @@
package com.baeldung.restassured;
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import io.restassured.RestAssured;
import io.restassured.http.Cookie;
import io.restassured.response.Response;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
public class RestAssuredAdvancedLiveTest {
@Before
public void setup(){
RestAssured.baseURI = "https://api.github.com";
RestAssured.port = 443;
}
@Test
public void whenMeasureResponseTime_thenOK(){
Response response = RestAssured.get("/users/eugenp");
long timeInMS = response.time();
long timeInS = response.timeIn(TimeUnit.SECONDS);
assertEquals(timeInS, timeInMS/1000);
}
@Test
public void whenValidateResponseTime_thenSuccess(){
when().get("/users/eugenp").then().time(lessThan(5000L));
}
@Test
public void whenValidateResponseTimeInSeconds_thenSuccess(){
when().get("/users/eugenp").then().time(lessThan(5L),TimeUnit.SECONDS);
}
//===== parameter
@Test
public void whenUseQueryParam_thenOK(){
given().queryParam("q", "john").when().get("/search/users").then().statusCode(200);
given().param("q", "john").when().get("/search/users").then().statusCode(200);
}
@Test
public void whenUseMultipleQueryParam_thenOK(){
int perPage = 20;
given().queryParam("q", "john").queryParam("per_page",perPage).when().get("/search/users").then().body("items.size()", is(perPage));
given().queryParams("q", "john","per_page",perPage).when().get("/search/users").then().body("items.size()", is(perPage));
}
@Test
public void whenUseFormParam_thenSuccess(){
given().log().all().formParams("username", "john","password","1234").post("/");
given().log().all().params("username", "john","password","1234").post("/");
}
@Test
public void whenUsePathParam_thenOK(){
given().pathParam("user", "eugenp").when().get("/users/{user}/repos").then().log().all().statusCode(200);
}
@Test
public void whenUseMultiplePathParam_thenOK(){
given().log().all().pathParams("owner", "eugenp","repo","tutorials").when().get("/repos/{owner}/{repo}").then().statusCode(200);
given().log().all().pathParams("owner", "eugenp").when().get("/repos/{owner}/{repo}","tutorials").then().statusCode(200);
}
//===== header
@Test
public void whenUseCustomHeader_thenOK(){
given().header("User-Agent", "MyAppName").when().get("/users/eugenp").then().statusCode(200);
}
@Test
public void whenUseMultipleHeaders_thenOK(){
given().header("User-Agent", "MyAppName","Accept-Charset","utf-8").when().get("/users/eugenp").then().statusCode(200);
}
//======= cookie
@Test
public void whenUseCookie_thenOK(){
given().cookie("session_id", "1234").when().get("/users/eugenp").then().statusCode(200);
}
@Test
public void whenUseCookieBuilder_thenOK(){
Cookie myCookie = new Cookie.Builder("session_id", "1234").setSecured(true).setComment("session id cookie").build();
given().cookie(myCookie).when().get("/users/eugenp").then().statusCode(200);
}
// ====== request
@Test
public void whenRequestGet_thenOK(){
when().request("GET", "/users/eugenp").then().statusCode(200);
}
@Test
public void whenRequestHead_thenOK(){
when().request("HEAD", "/users/eugenp").then().statusCode(200);
}
//======= log
@Test
public void whenLogRequest_thenOK(){
given().log().all().when().get("/users/eugenp").then().statusCode(200);
}
@Test
public void whenLogResponse_thenOK(){
when().get("/repos/eugenp/tutorials").then().log().body().statusCode(200);
}
@Test
public void whenLogResponseIfErrorOccurred_thenSuccess(){
when().get("/users/eugenp").then().log().ifError();
when().get("/users/eugenp").then().log().ifStatusCodeIsEqualTo(500);
when().get("/users/eugenp").then().log().ifStatusCodeMatches(greaterThan(200));
}
@Test
public void whenLogOnlyIfValidationFailed_thenSuccess(){
when().get("/users/eugenp").then().log().ifValidationFails().statusCode(200);
given().log().ifValidationFails().when().get("/users/eugenp").then().statusCode(200);
}
}
@@ -0,0 +1,105 @@
package com.baeldung.restassured;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
public class RestAssuredIntegrationTest {
private static final int PORT = 8083;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String EVENTS_PATH = "/events?id=390";
private static final String APPLICATION_JSON = "application/json";
private static final String GAME_ODDS = getEventJson();
@BeforeClass
public static void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
RestAssured.port = PORT;
configureFor("localhost", PORT);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody(GAME_ODDS)));
}
@Test
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
get("/events?id=390").then().assertThat()
.body("odd.ck", equalTo(12.2f));
}
@Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
get("/events?id=390").then().statusCode(200).assertThat()
.body("id", equalTo("390"));
}
@Test
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
get("/events?id=390").then().assertThat()
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
}
@Test
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
get("/events?id=390").then().assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json"));
}
@Test
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
.newBuilder()
.setValidationConfiguration(
ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV4)
.freeze()).freeze();
get("/events?id=390")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
jsonSchemaFactory));
}
@Test
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
get("/events?id=390")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
settings().with().checkedValidation(false)));
}
@AfterClass
public static void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
private static String getEventJson() {
return Util.inputStreamToString(RestAssuredIntegrationTest.class
.getResourceAsStream("/event_0.json"));
}
}
@@ -0,0 +1,55 @@
package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.hasItems;
public class RestAssuredXML2IntegrationTest {
private static final int PORT = 8082;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String EVENTS_PATH = "/teachers";
private static final String APPLICATION_XML = "application/xml";
private static final String TEACHERS = getXml();
@BeforeClass
public static void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
RestAssured.port = PORT;
configureFor("localhost", PORT);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(TEACHERS)));
}
@Test
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
get("/teachers")
.then()
.body("teachers.teacher.find { it.@department == 'science' }.subject",
hasItems("math", "physics"));
}
private static String getXml() {
return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class
.getResourceAsStream("/teachers.xml"));
}
@AfterClass
public static void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
}
@@ -0,0 +1,90 @@
package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.post;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
public class RestAssuredXMLIntegrationTest {
private static final int PORT = 8081;
private static WireMockServer wireMockServer = new WireMockServer(PORT);
private static final String EVENTS_PATH = "/employees";
private static final String APPLICATION_XML = "application/xml";
private static final String EMPLOYEES = getXml();
@BeforeClass
public static void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
configureFor("localhost", PORT);
RestAssured.port = PORT;
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(EMPLOYEES)));
}
@Test
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
post("/employees").then().assertThat()
.body("employees.employee.first-name", equalTo("Jane"));
}
@Test
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
post("/employees").then().assertThat()
.body("employees.employee.first-name", equalTo("Jane"))
.body("employees.employee.last-name", equalTo("Daisy"))
.body("employees.employee.sex", equalTo("f"));
}
@Test
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"),
"employees.employee.last-name", equalTo("Daisy"),
"employees.employee.sex", equalTo("f"));
}
@Test
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name",
containsString("Ja")));
}
@Test
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
}
private static String getXml() {
return Util
.inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml"));
}
@AfterClass
public static void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
}
@@ -0,0 +1,15 @@
package com.baeldung.restassured;
import java.io.InputStream;
import java.util.Scanner;
final class Util {
private Util() {
}
static String inputStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
@@ -0,0 +1,38 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
/**
* For this Live Test we need:
* * a running instance of the service located in the spring-security-rest-basic-auth module.
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-security-rest-basic-auth">spring-security-rest-basic-auth module</a>
*
*/
public class BasicAuthenticationLiveTest {
private static final String USER = "user1";
private static final String PASSWORD = "user1Pass";
private static final String SVC_URL = "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
get(SVC_URL).then()
.assertThat()
.statusCode(HttpStatus.UNAUTHORIZED.value());
}
@Test
public void givenBasicAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
given().auth()
.basic(USER, PASSWORD)
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value());
}
}
@@ -0,0 +1,56 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
/**
* For this Live Test we need:
* * a running instance of the service located in the spring-boot-admin/spring-boot-admin-server module.
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-boot-admin/spring-boot-admin-server">spring-boot-admin/spring-boot-admin-server module</a>
*
*/
public class BasicPreemtiveAuthenticationLiveTest {
private static final String USER = "admin";
private static final String PASSWORD = "admin";
private static final String SVC_URL = "http://localhost:8080/api/applications/";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
get(SVC_URL).then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(containsString("<form"), containsString("action=\"login\""));
}
@Test
public void givenNonPreemtiveBasicAuthentication_whenRequestSecuredResource_thenLoginPageRetrieved() {
given().auth()
.basic(USER, PASSWORD)
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(containsString("<form"), containsString("action=\"login\""));
}
@Test
public void givenPreemtiveBasicAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
given().auth()
.preemptive()
.basic(USER, PASSWORD)
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("size()", is(1));
}
}
@@ -0,0 +1,40 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
/**
* For this Live Test we need:
* * a running instance of the service located in the spring-security-mvc-digest-auth module.
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-security-mvc-digest-auth">spring-security-mvc-digest-auth module</a>
*
*/
public class DigestAuthenticationLiveTest {
private static final String USER = "user1";
private static final String PASSWORD = "user1Pass";
private static final String SVC_URL = "http://localhost:8080/spring-security-mvc-digest-auth/homepage.html";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
get(SVC_URL).then()
.assertThat()
.statusCode(HttpStatus.UNAUTHORIZED.value());
}
@Test
public void givenFormAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
given().auth()
.digest(USER, PASSWORD)
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(containsString("This is the body of the sample view"));
}
}
@@ -0,0 +1,57 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.isEmptyString;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import io.restassured.authentication.FormAuthConfig;
/**
* For this Live Test we need:
* * a running instance of the service located in the spring-security-mvc-login module.
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-security-mvc-login">spring-security-mvc-login module</a>
*
*/
public class FormAuthenticationLiveTest {
private static final String USER = "user1";
private static final String PASSWORD = "user1Pass";
private static final String SVC_URL = "http://localhost:8080/spring-security-mvc-login/secured";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenLoginFormResponse() {
get(SVC_URL).then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(containsString("<form"), containsString("action=\"perform_login\""));
}
@Test
public void givenParsingFormAuthentication_whenRequestSecuredResource_thenLoginFormResponse() {
// Form can't be parsed correctly because the app is in servlet container, thus the form's 'action' attribute doesn't include the correct URI
given().auth()
.form(USER, PASSWORD)
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(containsString("<form"), containsString("action=\"perform_login\""));
}
@Test
public void givenFormAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
given().auth()
.form(USER, PASSWORD, new FormAuthConfig("/spring-security-mvc-login/perform_login", "username", "password"))
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(isEmptyString());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
/**
* For this Live Test we need:
* * a running instance of the service located in the spring-boot-admin/spring-boot-admin-server module.
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-boot-admin/spring-boot-admin-server">spring-boot-admin/spring-boot-admin-server module</a>
*
*/
public class FormAutoconfAuthenticationLiveTest {
private static final String USER = "admin";
private static final String PASSWORD = "admin";
private static final String SVC_URL = "http://localhost:8080/ger1/api/applications/";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
get(SVC_URL).then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.content(containsString("<form"), containsString("action=\"login\""));
}
@Test
public void givenParsingFormAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
given().auth()
.form(USER, PASSWORD)
.when()
.get(SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("size()", is(1));
}
}
@@ -0,0 +1,61 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasKey;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
/**
* For this Live Test we need:
* * a running instance of the authorization server located in the spring-security-oauth repo - oauth-authorization-server module.
* @see <a href="https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-authorization-server">spring-security-oauth/oauth-authorization-server module</a>
*
* * a running instance of the service located in the spring-security-oauth repo - oauth-resource-server-1 module.
* @see <a href="https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-resource-server-1">spring-security-oauth/oauth-resource-server-1 module</a>
*
*/
public class OAuth2AuthenticationLiveTest {
private static final String USER = "john";
private static final String PASSWORD = "123";
private static final String CLIENT_ID = "fooClientIdPassword";
private static final String SECRET = "secret";
private static final String AUTH_SVC_TOKEN_URL = "http://localhost:8081/spring-security-oauth-server/oauth/token";
private static final String RESOURCE_SVC_URL = "http://localhost:8082/spring-security-oauth-resource/foos/1";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
get(RESOURCE_SVC_URL).then()
.assertThat()
.statusCode(HttpStatus.UNAUTHORIZED.value());
}
@Test
public void givenAccessTokenAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
String accessToken = given().auth()
.basic(CLIENT_ID, SECRET)
.formParam("grant_type", "password")
.formParam("username", USER)
.formParam("password", PASSWORD)
.formParam("scope", "read foo")
.when()
.post(AUTH_SVC_TOKEN_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.extract()
.path("access_token");
given().auth()
.oauth2(accessToken)
.when()
.get(RESOURCE_SVC_URL)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("$", hasKey("id"))
.body("$", hasKey("name"));
}
}
@@ -0,0 +1,53 @@
package com.baeldung.restassured.authentication;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasKey;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import io.restassured.http.ContentType;
/**
* For this Live Test we need to obtain a valid Access Token and Token Secret:
* * start spring-mvc-simple application in debug mode
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-mvc-simple">spring-mvc-simple module</a>
* * calling localhost:8080/spring-mvc-simple/twitter/authorization/ using the browser
* * debug the callback function where we can obtain the fields
*/
public class OAuthAuthenticationLiveTest {
// We can obtain these two from the spring-mvc-simple / TwitterController class
private static final String OAUTH_API_KEY = "PSRszoHhRDVhyo2RIkThEbWko";
private static final String OAUTH_API_SECRET = "prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL";
private static final String TWITTER_ENDPOINT = "https://api.twitter.com/1.1/account/settings.json";
/* We can obtain the following by:
* - starting the spring-mvc-simple application
* - calling localhost:8080/spring-mvc-simple/twitter/authorization/
* - debugging the callback function */
private static final String ACCESS_TOKEN = "...";
private static final String TOKEN_SECRET = "...";
@Test
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
get(TWITTER_ENDPOINT).then()
.assertThat()
.statusCode(HttpStatus.BAD_REQUEST.value());
}
@Test
public void givenAccessTokenAuthentication_whenRequestSecuredResource_thenResourceIsRequested() {
given().accept(ContentType.JSON)
.auth()
.oauth(OAUTH_API_KEY, OAUTH_API_SECRET, ACCESS_TOKEN, TOKEN_SECRET)
.when()
.get(TWITTER_ENDPOINT)
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("$", hasKey("geo_enabled"))
.body("$", hasKey("language"));
}
}
@@ -0,0 +1,149 @@
package com.baeldung.restassured.controller;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.restassured.model.Movie;
import com.baeldung.restassured.service.AppService;
import io.restassured.response.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AppControllerIntegrationTest {
@LocalServerPort
private int port;
private String uri;
@PostConstruct
public void init() {
uri = "http://localhost:" + port;
}
@MockBean
AppService appService;
@Test
public void givenMovieId_whenMakingGetRequestToMovieEndpoint_thenReturnMovie() {
Movie testMovie = new Movie(1, "movie1", "summary1");
when(appService.findMovie(1)).thenReturn(testMovie);
get(uri + "/movie/" + testMovie.getId()).then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("id", equalTo(testMovie.getId()))
.body("name", equalTo(testMovie.getName()))
.body("synopsis", notNullValue());
Movie result = get(uri + "/movie/" + testMovie.getId()).then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.extract()
.as(Movie.class);
assertThat(result).isEqualTo(testMovie);
String responseString = get(uri + "/movie/" + testMovie.getId()).then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.extract()
.asString();
assertThat(responseString).isNotEmpty();
}
@Test
public void whenCallingMoviesEndpoint_thenReturnAllMovies() {
Set<Movie> movieSet = new HashSet<>();
movieSet.add(new Movie(1, "movie1", "summary1"));
movieSet.add(new Movie(2, "movie2", "summary2"));
when(appService.getAll()).thenReturn(movieSet);
get(uri + "/movies").then()
.statusCode(HttpStatus.OK.value())
.assertThat()
.body("size()", is(2));
Movie[] movies = get(uri + "/movies").then()
.statusCode(200)
.extract()
.as(Movie[].class);
assertThat(movies.length).isEqualTo(2);
}
@Test
public void givenMovie_whenMakingPostRequestToMovieEndpoint_thenCorrect() {
Map<String, String> request = new HashMap<>();
request.put("id", "11");
request.put("name", "movie1");
request.put("synopsis", "summary1");
int movieId = given().contentType("application/json")
.body(request)
.when()
.post(uri + "/movie")
.then()
.assertThat()
.statusCode(HttpStatus.CREATED.value())
.extract()
.path("id");
assertThat(movieId).isEqualTo(11);
}
@Test
public void whenCallingWelcomeEndpoint_thenCorrect() {
get(uri + "/welcome").then()
.assertThat()
.header("sessionId", notNullValue())
.cookie("token", notNullValue());
Response response = get(uri + "/welcome");
String headerName = response.getHeader("sessionId");
String cookieValue = response.getCookie("token");
assertThat(headerName).isNotBlank();
assertThat(cookieValue).isNotBlank();
}
@Test
public void givenId_whenCallingDowloadEndpoint_thenCorrect() throws IOException {
File file = new ClassPathResource("test.txt").getFile();
long fileSize = file.length();
when(appService.getFile(1)).thenReturn(file);
byte[] result = get(uri + "/download/1").asByteArray();
assertThat(result.length).isEqualTo(fileSize);
}
}
@@ -0,0 +1,40 @@
package com.baeldung.restassured.learner;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class CourseControllerIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void initialiseRestAssuredMockMvcWebApplicationContext() {
RestAssuredMockMvc.webAppContextSetup(webApplicationContext);
}
@Test
public void givenNoMatchingCourseCodeWhenGetCourseThenRespondWithStatusNotFound() {
String nonMatchingCourseCode = "nonMatchingCourseCode";
given()
.when()
.get("/courses/" + nonMatchingCourseCode)
.then()
.log().ifValidationFails()
.statusCode(NOT_FOUND.value());
}
}
@@ -0,0 +1,63 @@
package com.baeldung.restassured.learner;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static io.restassured.http.ContentType.JSON;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.HttpStatus.OK;
@RunWith(MockitoJUnitRunner.class)
public class CourseControllerUnitTest {
@Mock
private CourseService courseService;
@InjectMocks
private CourseController courseController;
@InjectMocks
private CourseControllerExceptionHandler courseControllerExceptionHandler;
@Before
public void initialiseRestAssuredMockMvcStandalone() {
RestAssuredMockMvc.standaloneSetup(courseController, courseControllerExceptionHandler);
}
@Test
public void givenNoExistingCoursesWhenGetCoursesThenRespondWithStatusOkAndEmptyArray() {
when(courseService.getCourses()).thenReturn(Collections.emptyList());
given()
.when()
.get("/courses")
.then()
.log().ifValidationFails()
.statusCode(OK.value())
.contentType(JSON)
.body(is(equalTo("[]")));
}
@Test
public void givenNoMatchingCoursesWhenGetCoursesThenRespondWithStatusNotFound() {
String nonMatchingCourseCode = "nonMatchingCourseCode";
when(courseService.getCourse(nonMatchingCourseCode)).thenThrow(new CourseNotFoundException(nonMatchingCourseCode));
given()
.when()
.get("/courses/" + nonMatchingCourseCode)
.then()
.log().ifValidationFails()
.statusCode(NOT_FOUND.value());
}
}
@@ -0,0 +1,7 @@
<employees>
<employee category="skilled">
<first-name>Jane</first-name>
<last-name>Daisy</last-name>
<sex>f</sex>
</employee>
</employees>
@@ -0,0 +1,43 @@
{
"id": "390",
"odd": {
"price": "1.20",
"status": 2,
"ck": 12.2,
"name": "2"
},
"data": {
"countryId": 35,
"countryName": "Norway",
"leagueName": "Norway 3",
"status": 0,
"sportName": "Soccer",
"time": "2016-06-12T12:00:00Z"
},
"odds": [{
"price": "1.30",
"status": 0,
"ck": 12.2,
"name": "1"
},
{
"price":"5.25",
"status": 1,
"ck": 13.1,
"name": "X"
},
{
"price": "2.70",
"status": 0,
"ck": 12.2,
"name": "0"
},
{
"price": "1.20",
"status": 2,
"ck": 13.1,
"name": "2"
}
]
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,28 @@
{
"odds": [{
"price": 1.30,
"status": 0,
"ck": 12.2,
"name": "1"
},
{
"price": 5.25,
"status": 1,
"ck": 13.1,
"name": "X"
},
{
"price": 2.70,
"status": 0,
"ck": 12.2,
"name": "0"
},
{
"price": 1.20,
"status": 2,
"ck": 13.1,
"name": "2"
}
]
}
@@ -0,0 +1,10 @@
<teachers>
<teacher department="science" id='309'>
<subject>math</subject>
<subject>physics</subject>
</teacher>
<teacher department="arts" id='310'>
<subject>political education</subject>
<subject>english</subject>
</teacher>
</teachers>
@@ -0,0 +1 @@
Test file