Skip to content

Commit e5613a8

Browse files
authored
Merge pull request #2782 from wiremock/multipart-request-template-model
Multipart request template model
2 parents c80195a + 91eda2f commit e5613a8

File tree

8 files changed

+280
-13
lines changed

8 files changed

+280
-13
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* Copyright (C) 2024 Thomas Akehurst
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.github.tomakehurst.wiremock.extension.responsetemplating;
17+
18+
import com.github.tomakehurst.wiremock.common.ListOrSingle;
19+
import com.github.tomakehurst.wiremock.http.Body;
20+
import java.util.Map;
21+
import java.util.TreeMap;
22+
23+
public class RequestPartTemplateModel {
24+
25+
private final String name;
26+
private final Map<String, ListOrSingle<String>> headers;
27+
private final Body body;
28+
29+
public RequestPartTemplateModel(
30+
String name, Map<String, ListOrSingle<String>> headers, Body body) {
31+
this.name = name;
32+
this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
33+
this.headers.putAll(headers);
34+
this.body = body;
35+
}
36+
37+
public String getName() {
38+
return name;
39+
}
40+
41+
public Map<String, ListOrSingle<String>> getHeaders() {
42+
return headers;
43+
}
44+
45+
public String getBody() {
46+
return body.asString();
47+
}
48+
49+
public String getBodyAsBase64() {
50+
return body.asBase64();
51+
}
52+
53+
public boolean isBinary() {
54+
return body.isBinary();
55+
}
56+
}

src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/RequestTemplateModel.java

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package com.github.tomakehurst.wiremock.extension.responsetemplating;
1717

1818
import com.github.tomakehurst.wiremock.common.ListOrSingle;
19+
import com.github.tomakehurst.wiremock.http.Body;
1920
import com.github.tomakehurst.wiremock.http.RequestMethod;
2021
import java.util.Map;
2122

