Skip to content

Commit

Permalink
Merge pull request #2782 from wiremock/multipart-request-template-model
Browse files Browse the repository at this point in the history
Multipart request template model
  • Loading branch information
leeturner authored Jun 28, 2024
2 parents c80195a + 91eda2f commit e5613a8
Show file tree
Hide file tree
Showing 8 changed files with 280 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2024 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock.extension.responsetemplating;

import com.github.tomakehurst.wiremock.common.ListOrSingle;
import com.github.tomakehurst.wiremock.http.Body;
import java.util.Map;
import java.util.TreeMap;

public class RequestPartTemplateModel {

private final String name;
private final Map<String, ListOrSingle<String>> headers;
private final Body body;

public RequestPartTemplateModel(
String name, Map<String, ListOrSingle<String>> headers, Body body) {
this.name = name;
this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
this.headers.putAll(headers);
this.body = body;
}

public String getName() {
return name;
}

public Map<String, ListOrSingle<String>> getHeaders() {
return headers;
}

public String getBody() {
return body.asString();
}

public String getBodyAsBase64() {
return body.asBase64();
}

public boolean isBinary() {
return body.isBinary();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.github.tomakehurst.wiremock.extension.responsetemplating;

import com.github.tomakehurst.wiremock.common.ListOrSingle;
import com.github.tomakehurst.wiremock.http.Body;
import com.github.tomakehurst.wiremock.http.RequestMethod;
import java.util.Map;

Expand All @@ -25,19 +26,26 @@ public class RequestTemplateModel {
private final RequestLine requestLine;
private final Map<String, ListOrSingle<String>> headers;
private final Map<String, ListOrSingle<String>> cookies;
private final String body;

private final boolean isMultipart;
private final Body body;
private final Map<String, RequestPartTemplateModel> parts;

protected RequestTemplateModel(
String id,
RequestLine requestLine,
Map<String, ListOrSingle<String>> headers,
Map<String, ListOrSingle<String>> cookies,
String body) {
boolean isMultipart,
Body body,
Map<String, RequestPartTemplateModel> parts) {
this.id = id;
this.requestLine = requestLine;
this.headers = headers;
this.cookies = cookies;
this.isMultipart = isMultipart;
this.body = body;
this.parts = parts;
}

public String getId() {
Expand Down Expand Up @@ -97,7 +105,23 @@ public Map<String, ListOrSingle<String>> getCookies() {
}

public String getBody() {
return body;
return body.asString();
}

public String getBodyAsBase64() {
return body.asBase64();
}

public boolean isBinary() {
return body.isBinary();
}

public boolean isMultipart() {
return isMultipart;
}

public Map<String, RequestPartTemplateModel> getParts() {
return parts;
}

public String getClientIp() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import com.github.tomakehurst.wiremock.extension.TemplateModelDataProviderExtension;
import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.SystemValueHelper;
import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.WireMockHelpers;
import com.github.tomakehurst.wiremock.http.Body;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
Expand Down Expand Up @@ -166,7 +168,29 @@ private static RequestTemplateModel buildRequestModel(Request request) {
requestLine,
adaptedHeaders,
adaptedCookies,
request.getBodyAsString());
request.isMultipart(),
Body.ofBinaryOrText(request.getBody(), request.contentTypeHeader()),
buildRequestPartModel(request));
}

private static Map<String, RequestPartTemplateModel> buildRequestPartModel(Request request) {

if (request.isMultipart()) {
return request.getParts().stream()
.collect(
Collectors.toMap(
Request.Part::getName,
part ->
new RequestPartTemplateModel(
part.getName(),
part.getHeaders().all().stream()
.collect(
Collectors.toMap(
HttpHeader::key, header -> ListOrSingle.of(header.values()))),
part.getBody())));
}

return Collections.emptyMap();
}

public long getCacheSize() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ static Body fromString(String str) {

public static Body ofBinaryOrText(byte[] content, ContentTypeHeader contentTypeHeader) {
return new Body(
content, ContentTypes.determineIsTextFromMimeType(contentTypeHeader.mimeTypePart()));
content, !ContentTypes.determineIsTextFromMimeType(contentTypeHeader.mimeTypePart()));
}

public static Body fromOneOf(byte[] bytes, String str, JsonNode json, String base64) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public ContentTypeHeader or(String stringValue) {
}

public String mimeTypePart() {
return parts != null ? parts[0] : null;
return parts != null && parts.length > 0 ? parts[0] : null;
}

public Optional<String> encodingPart() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2019-2023 Thomas Akehurst
* Copyright (C) 2019-2024 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,10 +15,7 @@
*/
package com.github.tomakehurst.wiremock.http.multipart;

import com.github.tomakehurst.wiremock.http.Body;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.HttpHeaders;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
Expand Down Expand Up @@ -63,7 +60,7 @@ public HttpHeaders getHeaders() {

@Override
public Body getBody() {
return new Body(fileItem.get());
return Body.ofBinaryOrText(fileItem.get(), new ContentTypeHeader(fileItem.getContentType()));
}

public static final Function<FileItem, Request.Part> TO_PARTS = FileItemPartAdapter::new;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* Copyright (C) 2024 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;
import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.core5.http.ContentType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

public class MultipartTemplatingAcceptanceTest {

WireMockTestClient client;

@RegisterExtension
public static WireMockExtension wm =
WireMockExtension.newInstance()
.options(options().dynamicPort().templatingEnabled(true).globalTemplating(true))
.build();

@BeforeEach
void init() {
client = new WireMockTestClient(wm.getPort());
}

@Test
public void multipartRequestPartsAreAvailableViaTemplating() {
wm.stubFor(
post("/templated")
.willReturn(
ok(
"multipart:{{request.multipart}}\n"
+ "text:binary={{request.parts.text.binary}}:{{request.parts.text.headers.content-type}}:{{request.parts.text.body}}\n"
+ "file:binary={{request.parts.file.binary}}:{{request.parts.file.headers.content-type}}:{{request.parts.file.bodyAsBase64}}")));

WireMockResponse response =
client.post(
"/templated",
MultipartEntityBuilder.create()
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
.addBinaryBody(
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
.build());

assertThat(
response.content(),
is(
"multipart:true\n"
+ "text:binary=false:text/plain; charset=ISO-8859-1:hello\n"
+ "file:binary=true:application/octet-stream:QUJDRA=="));
}

@Test
public void multipartRequestPartsHeadersAreCaseInsensitive() {
wm.stubFor(
post("/templated")
.willReturn(
ok(
"multipart:{{request.multipart}}\n"
+ "text:content-type={{request.parts.text.headers.CoNtEnT-TyPe}}\n"
+ "file:content-type={{request.parts.file.headers.cOnTeNt-tYpE}}")));

WireMockResponse response =
client.post(
"/templated",
MultipartEntityBuilder.create()
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
.addBinaryBody(
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
.build());

assertThat(
response.content(),
is(
"multipart:true\n"
+ "text:content-type=text/plain; charset=ISO-8859-1\n"
+ "file:content-type=application/octet-stream"));
}

@Test
public void returnsEmptyPartsInTemplateWhenRequestIsNotMultipart() {
wm.stubFor(
post("/templated")
.willReturn(
ok(
"multipart:{{request.multipart}}\n"
+ "text:{{request.parts.text.headers.content-type}}:{{request.parts.text.body}}")));

WireMockResponse response = client.postJson("/templated", "{}");

assertThat(response.content(), is("multipart:false\n" + "text::"));
}

@Test
public void ableToReturnTheNumberOfParts() {
wm.stubFor(
post("/templated")
.willReturn(
ok("multipart:{{request.multipart}}\n" + "part count = {{size request.parts}}")));
WireMockResponse response =
client.post(
"/templated",
MultipartEntityBuilder.create()
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
.addBinaryBody(
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
.build());

assertThat(response.content(), is("multipart:true\n" + "part count = 2"));
}

@Test
public void ableToIterateOverParts() {
wm.stubFor(
post("/templated")
.willReturn(
ok(
"multipart:{{request.multipart}}\n"
+ "{{#each request.parts as |part|}}{{part.name}}:{{part.headers.content-type}}:{{part.body}}/\n{{/each}}")));
WireMockResponse response =
client.post(
"/templated",
MultipartEntityBuilder.create()
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
.addBinaryBody(
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
.build());

assertThat(
response.content(),
is(
"multipart:true\n"
+ "file:application/octet-stream:ABCD/\n"
+ "text:text/plain; charset=ISO-8859-1:hello/\n"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ void canReadPathSegmentsByIndexWhenStubUsesPathTemplate() {
}

@Test
void canReadNumericPathVariableValuesWhenUsingPathTemnplate() {
void canReadNumericPathVariableValuesWhenUsingPathTemplate() {
wm.stubFor(
get(urlPathTemplate("/v1/first/{0}/second/{1}"))
.willReturn(ok("1: {{request.path.0}}, 2: {{request.path.1}}")));
Expand All @@ -317,6 +317,15 @@ void canLoopOverPathSegmentsWhenUsingPathTemplate() {
assertThat(content, is(" v1 first first1 second second2 "));
}

@Test
void bodyAsBase64IsAvailableOnTheRequestModel() {
wm.stubFor(post("/v1/base64").willReturn(ok("{{request.bodyAsBase64}}")));

String content = client.postJson("/v1/base64", "{'foo':'bar'}").content();

assertThat(content, is("eydmb28nOidiYXInfQ=="));
}

@Test
void exceptionThrownWhileRenderingIsReportedViaSubEvent() {
wm.stubFor(get("/bad").willReturn(ok("{{math '1' '/' 0}}")));
Expand Down

0 comments on commit e5613a8

Please sign in to comment.