@@ -14,9 +14,12 @@ import org.mockserver.matchers.Times
14
14
import org.mockserver.model.Header
15
15
16
16
import static org.hamcrest.Matchers.endsWith
17
+ import static org.hamcrest.Matchers.greaterThanOrEqualTo
17
18
import static org.junit.Assert.assertEquals
18
19
import static org.junit.Assert.assertThat
19
20
import static org.junit.Assert.assertTrue
21
+ import static org.junit.Assert.fail
22
+ import static org.junit.Assume.assumeThat
20
23
import static org.mockito.Matchers.any
21
24
import static org.mockito.Mockito.mock
22
25
import static org.mockito.Mockito.never
@@ -237,6 +240,49 @@ class FilterTest extends ProxyResourceTest {
237
240
verify(mockProxy, never()). addResponseFilter(any(ResponseFilter ))
238
241
}
239
242
243
+ @Test
244
+ void testCanShortCircuitRequestWithJavascript () {
245
+ def javaVersion = System . getProperty(" java.specification.version" ) as double
246
+ assumeThat(" Skipping Nashorn-dependent test on Java 1.7" , javaVersion, greaterThanOrEqualTo(1.8d ))
247
+
248
+ final String requestFilterJavaScript =
249
+ '''
250
+ // "import" classes
251
+ var DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse');
252
+ var HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus');
253
+ var HttpObjectUtil = Java.type('net.lightbody.bmp.util.HttpObjectUtil');
254
+
255
+ // create a new DefaultFullHttpResponse that will short-circuit the request
256
+ var shortCircuitRequest = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.PAYMENT_REQUIRED);
257
+
258
+ // use the convenient HttpObjectUtil.replaceTextHttpEntityBody() method to set the entity body
259
+ var responseBody = 'You have to pay the troll toll to get into this Proxy\\ 's soul';
260
+ HttpObjectUtil.replaceTextHttpEntityBody(shortCircuitRequest, responseBody);
261
+
262
+ // return the short-circuit FullHttpResponse
263
+ shortCircuitRequest;
264
+ '''
265
+
266
+ Request<String > mockRestRequest = createMockRestRequestWithEntity(requestFilterJavaScript)
267
+
268
+ proxyResource. addRequestFilter(proxyPort, mockRestRequest)
269
+
270
+ HTTPBuilder http = getHttpBuilder()
271
+
272
+ http. request(Method . GET , ContentType . TEXT_PLAIN ) { req ->
273
+ uri. path = " /testShortCircuit"
274
+
275
+ response. success = { resp , reader ->
276
+ fail (" Expected short-circuit response to return an HTTP 402 Payment Required" )
277
+ }
278
+
279
+ response. failure = { resp , reader ->
280
+ assertEquals (" Expected short-circuit response to return an HTTP 402 Payment Required" , 402 , resp. status)
281
+ assertEquals (" Expected short-circuit response to contain body text set in Javascript" , " You have to pay the troll toll to get into this Proxy's soul" , reader. text)
282
+ }
283
+ }
284
+ }
285
+
240
286
@Override
241
287
String [] getArgs () {
242
288
return [" --use-littleproxy" , " true" ]
0 commit comments