@@ -25,19 +26,26 @@ public class RequestTemplateModel {
2526
private final RequestLine requestLine;
2627
private final Map<String, ListOrSingle<String>> headers;
2728
private final Map<String, ListOrSingle<String>> cookies;
28-
private final String body;
29+
30+
private final boolean isMultipart;
31+
private final Body body;
32+
private final Map<String, RequestPartTemplateModel> parts;
2933

3034
protected RequestTemplateModel(
3135
String id,
3236
RequestLine requestLine,
3337
Map<String, ListOrSingle<String>> headers,
3438
Map<String, ListOrSingle<String>> cookies,
35-
String body) {
39+
boolean isMultipart,
40+
Body body,
41+
Map<String, RequestPartTemplateModel> parts) {
3642
this.id = id;
3743
this.requestLine = requestLine;
3844
this.headers = headers;
3945
this.cookies = cookies;
46+
this.isMultipart = isMultipart;
4047
this.body = body;
48+
this.parts = parts;
4149
}
4250

4351
public String getId() {
@@ -97,7 +105,23 @@ public Map<String, ListOrSingle<String>> getCookies() {
97105
}
98106

99107
public String getBody() {
100-
return body;
108+
return body.asString();
109+
}
110+
111+
public String getBodyAsBase64() {
112+
return body.asBase64();
113+
}
114+
115+
public boolean isBinary() {
116+
return body.isBinary();
117+
}
118+
119+
public boolean isMultipart() {
120+
return isMultipart;
121+
}
122+
123+
public Map<String, RequestPartTemplateModel> getParts() {
124+
return parts;
101125
}
102126

103127
public String getClientIp() {

src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/TemplateEngine.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
import com.github.tomakehurst.wiremock.extension.TemplateModelDataProviderExtension;
3333
import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.SystemValueHelper;
3434
import com.github.tomakehurst.wiremock.extension.responsetemplating.helpers.WireMockHelpers;
35+
import com.github.tomakehurst.wiremock.http.Body;
36+
import com.github.tomakehurst.wiremock.http.HttpHeader;
3537
import com.github.tomakehurst.wiremock.http.Request;
3638
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
3739
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
@@ -166,7 +168,29 @@ private static RequestTemplateModel buildRequestModel(Request request) {
166168
requestLine,
167169
adaptedHeaders,
168170
adaptedCookies,
169-
request.getBodyAsString());
171+
request.isMultipart(),
172+
Body.ofBinaryOrText(request.getBody(), request.contentTypeHeader()),
173+
buildRequestPartModel(request));
174+
}
175+
176+
private static Map<String, RequestPartTemplateModel> buildRequestPartModel(Request request) {
177+
178+
if (request.isMultipart()) {
179+
return request.getParts().stream()
180+
.collect(
181+
Collectors.toMap(
182+
Request.Part::getName,
183+
part ->
184+
new RequestPartTemplateModel(
185+
part.getName(),
186+
part.getHeaders().all().stream()
187+
.collect(
188+
Collectors.toMap(
189+
HttpHeader::key, header -> ListOrSingle.of(header.values()))),
190+
part.getBody())));
191+
}
192+
193+
return Collections.emptyMap();
170194
}
171195

172196
public long getCacheSize() {

src/main/java/com/github/tomakehurst/wiremock/http/Body.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ static Body fromString(String str) {
7575

7676
public static Body ofBinaryOrText(byte[] content, ContentTypeHeader contentTypeHeader) {
7777
return new Body(
78-
content, ContentTypes.determineIsTextFromMimeType(contentTypeHeader.mimeTypePart()));
78+
content, !ContentTypes.determineIsTextFromMimeType(contentTypeHeader.mimeTypePart()));
7979
}
8080

8181
public static Body fromOneOf(byte[] bytes, String str, JsonNode json, String base64) {

src/main/java/com/github/tomakehurst/wiremock/http/ContentTypeHeader.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public ContentTypeHeader or(String stringValue) {
4444
}
4545

4646
public String mimeTypePart() {
47-
return parts != null ? parts[0] : null;
47+
return parts != null && parts.length > 0 ? parts[0] : null;
4848
}
4949

5050
public Optional<String> encodingPart() {

src/main/java/com/github/tomakehurst/wiremock/http/multipart/FileItemPartAdapter.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (C) 2019-2023 Thomas Akehurst
2+
* Copyright (C) 2019-2024 Thomas Akehurst
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -15,10 +15,7 @@
1515
*/
1616
package com.github.tomakehurst.wiremock.http.multipart;
1717

18-
import com.github.tomakehurst.wiremock.http.Body;
19-
import com.github.tomakehurst.wiremock.http.HttpHeader;
20-
import com.github.tomakehurst.wiremock.http.HttpHeaders;
21-
import com.github.tomakehurst.wiremock.http.Request;
18+
import com.github.tomakehurst.wiremock.http.*;
2219
import java.util.ArrayList;
2320
import java.util.Collections;
2421
import java.util.Iterator;
@@ -63,7 +60,7 @@ public HttpHeaders getHeaders() {
6360

6461
@Override
6562
public Body getBody() {
66-
return new Body(fileItem.get());
63+
return Body.ofBinaryOrText(fileItem.get(), new ContentTypeHeader(fileItem.getContentType()));
6764
}
6865

6966
public static final Function<FileItem, Request.Part> TO_PARTS = FileItemPartAdapter::new;
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
/*
2+
* Copyright (C) 2024 Thomas Akehurst
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.github.tomakehurst.wiremock;
17+
18+
import static com.github.tomakehurst.wiremock.client.WireMock.*;
19+
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
20+
import static org.hamcrest.MatcherAssert.assertThat;
21+
import static org.hamcrest.Matchers.is;
22+
23+
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
24+
import com.github.tomakehurst.wiremock.testsupport.WireMockResponse;
25+
import com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;
26+
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
27+
import org.apache.hc.core5.http.ContentType;
28+
import org.junit.jupiter.api.BeforeEach;
29+
import org.junit.jupiter.api.Test;
30+
import org.junit.jupiter.api.extension.RegisterExtension;
31+
32+
public class MultipartTemplatingAcceptanceTest {
33+
34+
WireMockTestClient client;
35+
36+
@RegisterExtension
37+
public static WireMockExtension wm =
38+
WireMockExtension.newInstance()
39+
.options(options().dynamicPort().templatingEnabled(true).globalTemplating(true))
40+
.build();
41+
42+
@BeforeEach
43+
void init() {
44+
client = new WireMockTestClient(wm.getPort());
45+
}
46+
47+
@Test
48+
public void multipartRequestPartsAreAvailableViaTemplating() {
49+
wm.stubFor(
50+
post("/templated")
51+
.willReturn(
52+
ok(
53+
"multipart:{{request.multipart}}\n"
54+
+ "text:binary={{request.parts.text.binary}}:{{request.parts.text.headers.content-type}}:{{request.parts.text.body}}\n"
55+
+ "file:binary={{request.parts.file.binary}}:{{request.parts.file.headers.content-type}}:{{request.parts.file.bodyAsBase64}}")));
56+
57+
WireMockResponse response =
58+
client.post(
59+
"/templated",
60+
MultipartEntityBuilder.create()
61+
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
62+
.addBinaryBody(
63+
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
64+
.build());
65+
66+
assertThat(
67+
response.content(),
68+
is(
69+
"multipart:true\n"
70+
+ "text:binary=false:text/plain; charset=ISO-8859-1:hello\n"
71+
+ "file:binary=true:application/octet-stream:QUJDRA=="));
72+
}
73+
74+
@Test
75+
public void multipartRequestPartsHeadersAreCaseInsensitive() {
76+
wm.stubFor(
77+
post("/templated")
78+
.willReturn(
79+
ok(
80+
"multipart:{{request.multipart}}\n"
81+
+ "text:content-type={{request.parts.text.headers.CoNtEnT-TyPe}}\n"
82+
+ "file:content-type={{request.parts.file.headers.cOnTeNt-tYpE}}")));
83+
84+
WireMockResponse response =
85+
client.post(
86+
"/templated",
87+
MultipartEntityBuilder.create()
88+
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
89+
.addBinaryBody(
90+
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
91+
.build());
92+
93+
assertThat(
94+
response.content(),
95+
is(
96+
"multipart:true\n"
97+
+ "text:content-type=text/plain; charset=ISO-8859-1\n"
98+
+ "file:content-type=application/octet-stream"));
99+
}
100+
101+
@Test
102+
public void returnsEmptyPartsInTemplateWhenRequestIsNotMultipart() {
103+
wm.stubFor(
104+
post("/templated")
105+
.willReturn(
106+
ok(
107+
"multipart:{{request.multipart}}\n"
108+
+ "text:{{request.parts.text.headers.content-type}}:{{request.parts.text.body}}")));
109+
110+
WireMockResponse response = client.postJson("/templated", "{}");
111+
112+
assertThat(response.content(), is("multipart:false\n" + "text::"));
113+
}
114+
115+
@Test
116+
public void ableToReturnTheNumberOfParts() {
117+
wm.stubFor(
118+
post("/templated")
119+
.willReturn(
120+
ok("multipart:{{request.multipart}}\n" + "part count = {{size request.parts}}")));
121+
WireMockResponse response =
122+
client.post(
123+
"/templated",
124+
MultipartEntityBuilder.create()
125+
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
126+
.addBinaryBody(
127+
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
128+
.build());
129+
130+
assertThat(response.content(), is("multipart:true\n" + "part count = 2"));
131+
}
132+
133+
@Test
134+
public void ableToIterateOverParts() {
135+
wm.stubFor(
136+
post("/templated")
137+
.willReturn(
138+
ok(
139+
"multipart:{{request.multipart}}\n"
140+
+ "{{#each request.parts as |part|}}{{part.name}}:{{part.headers.content-type}}:{{part.body}}/\n{{/each}}")));
141+
WireMockResponse response =
142+
client.post(
143+
"/templated",
144+
MultipartEntityBuilder.create()
145+
.addTextBody("text", "hello", ContentType.TEXT_PLAIN)
146+
.addBinaryBody(
147+
"file", "ABCD".getBytes(), ContentType.APPLICATION_OCTET_STREAM, "abcd.bin")
148+
.build());
149+
150+
assertThat(
151+
response.content(),
152+
is(
153+
"multipart:true\n"
154+
+ "file:application/octet-stream:ABCD/\n"
155+
+ "text:text/plain; charset=ISO-8859-1:hello/\n"));
156+
}
157+
}

src/test/java/com/github/tomakehurst/wiremock/ResponseTemplatingAcceptanceTest.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ void canReadPathSegmentsByIndexWhenStubUsesPathTemplate() {
296296
}
297297

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

320+
@Test
321+
void bodyAsBase64IsAvailableOnTheRequestModel() {
322+
wm.stubFor(post("/v1/base64").willReturn(ok("{{request.bodyAsBase64}}")));
323+
324+
String content = client.postJson("/v1/base64", "{'foo':'bar'}").content();
325+
326+
assertThat(content, is("eydmb28nOidiYXInfQ=="));
327+
}
328+
320329
@Test
321330
void exceptionThrownWhileRenderingIsReportedViaSubEvent() {
322331
wm.stubFor(get("/bad").willReturn(ok("{{math '1' '/' 0}}")));

0 commit comments

Comments
 (0)