Skip to content

Commit

Permalink
Introduce method in MockHttpServletRequestBuilder to set remote address
Browse files Browse the repository at this point in the history
Co-authored-by: Sam Brannen <sam@sambrannen.com>
Closes spring-projectsgh-30497
  • Loading branch information
leewin12 authored and mdeinum committed Jun 29, 2023
1 parent 4d0647a commit 5846b92
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
Expand Up @@ -103,6 +103,9 @@ public class MockHttpServletRequestBuilder
@Nullable
private MockHttpSession session;

@Nullable
private String remoteAddress;

@Nullable
private String characterEncoding;

Expand Down Expand Up @@ -525,6 +528,17 @@ public MockHttpServletRequestBuilder principal(Principal principal) {
return this;
}

/**
* Set the remote address of the request.
* @param remoteAddress the remote address (IP)
* @since 6.1
*/
public MockHttpServletRequestBuilder remoteAddress(String remoteAddress) {
Assert.hasText(remoteAddress, "'remoteAddress' must not be null or blank");
this.remoteAddress = remoteAddress;
return this;
}

/**
* An extension point for further initialization of {@link MockHttpServletRequest}
* in ways not built directly into the {@code MockHttpServletRequestBuilder}.
Expand Down Expand Up @@ -582,6 +596,9 @@ public Object merge(@Nullable Object parent) {
if (this.session == null) {
this.session = parentBuilder.session;
}
if (this.remoteAddress == null) {
this.remoteAddress = parentBuilder.remoteAddress;
}

if (this.characterEncoding == null) {
this.characterEncoding = parentBuilder.characterEncoding;
Expand Down Expand Up @@ -686,6 +703,9 @@ public final MockHttpServletRequest buildRequest(ServletContext servletContext)
if (this.principal != null) {
request.setUserPrincipal(this.principal);
}
if (this.remoteAddress != null) {
request.setRemoteAddr(this.remoteAddress);
}
if (this.session != null) {
request.setSession(this.session);
}
Expand Down
Expand Up @@ -559,6 +559,15 @@ void principal() {
assertThat(request.getUserPrincipal()).isEqualTo(user);
}

@Test
void remoteAddress() {
String ip = "10.0.0.1";
this.builder.remoteAddress(ip);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);

assertThat(request.getRemoteAddr()).isEqualTo(ip);
}

@Test // SPR-12945
void mergeInvokesDefaultRequestPostProcessorFirst() {
final String ATTR = "ATTR";
Expand Down

0 comments on commit 5846b92

Please sign in to comment.