Use MockMvcTester where possible.

Migrated simple content, header, and status checks to AssertJ. Leaving more detailed JSON path evaluations as-is.

See #2486
This commit is contained in:
Mark Paluch
2025-05-19 11:39:46 +02:00
parent 3a6fdaea44
commit ed67846fe6
11 changed files with 217 additions and 215 deletions

View File

@@ -15,13 +15,13 @@
*/
package org.springframework.data.rest.webmvc.halexplorer;
import static org.hamcrest.CoreMatchers.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -30,12 +30,12 @@ import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@@ -67,51 +67,45 @@ class HalExplorerIntegrationTests {
@Autowired WebApplicationContext context;
MockMvc mvc;
MockMvcTester mvc;
@BeforeEach
void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(context).//
defaultRequest(get(BASE_PATH).accept(MediaType.TEXT_HTML)).build();
mvc = MockMvcTester.from(context);
}
@Test // DATAREST-293
void exposesJsonUnderApiRootByDefault() throws Exception {
void exposesJsonUnderApiRootByDefault() {
mvc.perform(get(BASE_PATH).accept(MediaType.ALL)).//
andExpect(status().isOk()).//
andExpect(header().string(HttpHeaders.CONTENT_TYPE, startsWith(MediaTypes.VND_HAL_JSON.toString())));
assertThat(mvc.perform(get(BASE_PATH).accept(MediaType.ALL))).hasStatusOk().hasHeader(HttpHeaders.CONTENT_TYPE,
MediaTypes.VND_HAL_JSON.toString());
}
@Test // DATAREST-293
void redirectsToBrowserForApiRootAndHtml() throws Exception {
void redirectsToBrowserForApiRootAndHtml() {
mvc.perform(get(BASE_PATH).accept(MediaType.TEXT_HTML)).//
andExpect(status().isFound()).//
andExpect(header().string(HttpHeaders.LOCATION, endsWith(TARGET)));
assertThat(mvc.perform(get(BASE_PATH).accept(MediaType.TEXT_HTML))).hasStatus(HttpStatus.FOUND)
.hasHeader(HttpHeaders.LOCATION, "http://localhost" + TARGET);
}
@Test // DATAREST-293
void forwardsBrowserToIndexHtml() throws Exception {
void forwardsBrowserToIndexHtml() {
mvc.perform(get(BASE_PATH.concat("/explorer"))).//
andExpect(status().isFound()).//
andExpect(header().string(HttpHeaders.LOCATION, endsWith(TARGET)));
assertThat(mvc.perform(get(BASE_PATH.concat("/explorer")))).hasStatus(HttpStatus.FOUND)
.hasHeader(HttpHeaders.LOCATION, "http://localhost" + TARGET);
}
@Test // DATAREST-293
void exposesHalBrowser() throws Exception {
void exposesHalBrowser() {
mvc.perform(get(BASE_PATH.concat("/explorer/index.html"))).//
andExpect(status().isOk()).//
andExpect(content().string(containsString("HAL Explorer")));
assertThat(mvc.perform(get(BASE_PATH.concat("/explorer/index.html")))).hasStatusOk().bodyText()
.contains("HAL Explorer");
}
@Test // DATAREST-293
void retrunsApiIfHtmlIsNotExplicitlyListed() throws Exception {
void retrunsApiIfHtmlIsNotExplicitlyListed() {
mvc.perform(get(BASE_PATH).accept(MediaType.APPLICATION_JSON, MediaType.ALL)).//
andExpect(status().isOk()).//
andExpect(header().string(HttpHeaders.CONTENT_TYPE, startsWith(MediaType.APPLICATION_JSON_VALUE)));
assertThat(mvc.perform(get(BASE_PATH).accept(MediaType.APPLICATION_JSON, MediaType.ALL))).hasStatusOk()
.hasHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
}
}

View File

@@ -16,9 +16,7 @@
package org.springframework.data.rest.tests;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.CoreMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import io.micrometer.observation.ObservationRegistry;
import jakarta.servlet.Filter;
@@ -37,12 +35,15 @@ import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.observation.ServerRequestObservationContext;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -51,6 +52,8 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.test.web.servlet.assertj.MvcTestResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
@@ -84,48 +87,48 @@ public abstract class AbstractWebIntegrationTests {
@Autowired LinkDiscoverers discoverers;
protected TestMvcClient client;
protected MockMvc mvc;
protected MockMvc mockMvc;
protected MockMvcTester mvc;
protected ServerRequestObservationContext observationContext;
@BeforeEach
public void setUp() {
setupMockMvc();
this.client = new TestMvcClient(mvc, discoverers);
this.client = new TestMvcClient(mockMvc, discoverers);
}
protected void setupMockMvc() {
this.mvc = MockMvcBuilders.webAppContextSetup(context) //
this.mockMvc = MockMvcBuilders.webAppContextSetup(context) //
.defaultRequest(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)) //
.addFilters(new FilterImplementation()) //
.build();
this.mvc = MockMvcTester.create(mockMvc);
}
protected MockHttpServletResponse postAndGet(Link link, Object payload, MediaType mediaType) throws Exception {
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
MockHttpServletResponse response = mvc.perform(post(href).content(payload.toString()).contentType(mediaType))//
.andExpect(status().isCreated())//
.andExpect(header().string("Location", is(notNullValue())))//
.andReturn().getResponse();
MvcTestResult result = mvc.perform(post(href).content(payload.toString()).contentType(mediaType));
assertThat(result).hasStatus(HttpStatus.CREATED).headers().containsHeader(HttpHeaders.LOCATION);
String content = response.getContentAsString();
String content = result.getResponse().getContentAsString();
if (StringUtils.hasText(content)) {
return response;
return result.getResponse();
}
return client.request(response.getHeader("Location"));
return client.request(result.getResponse().getHeader("Location"));
}
protected MockHttpServletResponse putAndGet(Link link, Object payload, MediaType mediaType) throws Exception {
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType))//
.andExpect(status().is2xxSuccessful())//
.andReturn().getResponse();
MvcTestResult result = mvc.perform(put(href).content(payload.toString()).contentType(mediaType));
assertThat(result).hasStatus2xxSuccessful();
MockHttpServletResponse response = result.getResponse();
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(link);
}
@@ -134,9 +137,10 @@ public abstract class AbstractWebIntegrationTests {
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
MockHttpServletResponse response = mvc.perform(put(href).content(payload.toString()).contentType(mediaType))//
.andExpect(status().is5xxServerError())//
.andReturn().getResponse();
MvcTestResult result = mvc.perform(put(href).content(payload.toString()).contentType(mediaType));
assertThat(result).hasStatus5xxServerError();
MockHttpServletResponse response = result.getResponse();
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(link);
}
@@ -145,9 +149,11 @@ public abstract class AbstractWebIntegrationTests {
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
MockHttpServletResponse response = mvc.perform(MockMvcRequestBuilders.request(HttpMethod.PATCH, href).//
content(payload.toString()).contentType(mediaType)).andExpect(status().is2xxSuccessful())//
.andReturn().getResponse();
MvcTestResult result = mvc.perform(MockMvcRequestBuilders.request(HttpMethod.PATCH, href).//
content(payload.toString()).contentType(mediaType));
assertThat(result).hasStatus2xxSuccessful();
MockHttpServletResponse response = result.getResponse();
return StringUtils.hasText(response.getContentAsString()) ? response : client.request(href);
}
@@ -156,13 +162,13 @@ public abstract class AbstractWebIntegrationTests {
String href = link.isTemplated() ? link.expand().getHref() : link.getHref();
mvc.perform(delete(href))//
.andExpect(status().isNoContent())//
.andReturn().getResponse();
MvcTestResult result = mvc.perform(delete(href));
assertThat(result).hasStatus(HttpStatus.NO_CONTENT);
MockHttpServletResponse response = result.getResponse();
// Check that the resource is unavailable after a DELETE
mvc.perform(get(href))//
.andExpect(status().isNotFound());
assertThat(mvc.perform(get(href))).hasStatus(HttpStatus.NOT_FOUND);//
}
protected Link assertHasContentLinkWithRel(LinkRelation relation, MockHttpServletResponse response) throws Exception {

View File

@@ -28,7 +28,7 @@ import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.data.rest.webmvc.RestMediaTypes;
import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
@@ -60,7 +60,8 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
@Test
void exposesRootResource() throws Exception {
ResultActions actions = mvc.perform(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE)).andExpect(status().isOk());
ResultActions actions = mockMvc.perform(get("/").accept(TestMvcClient.DEFAULT_MEDIA_TYPE))
.andExpect(status().isOk());
for (LinkRelation rel : expectedRootLinkRels()) {
actions.andExpect(client.hasLinkWithRel(rel));
@@ -85,7 +86,8 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
client.follow(profileLink).andExpect(status().is2xxSuccessful());
// JSON Schema
client.follow(profileLink, RestMediaTypes.SCHEMA_JSON).andExpect(status().is2xxSuccessful());
client.follow(profileLink, org.springframework.data.rest.webmvc.RestMediaTypes.SCHEMA_JSON)
.andExpect(status().is2xxSuccessful());
// ALPS
client.follow(profileLink, MediaTypes.ALPS_JSON).andExpect(status().is2xxSuccessful());
@@ -95,7 +97,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
@Test // DATAREST-203
void servesHalWhenRequested() throws Exception {
mvc.perform(get("/")). //
mockMvc.perform(get("/")). //
andExpect(content().contentTypeCompatibleWith(MediaTypes.HAL_JSON)). //
andExpect(jsonPath("$._links", notNullValue()));
}
@@ -103,7 +105,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
@Test // DATAREST-203
void servesHalWhenJsonIsRequested() throws Exception {
mvc.perform(get("/").accept(MediaType.APPLICATION_JSON)). //
mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)). //
andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)). //
andExpect(jsonPath("$._links", notNullValue()));
}
@@ -125,8 +127,8 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
try {
client.follow(it).//
andExpect(client.hasLinkWithRel(IanaLinkRelations.SELF)).//
andExpect(jsonPath("$.domainType").doesNotExist());
andExpect(client.hasLinkWithRel(IanaLinkRelations.SELF)).//
andExpect(jsonPath("$.domainType").doesNotExist());
} catch (Exception e) {
throw new RuntimeException(e);
@@ -156,7 +158,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
content(payload).//
contentType(MediaType.APPLICATION_JSON);
mvc.perform(request). //
mockMvc.perform(request). //
andExpect(status().isCreated());
}
}
@@ -196,7 +198,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
MockHttpServletResponse response = client.request("/");
Link profileLink = client.assertHasLinkWithRel(LinkRelation.of("profile"), response);
mvc.perform(//
mockMvc.perform(//
get(profileLink.expand().getHref()).//
accept(ALPS_MEDIA_TYPE))
.//
@@ -207,7 +209,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
@Test // DATAREST-448
void returnsNotFoundForUriNotBackedByARepository() throws Exception {
mvc.perform(get("/index.html")).//
mockMvc.perform(get("/index.html")).//
andExpect(status().isNotFound());
}
@@ -218,7 +220,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
Link link = client.discoverUnique(rel);
MockHttpServletResponse response = mvc.perform(head(link.expand().getHref()))//
MockHttpServletResponse response = mockMvc.perform(head(link.expand().getHref()))//
.andExpect(status().isNoContent())//
.andReturn().getResponse();
@@ -241,12 +243,12 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
// Try to find non existing resource
uri = uri.concat(id);
status = mvc.perform(get(URI.create(uri))).andReturn().getResponse().getStatus();
status = mockMvc.perform(get(URI.create(uri))).andReturn().getResponse().getStatus();
} while (status != HttpStatus.NOT_FOUND.value());
// PATCH to non-existing resource
mvc.perform(patch(URI.create(uri))).andExpect(status().isNotFound());
mockMvc.perform(patch(URI.create(uri))).andExpect(status().isNotFound());
}
@Test // DATAREST-1003
@@ -256,7 +258,7 @@ public abstract class CommonWebTests extends AbstractWebIntegrationTests {
Link link = client.discoverUnique(string);
mvc.perform(get(link.expand().getHref())//
mockMvc.perform(get(link.expand().getHref())//
.accept(MediaType.valueOf("application/schema+json")))//
.andExpect(status().isNotAcceptable());
}

View File

@@ -16,11 +16,10 @@
package org.springframework.data.rest.webmvc.jpa;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.tests.AbstractWebIntegrationTests;
@@ -34,6 +33,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.assertj.MvcTestResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -86,15 +86,17 @@ class CorsIntegrationTests extends AbstractWebIntegrationTests {
Link findItems = client.discoverUnique(LinkRelation.of("items"));
// Preflight request
String header = mvc
MvcTestResult result = mvc
.perform(options(findItems.expand().getHref()).header(HttpHeaders.ORIGIN, "http://far.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) //
.andExpect(status().isOk()) //
.andReturn().getResponse().getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS);
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"));
assertThat(header.split(","))
.containsExactlyInAnyOrderElementsOf(
RepositoryRestHandlerMapping.DEFAULT_ALLOWED_METHODS.map(HttpMethod::name));
assertThat(result).hasStatus2xxSuccessful();
String header = //
result.getResponse().getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS);
assertThat(header.split(",")).containsExactlyInAnyOrderElementsOf(
RepositoryRestHandlerMapping.DEFAULT_ALLOWED_METHODS.map(HttpMethod::name));
}
@Test // DATAREST-573
@@ -103,16 +105,16 @@ class CorsIntegrationTests extends AbstractWebIntegrationTests {
Link findBooks = client.discoverUnique(LinkRelation.of("books"));
// Preflight request
mvc.perform(options(findBooks.expand().getHref()).header(HttpHeaders.ORIGIN, "http://far.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) //
.andExpect(status().isOk()) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example")) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PUT,POST"));
assertThat(mvc.perform(options(findBooks.expand().getHref()).header(HttpHeaders.ORIGIN, "http://far.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PUT,POST");
// CORS request
mvc.perform(get(findBooks.expand().getHref()).header(HttpHeaders.ORIGIN, "http://far.far.example")) //
.andExpect(status().isOk()) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example"));
assertThat(mvc.perform(get(findBooks.expand().getHref()).header(HttpHeaders.ORIGIN, "http://far.far.example"))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example");
}
/**
@@ -122,21 +124,20 @@ class CorsIntegrationTests extends AbstractWebIntegrationTests {
void appliesCorsConfigurationOnCustomControllers() throws Exception {
// Preflight request
mvc.perform(options("/books/xml/1234") //
assertThat(mvc.perform(options("/books/xml/1234") //
.header(HttpHeaders.ORIGIN, "http://far.far.example") //
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) //
.andExpect(status().isOk()) //
.andExpect(header().longValue(HttpHeaders.ACCESS_CONTROL_MAX_AGE, 77123)) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example")) //
// See https://jira.spring.io/browse/SPR-14792
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, containsString("GET,PUT,POST")));
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "77123") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PUT,POST");
// CORS request
mvc.perform(get("/books/xml/1234") //
assertThat(mvc.perform(get("/books/xml/1234") //
.header(HttpHeaders.ORIGIN, "http://far.far.example") //
.accept(MediaType.APPLICATION_XML)) //
.andExpect(status().isOk()) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example"));
.accept(MediaType.APPLICATION_XML))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example");
}
/**
@@ -146,13 +147,12 @@ class CorsIntegrationTests extends AbstractWebIntegrationTests {
void appliesCorsConfigurationOnCustomControllerMethod() throws Exception {
// Preflight request
mvc.perform(options("/books/pdf/1234").header(HttpHeaders.ORIGIN, "http://far.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) //
.andExpect(status().isOk()) //
.andExpect(header().longValue(HttpHeaders.ACCESS_CONTROL_MAX_AGE, 4711)) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example")) //
// See https://jira.spring.io/browse/SPR-14792
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, containsString("GET,PUT,POST")));
assertThat(mvc.perform(options("/books/pdf/1234").header(HttpHeaders.ORIGIN, "http://far.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "4711") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://far.far.example") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PUT,POST");
}
@Test // DATAREST-573
@@ -161,25 +161,26 @@ class CorsIntegrationTests extends AbstractWebIntegrationTests {
Link authorsLink = client.discoverUnique(LinkRelation.of("authors"));
// Preflight request
mvc.perform(options(authorsLink.expand().getHref()).header(HttpHeaders.ORIGIN, "http://not.so.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) //
.andExpect(status().isOk()) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://not.so.far.example")) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PATCH,POST"));
assertThat(
mvc.perform(options(authorsLink.expand().getHref()).header(HttpHeaders.ORIGIN, "http://not.so.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://not.so.far.example") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PATCH,POST");
}
@Test // DATAREST-573
void appliesCorsConfigurationOnRepositoryToCustomControllers() throws Exception {
// Preflight request
mvc.perform(options("/authors/pdf/1234").header(HttpHeaders.ORIGIN, "http://not.so.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")) //
.andExpect(status().isOk()) //
.andExpect(header().longValue(HttpHeaders.ACCESS_CONTROL_MAX_AGE, 1234)) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://not.so.far.example")) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) //
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PATCH,POST"));
assertThat(mvc.perform(options("/authors/pdf/1234").header(HttpHeaders.ORIGIN, "http://not.so.far.example")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET"))) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1234") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://not.so.far.example") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,PATCH,POST");
}
@RepositoryRestController

View File

@@ -40,6 +40,7 @@ import org.springframework.hateoas.IanaLinkRelations;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkRelation;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.json.AbstractJsonContentAssert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@@ -114,18 +115,20 @@ class JpaDefaultPageableWebTests extends AbstractWebIntegrationTests {
}
@Test // DATAREST-906
void shouldApplyDefaultPageable() throws Exception {
void shouldApplyDefaultPageable() {
mvc.perform(get("/books/default-pageable"))//
.andExpect(jsonPath("$.content[0].sales").value(0)) //
.andExpect(jsonPath("$.size").value(1));
AbstractJsonContentAssert<?> json = assertThat(mvc.perform(get("/books/default-pageable")))//
.bodyJson();
json.extractingPath("$.content[0].sales").asNumber().isEqualTo(0);
json.extractingPath("$.size").asNumber().isEqualTo(1);
}
@Test // DATAREST-906
void shouldOverrideDefaultPageable() throws Exception {
void shouldOverrideDefaultPageable() {
mvc.perform(get("/books/default-pageable?size=10"))//
.andExpect(jsonPath("$.content[0].sales").value(0)) //
.andExpect(jsonPath("$.size").value(10));
AbstractJsonContentAssert<?> json = assertThat(mvc.perform(get("/books/default-pageable?size=10")))//
.bodyJson();
json.extractingPath("$.content[0].sales").asNumber().isEqualTo(0);
json.extractingPath("$.size").asNumber().isEqualTo(10);
}
}

View File

@@ -50,6 +50,7 @@ import org.springframework.hateoas.Links;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.server.LinkRelationProvider;
import org.springframework.hateoas.server.RepresentationModelProcessor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
@@ -144,7 +145,7 @@ public class JpaWebTests extends CommonWebTests {
@Test // DATAREST-99
void doesNotExposeCreditCardRepository() throws Exception {
mvc.perform(get("/")). //
mockMvc.perform(get("/")). //
andExpect(status().isOk()). //
andExpect(doesNotHaveLinkWithRel(mappings.getMetadataFor(CreditCard.class).getRel()));
}
@@ -191,10 +192,10 @@ public class JpaWebTests extends CommonWebTests {
@Test // DATAREST-199
void createsOrderUsingPut() throws Exception {
mvc.perform(//
assertThat(mvc.perform(//
put("/orders/{id}", 4711).//
content(readFileFromClasspath("order.json")).contentType(MediaType.APPLICATION_JSON)//
).andExpect(status().isCreated());
)).hasStatus(HttpStatus.CREATED);
}
@Test // DATAREST-117
@@ -442,8 +443,7 @@ public class JpaWebTests extends CommonWebTests {
Link link = client.discoverUnique(LinkRelation.of("addresses"));
mvc.perform(get(link.getHref())).//
andExpect(status().isMethodNotAllowed());
assertThat(mvc.perform(get(link.getHref()))).hasStatus(HttpStatus.METHOD_NOT_ALLOWED);
}
@Test // DATAREST-217
@@ -451,8 +451,8 @@ public class JpaWebTests extends CommonWebTests {
Link link = client.discoverUnique(LinkRelation.of("addresses"));
mvc.perform(post(link.getHref()).content("{}").contentType(MediaType.APPLICATION_JSON)).//
andExpect(status().isMethodNotAllowed());
assertThat(mvc.perform(post(link.getHref()).content("{}").contentType(MediaType.APPLICATION_JSON)))
.hasStatus(HttpStatus.METHOD_NOT_ALLOWED);
}
/**
@@ -471,7 +471,7 @@ public class JpaWebTests extends CommonWebTests {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(orderLink.getHref());
String uri = builder.queryParam("projection", "summary").build().toUriString();
response = mvc.perform(get(uri))//
response = mockMvc.perform(get(uri))//
.andExpect(status().isOk())//
.andExpect(jsonPath("$.price", is(2.5)))//
.andReturn().getResponse();
@@ -538,8 +538,7 @@ public class JpaWebTests extends CommonWebTests {
Link receiptsLink = client.discoverUnique("receipts");
mvc.perform(delete(receiptsLink.getHref().concat("/{id}"), 4711)).//
andExpect(status().isNotFound());
assertThat(mvc.perform(delete(receiptsLink.getHref().concat("/{id}"), 4711))).hasStatus(HttpStatus.NOT_FOUND);
}
@Test // DATAREST-384
@@ -583,13 +582,12 @@ public class JpaWebTests extends CommonWebTests {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(tacosLink.getHref());
String concurrencyTag = createdReceipt.getHeader("ETag");
mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
.contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag)) //
.andExpect(status().is2xxSuccessful());
assertThat(mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
.contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag))).hasStatusOk();
mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
.contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, "\"falseETag\""))
.andExpect(status().isPreconditionFailed());
assertThat(mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
.contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, "\"falseETag\"")))
.hasStatus(HttpStatus.PRECONDITION_FAILED);
}
@Test // DATAREST-423
@@ -599,8 +597,7 @@ public class JpaWebTests extends CommonWebTests {
String authorUri = JsonPath.read(authorsResponse.getContentAsString(), "$._embedded.authors[0]._links.self.href");
mvc.perform(delete(authorUri)).//
andExpect(status().isIAmATeapot());
assertThat(mvc.perform(delete(authorUri))).hasStatus(HttpStatus.I_AM_A_TEAPOT);
}
@Test // DATAREST-523
@@ -614,13 +611,12 @@ public class JpaWebTests extends CommonWebTests {
for (int i = 1; i <= 2; i++) {
mvc.perform(post(frodosSiblingsLink.getHref()).//
assertThat(mvc.perform(post(frodosSiblingsLink.getHref()).//
content(bilboLink.getHref()).//
contentType(TEXT_URI_LIST)).//
andExpect(status().isNoContent());
contentType(TEXT_URI_LIST))).hasStatus(HttpStatus.NO_CONTENT);
mvc.perform(get(frodosSiblingsLink.getHref())).//
andExpect(jsonPath("$._embedded.people", hasSize(i)));
assertThat(mvc.perform(get(frodosSiblingsLink.getHref()))).bodyJson().extractingPath("$._embedded.people")
.asArray().hasSize(i);
}
}
@@ -630,7 +626,7 @@ public class JpaWebTests extends CommonWebTests {
MockHttpServletResponse response = client.request(client.discoverUnique(LinkRelation.of("people")));
String personHref = JsonPath.read(response.getContentAsString(), "$._embedded.people[0]._links.self.href");
response = mvc.perform(head(personHref))//
response = mockMvc.perform(head(personHref))//
.andExpect(status().isNoContent())//
.andReturn().getResponse();
@@ -684,14 +680,14 @@ public class JpaWebTests extends CommonWebTests {
void callUnmappedCustomRepositoryController() throws Exception {
// Invalid prefix
mvc.perform(post("/orders/v3/search/sort")).andExpect(status().isNotFound());
assertThat(mvc.perform(post("/orders/v3/search/sort"))).hasStatus(HttpStatus.NOT_FOUND);
// With mapped prefixes
mvc.perform(post("/orders/search/sort")).andExpect(status().isOk());
mvc.perform(post("/orders/search/sorted")).andExpect(status().isOk());
mvc.perform(post("/orders/v2/search/sort")).andExpect(status().isOk());
mvc.perform(post("/orders/v2/search/sorted")).andExpect(status().isOk());
mvc.perform(post("/orders/search/sort?sort=type&page=1&size=10")).andExpect(status().isOk());
assertThat(mvc.perform(post("/orders/search/sort"))).hasStatusOk();
assertThat(mvc.perform(post("/orders/search/sorted"))).hasStatusOk();
assertThat(mvc.perform(post("/orders/v2/search/sort"))).hasStatusOk();
assertThat(mvc.perform(post("/orders/v2/search/sorted"))).hasStatusOk();
assertThat(mvc.perform(post("/orders/search/sort?sort=type&page=1&size=10"))).hasStatusOk();
}
@Test // DATAREST-976
@@ -746,9 +742,7 @@ public class JpaWebTests extends CommonWebTests {
@Test // #1991
void answersToHalFormsRequests() throws Exception {
mvc.perform(get("/")
.accept(MediaTypes.HAL_FORMS_JSON))
.andExpect(status().isOk());
assertThat(mvc.perform(get("/").accept(MediaTypes.HAL_FORMS_JSON))).hasStatusOk();
}
@Test // #2212
@@ -848,8 +842,7 @@ public class JpaWebTests extends CommonWebTests {
Link categoriesLink = client.discoverUnique(LinkRelation.of("categories"));
MockHttpServletResponse test = postAndGet(categoriesLink, "{ \"name\" : \"test\" }",
MediaType.APPLICATION_JSON);
MockHttpServletResponse test = postAndGet(categoriesLink, "{ \"name\" : \"test\" }", MediaType.APPLICATION_JSON);
Link testLink = client.assertHasLinkWithRel(IanaLinkRelations.SELF, test);

View File

@@ -17,9 +17,9 @@ package org.springframework.data.rest.webmvc.jpa;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.data.rest.tests.AbstractWebIntegrationTests;
import org.springframework.data.rest.webmvc.RepositoryRestHandlerMapping;
@@ -59,11 +59,13 @@ class LocalConfigCorsIntegrationTests extends AbstractWebIntegrationTests {
.header(HttpHeaders.ORIGIN, "https://far.far.example") //
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST");
var response = mvc.perform(request).andExpect(status().isOk()).andReturn().getResponse();
assertThat(mvc.perform(request)) //
.hasStatusOk() //
.hasHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*") //
.headers().hasHeaderSatisfying(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, headers -> {
assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)).isEqualTo("*");
assertThat(response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS).split(","))
.containsExactlyInAnyOrderElementsOf(
RepositoryRestHandlerMapping.DEFAULT_ALLOWED_METHODS.map(HttpMethod::name));
assertThat(headers.get(0).split(",")).containsExactlyInAnyOrderElementsOf(
RepositoryRestHandlerMapping.DEFAULT_ALLOWED_METHODS.map(HttpMethod::name));
});
}
}

View File

@@ -15,10 +15,11 @@
*/
package org.springframework.data.rest.webmvc.support;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
@@ -67,7 +68,6 @@ class ExceptionHandlingCustomizationIntegrationTests extends AbstractWebIntegrat
Link link = client.discoverUnique("addresses");
mvc.perform(get(link.getHref())).//
andExpect(status().isInternalServerError());
assertThat(mvc.perform(get(link.getHref()))).hasStatus5xxServerError();
}
}

View File

@@ -212,11 +212,11 @@ class MongoWebTests extends CommonWebTests {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(tacosLink.getHref());
String concurrencyTag = createdReceipt.getHeader("ETag");
mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
mockMvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
.contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag))
.andExpect(status().is2xxSuccessful());
mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
mockMvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
.contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag))
.andExpect(status().isPreconditionFailed());
}
@@ -226,7 +226,7 @@ class MongoWebTests extends CommonWebTests {
Profile profile = repository.findAll().iterator().next();
String header = mvc.perform(get("/profiles/{id}", profile.getId())).//
String header = mockMvc.perform(get("/profiles/{id}", profile.getId())).//
andReturn().getResponse().getHeader("Last-Modified");
assertThat(header).isNot(new Condition<String>(it -> it == null || it.isEmpty(), "Foo"));
@@ -299,11 +299,11 @@ class MongoWebTests extends CommonWebTests {
.findLinkWithRel(IanaLinkRelations.SELF, response.getContentAsString()) //
.orElseThrow(() -> new IllegalStateException("Did not find self link"));
mvc.perform(get(receiptLink.getHref()).header(IF_MODIFIED_SINCE, response.getHeader(LAST_MODIFIED))).//
mockMvc.perform(get(receiptLink.getHref()).header(IF_MODIFIED_SINCE, response.getHeader(LAST_MODIFIED))).//
andExpect(status().isNotModified()).//
andExpect(header().string(ETAG, is(notNullValue())));
mvc.perform(get(receiptLink.getHref()).header(IF_NONE_MATCH, response.getHeader(ETAG))).//
mockMvc.perform(get(receiptLink.getHref()).header(IF_NONE_MATCH, response.getHeader(ETAG))).//
andExpect(status().isNotModified()).//
andExpect(header().string(ETAG, is(notNullValue())));
}
@@ -315,7 +315,7 @@ class MongoWebTests extends CommonWebTests {
Link link = client.discoverUnique("profiles", "search", "findProfileById");
mvc.perform(get(link.expand(profile.getId()).getHref())).//
mockMvc.perform(get(link.expand(profile.getId()).getHref())).//
andExpect(status().isOk());
}
@@ -324,7 +324,7 @@ class MongoWebTests extends CommonWebTests {
Link link = client.discoverUnique("profiles", "search", "findProfileById");
mvc.perform(get(link.expand("").getHref())).//
mockMvc.perform(get(link.expand("").getHref())).//
andExpect(status().isNotFound());
}
@@ -338,7 +338,7 @@ class MongoWebTests extends CommonWebTests {
String href = link.expand(thomasUri.getHref()).getHref();
mvc.perform(get(href)).andExpect(status().isOk());
mockMvc.perform(get(href)).andExpect(status().isOk());
}
@Test // DATAREST-835
@@ -348,7 +348,7 @@ class MongoWebTests extends CommonWebTests {
Profile profile = repository.findAll().iterator().next();
mvc.perform(get(link.expand(profile.getId()).getHref()))//
mockMvc.perform(get(link.expand(profile.getId()).getHref()))//
.andExpect(header().string(ETAG, is("\"0\"")))//
.andExpect(header().string(LAST_MODIFIED, is(notNullValue())));
}
@@ -360,7 +360,7 @@ class MongoWebTests extends CommonWebTests {
Profile profile = repository.findAll().iterator().next();
mvc.perform(get(link.expand(profile.getType()).getHref()))//
mockMvc.perform(get(link.expand(profile.getType()).getHref()))//
.andExpect(header().string(ETAG, is(nullValue())))//
.andExpect(header().string(LAST_MODIFIED, is(nullValue())));
}
@@ -372,7 +372,7 @@ class MongoWebTests extends CommonWebTests {
Link userLink = assertHasContentLinkWithRel(IanaLinkRelations.SELF, client.request(usersLink));
Link colleaguesLink = client.assertHasLinkWithRel("colleagues", client.request(userLink));
mvc.perform(get(colleaguesLink.expand().getHref()).accept(TEXT_URI_LIST)) //
mockMvc.perform(get(colleaguesLink.expand().getHref()).accept(TEXT_URI_LIST)) //
.andExpect(status().isOk()) //
.andExpect(header().string(CONTENT_TYPE, is(TEXT_URI_LIST.toString()))) //
.andExpect(content().string(TestMatchers.hasNumberOfLines(2)));
@@ -385,7 +385,7 @@ class MongoWebTests extends CommonWebTests {
Link userLink = assertHasContentLinkWithRel(IanaLinkRelations.SELF, client.request(usersLink));
Link managerLink = client.assertHasLinkWithRel("manager", client.request(userLink));
mvc.perform(get(managerLink.expand().getHref()).accept(TEXT_URI_LIST)) //
mockMvc.perform(get(managerLink.expand().getHref()).accept(TEXT_URI_LIST)) //
.andExpect(header().string(CONTENT_TYPE, is(TEXT_URI_LIST.toString()))) //
.andExpect(content().string(TestMatchers.hasNumberOfLines(1)));
}
@@ -397,10 +397,10 @@ class MongoWebTests extends CommonWebTests {
Link userLink = assertHasContentLinkWithRel(IanaLinkRelations.SELF, client.request(usersLink));
Link mapLink = client.assertHasLinkWithRel("map", client.request(userLink));
mvc.perform(get(mapLink.expand().getHref())) //
mockMvc.perform(get(mapLink.expand().getHref())) //
.andDo(MockMvcResultHandlers.print());
mvc.perform(get(mapLink.expand().getHref()).accept(TEXT_URI_LIST)) //
mockMvc.perform(get(mapLink.expand().getHref()).accept(TEXT_URI_LIST)) //
.andExpect(status().isUnsupportedMediaType());
}
@@ -417,7 +417,7 @@ class MongoWebTests extends CommonWebTests {
.with(new TemplateVariable("firstname", VariableType.REQUEST_PARAM)) //
.expand(parameters);
MockHttpServletResponse response = mvc//
MockHttpServletResponse response = mockMvc//
.perform(get(firstnameLikeA)) //
.andReturn() //
.getResponse();

View File

@@ -35,6 +35,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@@ -84,12 +85,13 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
*/
@Override
protected void setupMockMvc() {
this.mvc = MockMvcBuilders.webAppContextSetup(context).//
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).//
defaultRequest(get("/").//
accept(TestMvcClient.DEFAULT_MEDIA_TYPE))
.//
apply(springSecurity()).//
build();
this.mvc = MockMvcTester.create(mockMvc);
}
@Test // DATAREST-327
@@ -98,7 +100,7 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
// Getting the collection is not tested here. This is to get the URI that will later be tested for DELETE
final String people = client.discoverUnique("people").expand().getHref();
MockHttpServletResponse response = mvc.perform(get(people).//
MockHttpServletResponse response = mockMvc.perform(get(people).//
with(user("user").roles("USER"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.people[0]._links.self.href", response);
@@ -106,13 +108,13 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
// Clear any side effects of logging in to get the URI from security.
SecurityContextHolder.clearContext();
mvc.perform(delete(href)).andExpect(status().isUnauthorized());
mockMvc.perform(delete(href)).andExpect(status().isUnauthorized());
}
@Test // DATAREST-327
void deletePersonAccessDeniedForUsers() throws Exception {
MockHttpServletResponse response = mvc.perform(get(client.discoverUnique("people").expand().getHref()).//
MockHttpServletResponse response = mockMvc.perform(get(client.discoverUnique("people").expand().getHref()).//
with(user("user").roles("USER"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.people[0]._links.self.href", response);
@@ -120,14 +122,14 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
// Clear any side effects of logging in to get the URI from security.
SecurityContextHolder.clearContext();
mvc.perform(delete(href).with(user("user").roles("USER"))).//
mockMvc.perform(delete(href).with(user("user").roles("USER"))).//
andExpect(status().isForbidden());
}
@Test // DATAREST-327
void deletePersonAccessGrantedForAdmins() throws Exception {
MockHttpServletResponse response = mvc.perform(get(client.discoverUnique("people").expand().getHref()).//
MockHttpServletResponse response = mockMvc.perform(get(client.discoverUnique("people").expand().getHref()).//
with(user("user").roles("USER", "ADMIN"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.people[0]._links.self.href", response);
@@ -135,21 +137,21 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
// Clear any side effects of logging in to get the URI from security.
SecurityContextHolder.clearContext();
mvc.perform(delete(href).with(user("user").roles("USER", "ADMIN")))
mockMvc.perform(delete(href).with(user("user").roles("USER", "ADMIN")))
.andExpect(status().is2xxSuccessful());
}
@Test // DATAREST-327
void findAllPeopleAccessDeniedForNoCredentials() throws Throwable {
mvc.perform(get(client.discoverUnique("people").expand().getHref())).//
mockMvc.perform(get(client.discoverUnique("people").expand().getHref())).//
andExpect(status().isUnauthorized());
}
@Test // DATAREST-327
void findAllPeopleAccessGrantedForUsers() throws Throwable {
mvc.perform(get(client.discoverUnique("people").expand().getHref()).//
mockMvc.perform(get(client.discoverUnique("people").expand().getHref()).//
with(user("user").roles("USER"))).//
andExpect(status().isOk());
}
@@ -157,7 +159,7 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
@Test // DATAREST-327
void findAllPeopleAccessGrantedForAdmins() throws Throwable {
mvc.perform(get(client.discoverUnique("people").expand().getHref()).//
mockMvc.perform(get(client.discoverUnique("people").expand().getHref()).//
with(user("user").roles("USER", "ADMIN"))).//
andExpect(status().isOk());
}
@@ -166,7 +168,7 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
void deleteOrderAccessDeniedForNoCredentials() throws Exception {
// Getting the collection is not tested here. This is to get the URI that will later be tested for DELETE
MockHttpServletResponse response = mvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
MockHttpServletResponse response = mockMvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
with(user("user").roles("USER"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.orders[0]._links.self.href", response);
@@ -174,25 +176,25 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
// Clear any side effects of logging in to get the URI from security.
SecurityContextHolder.clearContext();
mvc.perform(delete(href)).andExpect(status().isUnauthorized());
mockMvc.perform(delete(href)).andExpect(status().isUnauthorized());
}
@Test // DATAREST-327
void deleteOrderAccessDeniedForUsers() throws Exception {
MockHttpServletResponse response = mvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
MockHttpServletResponse response = mockMvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
with(user("user").roles("USER"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.orders[0]._links.self.href", response);
mvc.perform(delete(href).with(user("user").roles("USER"))).//
mockMvc.perform(delete(href).with(user("user").roles("USER"))).//
andExpect(status().isForbidden());
}
@Test // DATAREST-327
void deleteOrderAccessGrantedForAdmins() throws Exception {
MockHttpServletResponse response = mvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
MockHttpServletResponse response = mockMvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
with(user("user").roles("USER"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.orders[0]._links.self.href", response);
@@ -200,21 +202,21 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
// Clear any side effects of logging in to get the URI from security.
SecurityContextHolder.clearContext();
mvc.perform(delete(href).with(user("user").roles("USER", "ADMIN")))
mockMvc.perform(delete(href).with(user("user").roles("USER", "ADMIN")))
.andExpect(status().is2xxSuccessful());
}
@Test // DATAREST-327
void findAllOrdersAccessDeniedForNoCredentials() throws Throwable {
mvc.perform(get(client.discoverUnique("orders").expand().getHref())).//
mockMvc.perform(get(client.discoverUnique("orders").expand().getHref())).//
andExpect(status().isUnauthorized());
}
@Test // DATAREST-327
void findAllOrdersAccessGrantedForUsers() throws Throwable {
mvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
mockMvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
with(user("user").roles("USER"))).//
andExpect(status().isOk());
}
@@ -222,7 +224,7 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
@Test // DATAREST-327
void findAllOrdersAccessGrantedForAdmins() throws Throwable {
mvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
mockMvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
with(user("user").roles("USER", "ADMIN"))).//
andExpect(status().isOk());
}
@@ -230,12 +232,12 @@ class SecurityIntegrationTests extends AbstractWebIntegrationTests {
@Test // #2070
void rejectsAccessToItemResourceIfNotAuthorized() throws Exception {
MockHttpServletResponse response = mvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
MockHttpServletResponse response = mockMvc.perform(get(client.discoverUnique("orders").expand().getHref()).//
with(user("user").roles("USER"))).//
andReturn().getResponse();
String href = assertHasJsonPathValue("$._embedded.orders[0]._links.self.href", response);
mvc.perform(get(href).with(user("user").roles("USER")))
mockMvc.perform(get(href).with(user("user").roles("USER")))
.andExpect(status().isForbidden());
}
}

View File

@@ -15,6 +15,7 @@
*/
package org.springframework.data.rest.tests.shop;
import static org.assertj.core.api.Assertions.*;
import static org.hamcrest.CoreMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@@ -100,33 +101,31 @@ class ShopIntegrationTests extends AbstractWebIntegrationTests {
}
@Test // GH-2239
void triggersCustomControllerWithAggregateReferenceToId() throws Exception {
void triggersCustomControllerWithAggregateReferenceToId() {
var uuid = UUID.randomUUID();
mvc.perform(get("/order-custom-id?order=/order/foo/bar/{id}", uuid))
.andExpect(status().is2xxSuccessful())
.andExpect(content().string("\"%s\"".formatted(uuid.toString())));
assertThat(mvc.perform(get("/order-custom-id?order=/order/foo/bar/{id}", uuid))).hasStatusOk()
.hasBodyTextEqualTo("\"%s\"".formatted(uuid.toString()));
}
@Test // GH-2239
void triggersCustomControllerWithAggregateReferenceToAggregate() throws Exception {
void triggersCustomControllerWithAggregateReferenceToAggregate() {
var uuid = orders.findAll().iterator().next().getId().getId();
mvc.perform(get("/order-custom?order=/order/foo/bar/{id}", uuid))
.andExpect(status().is2xxSuccessful())
.andExpect(content().string("\"%s\"".formatted(uuid.toString())));
assertThat(mvc.perform(get("/order-custom?order=/order/foo/bar/{id}", uuid))).hasStatusOk()
.hasBodyTextEqualTo("\"%s\"".formatted(uuid.toString()));
}
@Test // GH-2239
void triggersCustomControllerWithAggregateReferenceToAssociation() throws Exception {
void triggersCustomControllerWithAggregateReferenceToAssociation() {
var uuid = UUID.randomUUID();
mvc.perform(get("/order-custom-association?order=/order/foo/bar/{id}", uuid))
.andExpect(status().is2xxSuccessful())
.andExpect(content().string("\"%s\"".formatted(uuid.toString())));
assertThat(mvc.perform(get("/order-custom-association?order=/order/foo/bar/{id}", uuid))).hasStatusOk()
.hasBodyTextEqualTo("\"%s\"".formatted(uuid.toString()));
}
private static void expectRelatedResource(String name, ResultActions actions) throws Exception {