Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce a method in MockHttpServletRequestBuilder to set remote address #30497

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -526,6 +529,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 @@ -583,6 +597,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 @@ -687,6 +704,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