From 3ce520221d0240229c862b122d2b06c12a625732 Mon Sep 17 00:00:00 2001 From: Jesse McConnell Date: Tue, 4 Sep 2018 16:08:21 -0500 Subject: [PATCH 1/6] Updating to version 9.3.25.v20180904 --- VERSION.txt | 16 ++-- aggregates/jetty-all-compact3/pom.xml | 2 +- aggregates/jetty-all/pom.xml | 2 +- apache-jsp/pom.xml | 2 +- apache-jstl/pom.xml | 2 +- examples/async-rest/async-rest-jar/pom.xml | 2 +- examples/async-rest/async-rest-webapp/pom.xml | 2 +- examples/async-rest/pom.xml | 2 +- examples/embedded/pom.xml | 2 +- examples/pom.xml | 2 +- jetty-alpn/jetty-alpn-client/pom.xml | 2 +- jetty-alpn/jetty-alpn-java-client/pom.xml | 2 +- jetty-alpn/jetty-alpn-java-server/pom.xml | 2 +- jetty-alpn/jetty-alpn-server/pom.xml | 2 +- jetty-alpn/pom.xml | 2 +- jetty-annotations/pom.xml | 2 +- jetty-ant/pom.xml | 2 +- jetty-bom/pom.xml | 74 +++++++++---------- jetty-cdi/cdi-core/pom.xml | 2 +- jetty-cdi/cdi-full-servlet/pom.xml | 2 +- jetty-cdi/cdi-servlet/pom.xml | 2 +- jetty-cdi/cdi-websocket/pom.xml | 2 +- jetty-cdi/pom.xml | 2 +- jetty-cdi/test-cdi-webapp/pom.xml | 2 +- jetty-client/pom.xml | 2 +- jetty-continuation/pom.xml | 2 +- jetty-deploy/pom.xml | 2 +- jetty-distribution/pom.xml | 2 +- jetty-documentation/pom.xml | 2 +- jetty-fcgi/fcgi-client/pom.xml | 2 +- jetty-fcgi/fcgi-server/pom.xml | 2 +- jetty-fcgi/pom.xml | 2 +- .../pom.xml | 2 +- .../jetty-gcloud-session-manager/pom.xml | 2 +- jetty-gcloud/pom.xml | 2 +- jetty-hazelcast/pom.xml | 2 +- jetty-http-spi/pom.xml | 2 +- jetty-http/pom.xml | 2 +- jetty-http2/http2-alpn-tests/pom.xml | 2 +- jetty-http2/http2-client/pom.xml | 2 +- jetty-http2/http2-common/pom.xml | 2 +- jetty-http2/http2-hpack/pom.xml | 2 +- .../http2-http-client-transport/pom.xml | 2 +- jetty-http2/http2-server/pom.xml | 2 +- jetty-http2/pom.xml | 2 +- jetty-infinispan/pom.xml | 2 +- jetty-io/pom.xml | 2 +- jetty-jaas/pom.xml | 2 +- jetty-jaspi/pom.xml | 2 +- jetty-jmx/pom.xml | 2 +- jetty-jndi/pom.xml | 2 +- jetty-jspc-maven-plugin/pom.xml | 2 +- jetty-maven-plugin/pom.xml | 2 +- jetty-monitor/pom.xml | 2 +- jetty-nosql/pom.xml | 2 +- jetty-osgi/jetty-osgi-alpn/pom.xml | 2 +- jetty-osgi/jetty-osgi-boot-jsp/pom.xml | 2 +- jetty-osgi/jetty-osgi-boot-warurl/pom.xml | 2 +- jetty-osgi/jetty-osgi-boot/pom.xml | 2 +- jetty-osgi/jetty-osgi-httpservice/pom.xml | 2 +- jetty-osgi/pom.xml | 2 +- jetty-osgi/test-jetty-osgi-context/pom.xml | 2 +- jetty-osgi/test-jetty-osgi-fragment/pom.xml | 2 +- jetty-osgi/test-jetty-osgi-webapp/pom.xml | 2 +- jetty-osgi/test-jetty-osgi/pom.xml | 2 +- jetty-plus/pom.xml | 2 +- jetty-proxy/pom.xml | 2 +- jetty-quickstart/pom.xml | 2 +- jetty-rewrite/pom.xml | 2 +- jetty-runner/pom.xml | 2 +- jetty-security/pom.xml | 2 +- jetty-server/pom.xml | 2 +- jetty-servlet/pom.xml | 2 +- jetty-servlets/pom.xml | 2 +- jetty-spring/pom.xml | 2 +- jetty-start/pom.xml | 2 +- jetty-util-ajax/pom.xml | 2 +- jetty-util/pom.xml | 2 +- jetty-webapp/pom.xml | 2 +- .../javax-websocket-client-impl/pom.xml | 2 +- .../javax-websocket-server-impl/pom.xml | 2 +- jetty-websocket/pom.xml | 2 +- jetty-websocket/websocket-api/pom.xml | 2 +- jetty-websocket/websocket-client/pom.xml | 2 +- jetty-websocket/websocket-common/pom.xml | 2 +- jetty-websocket/websocket-server/pom.xml | 2 +- jetty-websocket/websocket-servlet/pom.xml | 2 +- jetty-xml/pom.xml | 2 +- pom.xml | 2 +- tests/pom.xml | 2 +- tests/test-continuation/pom.xml | 2 +- tests/test-http-client-transport/pom.xml | 2 +- tests/test-integration/pom.xml | 2 +- tests/test-jmx/jmx-webapp-it/pom.xml | 2 +- tests/test-jmx/jmx-webapp/pom.xml | 2 +- tests/test-jmx/pom.xml | 2 +- tests/test-loginservice/pom.xml | 2 +- tests/test-quickstart/pom.xml | 2 +- tests/test-sessions/pom.xml | 2 +- .../test-gcloud-memcached-sessions/pom.xml | 2 +- .../test-gcloud-sessions/pom.xml | 2 +- .../test-sessions/test-hash-sessions/pom.xml | 2 +- .../test-infinispan-sessions/pom.xml | 2 +- .../test-sessions/test-jdbc-sessions/pom.xml | 2 +- .../test-mongodb-sessions/pom.xml | 2 +- .../test-sessions-common/pom.xml | 2 +- tests/test-webapps/pom.xml | 2 +- tests/test-webapps/test-jaas-webapp/pom.xml | 2 +- tests/test-webapps/test-jetty-webapp/pom.xml | 2 +- tests/test-webapps/test-jndi-webapp/pom.xml | 2 +- .../test-webapps/test-mock-resources/pom.xml | 2 +- tests/test-webapps/test-proxy-webapp/pom.xml | 2 +- tests/test-webapps/test-servlet-spec/pom.xml | 2 +- .../test-container-initializer/pom.xml | 2 +- .../test-spec-webapp/pom.xml | 2 +- .../test-web-fragment/pom.xml | 2 +- .../test-webapps/test-webapp-rfc2616/pom.xml | 2 +- 117 files changed, 163 insertions(+), 157 deletions(-) diff --git a/VERSION.txt b/VERSION.txt index 6604b96ec62..0731f3697e9 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1,4 +1,9 @@ -jetty-9.3.25-SNAPSHOT +jetty-9.3.25.v20180904 - 04 September 2018 + + 2135 Android 8.1 needs direct buffers for SSL/TLS to work + + 2777 Workaround for Conscrypt's ssl == null + + 2787 BadMessageException wrapped as ServletException not handled + + 2860 Leakage of HttpDestinations in HttpClient + + 2871 Server reads -1 after client resets HTTP/2 stream jetty-9.3.24.v20180605 - 05 June 2018 + 2529 HttpParser cleanup @@ -69,8 +74,8 @@ jetty-9.3.21.v20170918 - 18 September 2017 jetty-9.3.20.v20170531 - 31 May 2017 + 523 TLS close behaviour breaking session resumption - + 1108 Improve logging in SslContextFactory when there are no approved - cipher suites + + 1108 Improve logging in SslContextFactory when there are no approved cipher + suites + 1527 Jetty BOM should not depend on jetty-parent + 1556 A timing channel in Password.java + 1567 XmlConfiguration will start the same object multiple times @@ -106,8 +111,9 @@ jetty-9.3.18.v20170406 - 06 April 2017 + 877 Programmatic servlet mappings cannot override mappings from webdefault.xml using quickstart + 1201 X-Forwarded-For incorrectly set in jetty-http-forwarded.xml - + 1316 Request.extract*Parameters() reports context - + 1322 Request.extract*Parameters() throws for bad UTF8 same as for bad ISO88591 + + 1316 Request.extract*Parameters() reports context + + 1322 Request.extract*Parameters() throws for bad UTF8 same as for bad + ISO88591 + 1326 Removed non-standard "%uXXXX" encoding support + 1417 Improve classloader dumping + 1439 Allow UNC paths to function as Resource bases diff --git a/aggregates/jetty-all-compact3/pom.xml b/aggregates/jetty-all-compact3/pom.xml index 9bb6e2a9320..782f0f1e1e8 100644 --- a/aggregates/jetty-all-compact3/pom.xml +++ b/aggregates/jetty-all-compact3/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../../pom.xml 4.0.0 diff --git a/aggregates/jetty-all/pom.xml b/aggregates/jetty-all/pom.xml index 959d1fa29ba..d3daf1aee03 100644 --- a/aggregates/jetty-all/pom.xml +++ b/aggregates/jetty-all/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../../pom.xml 4.0.0 diff --git a/apache-jsp/pom.xml b/apache-jsp/pom.xml index 57b8f84cbe5..5282539c124 100644 --- a/apache-jsp/pom.xml +++ b/apache-jsp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 apache-jsp diff --git a/apache-jstl/pom.xml b/apache-jstl/pom.xml index f2dbc1fab56..91be3d1d3c3 100644 --- a/apache-jstl/pom.xml +++ b/apache-jstl/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 apache-jstl diff --git a/examples/async-rest/async-rest-jar/pom.xml b/examples/async-rest/async-rest-jar/pom.xml index 96e52104f82..8adcefeefa5 100644 --- a/examples/async-rest/async-rest-jar/pom.xml +++ b/examples/async-rest/async-rest-jar/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty example-async-rest - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 org.eclipse.jetty.example-async-rest diff --git a/examples/async-rest/async-rest-webapp/pom.xml b/examples/async-rest/async-rest-webapp/pom.xml index 4820a5ffd8e..4d23a30bf13 100644 --- a/examples/async-rest/async-rest-webapp/pom.xml +++ b/examples/async-rest/async-rest-webapp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty example-async-rest - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 org.eclipse.jetty.example-async-rest diff --git a/examples/async-rest/pom.xml b/examples/async-rest/pom.xml index b6f1b7c21bc..b7b06937cb4 100644 --- a/examples/async-rest/pom.xml +++ b/examples/async-rest/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.examples examples-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/examples/embedded/pom.xml b/examples/embedded/pom.xml index 908f426ddf8..2e1248c0d15 100644 --- a/examples/embedded/pom.xml +++ b/examples/embedded/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.examples examples-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/examples/pom.xml b/examples/pom.xml index aa14e604cc1..261a24ab447 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml org.eclipse.jetty.examples diff --git a/jetty-alpn/jetty-alpn-client/pom.xml b/jetty-alpn/jetty-alpn-client/pom.xml index 32cbbb43dd6..87f64298452 100644 --- a/jetty-alpn/jetty-alpn-client/pom.xml +++ b/jetty-alpn/jetty-alpn-client/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-alpn-client diff --git a/jetty-alpn/jetty-alpn-java-client/pom.xml b/jetty-alpn/jetty-alpn-java-client/pom.xml index ae9765b91eb..ac8cc563d95 100644 --- a/jetty-alpn/jetty-alpn-java-client/pom.xml +++ b/jetty-alpn/jetty-alpn-java-client/pom.xml @@ -6,7 +6,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-alpn/jetty-alpn-java-server/pom.xml b/jetty-alpn/jetty-alpn-java-server/pom.xml index d23edf9d6a1..fe1b8fb20be 100644 --- a/jetty-alpn/jetty-alpn-java-server/pom.xml +++ b/jetty-alpn/jetty-alpn-java-server/pom.xml @@ -5,7 +5,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-alpn/jetty-alpn-server/pom.xml b/jetty-alpn/jetty-alpn-server/pom.xml index 8f2ce3bd55d..a15b0fb882b 100644 --- a/jetty-alpn/jetty-alpn-server/pom.xml +++ b/jetty-alpn/jetty-alpn-server/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-alpn-server diff --git a/jetty-alpn/pom.xml b/jetty-alpn/pom.xml index 7360314771e..c89a2a3561e 100644 --- a/jetty-alpn/pom.xml +++ b/jetty-alpn/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-alpn-parent diff --git a/jetty-annotations/pom.xml b/jetty-annotations/pom.xml index 240bec9b690..30d6940ba37 100644 --- a/jetty-annotations/pom.xml +++ b/jetty-annotations/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-annotations diff --git a/jetty-ant/pom.xml b/jetty-ant/pom.xml index 373b9e62b8a..4a9211f0916 100644 --- a/jetty-ant/pom.xml +++ b/jetty-ant/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-ant diff --git a/jetty-bom/pom.xml b/jetty-bom/pom.xml index cdc91a0364e..f3a226ba467 100644 --- a/jetty-bom/pom.xml +++ b/jetty-bom/pom.xml @@ -6,7 +6,7 @@ 4.0.0 jetty-bom - 9.3.25-SNAPSHOT + 9.3.25.v20180904 Jetty :: Bom Jetty BOM artifact http://www.eclipse.org/jetty @@ -98,7 +98,7 @@ org.eclipse.jetty jetty-annotations - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty @@ -118,22 +118,22 @@ org.eclipse.jetty jetty-client - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-continuation - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.fcgi fcgi-server - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.fcgi fcgi-server - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty @@ -148,82 +148,82 @@ org.eclipse.jetty jetty-hazelcast - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-http - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.http2 http2-client - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.http2 http2-common - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.http2 http2-hpack - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.http2 http2-http-client-transport - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty.http2 http2-server - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-http-spi - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-infinispan - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-io - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-jaas - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-jaspi - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-jmx - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-jndi - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-monitor - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-nosql - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty @@ -243,62 +243,62 @@ org.eclipse.jetty jetty-plus - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-proxy - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-quickstart - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-rewrite - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-security - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-server - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-servlet - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-servlets - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-spring - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-util - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-util-ajax - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-webapp - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty @@ -338,18 +338,18 @@ org.eclipse.jetty jetty-xml - 9.3.25-SNAPSHOT + 9.3.25.v20180904 org.eclipse.jetty jetty-distribution - 9.3.25-SNAPSHOT + 9.3.25.v20180904 zip org.eclipse.jetty jetty-distribution - 9.3.25-SNAPSHOT + 9.3.25.v20180904 tar.gz diff --git a/jetty-cdi/cdi-core/pom.xml b/jetty-cdi/cdi-core/pom.xml index 39d383934ee..4776e739c28 100644 --- a/jetty-cdi/cdi-core/pom.xml +++ b/jetty-cdi/cdi-core/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 cdi-core diff --git a/jetty-cdi/cdi-full-servlet/pom.xml b/jetty-cdi/cdi-full-servlet/pom.xml index bdf555c5a03..55ea2532f36 100644 --- a/jetty-cdi/cdi-full-servlet/pom.xml +++ b/jetty-cdi/cdi-full-servlet/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 cdi-full-servlet diff --git a/jetty-cdi/cdi-servlet/pom.xml b/jetty-cdi/cdi-servlet/pom.xml index 9c3bae09459..de494f2dd7c 100644 --- a/jetty-cdi/cdi-servlet/pom.xml +++ b/jetty-cdi/cdi-servlet/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 cdi-servlet diff --git a/jetty-cdi/cdi-websocket/pom.xml b/jetty-cdi/cdi-websocket/pom.xml index ba5f4ff0575..d2c64345216 100644 --- a/jetty-cdi/cdi-websocket/pom.xml +++ b/jetty-cdi/cdi-websocket/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 cdi-websocket diff --git a/jetty-cdi/pom.xml b/jetty-cdi/pom.xml index fecd9c83057..605017fe688 100644 --- a/jetty-cdi/pom.xml +++ b/jetty-cdi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 org.eclipse.jetty.cdi diff --git a/jetty-cdi/test-cdi-webapp/pom.xml b/jetty-cdi/test-cdi-webapp/pom.xml index a83c21b2d2b..d2d4eedd8c3 100644 --- a/jetty-cdi/test-cdi-webapp/pom.xml +++ b/jetty-cdi/test-cdi-webapp/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 test-cdi-webapp diff --git a/jetty-client/pom.xml b/jetty-client/pom.xml index 9c9d306632e..83a9c538a80 100644 --- a/jetty-client/pom.xml +++ b/jetty-client/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-continuation/pom.xml b/jetty-continuation/pom.xml index a00a09b3d73..04b586a43d4 100644 --- a/jetty-continuation/pom.xml +++ b/jetty-continuation/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-continuation diff --git a/jetty-deploy/pom.xml b/jetty-deploy/pom.xml index da82f1df685..77036328e52 100644 --- a/jetty-deploy/pom.xml +++ b/jetty-deploy/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-deploy diff --git a/jetty-distribution/pom.xml b/jetty-distribution/pom.xml index 053bd122883..37419926081 100644 --- a/jetty-distribution/pom.xml +++ b/jetty-distribution/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-distribution diff --git a/jetty-documentation/pom.xml b/jetty-documentation/pom.xml index df568cee774..6c45fdb179d 100644 --- a/jetty-documentation/pom.xml +++ b/jetty-documentation/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 jetty-documentation Jetty :: Documentation diff --git a/jetty-fcgi/fcgi-client/pom.xml b/jetty-fcgi/fcgi-client/pom.xml index fff3a9e9dde..3aa515b1ed6 100644 --- a/jetty-fcgi/fcgi-client/pom.xml +++ b/jetty-fcgi/fcgi-client/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.fcgi fcgi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-fcgi/fcgi-server/pom.xml b/jetty-fcgi/fcgi-server/pom.xml index d0ef73a9557..131230bb8ea 100644 --- a/jetty-fcgi/fcgi-server/pom.xml +++ b/jetty-fcgi/fcgi-server/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.fcgi fcgi-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-fcgi/pom.xml b/jetty-fcgi/pom.xml index e2fd807e12b..7a0432ae16c 100644 --- a/jetty-fcgi/pom.xml +++ b/jetty-fcgi/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml b/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml index 3de1ece81a2..c09efd587b3 100644 --- a/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml +++ b/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.gcloud gcloud-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml index 8070a543943..82bac4af0bb 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml +++ b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.gcloud gcloud-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-gcloud/pom.xml b/jetty-gcloud/pom.xml index 1fa392015e8..cdd06a9b231 100644 --- a/jetty-gcloud/pom.xml +++ b/jetty-gcloud/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-hazelcast/pom.xml b/jetty-hazelcast/pom.xml index 511492a8bc7..ecb2656b35c 100644 --- a/jetty-hazelcast/pom.xml +++ b/jetty-hazelcast/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-hazelcast diff --git a/jetty-http-spi/pom.xml b/jetty-http-spi/pom.xml index ce8f815c04a..cd1fda621d6 100644 --- a/jetty-http-spi/pom.xml +++ b/jetty-http-spi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-http-spi diff --git a/jetty-http/pom.xml b/jetty-http/pom.xml index a143115d0f3..c397562903b 100644 --- a/jetty-http/pom.xml +++ b/jetty-http/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-http diff --git a/jetty-http2/http2-alpn-tests/pom.xml b/jetty-http2/http2-alpn-tests/pom.xml index eec8d5e5845..b80c9bbe140 100644 --- a/jetty-http2/http2-alpn-tests/pom.xml +++ b/jetty-http2/http2-alpn-tests/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-http2/http2-client/pom.xml b/jetty-http2/http2-client/pom.xml index 48d02dd6a9b..065060836fe 100644 --- a/jetty-http2/http2-client/pom.xml +++ b/jetty-http2/http2-client/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-http2/http2-common/pom.xml b/jetty-http2/http2-common/pom.xml index f35e030e572..905f44b805f 100644 --- a/jetty-http2/http2-common/pom.xml +++ b/jetty-http2/http2-common/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-http2/http2-hpack/pom.xml b/jetty-http2/http2-hpack/pom.xml index fce9fe831f8..cc1966988a3 100644 --- a/jetty-http2/http2-hpack/pom.xml +++ b/jetty-http2/http2-hpack/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-http2/http2-http-client-transport/pom.xml b/jetty-http2/http2-http-client-transport/pom.xml index c5ee757fa44..20e3be54ae9 100644 --- a/jetty-http2/http2-http-client-transport/pom.xml +++ b/jetty-http2/http2-http-client-transport/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-http2/http2-server/pom.xml b/jetty-http2/http2-server/pom.xml index 41998455407..069c2d93fbb 100644 --- a/jetty-http2/http2-server/pom.xml +++ b/jetty-http2/http2-server/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-http2/pom.xml b/jetty-http2/pom.xml index ddebfa63b22..ec094f57c8f 100644 --- a/jetty-http2/pom.xml +++ b/jetty-http2/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-infinispan/pom.xml b/jetty-infinispan/pom.xml index e342f68051f..8c699c72ba8 100644 --- a/jetty-infinispan/pom.xml +++ b/jetty-infinispan/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-infinispan diff --git a/jetty-io/pom.xml b/jetty-io/pom.xml index 6742e92b40e..7fd6aadc4eb 100644 --- a/jetty-io/pom.xml +++ b/jetty-io/pom.xml @@ -2,7 +2,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-io diff --git a/jetty-jaas/pom.xml b/jetty-jaas/pom.xml index 7051a7f2ec3..3edf1ebfa08 100644 --- a/jetty-jaas/pom.xml +++ b/jetty-jaas/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-jaas diff --git a/jetty-jaspi/pom.xml b/jetty-jaspi/pom.xml index 124fabbda36..c031240497a 100644 --- a/jetty-jaspi/pom.xml +++ b/jetty-jaspi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-jaspi diff --git a/jetty-jmx/pom.xml b/jetty-jmx/pom.xml index b537322b464..3460f3286a1 100644 --- a/jetty-jmx/pom.xml +++ b/jetty-jmx/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-jmx diff --git a/jetty-jndi/pom.xml b/jetty-jndi/pom.xml index 574d01ca6aa..d9bd2fc65d6 100644 --- a/jetty-jndi/pom.xml +++ b/jetty-jndi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-jndi diff --git a/jetty-jspc-maven-plugin/pom.xml b/jetty-jspc-maven-plugin/pom.xml index 65760251369..78d9a40f983 100644 --- a/jetty-jspc-maven-plugin/pom.xml +++ b/jetty-jspc-maven-plugin/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-jspc-maven-plugin diff --git a/jetty-maven-plugin/pom.xml b/jetty-maven-plugin/pom.xml index 38baa1836b6..1c395f3fc4d 100644 --- a/jetty-maven-plugin/pom.xml +++ b/jetty-maven-plugin/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-maven-plugin diff --git a/jetty-monitor/pom.xml b/jetty-monitor/pom.xml index ded9f9f2410..a6065e2a074 100644 --- a/jetty-monitor/pom.xml +++ b/jetty-monitor/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-monitor diff --git a/jetty-nosql/pom.xml b/jetty-nosql/pom.xml index c3d3277663d..6cd4f361513 100644 --- a/jetty-nosql/pom.xml +++ b/jetty-nosql/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-nosql diff --git a/jetty-osgi/jetty-osgi-alpn/pom.xml b/jetty-osgi/jetty-osgi-alpn/pom.xml index 17ef0763bed..9564d160909 100644 --- a/jetty-osgi/jetty-osgi-alpn/pom.xml +++ b/jetty-osgi/jetty-osgi-alpn/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-osgi-alpn diff --git a/jetty-osgi/jetty-osgi-boot-jsp/pom.xml b/jetty-osgi/jetty-osgi-boot-jsp/pom.xml index 64a7e1da0a9..5eb65f567d8 100644 --- a/jetty-osgi/jetty-osgi-boot-jsp/pom.xml +++ b/jetty-osgi/jetty-osgi-boot-jsp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-osgi-boot-jsp diff --git a/jetty-osgi/jetty-osgi-boot-warurl/pom.xml b/jetty-osgi/jetty-osgi-boot-warurl/pom.xml index e1ecf5663d7..4ceee57d6c6 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/pom.xml +++ b/jetty-osgi/jetty-osgi-boot-warurl/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/jetty-osgi/jetty-osgi-boot/pom.xml b/jetty-osgi/jetty-osgi-boot/pom.xml index 0d6b5c18340..95f3d44c12b 100644 --- a/jetty-osgi/jetty-osgi-boot/pom.xml +++ b/jetty-osgi/jetty-osgi-boot/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-osgi-boot diff --git a/jetty-osgi/jetty-osgi-httpservice/pom.xml b/jetty-osgi/jetty-osgi-httpservice/pom.xml index c4370a7c206..666efea1ab2 100644 --- a/jetty-osgi/jetty-osgi-httpservice/pom.xml +++ b/jetty-osgi/jetty-osgi-httpservice/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-httpservice diff --git a/jetty-osgi/pom.xml b/jetty-osgi/pom.xml index 5954ad3227c..f3472edb7d4 100644 --- a/jetty-osgi/pom.xml +++ b/jetty-osgi/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-osgi/test-jetty-osgi-context/pom.xml b/jetty-osgi/test-jetty-osgi-context/pom.xml index 29dea401d72..dd4dda3823c 100644 --- a/jetty-osgi/test-jetty-osgi-context/pom.xml +++ b/jetty-osgi/test-jetty-osgi-context/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 test-jetty-osgi-context diff --git a/jetty-osgi/test-jetty-osgi-fragment/pom.xml b/jetty-osgi/test-jetty-osgi-fragment/pom.xml index 0cf7df5e70e..d960f9e2e46 100644 --- a/jetty-osgi/test-jetty-osgi-fragment/pom.xml +++ b/jetty-osgi/test-jetty-osgi-fragment/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/jetty-osgi/test-jetty-osgi-webapp/pom.xml b/jetty-osgi/test-jetty-osgi-webapp/pom.xml index a881e57dc89..4ba749bf6be 100644 --- a/jetty-osgi/test-jetty-osgi-webapp/pom.xml +++ b/jetty-osgi/test-jetty-osgi-webapp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/jetty-osgi/test-jetty-osgi/pom.xml b/jetty-osgi/test-jetty-osgi/pom.xml index b2db4bb8005..f8ac7a4c6a5 100644 --- a/jetty-osgi/test-jetty-osgi/pom.xml +++ b/jetty-osgi/test-jetty-osgi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/jetty-plus/pom.xml b/jetty-plus/pom.xml index 0f7195f40a6..613d7e7a9fb 100644 --- a/jetty-plus/pom.xml +++ b/jetty-plus/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-plus diff --git a/jetty-proxy/pom.xml b/jetty-proxy/pom.xml index 4b0dd923873..1ac9fb1394b 100644 --- a/jetty-proxy/pom.xml +++ b/jetty-proxy/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-proxy diff --git a/jetty-quickstart/pom.xml b/jetty-quickstart/pom.xml index f2181ea4af1..b5ef9bca10e 100644 --- a/jetty-quickstart/pom.xml +++ b/jetty-quickstart/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 org.eclipse.jetty diff --git a/jetty-rewrite/pom.xml b/jetty-rewrite/pom.xml index 4126d29dfcc..b5055f8427e 100644 --- a/jetty-rewrite/pom.xml +++ b/jetty-rewrite/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-rewrite diff --git a/jetty-runner/pom.xml b/jetty-runner/pom.xml index 509334a40eb..2c05b3efc71 100644 --- a/jetty-runner/pom.xml +++ b/jetty-runner/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-runner diff --git a/jetty-security/pom.xml b/jetty-security/pom.xml index 78dc7ea61d2..f9a6a6424f9 100644 --- a/jetty-security/pom.xml +++ b/jetty-security/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-security diff --git a/jetty-server/pom.xml b/jetty-server/pom.xml index 765d5312a1a..5c39686205d 100644 --- a/jetty-server/pom.xml +++ b/jetty-server/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-server diff --git a/jetty-servlet/pom.xml b/jetty-servlet/pom.xml index ae731657af5..d85c55e34ca 100644 --- a/jetty-servlet/pom.xml +++ b/jetty-servlet/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-servlet diff --git a/jetty-servlets/pom.xml b/jetty-servlets/pom.xml index 7de4109346c..4121699bcbb 100644 --- a/jetty-servlets/pom.xml +++ b/jetty-servlets/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-servlets diff --git a/jetty-spring/pom.xml b/jetty-spring/pom.xml index 36cc0a15681..77947040483 100644 --- a/jetty-spring/pom.xml +++ b/jetty-spring/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-spring diff --git a/jetty-start/pom.xml b/jetty-start/pom.xml index 0f8bbb9d1bb..3a94bfb9a77 100644 --- a/jetty-start/pom.xml +++ b/jetty-start/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-start diff --git a/jetty-util-ajax/pom.xml b/jetty-util-ajax/pom.xml index 51880f96d22..bf6ae9f2c97 100644 --- a/jetty-util-ajax/pom.xml +++ b/jetty-util-ajax/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-util-ajax diff --git a/jetty-util/pom.xml b/jetty-util/pom.xml index 68a0addcf55..9da8b5f2e95 100644 --- a/jetty-util/pom.xml +++ b/jetty-util/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-util diff --git a/jetty-webapp/pom.xml b/jetty-webapp/pom.xml index bc6f47be9a7..3c4f377fe06 100644 --- a/jetty-webapp/pom.xml +++ b/jetty-webapp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-webapp diff --git a/jetty-websocket/javax-websocket-client-impl/pom.xml b/jetty-websocket/javax-websocket-client-impl/pom.xml index cde43f28d62..90c87d4516d 100644 --- a/jetty-websocket/javax-websocket-client-impl/pom.xml +++ b/jetty-websocket/javax-websocket-client-impl/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/javax-websocket-server-impl/pom.xml b/jetty-websocket/javax-websocket-server-impl/pom.xml index 23f7f305438..d0588f91216 100644 --- a/jetty-websocket/javax-websocket-server-impl/pom.xml +++ b/jetty-websocket/javax-websocket-server-impl/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/pom.xml b/jetty-websocket/pom.xml index f214e2cb075..b62dc9d8ede 100644 --- a/jetty-websocket/pom.xml +++ b/jetty-websocket/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/websocket-api/pom.xml b/jetty-websocket/websocket-api/pom.xml index c80acabba17..d44c3f06e79 100644 --- a/jetty-websocket/websocket-api/pom.xml +++ b/jetty-websocket/websocket-api/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/websocket-client/pom.xml b/jetty-websocket/websocket-client/pom.xml index 58b22d18927..a5185b1fce4 100644 --- a/jetty-websocket/websocket-client/pom.xml +++ b/jetty-websocket/websocket-client/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/websocket-common/pom.xml b/jetty-websocket/websocket-common/pom.xml index fcb68a85a18..525ec6aea99 100644 --- a/jetty-websocket/websocket-common/pom.xml +++ b/jetty-websocket/websocket-common/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/websocket-server/pom.xml b/jetty-websocket/websocket-server/pom.xml index 4a99ff4417e..d302bd904c4 100644 --- a/jetty-websocket/websocket-server/pom.xml +++ b/jetty-websocket/websocket-server/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-websocket/websocket-servlet/pom.xml b/jetty-websocket/websocket-servlet/pom.xml index f98f9e90dff..685759f4ae4 100644 --- a/jetty-websocket/websocket-servlet/pom.xml +++ b/jetty-websocket/websocket-servlet/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/jetty-xml/pom.xml b/jetty-xml/pom.xml index e02fa39eb62..a72418c54cf 100644 --- a/jetty-xml/pom.xml +++ b/jetty-xml/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jetty-xml diff --git a/pom.xml b/pom.xml index 0f49c3d530d..267b098896e 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ 4.0.0 jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 Jetty :: Project http://www.eclipse.org/jetty pom diff --git a/tests/pom.xml b/tests/pom.xml index a054e723fa8..e9c99acbcff 100644 --- a/tests/pom.xml +++ b/tests/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml org.eclipse.jetty.tests diff --git a/tests/test-continuation/pom.xml b/tests/test-continuation/pom.xml index 0f307ea8f09..49754c9a93a 100644 --- a/tests/test-continuation/pom.xml +++ b/tests/test-continuation/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/tests/test-http-client-transport/pom.xml b/tests/test-http-client-transport/pom.xml index f14fb8e8616..3d6654c6e10 100644 --- a/tests/test-http-client-transport/pom.xml +++ b/tests/test-http-client-transport/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 diff --git a/tests/test-integration/pom.xml b/tests/test-integration/pom.xml index 30b51e6bc02..bfa23de3505 100644 --- a/tests/test-integration/pom.xml +++ b/tests/test-integration/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 test-integration diff --git a/tests/test-jmx/jmx-webapp-it/pom.xml b/tests/test-jmx/jmx-webapp-it/pom.xml index c464917c16c..28663e4cc9f 100644 --- a/tests/test-jmx/jmx-webapp-it/pom.xml +++ b/tests/test-jmx/jmx-webapp-it/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-jmx-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 jmx-webapp-it diff --git a/tests/test-jmx/jmx-webapp/pom.xml b/tests/test-jmx/jmx-webapp/pom.xml index d3f2da2d04d..0d0834c7496 100644 --- a/tests/test-jmx/jmx-webapp/pom.xml +++ b/tests/test-jmx/jmx-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-jmx-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 jmx-webapp war diff --git a/tests/test-jmx/pom.xml b/tests/test-jmx/pom.xml index d1ba9c7b234..42b7d018fda 100644 --- a/tests/test-jmx/pom.xml +++ b/tests/test-jmx/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 4.0.0 test-jmx-parent diff --git a/tests/test-loginservice/pom.xml b/tests/test-loginservice/pom.xml index 5c26533295e..20eeb23080a 100644 --- a/tests/test-loginservice/pom.xml +++ b/tests/test-loginservice/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-loginservice Jetty Tests :: Login Service diff --git a/tests/test-quickstart/pom.xml b/tests/test-quickstart/pom.xml index eab6c64eee5..0791cd6ad85 100644 --- a/tests/test-quickstart/pom.xml +++ b/tests/test-quickstart/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/tests/test-sessions/pom.xml b/tests/test-sessions/pom.xml index a6d02bf8aee..155bc8ff885 100644 --- a/tests/test-sessions/pom.xml +++ b/tests/test-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-sessions-parent Jetty Tests :: Sessions :: Parent diff --git a/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml b/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml index 934940bf7a1..22d479af904 100644 --- a/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml +++ b/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-gcloud-memcached-sessions Jetty Tests :: Sessions :: GCloud with Memcached diff --git a/tests/test-sessions/test-gcloud-sessions/pom.xml b/tests/test-sessions/test-gcloud-sessions/pom.xml index 41610190957..c12f9b487d9 100644 --- a/tests/test-sessions/test-gcloud-sessions/pom.xml +++ b/tests/test-sessions/test-gcloud-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-gcloud-sessions Jetty Tests :: Sessions :: GCloud diff --git a/tests/test-sessions/test-hash-sessions/pom.xml b/tests/test-sessions/test-hash-sessions/pom.xml index ad0609b7f1e..1f554692a8c 100644 --- a/tests/test-sessions/test-hash-sessions/pom.xml +++ b/tests/test-sessions/test-hash-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-hash-sessions Jetty Tests :: Sessions :: Hash diff --git a/tests/test-sessions/test-infinispan-sessions/pom.xml b/tests/test-sessions/test-infinispan-sessions/pom.xml index 96c2a735162..0716fd3f25d 100644 --- a/tests/test-sessions/test-infinispan-sessions/pom.xml +++ b/tests/test-sessions/test-infinispan-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-infinispan-sessions Jetty Tests :: Sessions :: Infinispan diff --git a/tests/test-sessions/test-jdbc-sessions/pom.xml b/tests/test-sessions/test-jdbc-sessions/pom.xml index c2b723170e1..26361427a99 100644 --- a/tests/test-sessions/test-jdbc-sessions/pom.xml +++ b/tests/test-sessions/test-jdbc-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-jdbc-sessions Jetty Tests :: Sessions :: JDBC diff --git a/tests/test-sessions/test-mongodb-sessions/pom.xml b/tests/test-sessions/test-mongodb-sessions/pom.xml index a19940b6df5..9f6c71775d2 100644 --- a/tests/test-sessions/test-mongodb-sessions/pom.xml +++ b/tests/test-sessions/test-mongodb-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-mongodb-sessions Jetty Tests :: Sessions :: Mongo diff --git a/tests/test-sessions/test-sessions-common/pom.xml b/tests/test-sessions/test-sessions-common/pom.xml index ec82a43e164..230cdf8c284 100644 --- a/tests/test-sessions/test-sessions-common/pom.xml +++ b/tests/test-sessions/test-sessions-common/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-sessions-common Jetty Tests :: Sessions :: Common diff --git a/tests/test-webapps/pom.xml b/tests/test-webapps/pom.xml index 23317becad2..9cffd39ebe7 100644 --- a/tests/test-webapps/pom.xml +++ b/tests/test-webapps/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml test-webapps-parent diff --git a/tests/test-webapps/test-jaas-webapp/pom.xml b/tests/test-webapps/test-jaas-webapp/pom.xml index 35a4af787db..26d2013b867 100644 --- a/tests/test-webapps/test-jaas-webapp/pom.xml +++ b/tests/test-webapps/test-jaas-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-jaas-webapp Jetty Tests :: WebApp :: JAAS diff --git a/tests/test-webapps/test-jetty-webapp/pom.xml b/tests/test-webapps/test-jetty-webapp/pom.xml index 39700b75992..ea6f3a772a2 100644 --- a/tests/test-webapps/test-jetty-webapp/pom.xml +++ b/tests/test-webapps/test-jetty-webapp/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/tests/test-webapps/test-jndi-webapp/pom.xml b/tests/test-webapps/test-jndi-webapp/pom.xml index 1b6d507a566..2c06d8c38d3 100644 --- a/tests/test-webapps/test-jndi-webapp/pom.xml +++ b/tests/test-webapps/test-jndi-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-jndi-webapp Jetty Tests :: WebApp :: JNDI diff --git a/tests/test-webapps/test-mock-resources/pom.xml b/tests/test-webapps/test-mock-resources/pom.xml index 8a35ebfe4c1..1d7d7d5e88a 100644 --- a/tests/test-webapps/test-mock-resources/pom.xml +++ b/tests/test-webapps/test-mock-resources/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 Jetty Tests :: WebApp :: Mock Resources test-mock-resources diff --git a/tests/test-webapps/test-proxy-webapp/pom.xml b/tests/test-webapps/test-proxy-webapp/pom.xml index 08aa5bc01ec..a41bcfd009e 100644 --- a/tests/test-webapps/test-proxy-webapp/pom.xml +++ b/tests/test-webapps/test-proxy-webapp/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 ../pom.xml 4.0.0 diff --git a/tests/test-webapps/test-servlet-spec/pom.xml b/tests/test-webapps/test-servlet-spec/pom.xml index 0aacab26dd2..87f46d6d9c9 100644 --- a/tests/test-webapps/test-servlet-spec/pom.xml +++ b/tests/test-webapps/test-servlet-spec/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-servlet-spec-parent Jetty Tests :: Spec Test WebApp :: Parent diff --git a/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml b/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml index 90a62435c6e..a88f567d182 100644 --- a/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml +++ b/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-servlet-spec-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-container-initializer jar diff --git a/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml b/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml index 74207b0998c..c6bffec5b05 100644 --- a/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml +++ b/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-servlet-spec-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 Jetty Tests :: Webapps :: Spec Webapp test-spec-webapp diff --git a/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml b/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml index 08014af99ce..e9837bf07f2 100644 --- a/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml +++ b/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-servlet-spec-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 Jetty Tests :: WebApp :: Servlet Spec :: Fragment Jar diff --git a/tests/test-webapps/test-webapp-rfc2616/pom.xml b/tests/test-webapps/test-webapp-rfc2616/pom.xml index edb3f821fe4..74c447f9711 100644 --- a/tests/test-webapps/test-webapp-rfc2616/pom.xml +++ b/tests/test-webapps/test-webapp-rfc2616/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25-SNAPSHOT + 9.3.25.v20180904 test-webapp-rfc2616 Jetty Tests :: WebApp :: RFC2616 From 863a19bccfc1d9b4190c9e52343c08c51dbf5d96 Mon Sep 17 00:00:00 2001 From: Jesse McConnell Date: Tue, 4 Sep 2018 17:23:31 -0500 Subject: [PATCH 2/6] Updating to version 9.3.26-SNAPSHOT --- VERSION.txt | 2 + aggregates/jetty-all-compact3/pom.xml | 2 +- aggregates/jetty-all/pom.xml | 2 +- apache-jsp/pom.xml | 2 +- apache-jstl/pom.xml | 2 +- examples/async-rest/async-rest-jar/pom.xml | 2 +- examples/async-rest/async-rest-webapp/pom.xml | 2 +- examples/async-rest/pom.xml | 2 +- examples/embedded/pom.xml | 2 +- examples/pom.xml | 2 +- jetty-alpn/jetty-alpn-client/pom.xml | 2 +- jetty-alpn/jetty-alpn-java-client/pom.xml | 2 +- jetty-alpn/jetty-alpn-java-server/pom.xml | 2 +- jetty-alpn/jetty-alpn-server/pom.xml | 2 +- jetty-alpn/pom.xml | 2 +- jetty-annotations/pom.xml | 2 +- jetty-ant/pom.xml | 2 +- jetty-bom/pom.xml | 72 +++++++++---------- jetty-cdi/cdi-core/pom.xml | 2 +- jetty-cdi/cdi-full-servlet/pom.xml | 2 +- jetty-cdi/cdi-servlet/pom.xml | 2 +- jetty-cdi/cdi-websocket/pom.xml | 2 +- jetty-cdi/pom.xml | 2 +- jetty-cdi/test-cdi-webapp/pom.xml | 2 +- jetty-client/pom.xml | 2 +- jetty-continuation/pom.xml | 2 +- jetty-deploy/pom.xml | 2 +- jetty-distribution/pom.xml | 2 +- jetty-documentation/pom.xml | 2 +- jetty-fcgi/fcgi-client/pom.xml | 2 +- jetty-fcgi/fcgi-server/pom.xml | 2 +- jetty-fcgi/pom.xml | 2 +- .../pom.xml | 2 +- .../jetty-gcloud-session-manager/pom.xml | 2 +- jetty-gcloud/pom.xml | 2 +- jetty-hazelcast/pom.xml | 2 +- jetty-http-spi/pom.xml | 2 +- jetty-http/pom.xml | 2 +- jetty-http2/http2-alpn-tests/pom.xml | 2 +- jetty-http2/http2-client/pom.xml | 2 +- jetty-http2/http2-common/pom.xml | 2 +- jetty-http2/http2-hpack/pom.xml | 2 +- .../http2-http-client-transport/pom.xml | 2 +- jetty-http2/http2-server/pom.xml | 2 +- jetty-http2/pom.xml | 2 +- jetty-infinispan/pom.xml | 2 +- jetty-io/pom.xml | 2 +- jetty-jaas/pom.xml | 2 +- jetty-jaspi/pom.xml | 2 +- jetty-jmx/pom.xml | 2 +- jetty-jndi/pom.xml | 2 +- jetty-jspc-maven-plugin/pom.xml | 2 +- jetty-maven-plugin/pom.xml | 2 +- jetty-monitor/pom.xml | 2 +- jetty-nosql/pom.xml | 2 +- jetty-osgi/jetty-osgi-alpn/pom.xml | 2 +- jetty-osgi/jetty-osgi-boot-jsp/pom.xml | 2 +- jetty-osgi/jetty-osgi-boot-warurl/pom.xml | 2 +- jetty-osgi/jetty-osgi-boot/pom.xml | 2 +- jetty-osgi/jetty-osgi-httpservice/pom.xml | 2 +- jetty-osgi/pom.xml | 2 +- jetty-osgi/test-jetty-osgi-context/pom.xml | 2 +- jetty-osgi/test-jetty-osgi-fragment/pom.xml | 2 +- jetty-osgi/test-jetty-osgi-webapp/pom.xml | 2 +- jetty-osgi/test-jetty-osgi/pom.xml | 2 +- jetty-plus/pom.xml | 2 +- jetty-proxy/pom.xml | 2 +- jetty-quickstart/pom.xml | 2 +- jetty-rewrite/pom.xml | 2 +- jetty-runner/pom.xml | 2 +- jetty-security/pom.xml | 2 +- jetty-server/pom.xml | 2 +- jetty-servlet/pom.xml | 2 +- jetty-servlets/pom.xml | 2 +- jetty-spring/pom.xml | 2 +- jetty-start/pom.xml | 2 +- jetty-util-ajax/pom.xml | 2 +- jetty-util/pom.xml | 2 +- jetty-webapp/pom.xml | 2 +- .../javax-websocket-client-impl/pom.xml | 2 +- .../javax-websocket-server-impl/pom.xml | 2 +- jetty-websocket/pom.xml | 2 +- jetty-websocket/websocket-api/pom.xml | 2 +- jetty-websocket/websocket-client/pom.xml | 2 +- jetty-websocket/websocket-common/pom.xml | 2 +- jetty-websocket/websocket-server/pom.xml | 2 +- jetty-websocket/websocket-servlet/pom.xml | 2 +- jetty-xml/pom.xml | 2 +- pom.xml | 2 +- tests/pom.xml | 2 +- tests/test-continuation/pom.xml | 2 +- tests/test-http-client-transport/pom.xml | 2 +- tests/test-integration/pom.xml | 2 +- tests/test-jmx/jmx-webapp-it/pom.xml | 2 +- tests/test-jmx/jmx-webapp/pom.xml | 2 +- tests/test-jmx/pom.xml | 2 +- tests/test-loginservice/pom.xml | 2 +- tests/test-quickstart/pom.xml | 2 +- tests/test-sessions/pom.xml | 2 +- .../test-gcloud-memcached-sessions/pom.xml | 2 +- .../test-gcloud-sessions/pom.xml | 2 +- .../test-sessions/test-hash-sessions/pom.xml | 2 +- .../test-infinispan-sessions/pom.xml | 2 +- .../test-sessions/test-jdbc-sessions/pom.xml | 2 +- .../test-mongodb-sessions/pom.xml | 2 +- .../test-sessions-common/pom.xml | 2 +- tests/test-webapps/pom.xml | 2 +- tests/test-webapps/test-jaas-webapp/pom.xml | 2 +- tests/test-webapps/test-jetty-webapp/pom.xml | 2 +- tests/test-webapps/test-jndi-webapp/pom.xml | 2 +- .../test-webapps/test-mock-resources/pom.xml | 2 +- tests/test-webapps/test-proxy-webapp/pom.xml | 2 +- tests/test-webapps/test-servlet-spec/pom.xml | 2 +- .../test-container-initializer/pom.xml | 2 +- .../test-spec-webapp/pom.xml | 2 +- .../test-web-fragment/pom.xml | 2 +- .../test-webapps/test-webapp-rfc2616/pom.xml | 2 +- 117 files changed, 153 insertions(+), 151 deletions(-) diff --git a/VERSION.txt b/VERSION.txt index 0731f3697e9..1dc56d5bb93 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1,3 +1,5 @@ +jetty-9.3.26-SNAPSHOT + jetty-9.3.25.v20180904 - 04 September 2018 + 2135 Android 8.1 needs direct buffers for SSL/TLS to work + 2777 Workaround for Conscrypt's ssl == null diff --git a/aggregates/jetty-all-compact3/pom.xml b/aggregates/jetty-all-compact3/pom.xml index 782f0f1e1e8..0df0fdec62b 100644 --- a/aggregates/jetty-all-compact3/pom.xml +++ b/aggregates/jetty-all-compact3/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/aggregates/jetty-all/pom.xml b/aggregates/jetty-all/pom.xml index d3daf1aee03..d74b2d63e07 100644 --- a/aggregates/jetty-all/pom.xml +++ b/aggregates/jetty-all/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/apache-jsp/pom.xml b/apache-jsp/pom.xml index 5282539c124..a17a6d0cd9a 100644 --- a/apache-jsp/pom.xml +++ b/apache-jsp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 apache-jsp diff --git a/apache-jstl/pom.xml b/apache-jstl/pom.xml index 91be3d1d3c3..44a5d2fc3f9 100644 --- a/apache-jstl/pom.xml +++ b/apache-jstl/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 apache-jstl diff --git a/examples/async-rest/async-rest-jar/pom.xml b/examples/async-rest/async-rest-jar/pom.xml index 8adcefeefa5..ebe83497878 100644 --- a/examples/async-rest/async-rest-jar/pom.xml +++ b/examples/async-rest/async-rest-jar/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty example-async-rest - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 org.eclipse.jetty.example-async-rest diff --git a/examples/async-rest/async-rest-webapp/pom.xml b/examples/async-rest/async-rest-webapp/pom.xml index 4d23a30bf13..76fc8951017 100644 --- a/examples/async-rest/async-rest-webapp/pom.xml +++ b/examples/async-rest/async-rest-webapp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty example-async-rest - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 org.eclipse.jetty.example-async-rest diff --git a/examples/async-rest/pom.xml b/examples/async-rest/pom.xml index b7b06937cb4..edcb2dd8830 100644 --- a/examples/async-rest/pom.xml +++ b/examples/async-rest/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.examples examples-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/examples/embedded/pom.xml b/examples/embedded/pom.xml index 2e1248c0d15..a50d78bcbe6 100644 --- a/examples/embedded/pom.xml +++ b/examples/embedded/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.examples examples-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/examples/pom.xml b/examples/pom.xml index 261a24ab447..de046ebe5bb 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml org.eclipse.jetty.examples diff --git a/jetty-alpn/jetty-alpn-client/pom.xml b/jetty-alpn/jetty-alpn-client/pom.xml index 87f64298452..d39ff25320e 100644 --- a/jetty-alpn/jetty-alpn-client/pom.xml +++ b/jetty-alpn/jetty-alpn-client/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-alpn-client diff --git a/jetty-alpn/jetty-alpn-java-client/pom.xml b/jetty-alpn/jetty-alpn-java-client/pom.xml index ac8cc563d95..7d19310b9b5 100644 --- a/jetty-alpn/jetty-alpn-java-client/pom.xml +++ b/jetty-alpn/jetty-alpn-java-client/pom.xml @@ -6,7 +6,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-alpn/jetty-alpn-java-server/pom.xml b/jetty-alpn/jetty-alpn-java-server/pom.xml index fe1b8fb20be..13315a2844b 100644 --- a/jetty-alpn/jetty-alpn-java-server/pom.xml +++ b/jetty-alpn/jetty-alpn-java-server/pom.xml @@ -5,7 +5,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-alpn/jetty-alpn-server/pom.xml b/jetty-alpn/jetty-alpn-server/pom.xml index a15b0fb882b..8cef8ed4447 100644 --- a/jetty-alpn/jetty-alpn-server/pom.xml +++ b/jetty-alpn/jetty-alpn-server/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-alpn-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-alpn-server diff --git a/jetty-alpn/pom.xml b/jetty-alpn/pom.xml index c89a2a3561e..ef4517934ca 100644 --- a/jetty-alpn/pom.xml +++ b/jetty-alpn/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-alpn-parent diff --git a/jetty-annotations/pom.xml b/jetty-annotations/pom.xml index 30d6940ba37..18022ee86b6 100644 --- a/jetty-annotations/pom.xml +++ b/jetty-annotations/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-annotations diff --git a/jetty-ant/pom.xml b/jetty-ant/pom.xml index 4a9211f0916..9a39485be37 100644 --- a/jetty-ant/pom.xml +++ b/jetty-ant/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-ant diff --git a/jetty-bom/pom.xml b/jetty-bom/pom.xml index f3a226ba467..94d2e1cec4b 100644 --- a/jetty-bom/pom.xml +++ b/jetty-bom/pom.xml @@ -98,7 +98,7 @@ org.eclipse.jetty jetty-annotations - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty @@ -118,22 +118,22 @@ org.eclipse.jetty jetty-client - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-continuation - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.fcgi fcgi-server - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.fcgi fcgi-server - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty @@ -148,82 +148,82 @@ org.eclipse.jetty jetty-hazelcast - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-http - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.http2 http2-client - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.http2 http2-common - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.http2 http2-hpack - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.http2 http2-http-client-transport - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty.http2 http2-server - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-http-spi - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-infinispan - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-io - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-jaas - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-jaspi - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-jmx - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-jndi - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-monitor - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-nosql - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty @@ -243,62 +243,62 @@ org.eclipse.jetty jetty-plus - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-proxy - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-quickstart - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-rewrite - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-security - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-server - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-servlet - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-servlets - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-spring - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-util - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-util-ajax - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-webapp - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty @@ -338,18 +338,18 @@ org.eclipse.jetty jetty-xml - 9.3.25.v20180904 + 9.3.26-SNAPSHOT org.eclipse.jetty jetty-distribution - 9.3.25.v20180904 + 9.3.26-SNAPSHOT zip org.eclipse.jetty jetty-distribution - 9.3.25.v20180904 + 9.3.26-SNAPSHOT tar.gz diff --git a/jetty-cdi/cdi-core/pom.xml b/jetty-cdi/cdi-core/pom.xml index 4776e739c28..baa9ef6577a 100644 --- a/jetty-cdi/cdi-core/pom.xml +++ b/jetty-cdi/cdi-core/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 cdi-core diff --git a/jetty-cdi/cdi-full-servlet/pom.xml b/jetty-cdi/cdi-full-servlet/pom.xml index 55ea2532f36..8b8e0d0e4b1 100644 --- a/jetty-cdi/cdi-full-servlet/pom.xml +++ b/jetty-cdi/cdi-full-servlet/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 cdi-full-servlet diff --git a/jetty-cdi/cdi-servlet/pom.xml b/jetty-cdi/cdi-servlet/pom.xml index de494f2dd7c..3e0fb793347 100644 --- a/jetty-cdi/cdi-servlet/pom.xml +++ b/jetty-cdi/cdi-servlet/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 cdi-servlet diff --git a/jetty-cdi/cdi-websocket/pom.xml b/jetty-cdi/cdi-websocket/pom.xml index d2c64345216..271d181b7aa 100644 --- a/jetty-cdi/cdi-websocket/pom.xml +++ b/jetty-cdi/cdi-websocket/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 cdi-websocket diff --git a/jetty-cdi/pom.xml b/jetty-cdi/pom.xml index 605017fe688..a62f9c15580 100644 --- a/jetty-cdi/pom.xml +++ b/jetty-cdi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 org.eclipse.jetty.cdi diff --git a/jetty-cdi/test-cdi-webapp/pom.xml b/jetty-cdi/test-cdi-webapp/pom.xml index d2d4eedd8c3..9e0c58fad51 100644 --- a/jetty-cdi/test-cdi-webapp/pom.xml +++ b/jetty-cdi/test-cdi-webapp/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.cdi jetty-cdi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 test-cdi-webapp diff --git a/jetty-client/pom.xml b/jetty-client/pom.xml index 83a9c538a80..f770458a0cc 100644 --- a/jetty-client/pom.xml +++ b/jetty-client/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-continuation/pom.xml b/jetty-continuation/pom.xml index 04b586a43d4..3f73d4d2d87 100644 --- a/jetty-continuation/pom.xml +++ b/jetty-continuation/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-continuation diff --git a/jetty-deploy/pom.xml b/jetty-deploy/pom.xml index 77036328e52..07ebe56d85d 100644 --- a/jetty-deploy/pom.xml +++ b/jetty-deploy/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-deploy diff --git a/jetty-distribution/pom.xml b/jetty-distribution/pom.xml index 37419926081..9ac219878ab 100644 --- a/jetty-distribution/pom.xml +++ b/jetty-distribution/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-distribution diff --git a/jetty-documentation/pom.xml b/jetty-documentation/pom.xml index 6c45fdb179d..e99090460c1 100644 --- a/jetty-documentation/pom.xml +++ b/jetty-documentation/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT jetty-documentation Jetty :: Documentation diff --git a/jetty-fcgi/fcgi-client/pom.xml b/jetty-fcgi/fcgi-client/pom.xml index 3aa515b1ed6..89db76a3be2 100644 --- a/jetty-fcgi/fcgi-client/pom.xml +++ b/jetty-fcgi/fcgi-client/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.fcgi fcgi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-fcgi/fcgi-server/pom.xml b/jetty-fcgi/fcgi-server/pom.xml index 131230bb8ea..99400921541 100644 --- a/jetty-fcgi/fcgi-server/pom.xml +++ b/jetty-fcgi/fcgi-server/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.fcgi fcgi-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-fcgi/pom.xml b/jetty-fcgi/pom.xml index 7a0432ae16c..008a7b87e23 100644 --- a/jetty-fcgi/pom.xml +++ b/jetty-fcgi/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml b/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml index c09efd587b3..72c4c84c32e 100644 --- a/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml +++ b/jetty-gcloud/jetty-gcloud-memcached-session-manager/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.gcloud gcloud-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml index 82bac4af0bb..f93f0e2706e 100644 --- a/jetty-gcloud/jetty-gcloud-session-manager/pom.xml +++ b/jetty-gcloud/jetty-gcloud-session-manager/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.gcloud gcloud-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-gcloud/pom.xml b/jetty-gcloud/pom.xml index cdd06a9b231..4f06a0b3c2f 100644 --- a/jetty-gcloud/pom.xml +++ b/jetty-gcloud/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-hazelcast/pom.xml b/jetty-hazelcast/pom.xml index ecb2656b35c..5eac93d3727 100644 --- a/jetty-hazelcast/pom.xml +++ b/jetty-hazelcast/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-hazelcast diff --git a/jetty-http-spi/pom.xml b/jetty-http-spi/pom.xml index cd1fda621d6..bb67e023e7a 100644 --- a/jetty-http-spi/pom.xml +++ b/jetty-http-spi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-http-spi diff --git a/jetty-http/pom.xml b/jetty-http/pom.xml index c397562903b..aec01c96acf 100644 --- a/jetty-http/pom.xml +++ b/jetty-http/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-http diff --git a/jetty-http2/http2-alpn-tests/pom.xml b/jetty-http2/http2-alpn-tests/pom.xml index b80c9bbe140..df0de9987c9 100644 --- a/jetty-http2/http2-alpn-tests/pom.xml +++ b/jetty-http2/http2-alpn-tests/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-http2/http2-client/pom.xml b/jetty-http2/http2-client/pom.xml index 065060836fe..48523fa1c19 100644 --- a/jetty-http2/http2-client/pom.xml +++ b/jetty-http2/http2-client/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-http2/http2-common/pom.xml b/jetty-http2/http2-common/pom.xml index 905f44b805f..b504eaec5ff 100644 --- a/jetty-http2/http2-common/pom.xml +++ b/jetty-http2/http2-common/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-http2/http2-hpack/pom.xml b/jetty-http2/http2-hpack/pom.xml index cc1966988a3..ccc404d802a 100644 --- a/jetty-http2/http2-hpack/pom.xml +++ b/jetty-http2/http2-hpack/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-http2/http2-http-client-transport/pom.xml b/jetty-http2/http2-http-client-transport/pom.xml index 20e3be54ae9..699a5b5e700 100644 --- a/jetty-http2/http2-http-client-transport/pom.xml +++ b/jetty-http2/http2-http-client-transport/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-http2/http2-server/pom.xml b/jetty-http2/http2-server/pom.xml index 069c2d93fbb..60641373251 100644 --- a/jetty-http2/http2-server/pom.xml +++ b/jetty-http2/http2-server/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.http2 http2-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-http2/pom.xml b/jetty-http2/pom.xml index ec094f57c8f..5dd75aa50b3 100644 --- a/jetty-http2/pom.xml +++ b/jetty-http2/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-infinispan/pom.xml b/jetty-infinispan/pom.xml index 8c699c72ba8..8bf01928bc6 100644 --- a/jetty-infinispan/pom.xml +++ b/jetty-infinispan/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-infinispan diff --git a/jetty-io/pom.xml b/jetty-io/pom.xml index 7fd6aadc4eb..6144f51fbcf 100644 --- a/jetty-io/pom.xml +++ b/jetty-io/pom.xml @@ -2,7 +2,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-io diff --git a/jetty-jaas/pom.xml b/jetty-jaas/pom.xml index 3edf1ebfa08..767592ca63c 100644 --- a/jetty-jaas/pom.xml +++ b/jetty-jaas/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-jaas diff --git a/jetty-jaspi/pom.xml b/jetty-jaspi/pom.xml index c031240497a..d5dd7da3086 100644 --- a/jetty-jaspi/pom.xml +++ b/jetty-jaspi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-jaspi diff --git a/jetty-jmx/pom.xml b/jetty-jmx/pom.xml index 3460f3286a1..14110402cf2 100644 --- a/jetty-jmx/pom.xml +++ b/jetty-jmx/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-jmx diff --git a/jetty-jndi/pom.xml b/jetty-jndi/pom.xml index d9bd2fc65d6..8516b15f68f 100644 --- a/jetty-jndi/pom.xml +++ b/jetty-jndi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-jndi diff --git a/jetty-jspc-maven-plugin/pom.xml b/jetty-jspc-maven-plugin/pom.xml index 78d9a40f983..5c293cd3eed 100644 --- a/jetty-jspc-maven-plugin/pom.xml +++ b/jetty-jspc-maven-plugin/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-jspc-maven-plugin diff --git a/jetty-maven-plugin/pom.xml b/jetty-maven-plugin/pom.xml index 1c395f3fc4d..c4763ee8a73 100644 --- a/jetty-maven-plugin/pom.xml +++ b/jetty-maven-plugin/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-maven-plugin diff --git a/jetty-monitor/pom.xml b/jetty-monitor/pom.xml index a6065e2a074..f38fb9932a3 100644 --- a/jetty-monitor/pom.xml +++ b/jetty-monitor/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-monitor diff --git a/jetty-nosql/pom.xml b/jetty-nosql/pom.xml index 6cd4f361513..7d91403fc60 100644 --- a/jetty-nosql/pom.xml +++ b/jetty-nosql/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-nosql diff --git a/jetty-osgi/jetty-osgi-alpn/pom.xml b/jetty-osgi/jetty-osgi-alpn/pom.xml index 9564d160909..da3b2d72ac3 100644 --- a/jetty-osgi/jetty-osgi-alpn/pom.xml +++ b/jetty-osgi/jetty-osgi-alpn/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-osgi-alpn diff --git a/jetty-osgi/jetty-osgi-boot-jsp/pom.xml b/jetty-osgi/jetty-osgi-boot-jsp/pom.xml index 5eb65f567d8..0ab52984bc9 100644 --- a/jetty-osgi/jetty-osgi-boot-jsp/pom.xml +++ b/jetty-osgi/jetty-osgi-boot-jsp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-osgi-boot-jsp diff --git a/jetty-osgi/jetty-osgi-boot-warurl/pom.xml b/jetty-osgi/jetty-osgi-boot-warurl/pom.xml index 4ceee57d6c6..002ddf9df44 100644 --- a/jetty-osgi/jetty-osgi-boot-warurl/pom.xml +++ b/jetty-osgi/jetty-osgi-boot-warurl/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/jetty-osgi/jetty-osgi-boot/pom.xml b/jetty-osgi/jetty-osgi-boot/pom.xml index 95f3d44c12b..ef53810a31f 100644 --- a/jetty-osgi/jetty-osgi-boot/pom.xml +++ b/jetty-osgi/jetty-osgi-boot/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-osgi-boot diff --git a/jetty-osgi/jetty-osgi-httpservice/pom.xml b/jetty-osgi/jetty-osgi-httpservice/pom.xml index 666efea1ab2..4372e4f3c78 100644 --- a/jetty-osgi/jetty-osgi-httpservice/pom.xml +++ b/jetty-osgi/jetty-osgi-httpservice/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-httpservice diff --git a/jetty-osgi/pom.xml b/jetty-osgi/pom.xml index f3472edb7d4..03f2da51ac1 100644 --- a/jetty-osgi/pom.xml +++ b/jetty-osgi/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-osgi/test-jetty-osgi-context/pom.xml b/jetty-osgi/test-jetty-osgi-context/pom.xml index dd4dda3823c..1640f817a28 100644 --- a/jetty-osgi/test-jetty-osgi-context/pom.xml +++ b/jetty-osgi/test-jetty-osgi-context/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 test-jetty-osgi-context diff --git a/jetty-osgi/test-jetty-osgi-fragment/pom.xml b/jetty-osgi/test-jetty-osgi-fragment/pom.xml index d960f9e2e46..1723824168f 100644 --- a/jetty-osgi/test-jetty-osgi-fragment/pom.xml +++ b/jetty-osgi/test-jetty-osgi-fragment/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/jetty-osgi/test-jetty-osgi-webapp/pom.xml b/jetty-osgi/test-jetty-osgi-webapp/pom.xml index 4ba749bf6be..9ade1022c5e 100644 --- a/jetty-osgi/test-jetty-osgi-webapp/pom.xml +++ b/jetty-osgi/test-jetty-osgi-webapp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/jetty-osgi/test-jetty-osgi/pom.xml b/jetty-osgi/test-jetty-osgi/pom.xml index f8ac7a4c6a5..44aa739887b 100644 --- a/jetty-osgi/test-jetty-osgi/pom.xml +++ b/jetty-osgi/test-jetty-osgi/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.osgi jetty-osgi-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/jetty-plus/pom.xml b/jetty-plus/pom.xml index 613d7e7a9fb..843578387f2 100644 --- a/jetty-plus/pom.xml +++ b/jetty-plus/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-plus diff --git a/jetty-proxy/pom.xml b/jetty-proxy/pom.xml index 1ac9fb1394b..890a8ba7883 100644 --- a/jetty-proxy/pom.xml +++ b/jetty-proxy/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-proxy diff --git a/jetty-quickstart/pom.xml b/jetty-quickstart/pom.xml index b5ef9bca10e..83239bd5729 100644 --- a/jetty-quickstart/pom.xml +++ b/jetty-quickstart/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 org.eclipse.jetty diff --git a/jetty-rewrite/pom.xml b/jetty-rewrite/pom.xml index b5055f8427e..6ff620dfbfe 100644 --- a/jetty-rewrite/pom.xml +++ b/jetty-rewrite/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-rewrite diff --git a/jetty-runner/pom.xml b/jetty-runner/pom.xml index 2c05b3efc71..09c9bdd9d34 100644 --- a/jetty-runner/pom.xml +++ b/jetty-runner/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-runner diff --git a/jetty-security/pom.xml b/jetty-security/pom.xml index f9a6a6424f9..eb847de5578 100644 --- a/jetty-security/pom.xml +++ b/jetty-security/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-security diff --git a/jetty-server/pom.xml b/jetty-server/pom.xml index 5c39686205d..01fbb9648b3 100644 --- a/jetty-server/pom.xml +++ b/jetty-server/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-server diff --git a/jetty-servlet/pom.xml b/jetty-servlet/pom.xml index d85c55e34ca..3d74eefec31 100644 --- a/jetty-servlet/pom.xml +++ b/jetty-servlet/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-servlet diff --git a/jetty-servlets/pom.xml b/jetty-servlets/pom.xml index 4121699bcbb..2d9c6c7ca25 100644 --- a/jetty-servlets/pom.xml +++ b/jetty-servlets/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-servlets diff --git a/jetty-spring/pom.xml b/jetty-spring/pom.xml index 77947040483..e1ad8241f05 100644 --- a/jetty-spring/pom.xml +++ b/jetty-spring/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-spring diff --git a/jetty-start/pom.xml b/jetty-start/pom.xml index 3a94bfb9a77..93a923ae689 100644 --- a/jetty-start/pom.xml +++ b/jetty-start/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-start diff --git a/jetty-util-ajax/pom.xml b/jetty-util-ajax/pom.xml index bf6ae9f2c97..2fa2f5701d4 100644 --- a/jetty-util-ajax/pom.xml +++ b/jetty-util-ajax/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-util-ajax diff --git a/jetty-util/pom.xml b/jetty-util/pom.xml index 9da8b5f2e95..1597b0759dd 100644 --- a/jetty-util/pom.xml +++ b/jetty-util/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-util diff --git a/jetty-webapp/pom.xml b/jetty-webapp/pom.xml index 3c4f377fe06..95a93593abf 100644 --- a/jetty-webapp/pom.xml +++ b/jetty-webapp/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-webapp diff --git a/jetty-websocket/javax-websocket-client-impl/pom.xml b/jetty-websocket/javax-websocket-client-impl/pom.xml index 90c87d4516d..7d993104b17 100644 --- a/jetty-websocket/javax-websocket-client-impl/pom.xml +++ b/jetty-websocket/javax-websocket-client-impl/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/javax-websocket-server-impl/pom.xml b/jetty-websocket/javax-websocket-server-impl/pom.xml index d0588f91216..ae29b521508 100644 --- a/jetty-websocket/javax-websocket-server-impl/pom.xml +++ b/jetty-websocket/javax-websocket-server-impl/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/pom.xml b/jetty-websocket/pom.xml index b62dc9d8ede..965eb238f09 100644 --- a/jetty-websocket/pom.xml +++ b/jetty-websocket/pom.xml @@ -3,7 +3,7 @@ jetty-project org.eclipse.jetty - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/websocket-api/pom.xml b/jetty-websocket/websocket-api/pom.xml index d44c3f06e79..56d4e5a0e57 100644 --- a/jetty-websocket/websocket-api/pom.xml +++ b/jetty-websocket/websocket-api/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/websocket-client/pom.xml b/jetty-websocket/websocket-client/pom.xml index a5185b1fce4..cbce40bc370 100644 --- a/jetty-websocket/websocket-client/pom.xml +++ b/jetty-websocket/websocket-client/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/websocket-common/pom.xml b/jetty-websocket/websocket-common/pom.xml index 525ec6aea99..492fba103ed 100644 --- a/jetty-websocket/websocket-common/pom.xml +++ b/jetty-websocket/websocket-common/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/websocket-server/pom.xml b/jetty-websocket/websocket-server/pom.xml index d302bd904c4..540374852b2 100644 --- a/jetty-websocket/websocket-server/pom.xml +++ b/jetty-websocket/websocket-server/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-websocket/websocket-servlet/pom.xml b/jetty-websocket/websocket-servlet/pom.xml index 685759f4ae4..b879bb67406 100644 --- a/jetty-websocket/websocket-servlet/pom.xml +++ b/jetty-websocket/websocket-servlet/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.websocket websocket-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/jetty-xml/pom.xml b/jetty-xml/pom.xml index a72418c54cf..fe34e0e299e 100644 --- a/jetty-xml/pom.xml +++ b/jetty-xml/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jetty-xml diff --git a/pom.xml b/pom.xml index 267b098896e..79654792dc5 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ 4.0.0 jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT Jetty :: Project http://www.eclipse.org/jetty pom diff --git a/tests/pom.xml b/tests/pom.xml index e9c99acbcff..40aa5ee39e3 100644 --- a/tests/pom.xml +++ b/tests/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty jetty-project - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml org.eclipse.jetty.tests diff --git a/tests/test-continuation/pom.xml b/tests/test-continuation/pom.xml index 49754c9a93a..e008e94edfb 100644 --- a/tests/test-continuation/pom.xml +++ b/tests/test-continuation/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/tests/test-http-client-transport/pom.xml b/tests/test-http-client-transport/pom.xml index 3d6654c6e10..e0c777dd1c1 100644 --- a/tests/test-http-client-transport/pom.xml +++ b/tests/test-http-client-transport/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 diff --git a/tests/test-integration/pom.xml b/tests/test-integration/pom.xml index bfa23de3505..f55e340594f 100644 --- a/tests/test-integration/pom.xml +++ b/tests/test-integration/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 test-integration diff --git a/tests/test-jmx/jmx-webapp-it/pom.xml b/tests/test-jmx/jmx-webapp-it/pom.xml index 28663e4cc9f..c959131c2af 100644 --- a/tests/test-jmx/jmx-webapp-it/pom.xml +++ b/tests/test-jmx/jmx-webapp-it/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-jmx-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 jmx-webapp-it diff --git a/tests/test-jmx/jmx-webapp/pom.xml b/tests/test-jmx/jmx-webapp/pom.xml index 0d0834c7496..775b4ddb323 100644 --- a/tests/test-jmx/jmx-webapp/pom.xml +++ b/tests/test-jmx/jmx-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-jmx-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT jmx-webapp war diff --git a/tests/test-jmx/pom.xml b/tests/test-jmx/pom.xml index 42b7d018fda..4421ac9148f 100644 --- a/tests/test-jmx/pom.xml +++ b/tests/test-jmx/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT 4.0.0 test-jmx-parent diff --git a/tests/test-loginservice/pom.xml b/tests/test-loginservice/pom.xml index 20eeb23080a..2a184fab528 100644 --- a/tests/test-loginservice/pom.xml +++ b/tests/test-loginservice/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-loginservice Jetty Tests :: Login Service diff --git a/tests/test-quickstart/pom.xml b/tests/test-quickstart/pom.xml index 0791cd6ad85..409e88aa309 100644 --- a/tests/test-quickstart/pom.xml +++ b/tests/test-quickstart/pom.xml @@ -2,7 +2,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/tests/test-sessions/pom.xml b/tests/test-sessions/pom.xml index 155bc8ff885..6f16eff2a58 100644 --- a/tests/test-sessions/pom.xml +++ b/tests/test-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-sessions-parent Jetty Tests :: Sessions :: Parent diff --git a/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml b/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml index 22d479af904..e31bb7cc343 100644 --- a/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml +++ b/tests/test-sessions/test-gcloud-memcached-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-gcloud-memcached-sessions Jetty Tests :: Sessions :: GCloud with Memcached diff --git a/tests/test-sessions/test-gcloud-sessions/pom.xml b/tests/test-sessions/test-gcloud-sessions/pom.xml index c12f9b487d9..a9b261b85f7 100644 --- a/tests/test-sessions/test-gcloud-sessions/pom.xml +++ b/tests/test-sessions/test-gcloud-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-gcloud-sessions Jetty Tests :: Sessions :: GCloud diff --git a/tests/test-sessions/test-hash-sessions/pom.xml b/tests/test-sessions/test-hash-sessions/pom.xml index 1f554692a8c..6a99e907486 100644 --- a/tests/test-sessions/test-hash-sessions/pom.xml +++ b/tests/test-sessions/test-hash-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-hash-sessions Jetty Tests :: Sessions :: Hash diff --git a/tests/test-sessions/test-infinispan-sessions/pom.xml b/tests/test-sessions/test-infinispan-sessions/pom.xml index 0716fd3f25d..ac6db1b49e0 100644 --- a/tests/test-sessions/test-infinispan-sessions/pom.xml +++ b/tests/test-sessions/test-infinispan-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-infinispan-sessions Jetty Tests :: Sessions :: Infinispan diff --git a/tests/test-sessions/test-jdbc-sessions/pom.xml b/tests/test-sessions/test-jdbc-sessions/pom.xml index 26361427a99..9c09f461cbc 100644 --- a/tests/test-sessions/test-jdbc-sessions/pom.xml +++ b/tests/test-sessions/test-jdbc-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-jdbc-sessions Jetty Tests :: Sessions :: JDBC diff --git a/tests/test-sessions/test-mongodb-sessions/pom.xml b/tests/test-sessions/test-mongodb-sessions/pom.xml index 9f6c71775d2..d99300f9f16 100644 --- a/tests/test-sessions/test-mongodb-sessions/pom.xml +++ b/tests/test-sessions/test-mongodb-sessions/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-mongodb-sessions Jetty Tests :: Sessions :: Mongo diff --git a/tests/test-sessions/test-sessions-common/pom.xml b/tests/test-sessions/test-sessions-common/pom.xml index 230cdf8c284..4bdab9696b1 100644 --- a/tests/test-sessions/test-sessions-common/pom.xml +++ b/tests/test-sessions/test-sessions-common/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-sessions-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-sessions-common Jetty Tests :: Sessions :: Common diff --git a/tests/test-webapps/pom.xml b/tests/test-webapps/pom.xml index 9cffd39ebe7..2043cb730b8 100644 --- a/tests/test-webapps/pom.xml +++ b/tests/test-webapps/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests tests-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml test-webapps-parent diff --git a/tests/test-webapps/test-jaas-webapp/pom.xml b/tests/test-webapps/test-jaas-webapp/pom.xml index 26d2013b867..a6724ead9d5 100644 --- a/tests/test-webapps/test-jaas-webapp/pom.xml +++ b/tests/test-webapps/test-jaas-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-jaas-webapp Jetty Tests :: WebApp :: JAAS diff --git a/tests/test-webapps/test-jetty-webapp/pom.xml b/tests/test-webapps/test-jetty-webapp/pom.xml index ea6f3a772a2..9ba2b6ddf35 100644 --- a/tests/test-webapps/test-jetty-webapp/pom.xml +++ b/tests/test-webapps/test-jetty-webapp/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/tests/test-webapps/test-jndi-webapp/pom.xml b/tests/test-webapps/test-jndi-webapp/pom.xml index 2c06d8c38d3..2f76a51d848 100644 --- a/tests/test-webapps/test-jndi-webapp/pom.xml +++ b/tests/test-webapps/test-jndi-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-jndi-webapp Jetty Tests :: WebApp :: JNDI diff --git a/tests/test-webapps/test-mock-resources/pom.xml b/tests/test-webapps/test-mock-resources/pom.xml index 1d7d7d5e88a..370b9a3caeb 100644 --- a/tests/test-webapps/test-mock-resources/pom.xml +++ b/tests/test-webapps/test-mock-resources/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT Jetty Tests :: WebApp :: Mock Resources test-mock-resources diff --git a/tests/test-webapps/test-proxy-webapp/pom.xml b/tests/test-webapps/test-proxy-webapp/pom.xml index a41bcfd009e..72d6f7e6b8a 100644 --- a/tests/test-webapps/test-proxy-webapp/pom.xml +++ b/tests/test-webapps/test-proxy-webapp/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT ../pom.xml 4.0.0 diff --git a/tests/test-webapps/test-servlet-spec/pom.xml b/tests/test-webapps/test-servlet-spec/pom.xml index 87f46d6d9c9..d585ace3003 100644 --- a/tests/test-webapps/test-servlet-spec/pom.xml +++ b/tests/test-webapps/test-servlet-spec/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-servlet-spec-parent Jetty Tests :: Spec Test WebApp :: Parent diff --git a/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml b/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml index a88f567d182..b77bfb94945 100644 --- a/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml +++ b/tests/test-webapps/test-servlet-spec/test-container-initializer/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-servlet-spec-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-container-initializer jar diff --git a/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml b/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml index c6bffec5b05..7c685102c40 100644 --- a/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml +++ b/tests/test-webapps/test-servlet-spec/test-spec-webapp/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-servlet-spec-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT Jetty Tests :: Webapps :: Spec Webapp test-spec-webapp diff --git a/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml b/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml index e9837bf07f2..d4766420f18 100644 --- a/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml +++ b/tests/test-webapps/test-servlet-spec/test-web-fragment/pom.xml @@ -3,7 +3,7 @@ org.eclipse.jetty.tests test-servlet-spec-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT Jetty Tests :: WebApp :: Servlet Spec :: Fragment Jar diff --git a/tests/test-webapps/test-webapp-rfc2616/pom.xml b/tests/test-webapps/test-webapp-rfc2616/pom.xml index 74c447f9711..7e447dc0f57 100644 --- a/tests/test-webapps/test-webapp-rfc2616/pom.xml +++ b/tests/test-webapps/test-webapp-rfc2616/pom.xml @@ -4,7 +4,7 @@ org.eclipse.jetty.tests test-webapps-parent - 9.3.25.v20180904 + 9.3.26-SNAPSHOT test-webapp-rfc2616 Jetty Tests :: WebApp :: RFC2616 From a3f1592c50c3af7001a5ab3c773768660eb8d07a Mon Sep 17 00:00:00 2001 From: Joakim Erdfelt Date: Tue, 4 Sep 2018 19:07:17 -0500 Subject: [PATCH 3/6] Issue #2431 - Upgrade to Junit 5 (#2436) + Changes needed for new Junit 5 + Migrating from Vintage junit API to Jupiter junit API + Relies on SNAPSHOT jetty-test-helper - this will be a formal release once this issue has been resolved satisfactory + Have jenkins always pull latest SNAPSHOT for each build + Adding jetty.snapshots repository + Using surefire 2.22.0 per advice from junit + Ensuring true to work around issue junit-team/junit5#801 + Disabling always in maven-surefire-plugin due to bug https://github.com/junit-team/junit5/issues/801 + OSGi tests must remain at vintage due to PaxExam + Moving from vintage TestingDir to jupiter WorkDir + Fixing imports to use jupiter, not vintage + Migrating vintage ExpectedException to jupiter assertThrows + Migrating vintage TestName to jupiter TestInfo + Migrating @RunWith(Parameterized.class) to @ParameterizedTest with Argument Sources + Migrating assertTrue(val.contains(needle)) to assertThat(val, containsString(needle)) + Aligning junit versions per recommendations from @sormuras + Adjusting parameter order change for assertEquals() + Test LifeCycle Annotation Migration junit 4 | junit 5 / jupiter ------------ | ----------- @Before | @BeforeEach @After | @AfterEach @BeforeClass | @BeforeAll @AfterClass | @AfterAll Signed-off-by: Joakim Erdfelt Signed-off-by: olivier lamy --- Jenkinsfile | 4 +- apache-jsp/pom.xml | 7 + .../jetty/jsp/TestJettyJspServlet.java | 46 +- .../jetty/jsp/TestJettyTldPreScanned.java | 4 +- .../jetty/jsp/TestJspFileNameToClass.java | 28 +- .../eclipse/jetty/jstl/JspIncludeTest.java | 12 +- .../java/org/eclipse/jetty/jstl/JstlTest.java | 13 +- jetty-alpn/jetty-alpn-java-server/pom.xml | 9 +- .../jetty/alpn/java/server/JDK9ALPNTest.java | 10 +- .../TestAnnotationConfiguration.java | 10 +- .../TestAnnotationInheritance.java | 33 +- .../annotations/TestAnnotationParser.java | 46 +- .../TestSecurityAnnotationConversions.java | 12 +- .../annotations/TestServletAnnotations.java | 33 +- .../resources/TestResourceAnnotations.java | 14 +- .../eclipse/jetty/ant/JettyAntTaskTest.java | 4 +- jetty-bom/pom.xml | 2 +- .../jetty/cdi/core/AbstractWeldTest.java | 8 +- .../cdi/servlet/WeldInitializationTest.java | 12 +- .../jetty/cdi/websocket/CheckSocket.java | 12 +- .../cdi/websocket/basicapp/BasicAppTest.java | 12 +- .../websocket/basicscope/ScopeBasicsTest.java | 12 +- .../cdi/websocket/cdiapp/CdiAppTest.java | 12 +- .../wsscope/WebSocketScopeBaselineTest.java | 12 +- .../wsscope/WebSocketScopeSessionTest.java | 12 +- .../java/org/eclipse/jetty/tests/HelloIT.java | 4 +- .../org/eclipse/jetty/tests/ServerInfoIT.java | 4 +- .../eclipse/jetty/tests/ws/SessionInfoIT.java | 4 +- jetty-client/pom.xml | 2 +- .../client/AbstractHttpClientServerTest.java | 145 +- .../client/ClientConnectionCloseTest.java | 85 +- .../jetty/client/ConnectionPoolTest.java | 81 +- .../jetty/client/ContentResponseTest.java | 82 +- .../jetty/client/ExternalSiteTest.java | 43 +- .../jetty/client/GZIPContentDecoderTest.java | 13 +- .../client/HostnameVerificationTest.java | 42 +- .../client/HttpAuthenticationStoreTest.java | 14 +- .../client/HttpClientAsyncContentTest.java | 36 +- .../client/HttpClientAuthenticationTest.java | 485 ++-- .../client/HttpClientChunkedContentTest.java | 21 +- .../client/HttpClientCustomProxyTest.java | 21 +- .../HttpClientExplicitConnectionTest.java | 68 +- .../jetty/client/HttpClientFailureTest.java | 46 +- .../jetty/client/HttpClientGZIPTest.java | 88 +- .../jetty/client/HttpClientProxyTest.java | 122 +- .../jetty/client/HttpClientRedirectTest.java | 392 +-- .../client/HttpClientSynchronizationTest.java | 40 +- .../jetty/client/HttpClientTLSTest.java | 118 +- .../eclipse/jetty/client/HttpClientTest.java | 782 +++--- .../jetty/client/HttpClientURITest.java | 363 +-- .../HttpClientUploadDuringServerShutdown.java | 19 +- .../client/HttpConnectionLifecycleTest.java | 256 +- .../eclipse/jetty/client/HttpCookieTest.java | 302 ++- .../jetty/client/HttpRequestAbortTest.java | 328 ++- .../jetty/client/HttpResponseAbortTest.java | 80 +- .../HttpResponseConcurrentAbortTest.java | 82 +- .../InsufficientThreadsDetectionTest.java | 24 +- .../eclipse/jetty/client/LivelockTest.java | 51 +- .../jetty/client/ProxyConfigurationTest.java | 33 +- .../client/ServerConnectionCloseTest.java | 22 +- .../eclipse/jetty/client/Socks4ProxyTest.java | 47 +- .../client/TLSServerConnectionCloseTest.java | 60 +- .../client/ValidatingConnectionPoolTest.java | 70 +- .../org/eclipse/jetty/client/api/Usage.java | 40 +- .../http/HttpDestinationOverHTTPTest.java | 150 +- .../client/http/HttpReceiverOverHTTPTest.java | 156 +- .../client/http/HttpSenderOverHTTPTest.java | 68 +- .../jetty/client/jmx/HttpClientJMXTest.java | 12 +- .../client/ssl/NeedWantClientAuthTest.java | 37 +- .../jetty/client/ssl/SslBytesClientTest.java | 106 +- .../jetty/client/ssl/SslBytesServerTest.java | 579 ++-- .../jetty/client/ssl/SslBytesTest.java | 11 +- .../jetty/client/ssl/SslConnectionTest.java | 16 +- .../util/DeferredContentProviderTest.java | 37 +- .../util/InputStreamContentProviderTest.java | 75 +- .../util/MultiPartContentProviderTest.java | 196 +- .../client/util/TypedContentProviderTest.java | 71 +- .../deploy/AppLifeCyclePathCollector.java | 8 +- .../jetty/deploy/AppLifeCycleTest.java | 21 +- .../DeploymentManagerLifeCyclePathTest.java | 2 +- .../jetty/deploy/DeploymentManagerTest.java | 33 +- .../GlobalWebappConfigBindingTest.java | 34 +- .../eclipse/jetty/deploy/graph/GraphTest.java | 66 +- ...ScanningAppProviderRuntimeUpdatesTest.java | 37 +- .../ScanningAppProviderStartupTest.java | 21 +- .../deploy/providers/WebAppProviderTest.java | 41 +- .../jetty/deploy/test/XmlConfiguredJetty.java | 37 +- .../fcgi/generator/ClientGeneratorTest.java | 39 +- .../jetty/fcgi/parser/ClientParserTest.java | 56 +- .../server/AbstractHttpClientServerTest.java | 12 +- .../server/ExternalFastCGIServerTest.java | 11 +- .../jetty/fcgi/server/HttpClientTest.java | 171 +- .../server/proxy/FastCGIProxyServletTest.java | 80 +- .../fcgi/server/proxy/TryFilesFilterTest.java | 20 +- .../session/TestHazelcastSessions.java | 12 +- .../eclipse/jetty/http/spi/TestSPIServer.java | 4 +- .../jetty/http/GZIPContentDecoderTest.java | 22 +- .../org/eclipse/jetty/http/HttpFieldTest.java | 12 +- .../jetty/http/HttpFieldsMatchers.java | 47 + .../eclipse/jetty/http/HttpFieldsTest.java | 104 +- .../jetty/http/HttpGeneratorClientTest.java | 220 +- .../http/HttpGeneratorServerHTTPTest.java | 79 +- .../jetty/http/HttpGeneratorServerTest.java | 27 +- .../eclipse/jetty/http/HttpParserTest.java | 1173 ++++---- .../jetty/http/HttpStatusCodeTest.java | 10 +- .../eclipse/jetty/http/HttpTesterTest.java | 4 +- .../eclipse/jetty/http/HttpURIParseTest.java | 222 +- .../org/eclipse/jetty/http/HttpURITest.java | 10 +- .../org/eclipse/jetty/http/MimeTypesTest.java | 14 +- .../jetty/http/MultiPartCaptureTest.java | 351 ++- .../http/MultiPartFormInputStreamTest.java | 408 ++- .../jetty/http/MultiPartParserTest.java | 140 +- .../org/eclipse/jetty/http/PathMapTest.java | 125 +- .../org/eclipse/jetty/http/QuotedCSVTest.java | 16 +- .../jetty/http/QuotedQualityCSVTest.java | 38 +- .../org/eclipse/jetty/http/SyntaxTest.java | 6 +- .../matchers/HttpFieldsContainsHeaderKey.java | 58 + .../HttpFieldsContainsHeaderValue.java | 75 + .../http/matchers/HttpFieldsMatchersTest.java | 118 + .../jetty/http/pathmap/PathMappingsTest.java | 126 +- .../jetty/http/pathmap/PathSpecAssert.java | 2 +- .../jetty/http/pathmap/RegexPathSpecTest.java | 46 +- .../pathmap/ServletPathSpecMatchListTest.java | 52 +- .../pathmap/ServletPathSpecOrderTest.java | 88 +- .../http/pathmap/ServletPathSpecTest.java | 70 +- .../UriTemplatePathSpecBadSpecsTest.java | 84 +- .../http/pathmap/UriTemplatePathSpecTest.java | 138 +- .../http2/alpn/tests/ALPNNegotiationTest.java | 32 +- .../http2/alpn/tests/AbstractALPNTest.java | 25 +- .../jetty/http2/client/AbstractTest.java | 8 +- .../jetty/http2/client/AsyncIOTest.java | 15 +- .../jetty/http2/client/AsyncServletTest.java | 45 +- .../http2/client/ConnectTimeoutTest.java | 15 +- .../http2/client/FlowControlStalledTest.java | 27 +- .../http2/client/FlowControlStrategyTest.java | 117 +- .../http2/client/FlowControlWindowsTest.java | 30 +- .../eclipse/jetty/http2/client/HTTP2Test.java | 100 +- .../jetty/http2/client/IdleTimeoutTest.java | 66 +- .../jetty/http2/client/InterleavingTest.java | 20 +- .../jetty/http2/client/InvalidServerTest.java | 10 +- .../http2/client/MaxPushedStreamsTest.java | 12 +- .../eclipse/jetty/http2/client/PingTest.java | 13 +- .../jetty/http2/client/PrefaceTest.java | 35 +- .../jetty/http2/client/PriorityTest.java | 30 +- .../jetty/http2/client/ProxyProtocolTest.java | 44 +- .../eclipse/jetty/http2/client/ProxyTest.java | 17 +- .../http2/client/PushCacheFilterTest.java | 76 +- .../jetty/http2/client/RawHTTP2ProxyTest.java | 17 +- .../http2/client/SessionFailureTest.java | 19 +- .../http2/client/SmallThreadPoolLoadTest.java | 17 +- .../jetty/http2/client/StreamCloseTest.java | 72 +- .../jetty/http2/client/StreamCountTest.java | 26 +- .../jetty/http2/client/StreamResetTest.java | 74 +- .../jetty/http2/client/TrailersTest.java | 70 +- .../http2/frames/ContinuationParseTest.java | 24 +- .../http2/frames/DataGenerateParseTest.java | 25 +- .../http2/frames/GoAwayGenerateParseTest.java | 24 +- .../frames/HeadersGenerateParseTest.java | 52 +- .../http2/frames/MaxFrameSizeParseTest.java | 7 +- .../http2/frames/PingGenerateParseTest.java | 26 +- .../frames/PriorityGenerateParseTest.java | 26 +- .../frames/PushPromiseGenerateParseTest.java | 31 +- .../http2/frames/ResetGenerateParseTest.java | 18 +- .../frames/SettingsGenerateParseTest.java | 40 +- .../jetty/http2/frames/UnknownParseTest.java | 10 +- .../frames/WindowUpdateGenerateParseTest.java | 18 +- jetty-http2/http2-hpack/pom.xml | 7 + .../jetty/http2/hpack/HpackContextTest.java | 26 +- .../jetty/http2/hpack/HpackDecoderTest.java | 284 +- .../jetty/http2/hpack/HpackEncoderTest.java | 26 +- .../jetty/http2/hpack/HpackPerfTest.java | 10 +- .../eclipse/jetty/http2/hpack/HpackTest.java | 15 +- .../jetty/http2/hpack/HuffmanTest.java | 104 +- .../jetty/http2/hpack/NBitIntegerTest.java | 18 +- .../jetty/http2/client/http/AbstractTest.java | 8 +- .../client/http/DirectHTTP2OverTLSTest.java | 16 +- .../HttpClientTransportOverHTTP2Test.java | 120 +- .../client/http/MaxConcurrentStreamsTest.java | 94 +- .../client/http/PushedResourcesTest.java | 38 +- .../http2/server/AbstractServerTest.java | 8 +- .../eclipse/jetty/http2/server/CloseTest.java | 29 +- .../jetty/http2/server/HTTP2CServerTest.java | 49 +- .../jetty/http2/server/HTTP2ServerTest.java | 56 +- .../jetty/io/ArrayByteBufferPoolTest.java | 8 +- .../jetty/io/ByteArrayEndPointTest.java | 42 +- .../eclipse/jetty/io/CyclicTimeoutTest.java | 60 +- .../java/org/eclipse/jetty/io/IOTest.java | 39 +- .../org/eclipse/jetty/io/IdleTimeoutTest.java | 33 +- .../jetty/io/MappedByteBufferPoolTest.java | 12 +- .../java/org/eclipse/jetty/io/NIOTest.java | 13 +- .../eclipse/jetty/io/SelectorManagerTest.java | 29 +- .../SocketChannelEndPointInterestsTest.java | 17 +- .../SocketChannelEndPointOpenCloseTest.java | 16 +- .../jetty/io/SocketChannelEndPointTest.java | 150 +- .../eclipse/jetty/io/SslConnectionTest.java | 80 +- .../jetty/io/SslEngineBehaviorTest.java | 27 +- .../eclipse/jetty/io/WriteFlusherTest.java | 205 +- .../jetty/jaas/JAASLdapLoginServiceTest.java | 1 + .../jetty/jaas/JAASLoginServiceTest.java | 8 +- .../eclipse/jetty/jaas/TestLoginModule.java | 2 +- .../jetty/security/jaspi/JaspiTest.java | 12 +- .../jetty/http/jmh/MultiPartBenchmark.java | 30 +- .../jetty/jmx/ConnectorServerTest.java | 71 +- .../jmx/MBeanContainerLifeCycleTest.java | 26 +- .../eclipse/jetty/jmx/MBeanContainerTest.java | 46 +- .../eclipse/jetty/jmx/ObjectMBeanTest.java | 79 +- .../jetty/jmx/ObjectMBeanUtilTest.java | 112 +- .../java/org/eclipse/jetty/jmx/PojoTest.java | 2 +- .../jetty/util/log/jmx/LogMBeanTest.java | 20 +- .../factories/TestMailSessionReference.java | 8 +- .../org/eclipse/jetty/jndi/java/TestJNDI.java | 10 +- .../jetty/jndi/java/TestLocalJNDI.java | 12 +- jetty-jspc-maven-plugin/pom.xml | 2 +- jetty-maven-plugin/pom.xml | 2 +- .../src/it/jetty-cdi-run-forked/pom.xml | 2 +- .../src/it/jetty-deploy-war-mojo-it/pom.xml | 2 +- .../jetty-simple-webapp/pom.xml | 2 +- .../jetty-simple-webapp/pom.xml | 2 +- .../jetty-simple-webapp/pom.xml | 2 +- .../jetty-simple-webapp/pom.xml | 4 +- .../jetty-simple-webapp/pom.xml | 4 +- .../jetty-simple-webapp/pom.xml | 2 +- .../it/run-mojo-gwt-it/beer-server/pom.xml | 2 +- .../jetty/maven/plugin/it/TestGetContent.java | 26 +- .../session/TestMemcachedSessions.java | 8 +- .../jetty/osgi/test/SimpleJavaxWebSocket.java | 1 - .../osgi/test/TestJettyOSGiBootHTTP2.java | 13 +- .../TestJettyOSGiBootWithJavaxWebSocket.java | 1 - .../eclipse/jetty/osgi/test/TestOSGiUtil.java | 28 +- .../overlays/OverlayedAppProviderTest.java | 60 +- .../jetty/plus/jndi/TestNamingEntries.java | 22 +- .../jetty/plus/jndi/TestNamingEntryUtil.java | 26 +- .../webapp/PlusDescriptorProcessorTest.java | 44 +- .../jetty/plus/webapp/TestConfiguration.java | 6 +- .../proxy/AbstractConnectHandlerTest.java | 10 +- .../proxy/AsyncMiddleManServletTest.java | 165 +- .../jetty/proxy/BalancerServletTest.java | 20 +- .../jetty/proxy/CachingProxyServlet.java | 85 + .../jetty/proxy/ConnectHandlerSSLTest.java | 22 +- .../jetty/proxy/ConnectHandlerTest.java | 130 +- .../jetty/proxy/ForwardProxyServerTest.java | 79 +- .../proxy/ForwardProxyTLSServerTest.java | 210 +- .../jetty/proxy/ProxyServletFailureTest.java | 165 +- .../jetty/proxy/ProxyServletLoadTest.java | 46 +- .../eclipse/jetty/proxy/ProxyServletTest.java | 566 ++-- .../eclipse/jetty/proxy/ReverseProxyTest.java | 26 +- .../test/resources/jetty-logging.properties | 1 + .../jetty/quickstart/FooContextListener.java | 10 +- .../jetty/quickstart/TestQuickStart.java | 8 +- .../rewrite/handler/AbstractRuleTestCase.java | 4 +- .../handler/CookiePatternRuleTest.java | 44 +- .../ForwardedSchemeHeaderRuleTest.java | 8 +- .../handler/HeaderPatternRuleTest.java | 8 +- .../rewrite/handler/HeaderRegexRuleTest.java | 8 +- .../rewrite/handler/MsieSslRuleTest.java | 8 +- .../rewrite/handler/PatternRuleTest.java | 14 +- .../handler/RedirectPatternRuleTest.java | 10 +- .../handler/RedirectRegexRuleTest.java | 10 +- .../jetty/rewrite/handler/RegexRuleTest.java | 14 +- .../handler/ResponsePatternRuleTest.java | 8 +- .../rewrite/handler/RewriteHandlerTest.java | 10 +- .../handler/RewritePatternRuleTest.java | 9 +- .../rewrite/handler/RewriteRegexRuleTest.java | 171 +- .../handler/TerminatingPatternRuleTest.java | 10 +- .../handler/TerminatingRegexRuleTest.java | 10 +- .../rewrite/handler/ValidUrlRuleTest.java | 21 +- .../handler/VirtualHostRuleContainerTest.java | 37 +- jetty-runner/pom.xml | 15 +- jetty-security/pom.xml | 7 + .../jetty/security/AliasedConstraintTest.java | 43 +- .../jetty/security/ConstraintTest.java | 836 +++--- .../jetty/security/DataConstraintsTest.java | 92 +- .../jetty/security/PropertyUserStoreTest.java | 103 +- .../security/SpecExampleConstraintTest.java | 20 +- .../eclipse/jetty/security/UserStoreTest.java | 33 +- .../SpnegoAuthenticatorTest.java | 12 +- .../jetty/server/AbstractHttpTest.java | 43 +- .../jetty/server/AsyncRequestReadTest.java | 23 +- .../eclipse/jetty/server/AsyncStressTest.java | 31 +- .../server/CheckReverseProxyHeadersTest.java | 12 +- .../jetty/server/ClassLoaderDumptTest.java | 4 +- .../jetty/server/ConnectionOpenCloseTest.java | 62 +- .../jetty/server/ConnectorCloseTestBase.java | 7 +- .../jetty/server/ConnectorTimeoutTest.java | 400 +-- .../jetty/server/CookieCutterTest.java | 11 +- .../server/CookieCutter_LenientTest.java | 243 +- .../server/CustomResourcesMonitorTest.java | 14 +- .../jetty/server/ErrorHandlerTest.java | 12 +- .../jetty/server/ExtendedServerTest.java | 21 +- .../ForwardedRequestCustomizerTest.java | 22 +- .../jetty/server/GracefulStopTest.java | 74 +- .../eclipse/jetty/server/HalfCloseTest.java | 7 +- .../server/HostHeaderCustomizerTest.java | 28 +- .../jetty/server/HttpChannelEventTest.java | 41 +- .../jetty/server/HttpConnectionTest.java | 60 +- .../jetty/server/HttpInputAsyncStateTest.java | 36 +- .../eclipse/jetty/server/HttpInputTest.java | 396 ++- ...ManyWaysToAsyncCommitBadBehaviourTest.java | 52 +- .../server/HttpManyWaysToAsyncCommitTest.java | 351 +-- .../server/HttpManyWaysToCommitTest.java | 293 +- .../eclipse/jetty/server/HttpOutputTest.java | 32 +- .../jetty/server/HttpServerTestBase.java | 97 +- .../jetty/server/HttpServerTestFixture.java | 11 +- .../server/HttpVersionCustomizerTest.java | 24 +- .../eclipse/jetty/server/HttpWriterTest.java | 17 +- .../jetty/server/InclusiveByteRangeTest.java | 111 +- .../InsufficientThreadsDetectionTest.java | 39 +- .../jetty/server/LocalAsyncContextTest.java | 26 +- .../jetty/server/LocalConnectorTest.java | 17 +- .../jetty/server/LowResourcesMonitorTest.java | 44 +- .../server/NetworkTrafficListenerTest.java | 13 +- .../jetty/server/NotAcceptingTest.java | 28 +- .../jetty/server/PartialRFC2616Test.java | 48 +- .../jetty/server/ProxyConnectionTest.java | 48 +- .../jetty/server/ProxyProtocolTest.java | 17 +- .../org/eclipse/jetty/server/RequestTest.java | 115 +- .../jetty/server/ResourceCacheTest.java | 49 +- .../eclipse/jetty/server/ResponseTest.java | 102 +- .../ServerConnectorAsyncContextTest.java | 3 - .../server/ServerConnectorCloseTest.java | 14 +- .../server/ServerConnectorHttpServerTest.java | 7 +- .../jetty/server/ServerConnectorTest.java | 24 +- .../server/ServerConnectorTimeoutTest.java | 60 +- .../jetty/server/ShutdownMonitorTest.java | 24 +- .../SlowClientWithPipelinedRequestTest.java | 22 +- .../org/eclipse/jetty/server/StressTest.java | 52 +- .../jetty/server/ThreadStarvationTest.java | 96 +- .../handler/AllowSymLinkAliasCheckerTest.java | 100 +- .../handler/BadRequestLogHandlerTest.java | 72 +- .../handler/BufferedResponseHandlerTest.java | 16 +- .../handler/ContextHandlerCollectionTest.java | 23 +- .../ContextHandlerGetResourceTest.java | 50 +- .../server/handler/ContextHandlerTest.java | 334 +-- .../server/handler/DebugHandlerTest.java | 16 +- .../server/handler/DefaultHandlerTest.java | 37 +- .../jetty/server/handler/HandlerTest.java | 109 +- .../server/handler/IPAccessHandlerTest.java | 66 +- .../server/handler/RequestLogHandlerTest.java | 85 +- .../jetty/server/handler/RequestLogTest.java | 12 +- .../handler/ResourceHandlerRangeTest.java | 24 +- .../server/handler/ResourceHandlerTest.java | 35 +- .../server/handler/ScopedHandlerTest.java | 8 +- .../handler/SecuredRedirectHandlerTest.java | 12 +- .../server/handler/ShutdownHandlerTest.java | 21 +- .../server/handler/StatisticsHandlerTest.java | 18 +- .../handler/ThreadLimitHandlerTest.java | 36 +- .../server/session/SessionCookieTest.java | 6 +- .../jetty/server/ssl/SSLCloseTest.java | 2 +- .../jetty/server/ssl/SSLEngineTest.java | 21 +- .../SSLSelectChannelConnectorLoadTest.java | 12 +- .../ssl/SelectChannelServerSslTest.java | 37 +- .../jetty/server/ssl/SlowClientsTest.java | 92 +- .../ssl/SniSslConnectionFactoryTest.java | 72 +- .../server/ssl/SslConnectionFactoryTest.java | 47 +- .../ssl/SslContextFactoryReloadTest.java | 38 +- .../ssl/SslSelectChannelTimeoutTest.java | 4 +- .../jetty/server/ssl/SslUploadTest.java | 18 +- .../AsyncContextDispatchWithQueryStrings.java | 14 +- .../servlet/AsyncContextListenersTest.java | 21 +- .../jetty/servlet/AsyncContextTest.java | 17 +- .../jetty/servlet/AsyncListenerTest.java | 16 +- .../jetty/servlet/AsyncServletIOTest.java | 67 +- .../servlet/AsyncServletLongPollTest.java | 22 +- .../jetty/servlet/AsyncServletTest.java | 35 +- .../servlet/ComplianceViolations2616Test.java | 16 +- .../servlet/DefaultServletRangesTest.java | 62 +- .../jetty/servlet/DefaultServletTest.java | 2349 ++++++++++------- .../jetty/servlet/DispatcherForwardTest.java | 49 +- .../eclipse/jetty/servlet/DispatcherTest.java | 36 +- .../eclipse/jetty/servlet/EncodedURITest.java | 12 +- .../eclipse/jetty/servlet/ErrorPageTest.java | 12 +- .../jetty/servlet/FilterHolderTest.java | 5 +- .../jetty/servlet/GzipHandlerTest.java | 14 +- .../org/eclipse/jetty/servlet/HolderTest.java | 16 +- .../jetty/servlet/IncludedServletTest.java | 12 +- .../eclipse/jetty/servlet/InvokerTest.java | 12 +- .../jetty/servlet/PostServletTest.java | 27 +- .../jetty/servlet/RequestHeadersTest.java | 14 +- .../eclipse/jetty/servlet/RequestURITest.java | 100 +- .../jetty/servlet/ResponseHeadersTest.java | 12 +- .../jetty/servlet/SSLAsyncIOServletTest.java | 184 +- .../servlet/ServletContextHandlerTest.java | 63 +- .../servlet/ServletContextResourcesTest.java | 12 +- .../jetty/servlet/ServletHandlerTest.java | 12 +- .../jetty/servlet/ServletHolderTest.java | 59 +- .../jetty/servlet/ServletRequestLogTest.java | 294 ++- .../jetty/servlet/StatisticsServletTest.java | 46 +- .../gzip/AsyncTimeoutCompleteWrite.java | 2 +- .../handler/gzip/GzipContentLengthTest.java | 185 +- .../gzip/GzipDefaultNoRecompressTest.java | 42 +- .../server/handler/gzip/GzipDefaultTest.java | 85 +- .../jetty/server/handler/gzip/GzipTester.java | 70 +- .../handler/gzip/IncludedGzipMinSizeTest.java | 15 +- .../server/handler/gzip/IncludedGzipTest.java | 22 +- .../jetty/servlets/AbstractDoSFilterTest.java | 65 +- .../servlets/CloseableDoSFilterTest.java | 12 +- .../jetty/servlets/ConcatServletTest.java | 36 +- .../jetty/servlets/CrossOriginFilterTest.java | 307 ++- .../servlets/DataRateLimitedServletTest.java | 21 +- .../jetty/servlets/DoSFilterJMXTest.java | 25 +- .../eclipse/jetty/servlets/DoSFilterTest.java | 42 +- .../servlets/EventSourceServletTest.java | 51 +- .../jetty/servlets/GzipFilterLayeredTest.java | 148 +- .../jetty/servlets/HeaderFilterTest.java | 23 +- .../IncludeExcludeBasedFilterTest.java | 45 +- .../jetty/servlets/MultipartFilterTest.java | 36 +- .../eclipse/jetty/servlets/PutFilterTest.java | 26 +- .../eclipse/jetty/servlets/QoSFilterTest.java | 25 +- .../jetty/servlets/ThreadStarvationTest.java | 25 +- .../spring/SpringXmlConfigurationTest.java | 10 +- .../jetty/spring/TestConfiguration.java | 4 +- .../org/eclipse/jetty/start/BaseHomeTest.java | 29 +- .../jetty/start/CommandLineBuilderTest.java | 8 +- .../jetty/start/ConfigurationAssert.java | 13 +- .../java/org/eclipse/jetty/start/FSTest.java | 15 +- .../org/eclipse/jetty/start/FileArgTest.java | 94 +- .../jetty/start/IncludeJettyDirTest.java | 29 +- .../eclipse/jetty/start/JarVersionTest.java | 7 +- .../org/eclipse/jetty/start/MainTest.java | 29 +- .../jetty/start/ModuleGraphWriterTest.java | 15 +- .../org/eclipse/jetty/start/ModuleTest.java | 25 +- .../org/eclipse/jetty/start/ModulesTest.java | 19 +- .../eclipse/jetty/start/PathFinderTest.java | 15 +- .../jetty/start/PathMatchersAbsoluteTest.java | 69 +- .../start/PathMatchersSearchRootTest.java | 78 +- .../jetty/start/PropertyPassingTest.java | 21 +- .../org/eclipse/jetty/start/PropsTest.java | 6 +- .../jetty/start/SystemExitAsException.java | 79 - .../eclipse/jetty/start/TestBadUseCases.java | 45 +- .../java/org/eclipse/jetty/start/TestEnv.java | 3 +- .../org/eclipse/jetty/start/TestUseCases.java | 31 +- .../org/eclipse/jetty/start/VersionTest.java | 10 +- .../jetty/start/config/ConfigSourcesTest.java | 30 +- .../MavenLocalRepoFileInitializerTest.java | 27 +- .../jetty/unixsocket/UnixSocketTest.java | 81 +- .../ajax/JSONCollectionConvertorTest.java | 20 +- .../ajax/JSONPojoConvertorFactoryTest.java | 6 +- .../util/ajax/JSONPojoConvertorTest.java | 10 +- .../org/eclipse/jetty/util/ajax/JSONTest.java | 12 +- .../eclipse/jetty/util/resource/Resource.java | 14 + .../jetty/util/AtomicBiIntegerTest.java | 8 +- .../org/eclipse/jetty/util/B64CodeTest.java | 16 +- .../jetty/util/BlockingArrayQueueTest.java | 196 +- .../eclipse/jetty/util/BufferUtilTest.java | 42 +- .../eclipse/jetty/util/CollectionAssert.java | 11 +- .../org/eclipse/jetty/util/DateCacheTest.java | 46 +- .../jetty/util/FutureCallbackTest.java | 80 +- .../org/eclipse/jetty/util/HostPortTest.java | 105 +- .../eclipse/jetty/util/IPAddressMapTest.java | 8 +- .../jetty/util/IncludeExcludeSetTest.java | 6 +- .../jetty/util/IncludeExcludeTest.java | 6 +- .../jetty/util/InetAddressSetTest.java | 16 +- .../jetty/util/IteratingCallbackTest.java | 44 +- .../eclipse/jetty/util/JavaVersionTest.java | 4 +- .../org/eclipse/jetty/util/LazyListTest.java | 368 +-- .../eclipse/jetty/util/LeakDetectorTest.java | 11 +- .../jetty/util/MultiExceptionTest.java | 46 +- .../org/eclipse/jetty/util/MultiMapTest.java | 57 +- .../jetty/util/MultiPartInputStreamTest.java | 72 +- .../jetty/util/MultiReleaseJarFileTest.java | 27 +- .../eclipse/jetty/util/PathWatcherTest.java | 42 +- .../jetty/util/ProcessorUtilsTest.java | 22 +- .../jetty/util/QueueBenchmarkTest.java | 20 +- .../jetty/util/QuotedStringTokenizerTest.java | 8 +- .../jetty/util/ReadLineInputStreamTest.java | 122 +- .../org/eclipse/jetty/util/RegexSetTest.java | 52 +- .../util/RolloverFileOutputStreamTest.java | 13 +- .../org/eclipse/jetty/util/ScannerTest.java | 123 +- .../eclipse/jetty/util/SearchPatternTest.java | 88 +- .../util/SharedBlockingCallbackTest.java | 61 +- .../eclipse/jetty/util/StringUtilTest.java | 60 +- .../jetty/util/TestIntrospectionUtil.java | 33 +- .../jetty/util/TopologicalSortTest.java | 65 +- .../java/org/eclipse/jetty/util/TrieTest.java | 346 +-- .../org/eclipse/jetty/util/TypeUtilTest.java | 116 +- .../jetty/util/URIUtilCanonicalPathTest.java | 35 +- .../org/eclipse/jetty/util/URIUtilTest.java | 292 +- .../eclipse/jetty/util/URLEncodedTest.java | 287 +- .../org/eclipse/jetty/util/UptimeTest.java | 2 +- .../util/UrlEncodedInvalidEncodingTest.java | 90 +- .../jetty/util/UrlEncodedUtf8Test.java | 19 +- .../jetty/util/Utf8AppendableTest.java | 252 +- .../jetty/util/Utf8LineParserTest.java | 17 +- .../component/ContainerLifeCycleTest.java | 271 +- .../LifeCycleListenerNestedTest.java | 8 +- .../util/component/LifeCycleListenerTest.java | 28 +- .../jetty/util/log/CapturingJULHandler.java | 5 +- .../jetty/util/log/JavaUtilLogTest.java | 29 +- .../org/eclipse/jetty/util/log/LogTest.java | 55 +- .../eclipse/jetty/util/log/NamedLogTest.java | 2 +- .../eclipse/jetty/util/log/Slf4jHelper.java | 7 +- .../eclipse/jetty/util/log/StdErrCapture.java | 7 +- .../eclipse/jetty/util/log/StdErrLogTest.java | 152 +- .../util/resource/ClassPathResourceTest.java | 30 +- .../util/resource/FileSystemResourceTest.java | 713 ++--- .../jetty/util/resource/JarResourceTest.java | 32 +- .../jetty/util/resource/JrtResourceTest.java | 37 +- .../util/resource/ResourceAliasTest.java | 67 +- .../util/resource/ResourceCollectionTest.java | 36 +- .../jetty/util/resource/ResourceTest.java | 149 +- .../jetty/util/security/CredentialTest.java | 6 +- .../jetty/util/security/PasswordTest.java | 4 +- .../jetty/util/ssl/SslContextFactoryTest.java | 41 +- .../org/eclipse/jetty/util/ssl/X509Test.java | 4 +- .../util/statistic/CounterStatisticTest.java | 4 +- .../util/statistic/RateStatisticTest.java | 2 +- .../util/statistic/SampleStatisticTest.java | 14 +- .../jetty/util/thread/EatWhatYouKillTest.java | 11 +- .../eclipse/jetty/util/thread/LockerTest.java | 6 +- .../util/thread/QueuedThreadPoolTest.java | 27 +- .../thread/ReservedThreadExecutorTest.java | 25 +- .../jetty/util/thread/SchedulerTest.java | 147 +- .../jetty/util/thread/SweeperTest.java | 27 +- .../thread/ThreadClassLoaderScopeTest.java | 4 +- .../strategy/ExecuteProduceConsumeTest.java | 61 +- .../strategy/ExecutionStrategyTest.java | 112 +- jetty-webapp/pom.xml | 3 +- .../jetty/webapp/ClasspathPatternTest.java | 140 +- .../webapp/MetaInfConfigurationTest.java | 10 +- .../eclipse/jetty/webapp/OrderingTest.java | 30 +- .../jetty/webapp/WebAppClassLoaderTest.java | 36 +- .../WebAppClassLoaderUrlStreamTest.java | 8 +- .../jetty/webapp/WebAppContextTest.java | 29 +- .../jetty/webapp/WebInfConfigurationTest.java | 30 +- .../websocket/jsr356/AnnotatedEchoTest.java | 10 +- .../jsr356/AnnotatedEndpointConfigTest.java | 37 +- .../websocket/jsr356/ConfiguratorTest.java | 16 +- .../jetty/websocket/jsr356/CookiesTest.java | 43 +- .../websocket/jsr356/DecoderFactoryTest.java | 16 +- .../jsr356/DecoderReaderManySmallTest.java | 31 +- .../websocket/jsr356/DecoderReaderTest.java | 31 +- .../jsr356/DelayedStartClientTest.java | 8 +- .../websocket/jsr356/EncoderFactoryTest.java | 16 +- .../jetty/websocket/jsr356/EncoderTest.java | 66 +- .../websocket/jsr356/EndpointEchoClient.java | 7 +- .../websocket/jsr356/EndpointEchoTest.java | 15 +- .../websocket/jsr356/JsrSessionTest.java | 35 +- .../websocket/jsr356/LargeMessageTest.java | 13 +- .../jsr356/MessageHandlerFactoryTest.java | 20 +- .../jsr356/MessageReceivingTest.java | 32 +- .../annotations/JsrParamIdDecoderTest.java | 7 +- .../jsr356/decoders/IntegerDecoderTest.java | 7 +- .../PrimitiveDecoderMetadataSetTest.java | 11 +- ...tedEndpointScanner_GoodSignaturesTest.java | 126 +- ...EndpointScanner_InvalidSignaturesTest.java | 55 +- .../jsr356/endpoints/OnCloseTest.java | 75 +- .../jsr356/endpoints/TrackingSocket.java | 23 +- .../metadata/DecoderMetadataSetTest.java | 45 +- .../metadata/EncoderMetadataSetTest.java | 45 +- .../misbehaving/MisbehavingClassTest.java | 54 +- .../jsr356/utils/ReflectUtilsTest.java | 10 +- .../jsr356/server/AltFilterTest.java | 17 +- .../server/AnnotatedServerEndpointTest.java | 15 +- .../jsr356/server/BasicEndpointTest.java | 16 +- .../jsr356/server/BinaryStreamTest.java | 23 +- .../jsr356/server/ConfiguratorTest.java | 44 +- .../DelayedStartClientOnServerTest.java | 51 +- .../websocket/jsr356/server/EchoCase.java | 34 +- .../websocket/jsr356/server/EchoTest.java | 56 +- .../server/ExtensionStackProcessingTest.java | 40 +- .../jsr356/server/IdleTimeoutTest.java | 12 +- .../JettyServerEndpointConfiguratorTest.java | 4 +- .../jsr356/server/JsrBatchModeTest.java | 22 +- .../jsr356/server/LargeAnnotatedTest.java | 40 +- .../jsr356/server/LargeContainerTest.java | 20 +- .../LargeNestedClientContainerTest.java | 20 +- .../LargeOnOpenSessionConfiguredTest.java | 16 +- .../jsr356/server/MemoryUsageTest.java | 14 +- .../jsr356/server/OnMessageReturnTest.java | 16 +- .../jsr356/server/OnPartialTest.java | 23 +- .../websocket/jsr356/server/PingPongTest.java | 30 +- ...tedEndpointScanner_GoodSignaturesTest.java | 156 +- ...EndpointScanner_InvalidSignaturesTest.java | 54 +- .../websocket/jsr356/server/SessionTest.java | 179 +- .../jsr356/server/SessionTrackingTest.java | 22 +- .../websocket/jsr356/server/StreamTest.java | 23 +- .../jsr356/server/TextStreamTest.java | 23 +- .../jsr356/server/TrackingSocket.java | 23 +- .../websocket/jsr356/server/WSServer.java | 20 +- .../api/extensions/ExtensionConfigTest.java | 15 +- .../websocket/api/util/QuoteUtilTest.java | 23 +- .../api/util/QuoteUtil_QuoteTest.java | 42 +- .../jetty/websocket/api/util/WSURITest.java | 7 +- .../websocket/client/BadNetworkTest.java | 18 +- .../websocket/client/ClientCloseTest.java | 103 +- .../websocket/client/ClientConnectTest.java | 197 +- .../client/ConnectionManagerTest.java | 9 +- .../jetty/websocket/client/CookieTest.java | 28 +- .../websocket/client/HttpClientInitTest.java | 4 +- .../websocket/client/JettyTrackingSocket.java | 24 +- .../websocket/client/MaxMessageSocket.java | 12 +- .../jetty/websocket/client/SessionTest.java | 32 +- .../websocket/client/SlowClientTest.java | 25 +- .../websocket/client/SlowServerTest.java | 25 +- .../client/TomcatServerQuirksTest.java | 18 +- .../client/WebSocketClientBadUriTest.java | 57 +- .../client/WebSocketClientInitTest.java | 4 +- .../websocket/client/WebSocketClientTest.java | 38 +- .../websocket/common/AcceptHashTest.java | 11 +- .../jetty/websocket/common/CloseInfoTest.java | 4 +- .../common/ClosePayloadParserTest.java | 9 +- .../common/GeneratorParserRoundtripTest.java | 12 +- .../jetty/websocket/common/GeneratorTest.java | 23 +- .../jetty/websocket/common/ParserTest.java | 31 +- .../common/PingPayloadParserTest.java | 7 +- .../common/RFC6455ExamplesGeneratorTest.java | 2 +- .../common/RFC6455ExamplesParserTest.java | 29 +- .../common/SaneFrameOrderingAssertion.java | 16 +- .../common/TextPayloadParserTest.java | 32 +- .../websocket/common/WebSocketFrameTest.java | 11 +- .../common/WebSocketRemoteEndpointTest.java | 40 +- .../websocket/common/ab/TestABCase1_1.java | 45 +- .../websocket/common/ab/TestABCase1_2.java | 47 +- .../websocket/common/ab/TestABCase2.java | 49 +- .../websocket/common/ab/TestABCase3.java | 73 +- .../websocket/common/ab/TestABCase4.java | 21 +- .../websocket/common/ab/TestABCase7_3.java | 38 +- .../common/events/EventDriverFactoryTest.java | 11 +- .../common/events/EventDriverTest.java | 46 +- .../events/JettyAnnotatedScannerTest.java | 107 +- .../extensions/AbstractExtensionTest.java | 9 +- .../extensions/DummyOutgoingFrames.java | 6 - .../common/extensions/ExtensionStackTest.java | 20 +- .../common/extensions/ExtensionTool.java | 17 +- .../extensions/FragmentExtensionTest.java | 66 +- .../extensions/IdentityExtensionTest.java | 29 +- .../compress/ByteAccumulatorTest.java | 18 +- .../compress/DeflateFrameExtensionTest.java | 28 +- .../PerMessageDeflateExtensionTest.java | 42 +- .../io/CloseableLocalWebSocketSession.java | 5 +- .../websocket/common/io/FrameFlusherTest.java | 18 +- .../websocket/common/io/IOStateTest.java | 4 +- .../common/io/LocalWebSocketConnection.java | 6 - .../common/io/LocalWebSocketSession.java | 9 +- .../io/http/HttpResponseHeaderParserTest.java | 24 +- .../io/payload/DeMaskProcessorTest.java | 11 +- .../message/MessageInputStreamTest.java | 159 +- .../message/MessageOutputStreamTest.java | 35 +- .../common/message/MessageWriterTest.java | 35 +- .../message/TrackingInputStreamSocket.java | 11 +- .../common/message/TrackingSocket.java | 26 +- .../common/message/Utf8CharBufferTest.java | 33 +- .../common/test/ByteBufferAssert.java | 10 +- .../jetty/websocket/common/test/Fuzzed.java | 2 - .../jetty/websocket/common/test/Fuzzer.java | 22 +- .../common/test/IncomingFramesCapture.java | 19 +- .../common/test/OutgoingFramesCapture.java | 11 +- .../test/OutgoingNetworkBytesCapture.java | 7 +- .../common/test/RawFrameBuilder.java | 9 +- .../jetty/websocket/common/util/Hex.java | 3 + .../jetty/websocket/common/util/Sha1Sum.java | 9 +- .../websocket/common/util/StackUtil.java | 3 + .../common/util/Utf8PartialBuilderTest.java | 6 +- .../server/AnnotatedMaxMessageSizeTest.java | 46 +- .../jetty/websocket/server/BatchModeTest.java | 15 +- .../jetty/websocket/server/ChromeTest.java | 30 +- .../server/DecoratorsLegacyTest.java | 20 +- .../websocket/server/DecoratorsTest.java | 16 +- .../jetty/websocket/server/FirefoxTest.java | 14 +- .../server/FragmentExtensionTest.java | 30 +- .../server/IdentityExtensionTest.java | 20 +- .../websocket/server/IdleTimeoutTest.java | 22 +- .../server/ManyConnectionsCleanupTest.java | 16 +- .../PerMessageDeflateExtensionTest.java | 127 +- .../websocket/server/RequestHeadersTest.java | 16 +- .../websocket/server/SubProtocolTest.java | 16 +- .../websocket/server/SuspendResumeTest.java | 20 +- .../websocket/server/TooFastClientTest.java | 23 +- .../jetty/websocket/server/WSServer.java | 9 +- .../websocket/server/WebSocketCloseTest.java | 20 +- .../server/WebSocketInvalidVersionTest.java | 32 +- .../server/WebSocketOverSSLTest.java | 24 +- .../server/WebSocketProtocolTest.java | 22 +- .../server/WebSocketServerFactoryTest.java | 4 +- .../server/WebSocketServerSessionTest.java | 25 +- .../server/WebSocketServletRFCTest.java | 47 +- .../server/WebSocketUpgradeFilterTest.java | 93 +- .../websocket/server/ab/AbstractABCase.java | 23 +- .../websocket/server/ab/TestABCase1.java | 2 +- .../websocket/server/ab/TestABCase2.java | 2 +- .../websocket/server/ab/TestABCase3.java | 2 +- .../websocket/server/ab/TestABCase4.java | 2 +- .../websocket/server/ab/TestABCase5.java | 2 +- .../websocket/server/ab/TestABCase6.java | 2 +- .../server/ab/TestABCase6_BadUTF.java | 37 +- .../server/ab/TestABCase6_GoodUTF.java | 30 +- .../websocket/server/ab/TestABCase7.java | 2 +- .../server/ab/TestABCase7_BadStatusCodes.java | 73 +- .../ab/TestABCase7_GoodStatusCodes.java | 35 +- .../websocket/server/ab/TestABCase9.java | 2 +- .../websocket/server/helper/SafariD00.java | 8 +- .../misbehaving/MisbehavingClassTest.java | 18 +- .../eclipse/jetty/xml/TestConfiguration.java | 4 +- .../eclipse/jetty/xml/XmlAppendableTest.java | 8 +- .../jetty/xml/XmlConfigurationTest.java | 365 ++- .../org/eclipse/jetty/xml/XmlParserTest.java | 4 +- pom.xml | 80 +- .../jetty/continuation/ContinuationsTest.java | 347 +-- .../jetty/http/client/AbstractTest.java | 325 +-- .../jetty/http/client/AsyncIOServletTest.java | 476 ++-- .../http/client/AsyncRequestContentTest.java | 85 +- .../http/client/ConnectionStatisticsTest.java | 64 +- .../client/HttpChannelAssociationTest.java | 60 +- .../client/HttpClientConnectTimeoutTest.java | 95 +- .../http/client/HttpClientContinueTest.java | 319 ++- .../client/HttpClientIdleTimeoutTest.java | 97 +- .../jetty/http/client/HttpClientLoadTest.java | 224 +- .../http/client/HttpClientStreamTest.java | 588 +++-- .../jetty/http/client/HttpClientTest.java | 329 ++- .../http/client/HttpClientTimeoutTest.java | 297 ++- .../jetty/http/client/HttpTrailersTest.java | 124 +- .../client/RoundRobinConnectionPoolTest.java | 72 +- .../jetty/http/client/ServerTimeoutsTest.java | 416 +-- .../eclipse/jetty/http/client/Transport.java | 40 + .../jetty/http/client/TransportProvider.java | 56 + .../jetty/http/client/TransportScenario.java | 378 +++ tests/test-integration/pom.xml | 3 +- .../jetty/test/DefaultHandlerTest.java | 86 +- .../jetty/test/DeploymentErrorTest.java | 31 +- .../eclipse/jetty/test/DigestPostTest.java | 40 +- .../jetty/test/HttpInputIntegrationTest.java | 205 +- .../jsp/JspAndDefaultWithAliasesTest.java | 90 +- .../jsp/JspAndDefaultWithoutAliasesTest.java | 75 +- .../jetty/test/rfcs/RFC2616BaseTest.java | 323 +-- .../jetty/test/rfcs/RFC2616NIOHttpTest.java | 4 +- .../jetty/test/rfcs/RFC2616NIOHttpsTest.java | 8 +- .../jetty/test/support/JettyDistro.java | 33 +- .../test/support/TestableJettyServer.java | 16 +- .../rawhttp/HttpRequestTesterTest.java | 10 +- .../rawhttp/HttpResponseTesterTest.java | 44 +- .../org/eclipse/jetty/test/jmx/JmxIT.java | 16 +- .../jetty/DataSourceLoginServiceTest.java | 14 +- .../eclipse/jetty/JdbcLoginServiceTest.java | 20 +- .../quickstart/AttributeNormalizerTest.java | 342 +-- ...ttributeNormalizer_ToCanonicalUriTest.java | 30 +- .../jetty/quickstart/QuickStartTest.java | 6 +- .../session/ClusteredOrphanedSessionTest.java | 10 +- .../session/FileSessionDataStoreTest.java | 8 +- .../jetty/server/session/FileTestHelper.java | 8 +- .../server/session/TestFileSessions.java | 21 +- .../session/ClusteredOrphanedSessionTest.java | 6 +- .../ClusteredSessionScavengingTest.java | 5 +- .../session/GCloudSessionDataStoreTest.java | 4 +- .../session/GCloudSessionTestSupport.java | 6 +- .../jetty/gcloud/session/GCloudTestSuite.java | 13 +- .../session/InvalidationSessionTest.java | 4 +- .../test-hazelcast-sessions/pom.xml | 2 +- .../session/ClusteredOrphanedSessionTest.java | 10 +- .../ClusteredSessionScavengingTest.java | 10 +- ...lcastClusteredInvalidationSessionTest.java | 9 +- .../HazelcastSessionDataStoreTest.java | 10 +- .../session/HazelcastTestHelper.java | 4 +- .../client/ClientOrphanedSessionTest.java | 16 +- .../client/ClientSessionScavengingTest.java | 16 +- .../test-infinispan-sessions/pom.xml | 2 +- .../session/ClusteredOrphanedSessionTest.java | 8 +- .../ClusteredSessionScavengingTest.java | 8 +- .../InfinispanSessionDataStoreTest.java | 10 +- .../server/session/InfinispanTestSupport.java | 4 +- ...emoteClusteredInvalidationSessionTest.java | 8 +- .../RemoteClusteredSessionScavengingTest.java | 8 +- .../RemoteInfinispanSessionDataStoreTest.java | 10 +- .../remote/RemoteInfinispanTestSupport.java | 4 +- .../ClusteredInvalidationSessionTest.java | 5 +- .../session/ClusteredOrphanedSessionTest.java | 5 +- .../ClusteredSessionMigrationTest.java | 10 +- .../ClusteredSessionScavengingTest.java | 4 +- .../session/JDBCSessionDataStoreTest.java | 8 +- .../jetty/server/session/JdbcTestHelper.java | 4 +- .../ReloadedSessionMissingClassTest.java | 23 +- .../session/SessionTableSchemaTest.java | 16 +- .../session/WebAppObjectInSessionTest.java | 6 +- .../sessions/CachingSessionDataStoreTest.java | 8 +- .../test-mongodb-sessions/pom.xml | 2 +- .../nosql/mongodb/AttributeNameTest.java | 16 +- .../ClusteredInvalidateSessionTest.java | 8 +- .../mongodb/ClusteredOrphanedSessionTest.java | 10 +- .../ClusteredSessionScavengingTest.java | 8 +- .../mongodb/MongoSessionDataStoreTest.java | 8 +- .../jetty/nosql/mongodb/MongoTestHelper.java | 6 +- ...tractClusteredInvalidationSessionTest.java | 8 +- .../AbstractClusteredOrphanedSessionTest.java | 6 +- ...bstractClusteredSessionScavengingTest.java | 10 +- .../session/AbstractSessionDataStoreTest.java | 31 +- .../AbstractWebAppObjectInSessionTest.java | 6 +- .../server/session/TestSessionHandler.java | 2 +- .../session/WebAppObjectInSessionServlet.java | 11 +- .../ClientCrossContextSessionTest.java | 6 +- .../jetty/server/session/CreationTest.java | 33 +- .../session/DefaultSessionCacheTest.java | 19 +- .../session/DeleteUnloadableSessionTest.java | 8 +- .../server/session/DirtyAttributeTest.java | 6 +- .../jetty/server/session/IdleSessionTest.java | 8 +- .../server/session/ImmortalSessionTest.java | 8 +- .../ModifyMaxInactiveIntervalTest.java | 8 +- .../NonClusteredSessionScavengingTest.java | 16 +- .../server/session/NullSessionCacheTest.java | 11 +- .../server/session/RedirectSessionTest.java | 6 +- .../session/ReentrantRequestSessionTest.java | 14 +- .../server/session/RemoveSessionTest.java | 12 +- .../SameContextForwardedSessionTest.java | 12 +- .../server/session/SameNodeLoadTest.java | 12 +- .../server/session/SaveOptimizeTest.java | 26 +- .../session/SessionEvictionFailureTest.java | 8 +- .../SessionInvalidateCreateScavengeTest.java | 27 +- .../server/session/SessionListenerTest.java | 20 +- .../server/session/SessionRenewTest.java | 14 +- tests/test-webapps/test-http2-webapp/pom.xml | 4 +- .../jetty/test/webapp/HTTP2FromWebAppIT.java | 8 +- .../org/eclipse/jetty/ChatServletTest.java | 21 +- .../eclipse/jetty/DispatchServletTest.java | 24 +- .../java/org/eclipse/jetty/TestServer.java | 4 +- .../jetty/TestTransparentProxyServer.java | 4 +- 813 files changed, 23699 insertions(+), 22304 deletions(-) create mode 100644 jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsMatchers.java create mode 100644 jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderKey.java create mode 100644 jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderValue.java create mode 100644 jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsMatchersTest.java create mode 100644 jetty-proxy/src/test/java/org/eclipse/jetty/proxy/CachingProxyServlet.java delete mode 100644 jetty-start/src/test/java/org/eclipse/jetty/start/SystemExitAsException.java create mode 100644 tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/Transport.java create mode 100644 tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/TransportProvider.java create mode 100644 tests/test-http-client-transport/src/test/java/org/eclipse/jetty/http/client/TransportScenario.java diff --git a/Jenkinsfile b/Jenkinsfile index a971c18b0f1..7b36dbf4575 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -2,7 +2,7 @@ // in case of change update method isMainBuild def jdks = ["jdk8","jdk9","jdk10","jdk11"] -def oss = ["linux"] +def oss = ["linux"] def builds = [:] for (def os in oss) { for (def jdk in jdks) { @@ -18,7 +18,7 @@ def getFullBuild(jdk, os) { node(os) { // System Dependent Locations def mvnName = 'maven3.5' - def localRepo = "${env.JENKINS_HOME}/${env.EXECUTOR_NUMBER}" // ".repository" // + def localRepo = "${env.JENKINS_HOME}/${env.EXECUTOR_NUMBER}" // ".repository" // def settingsName = 'oss-settings.xml' def mavenOpts = '-Xms1g -Xmx4g -Djava.awt.headless=true' diff --git a/apache-jsp/pom.xml b/apache-jsp/pom.xml index 4296422c939..1110d177325 100644 --- a/apache-jsp/pom.xml +++ b/apache-jsp/pom.xml @@ -105,6 +105,13 @@ ${project.version} test + + org.eclipse.jetty + jetty-http + ${project.version} + tests + test + org.eclipse.jetty.toolchain jetty-test-helper diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java index eabb1261007..5bdc155ef4e 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyJspServlet.java @@ -18,7 +18,9 @@ package org.eclipse.jetty.jsp; -import static org.junit.Assert.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; import java.io.File; import java.io.IOException; @@ -31,21 +33,27 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspFactory; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.servlet.ServletTester; -import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; import org.apache.jasper.runtime.JspFactoryImpl; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.SimpleInstanceManager; -import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.http.HttpTester; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.servlet.ServletTester; +import org.eclipse.jetty.toolchain.test.MavenTestingUtils; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +@ExtendWith(WorkDirExtension.class) public class TestJettyJspServlet { - File _dir; - ServletTester _tester; + public WorkDir workdir; + + private File _dir; + private ServletTester _tester; public static class DfltServlet extends HttpServlet { @@ -67,7 +75,7 @@ public class TestJettyJspServlet } - @Before + @BeforeEach public void setUp () throws Exception { JspFactory.setDefaultFactory(new JspFactoryImpl()); @@ -75,7 +83,7 @@ public class TestJettyJspServlet _tester = new ServletTester("/context"); _tester.getContext().setClassLoader(new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader())); ServletHolder jspHolder = _tester.getContext().addServlet(JettyJspServlet.class, "/*"); - jspHolder.setInitParameter("scratchdir", MavenTestingUtils.getTargetTestingDir().getAbsolutePath()); + jspHolder.setInitParameter("scratchdir", workdir.getPath().toString()); _tester.getContext().setResourceBase(_dir.getAbsolutePath()); _tester.getContext().setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); ServletHolder dfltHolder = new ServletHolder(); @@ -86,7 +94,7 @@ public class TestJettyJspServlet _tester.start(); } - @After + @AfterEach public void tearDown() throws Exception { if (_tester != null) @@ -102,8 +110,10 @@ public class TestJettyJspServlet "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n"; - String response = _tester.getResponses(request); - assertTrue(!response.contains("This.Is.The.Default.")); + + String rawResponse = _tester.getResponses(request); + HttpTester.Response response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getContent(), not(containsString("This.Is.The.Default."))); } @@ -116,8 +126,8 @@ public class TestJettyJspServlet "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n"; - String response = _tester.getResponses(request); - assertTrue(response.contains("This.Is.The.Default.")); + String rawResponse = _tester.getResponses(request); + HttpTester.Response response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getContent(), containsString("This.Is.The.Default.")); } - } diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java index ca92ba4f403..9c738f987ff 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJettyTldPreScanned.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.jsp; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.net.URL; @@ -32,7 +32,7 @@ import org.apache.tomcat.util.descriptor.tld.TldResourcePath; import org.eclipse.jetty.apache.jsp.JettyTldPreScanned; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * TestJettyTldPreScanned diff --git a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java index dd9a8db249e..7f0966a7756 100644 --- a/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java +++ b/apache-jsp/src/test/java/org/eclipse/jetty/jsp/TestJspFileNameToClass.java @@ -18,9 +18,11 @@ package org.eclipse.jetty.jsp; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class TestJspFileNameToClass { @@ -32,27 +34,27 @@ public class TestJspFileNameToClass h.setName("test"); - Assert.assertEquals(null, h.getClassNameForJsp(null)); + assertEquals(null, h.getClassNameForJsp(null)); - Assert.assertEquals(null, h.getClassNameForJsp("")); + assertEquals(null, h.getClassNameForJsp("")); - Assert.assertEquals(null, h.getClassNameForJsp("/blah/")); + assertEquals(null, h.getClassNameForJsp("/blah/")); - Assert.assertEquals(null, h.getClassNameForJsp("//blah///")); + assertEquals(null, h.getClassNameForJsp("//blah///")); - Assert.assertEquals(null, h.getClassNameForJsp("/a/b/c/blah/")); + assertEquals(null, h.getClassNameForJsp("/a/b/c/blah/")); - Assert.assertEquals("org.apache.jsp.a.b.c.blah", h.getClassNameForJsp("/a/b/c/blah")); + assertEquals("org.apache.jsp.a.b.c.blah", h.getClassNameForJsp("/a/b/c/blah")); - Assert.assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("/blah.jsp")); + assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("/blah.jsp")); - Assert.assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("//blah.jsp")); + assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("//blah.jsp")); - Assert.assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("blah.jsp")); + assertEquals("org.apache.jsp.blah_jsp", h.getClassNameForJsp("blah.jsp")); - Assert.assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("/a/b/c/blah.jsp")); + assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("/a/b/c/blah.jsp")); - Assert.assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("a/b/c/blah.jsp")); + assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("a/b/c/blah.jsp")); } } diff --git a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java index 6dcaf993d89..a7b5069fdf0 100644 --- a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java +++ b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JspIncludeTest.java @@ -20,7 +20,7 @@ package org.eclipse.jetty.jstl; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; @@ -38,16 +38,16 @@ import org.eclipse.jetty.toolchain.test.JAR; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class JspIncludeTest { private static Server server; private static URI baseUri; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { // Setup Server @@ -96,7 +96,7 @@ public class JspIncludeTest baseUri = new URI(String.format("http://%s:%d/", host, port)); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { server.stop(); diff --git a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java index 4da11470965..b164d822a21 100644 --- a/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java +++ b/apache-jstl/src/test/java/org/eclipse/jetty/jstl/JstlTest.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.jstl; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; @@ -40,17 +40,16 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class JstlTest { private static Server server; private static URI baseUri; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { // Setup Server @@ -99,7 +98,7 @@ public class JstlTest baseUri = new URI(String.format("http://%s:%d/",host,port)); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { if (server != null) diff --git a/jetty-alpn/jetty-alpn-java-server/pom.xml b/jetty-alpn/jetty-alpn-java-server/pom.xml index beb0c456209..2d496426ea2 100644 --- a/jetty-alpn/jetty-alpn-java-server/pom.xml +++ b/jetty-alpn/jetty-alpn-java-server/pom.xml @@ -65,13 +65,8 @@ test - junit - junit - test - - - org.hamcrest - hamcrest-library + org.eclipse.jetty.toolchain + jetty-test-helper test diff --git a/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java b/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java index 063ddc4d9c2..2aa48a522eb 100644 --- a/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java +++ b/jetty-alpn/jetty-alpn-java-server/src/test/java/org/eclipse/jetty/alpn/java/server/JDK9ALPNTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.alpn.java.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -42,8 +45,7 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JDK9ALPNTest { @@ -109,7 +111,7 @@ public class JDK9ALPNTest InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.contains(" 200 ")); + assertThat(line, containsString(" 200 ")); while (true) { if (reader.readLine() == null) @@ -154,7 +156,7 @@ public class JDK9ALPNTest InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.contains(" 200 ")); + assertThat(line, containsString(" 200 ")); while (true) { if (reader.readLine() == null) diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java index 8fd11127898..4a0b25f79ce 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationConfiguration.java @@ -18,10 +18,10 @@ package org.eclipse.jetty.annotations; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.net.URL; @@ -38,7 +38,7 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.FragmentDescriptor; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * TestAnnotationConfiguration diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java index f67c8254396..6800a684f88 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationInheritance.java @@ -18,10 +18,14 @@ package org.eclipse.jetty.annotations; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasKey; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collections; @@ -37,8 +41,8 @@ import org.eclipse.jetty.annotations.AnnotationParser.AbstractHandler; import org.eclipse.jetty.annotations.AnnotationParser.ClassInfo; import org.eclipse.jetty.annotations.AnnotationParser.FieldInfo; import org.eclipse.jetty.annotations.AnnotationParser.MethodInfo; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * @@ -86,7 +90,7 @@ public class TestAnnotationInheritance } } - @After + @AfterEach public void destroy() throws Exception { classNames.clear(); @@ -171,17 +175,14 @@ public class TestAnnotationInheritance assertNotNull(map); assertFalse(map.isEmpty()); assertEquals(2, map.size()); - - - assertTrue (map.keySet().contains("org.eclipse.jetty.annotations.ClassA")); - assertTrue (map.keySet().contains("org.eclipse.jetty.annotations.InterfaceD")); + + assertThat(map, hasKey("org.eclipse.jetty.annotations.ClassA")); + assertThat(map, hasKey("org.eclipse.jetty.annotations.InterfaceD")); Set classes = map.get("org.eclipse.jetty.annotations.ClassA"); - assertEquals(1, classes.size()); - assertEquals ("org.eclipse.jetty.annotations.ClassB", classes.iterator().next()); + assertThat(classes, contains("org.eclipse.jetty.annotations.ClassB")); classes = map.get("org.eclipse.jetty.annotations.InterfaceD"); - assertEquals(2, classes.size()); - assertTrue(classes.contains("org.eclipse.jetty.annotations.ClassB")); - assertTrue(classes.contains(Foo.class.getName())); + assertThat(classes, containsInAnyOrder("org.eclipse.jetty.annotations.ClassB", + Foo.class.getName())); } } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java index 830eeba09bd..a734191fe35 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestAnnotationParser.java @@ -18,11 +18,13 @@ package org.eclipse.jetty.annotations; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.isIn; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileOutputStream; @@ -46,13 +48,14 @@ import org.eclipse.jetty.annotations.AnnotationParser.MethodInfo; import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.IO; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.TestingDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.eclipse.jetty.util.resource.PathResource; import org.eclipse.jetty.util.resource.Resource; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +@ExtendWith(WorkDirExtension.class) public class TestAnnotationParser { public static class TrackingAnnotationHandler extends AnnotationParser.AbstractHandler @@ -102,8 +105,7 @@ public class TestAnnotationParser } - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; @Test public void testSampleAnnotation() throws Exception @@ -140,7 +142,7 @@ public class TestAnnotationParser if (annotation == null || !"org.eclipse.jetty.annotations.Sample".equals(annotation)) return; assertEquals("org.eclipse.jetty.annotations.ClassA",info.getClassInfo().getClassName()); - assertTrue(methods.contains(info.getMethodName())); + assertThat(info.getMethodName(), isIn(methods)); assertEquals("org.eclipse.jetty.annotations.Sample",annotation); } } @@ -171,11 +173,9 @@ public class TestAnnotationParser @Override public void handle(FieldInfo info, String annotation) - { - if (annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation)) - return; - // there should not be any - fail(); + { + assertTrue(annotation == null || ! "org.eclipse.jetty.annotations.Multi".equals(annotation), + "There should not be any"); } @Override @@ -256,7 +256,7 @@ public class TestAnnotationParser parser.parse(Collections.singleton(tracker), basedir.toURI()); // Validate - Assert.assertThat("Found Class", tracker.foundClasses, contains(ClassA.class.getName())); + assertThat("Found Class", tracker.foundClasses, contains(ClassA.class.getName())); } @@ -271,9 +271,9 @@ public class TestAnnotationParser parser.parse(handlers, testJar); parser.parse(handlers, testJar2); List locations = handler.getParsedList("org.acme.ClassOne"); - Assert.assertNotNull(locations); - Assert.assertEquals(2, locations.size()); - Assert.assertTrue(!(locations.get(0).equals(locations.get(1)))); + assertNotNull(locations); + assertEquals(2, locations.size()); + assertTrue(!(locations.get(0).equals(locations.get(1)))); } @@ -288,9 +288,9 @@ public class TestAnnotationParser parser.parse(handlers, testJar); parser.parse(handlers, Resource.newResource(testClasses)); Listlocations = handler.getParsedList("org.acme.ClassOne"); - Assert.assertNotNull(locations); - Assert.assertEquals(2, locations.size()); - Assert.assertTrue(!(locations.get(0).equals(locations.get(1)))); + assertNotNull(locations); + assertEquals(2, locations.size()); + assertTrue(!(locations.get(0).equals(locations.get(1)))); } @@ -299,7 +299,7 @@ public class TestAnnotationParser { String classname = clazz.getName().replace('.',File.separatorChar) + ".class"; URL url = this.getClass().getResource('/'+classname); - Assert.assertThat("URL for: " + classname,url,notNullValue()); + assertThat("URL for: " + classname,url,notNullValue()); String classpath = classname.substring(0,classname.lastIndexOf(File.separatorChar)); FS.ensureDirExists(new File(basedir,classpath)); diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java index c361a46648c..7be020b0721 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestSecurityAnnotationConversions.java @@ -18,11 +18,11 @@ package org.eclipse.jetty.annotations; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Arrays; import java.util.List; @@ -41,7 +41,7 @@ import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletMapping; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSecurityAnnotationConversions { diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java index 9a4135e338f..cdba04fc7d7 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/TestServletAnnotations.java @@ -18,6 +18,15 @@ package org.eclipse.jetty.annotations; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -29,14 +38,7 @@ import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletMapping; import org.eclipse.jetty.webapp.DiscoveredAnnotation; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.Test; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; /** * TestServletAnnotations @@ -132,7 +134,7 @@ public class TestServletAnnotations resultMappings[0].getServletName().equals("DServlet"); for (String s:resultMappings[0].getPathSpecs()) { - assertTrue (s.equals("/") || s.equals("/bah/*")); + assertThat(s, anyOf(is("/"), is("/bah/*"))); } } @@ -185,7 +187,7 @@ public class TestServletAnnotations } } else - fail("Unexpected servlet mapping"); + fail("Unexpected servlet mapping: " + r); } } @@ -222,7 +224,7 @@ public class TestServletAnnotations assertEquals(1, r.getPathSpecs().length); } else - fail("Unexpected servlet name"); + fail("Unexpected servlet name: " + r); } } @@ -258,7 +260,7 @@ public class TestServletAnnotations { assertEquals(1, r.getPathSpecs().length); if (!r.getPathSpecs()[0].equals("/default") && !r.getPathSpecs()[0].equals("/other")) - fail("Unexpected path in mapping"); + fail("Unexpected path in mapping: " + r); } } @@ -282,8 +284,7 @@ public class TestServletAnnotations assertEquals(2, resultMappings[0].getPathSpecs().length); for (String s:resultMappings[0].getPathSpecs()) { - if (!s.equals("/") && !s.equals("/bah/*")) - fail("Unexpected path mapping"); + assertThat(s, anyOf(is("/"), is("/bah/*"))); } } @@ -299,8 +300,6 @@ public class TestServletAnnotations sh.setRoles(new HashSet(Arrays.asList(new String[]{"humpty", "dumpty"}))); DeclareRolesAnnotationHandler handler = new DeclareRolesAnnotationHandler(wac); handler.doHandle(ServletC.class); - assertTrue(sh.getRoles().contains("alice")); - assertTrue(sh.getRoles().contains("humpty")); - assertTrue(sh.getRoles().contains("dumpty")); + assertThat(sh.getRoles(), containsInAnyOrder("humpty", "alice", "dumpty")); } } diff --git a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java index 690ebbbb5fa..b6143c249dc 100644 --- a/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java +++ b/jetty-annotations/src/test/java/org/eclipse/jetty/annotations/resources/TestResourceAnnotations.java @@ -18,8 +18,8 @@ package org.eclipse.jetty.annotations.resources; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.lang.reflect.Field; import java.util.List; @@ -34,9 +34,9 @@ import org.eclipse.jetty.plus.annotation.Injection; import org.eclipse.jetty.plus.annotation.InjectionCollection; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestResourceAnnotations { @@ -48,7 +48,7 @@ public class TestResourceAnnotations private Object objA = 1000; private Object objB = 2000; - @Before + @BeforeEach public void init() throws Exception { server = new Server(); @@ -61,7 +61,7 @@ public class TestResourceAnnotations env = comp.createSubcontext("env"); } - @After + @AfterEach public void destroy() throws Exception { comp.destroySubcontext("env"); diff --git a/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java b/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java index 8f125cbc2fe..8ea6ab6dfc1 100644 --- a/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java +++ b/jetty-ant/src/test/java/org/eclipse/jetty/ant/JettyAntTaskTest.java @@ -19,13 +19,13 @@ package org.eclipse.jetty.ant; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.net.HttpURLConnection; import java.net.URI; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JettyAntTaskTest { diff --git a/jetty-bom/pom.xml b/jetty-bom/pom.xml index b6337cba5f1..dfc3f77f149 100644 --- a/jetty-bom/pom.xml +++ b/jetty-bom/pom.xml @@ -28,7 +28,7 @@ http://www.eclipse.org/jetty UTF-8 - 1.4 + 1.4 diff --git a/jetty-cdi/cdi-core/src/test/java/org/eclipse/jetty/cdi/core/AbstractWeldTest.java b/jetty-cdi/cdi-core/src/test/java/org/eclipse/jetty/cdi/core/AbstractWeldTest.java index d95bb87c215..7644f181ed3 100644 --- a/jetty-cdi/cdi-core/src/test/java/org/eclipse/jetty/cdi/core/AbstractWeldTest.java +++ b/jetty-cdi/cdi-core/src/test/java/org/eclipse/jetty/cdi/core/AbstractWeldTest.java @@ -25,8 +25,8 @@ import javax.enterprise.inject.spi.Bean; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; public abstract class AbstractWeldTest { @@ -42,14 +42,14 @@ public abstract class AbstractWeldTest } } - @BeforeClass + @BeforeAll public static void initWeld() { weld = new Weld(); container = weld.initialize(); } - @AfterClass + @AfterAll public static void shutdownWeld() { weld.shutdown(); diff --git a/jetty-cdi/cdi-servlet/src/test/java/org/eclipse/jetty/cdi/servlet/WeldInitializationTest.java b/jetty-cdi/cdi-servlet/src/test/java/org/eclipse/jetty/cdi/servlet/WeldInitializationTest.java index f5ccfad949c..b848115927a 100644 --- a/jetty-cdi/cdi-servlet/src/test/java/org/eclipse/jetty/cdi/servlet/WeldInitializationTest.java +++ b/jetty-cdi/cdi-servlet/src/test/java/org/eclipse/jetty/cdi/servlet/WeldInitializationTest.java @@ -20,7 +20,7 @@ package org.eclipse.jetty.cdi.servlet; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.InputStream; @@ -36,9 +36,9 @@ import org.eclipse.jetty.util.log.JettyLogHandler; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class WeldInitializationTest { @@ -46,7 +46,7 @@ public class WeldInitializationTest private static Server server; private static URI serverHttpURI; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { JettyLogHandler.config(); @@ -79,7 +79,7 @@ public class WeldInitializationTest serverHttpURI = new URI(String.format("http://%s:%d/",host,port)); } - @AfterClass + @AfterAll public static void stopServer() { try diff --git a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/CheckSocket.java b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/CheckSocket.java index f93bb88deb6..46120753e87 100644 --- a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/CheckSocket.java +++ b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/CheckSocket.java @@ -18,13 +18,13 @@ package org.eclipse.jetty.cdi.websocket; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import org.eclipse.jetty.toolchain.test.EventQueue; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.websocket.api.Session; @@ -37,19 +37,19 @@ public class CheckSocket extends WebSocketAdapter private static final Logger LOG = Log.getLogger(CheckSocket.class); private CountDownLatch closeLatch = new CountDownLatch(1); private CountDownLatch openLatch = new CountDownLatch(1); - private EventQueue textMessages = new EventQueue<>(); + public LinkedBlockingQueue textMessages = new LinkedBlockingQueue<>(); public void awaitClose(int timeout, TimeUnit timeunit) throws InterruptedException { - assertTrue("Timeout waiting for close",closeLatch.await(timeout,timeunit)); + assertTrue(closeLatch.await(timeout,timeunit), "Timeout waiting for close"); } public void awaitOpen(int timeout, TimeUnit timeunit) throws InterruptedException { - assertTrue("Timeout waiting for open",openLatch.await(timeout,timeunit)); + assertTrue(openLatch.await(timeout,timeunit), "Timeout waiting for open"); } - public EventQueue getTextMessages() + public LinkedBlockingQueue getTextMessages() { return textMessages; } diff --git a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicapp/BasicAppTest.java b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicapp/BasicAppTest.java index b1ce8f8badc..9574b9abca4 100644 --- a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicapp/BasicAppTest.java +++ b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicapp/BasicAppTest.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.cdi.websocket.basicapp; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.net.URI; @@ -40,9 +40,9 @@ import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.websocket.api.StatusCode; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class BasicAppTest { @@ -53,7 +53,7 @@ public class BasicAppTest private static URI serverHttpURI; private static URI serverWebsocketURI; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { JettyLogHandler.config(); @@ -88,7 +88,7 @@ public class BasicAppTest serverWebsocketURI = new URI(String.format("ws://%s:%d/",host,port)); } - @AfterClass + @AfterAll public static void stopServer() { try diff --git a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicscope/ScopeBasicsTest.java b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicscope/ScopeBasicsTest.java index 1e12eced75c..ef76864cde7 100644 --- a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicscope/ScopeBasicsTest.java +++ b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/basicscope/ScopeBasicsTest.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.cdi.websocket.basicscope; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Set; @@ -32,16 +32,16 @@ import org.eclipse.jetty.cdi.core.ScopedInstance; import org.eclipse.jetty.cdi.core.logging.Logging; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class ScopeBasicsTest { private static Weld weld; private static WeldContainer container; - @BeforeClass + @BeforeAll public static void startWeld() { Logging.config(); @@ -49,7 +49,7 @@ public class ScopeBasicsTest container = weld.initialize(); } - @AfterClass + @AfterAll public static void stopWeld() { weld.shutdown(); diff --git a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/cdiapp/CdiAppTest.java b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/cdiapp/CdiAppTest.java index 3b056bfcc49..6b384fbc127 100644 --- a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/cdiapp/CdiAppTest.java +++ b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/cdiapp/CdiAppTest.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.cdi.websocket.cdiapp; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.net.URI; @@ -42,9 +42,9 @@ import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.websocket.api.StatusCode; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class CdiAppTest { @@ -52,7 +52,7 @@ public class CdiAppTest private static Server server; private static URI serverWebsocketURI; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { JettyLogHandler.config(); @@ -87,7 +87,7 @@ public class CdiAppTest serverWebsocketURI = new URI(String.format("ws://%s:%d/",host,port)); } - @AfterClass + @AfterAll public static void stopServer() { try diff --git a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeBaselineTest.java b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeBaselineTest.java index 363fefcccc4..f780e60ab67 100644 --- a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeBaselineTest.java +++ b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeBaselineTest.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.cdi.websocket.wsscope; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Set; @@ -34,16 +34,16 @@ import org.eclipse.jetty.cdi.websocket.WebSocketScopeContext; import org.eclipse.jetty.cdi.websocket.annotation.WebSocketScope; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class WebSocketScopeBaselineTest { private static Weld weld; private static WeldContainer container; - @BeforeClass + @BeforeAll public static void startWeld() { Logging.config(); @@ -51,7 +51,7 @@ public class WebSocketScopeBaselineTest container = weld.initialize(); } - @AfterClass + @AfterAll public static void stopWeld() { weld.shutdown(); diff --git a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeSessionTest.java b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeSessionTest.java index 4933c807866..b8ad0835803 100644 --- a/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeSessionTest.java +++ b/jetty-cdi/cdi-websocket/src/test/java/org/eclipse/jetty/cdi/websocket/wsscope/WebSocketScopeSessionTest.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.cdi.websocket.wsscope; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Set; import java.util.concurrent.Callable; @@ -40,16 +40,16 @@ import org.eclipse.jetty.cdi.websocket.WebSocketScopeContext; import org.eclipse.jetty.websocket.api.Session; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class WebSocketScopeSessionTest { private static Weld weld; private static WeldContainer container; - @BeforeClass + @BeforeAll public static void startWeld() { Logging.config(); @@ -57,7 +57,7 @@ public class WebSocketScopeSessionTest container = weld.initialize(); } - @AfterClass + @AfterAll public static void stopWeld() { weld.shutdown(); diff --git a/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/HelloIT.java b/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/HelloIT.java index 6aacd3b761d..e90c413c2e3 100644 --- a/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/HelloIT.java +++ b/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/HelloIT.java @@ -19,12 +19,12 @@ package org.eclipse.jetty.tests; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.net.URI; import org.eclipse.jetty.toolchain.test.SimpleRequest; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Basic tests for a simple @WebServlet with no CDI diff --git a/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ServerInfoIT.java b/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ServerInfoIT.java index 21950b4d8b4..53eeb45b5d6 100644 --- a/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ServerInfoIT.java +++ b/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ServerInfoIT.java @@ -19,12 +19,12 @@ package org.eclipse.jetty.tests; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.net.URI; import org.eclipse.jetty.toolchain.test.SimpleRequest; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ServerInfoIT { diff --git a/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ws/SessionInfoIT.java b/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ws/SessionInfoIT.java index a530706bba5..9ff3c239045 100644 --- a/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ws/SessionInfoIT.java +++ b/jetty-cdi/test-cdi-it/src/test/java/org/eclipse/jetty/tests/ws/SessionInfoIT.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.tests.ws; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.net.URI; import java.util.concurrent.CountDownLatch; @@ -37,7 +37,7 @@ import javax.websocket.WebSocketContainer; import org.eclipse.jetty.toolchain.test.EventQueue; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SessionInfoIT { diff --git a/jetty-client/pom.xml b/jetty-client/pom.xml index a9955c6cab8..6062d1e3c03 100644 --- a/jetty-client/pom.xml +++ b/jetty-client/pom.xml @@ -37,7 +37,7 @@ org.eclipse.jetty.toolchain jetty-test-policy - ${jetty-test-policy-version} + ${jetty-test-policy.version} jar true **/*.keystore,**/*.pem diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java index dfbf06db406..16858c0c879 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/AbstractHttpClientServerTest.java @@ -18,96 +18,153 @@ package org.eclipse.jetty.client; -import java.util.Arrays; -import java.util.Collection; +import java.nio.file.Path; +import java.util.stream.Stream; import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.http.HttpScheme; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.toolchain.test.TestTracker; +import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.SocketAddressResolver; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; -@RunWith(Parameterized.class) public abstract class AbstractHttpClientServerTest { - @Parameterized.Parameters(name = "ssl={0}") - public static Collection parameters() - { - return Arrays.asList(new SslContextFactory[]{null}, new SslContextFactory[]{new SslContextFactory()}); - } - - @Rule - public final TestTracker tracker = new TestTracker(); - - protected SslContextFactory sslContextFactory; - protected String scheme; protected Server server; protected HttpClient client; protected ServerConnector connector; - public AbstractHttpClientServerTest(SslContextFactory sslContextFactory) + public void start(final Scenario scenario, Handler handler) throws Exception { - this.sslContextFactory = sslContextFactory; - this.scheme = (sslContextFactory == null ? HttpScheme.HTTP : HttpScheme.HTTPS).asString(); + startServer(scenario, handler); + startClient(scenario); } - public void start(Handler handler) throws Exception + protected void startServer(final Scenario scenario, Handler handler) throws Exception { - startServer(handler); - startClient(); - } - - protected void startServer(Handler handler) throws Exception - { - if (sslContextFactory != null) - { - sslContextFactory.setEndpointIdentificationAlgorithm(""); - sslContextFactory.setKeyStorePath("src/test/resources/keystore.jks"); - sslContextFactory.setKeyStorePassword("storepwd"); - } - if (server == null) { QueuedThreadPool serverThreads = new QueuedThreadPool(); serverThreads.setName("server"); server = new Server(serverThreads); } - connector = new ServerConnector(server, sslContextFactory); + connector = new ServerConnector(server, scenario.newSslContextFactory()); + connector.setPort(0); server.addConnector(connector); server.setHandler(handler); server.start(); } - protected void startClient() throws Exception + protected void startClient(final Scenario scenario) throws Exception { - startClient(new HttpClientTransportOverHTTP(1)); + startClient(scenario, new HttpClientTransportOverHTTP(1)); } - protected void startClient(HttpClientTransport transport) throws Exception + protected void startClient(final Scenario scenario, HttpClientTransport transport) throws Exception { QueuedThreadPool clientThreads = new QueuedThreadPool(); clientThreads.setName("client"); - client = new HttpClient(transport, sslContextFactory); + client = new HttpClient(transport, scenario.newSslContextFactory()); client.setExecutor(clientThreads); client.setSocketAddressResolver(new SocketAddressResolver.Sync()); client.start(); } - @After - public void dispose() throws Exception + @AfterEach + public void disposeClient() throws Exception { if (client != null) + { client.stop(); + client = null; + } + } + + @AfterEach + public void disposeServer() throws Exception + { if (server != null) + { server.stop(); - server = null; + server = null; + } + } + + public static class ScenarioProvider implements ArgumentsProvider { + @Override + public Stream provideArguments(ExtensionContext context) throws Exception + { + return Stream.of( + new NormalScenario(), + new SslScenario() + // TODO: add more ssl / non-ssl scenarios here + ).map(Arguments::of); + } + } + + public static class NonSslScenarioProvider implements ArgumentsProvider { + @Override + public Stream provideArguments(ExtensionContext context) throws Exception + { + return Stream.of( + new NormalScenario() + // TODO: add more non-ssl scenarios here + ).map(Arguments::of); + } + } + + public interface Scenario + { + default SslContextFactory newSslContextFactory() { return null; } + String getScheme(); + } + + public static class NormalScenario implements Scenario + { + @Override + public String getScheme() + { + return HttpScheme.HTTP.asString(); + } + + @Override + public String toString() + { + return "HTTP"; + } + } + + public static class SslScenario implements Scenario + { + @Override + public SslContextFactory newSslContextFactory() + { + Path keystorePath = MavenTestingUtils.getTestResourcePath("keystore.jks"); + + SslContextFactory ssl = new SslContextFactory(); + ssl.setEndpointIdentificationAlgorithm(""); + ssl.setKeyStorePath(keystorePath.toString()); + ssl.setKeyStorePassword("storepwd"); + return ssl; + } + + @Override + public String getScheme() + { + return HttpScheme.HTTPS.asString(); + } + + @Override + public String toString() + { + return "HTTPS"; + } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java index 6e1f7e27523..85aa2a97be2 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ClientConnectionCloseTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; @@ -39,22 +44,17 @@ import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class ClientConnectionCloseTest extends AbstractHttpClientServerTest { - public ClientConnectionCloseTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - - @Test - public void test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange(Scenario scenario) throws Exception { byte[] data = new byte[128 * 1024]; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -87,29 +87,30 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); ContentResponse response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) .content(new StringContentProvider("0")) .onRequestSuccess(request -> { HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - Assert.assertFalse(connection.getEndPoint().isOutputShutdown()); + assertFalse(connection.getEndPoint().isOutputShutdown()); }) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); - Assert.assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertArrayEquals(data, response.getContent()); + assertEquals(0, connectionPool.getConnectionCount()); } - @Test - public void test_ClientConnectionClose_ServerDoesNotRespond_ClientIdleTimeout() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ClientConnectionClose_ServerDoesNotRespond_ClientIdleTimeout(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -123,19 +124,19 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); CountDownLatch resultLatch = new CountDownLatch(1); long idleTimeout = 1000; client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .onRequestSuccess(request -> { HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - Assert.assertFalse(connection.getEndPoint().isOutputShutdown()); + assertFalse(connection.getEndPoint().isOutputShutdown()); }) .send(result -> { @@ -143,15 +144,16 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest resultLatch.countDown(); }); - Assert.assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); - Assert.assertEquals(0, connectionPool.getConnectionCount()); + assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertEquals(0, connectionPool.getConnectionCount()); } - @Test - public void test_ClientConnectionClose_ServerPartialResponse_ClientIdleTimeout() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ClientConnectionClose_ServerPartialResponse_ClientIdleTimeout(Scenario scenario) throws Exception { long idleTimeout = 1000; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -183,20 +185,20 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.allocate(8)); CountDownLatch resultLatch = new CountDownLatch(1); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) .content(content) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .onRequestSuccess(request -> { HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - Assert.assertFalse(connection.getEndPoint().isOutputShutdown()); + assertFalse(connection.getEndPoint().isOutputShutdown()); }) .send(result -> { @@ -206,14 +208,15 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest content.offer(ByteBuffer.allocate(8)); content.close(); - Assert.assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); - Assert.assertEquals(0, connectionPool.getConnectionCount()); + assertTrue(resultLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertEquals(0, connectionPool.getConnectionCount()); } - @Test - public void test_ClientConnectionClose_ServerNoConnectionClose_ClientCloses() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ClientConnectionClose_ServerNoConnectionClose_ClientCloses(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -237,21 +240,21 @@ public class ClientConnectionCloseTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); ContentResponse response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) .onRequestSuccess(request -> { HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP)connectionPool.getActiveConnections().iterator().next(); - Assert.assertFalse(connection.getEndPoint().isOutputShutdown()); + assertFalse(connection.getEndPoint().isOutputShutdown()); }) .onResponseHeaders(r -> r.getHeaders().remove(HttpHeader.CONNECTION)) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(0, connectionPool.getConnectionCount()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java index 56b4bc61bd3..26a810e3739 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ConnectionPoolTest.java @@ -18,13 +18,18 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -42,39 +47,32 @@ import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.IO; -import org.junit.After; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -@Ignore +@Disabled // Disabled by @gregw on issue #2540 - commit 621b946b10884e7308eacca241dcf8b5d6f6cff2 public class ConnectionPoolTest { private Server server; private ServerConnector connector; private HttpClient client; - @Parameterized.Parameters - public static ConnectionPool.Factory[] parameters() + public static Stream pools() { - return new ConnectionPool.Factory[] - { - destination -> new DuplexConnectionPool(destination, 8, destination), - destination -> new RoundRobinConnectionPool(destination, 8, destination) - }; + List pools = new ArrayList<>(); + pools.add(new Object[] { DuplexConnectionPool.class, + (ConnectionPool.Factory) + destination -> new DuplexConnectionPool(destination, 8, destination)}); + pools.add(new Object[] { RoundRobinConnectionPool.class, + (ConnectionPool.Factory) + destination -> new RoundRobinConnectionPool(destination, 8, destination)}); + return pools.stream().map(Arguments::of); } - private final ConnectionPool.Factory factory; - - public ConnectionPoolTest(ConnectionPool.Factory factory) - { - this.factory = factory; - } - - private void start(Handler handler) throws Exception + private void start(final ConnectionPool.Factory factory, Handler handler) throws Exception { server = new Server(); connector = new ServerConnector(server); @@ -83,23 +81,38 @@ public class ConnectionPoolTest HttpClientTransport transport = new HttpClientTransportOverHTTP(1); transport.setConnectionPoolFactory(factory); - client = new HttpClient(transport, null); - server.addBean(client); - server.start(); + + client = new HttpClient(transport, null); + client.start(); } - @After - public void dispose() throws Exception + @AfterEach + public void disposeServer() throws Exception { + connector = null; if (server != null) + { server.stop(); + server = null; + } } - @Test - public void test() throws Exception + @AfterEach + public void disposeClient() throws Exception { - start(new EmptyServerHandler() + if (client != null) + { + client.stop(); + client = null; + } + } + + @ParameterizedTest(name = "[{index}] {0}") + @MethodSource("pools") + public void test(Class connectionPoolClass, ConnectionPool.Factory factory) throws Exception + { + start(factory, new EmptyServerHandler() { @Override protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -143,8 +156,8 @@ public class ConnectionPoolTest IntStream.range(0, parallelism).parallel().forEach(i -> IntStream.range(0, runs).forEach(j -> run(latch, iterations, failures))); - Assert.assertTrue(latch.await(iterations, TimeUnit.SECONDS)); - Assert.assertTrue(failures.toString(), failures.isEmpty()); + assertTrue(latch.await(iterations, TimeUnit.SECONDS)); + assertTrue(failures.isEmpty(), failures.toString()); } private void run(CountDownLatch latch, int iterations, List failures) @@ -208,7 +221,7 @@ public class ConnectionPoolTest try { ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } catch (Throwable x) { diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java index cbb8a6496c7..201eaa53936 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ContentResponseTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.io.IOException; import java.util.Random; import java.util.concurrent.TimeUnit; @@ -30,23 +34,18 @@ import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class ContentResponseTest extends AbstractHttpClientServerTest { - public ContentResponseTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - - @Test - public void testResponseWithoutContentType() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testResponseWithoutContentType(Scenario scenario) throws Exception { final byte[] content = new byte[1024]; new Random().nextBytes(content); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -57,22 +56,23 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(content, response.getContent()); - Assert.assertNull(response.getMediaType()); - Assert.assertNull(response.getEncoding()); + assertEquals(200, response.getStatus()); + assertArrayEquals(content, response.getContent()); + assertNull(response.getMediaType()); + assertNull(response.getEncoding()); } - @Test - public void testResponseWithMediaType() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testResponseWithMediaType(Scenario scenario) throws Exception { final String content = "The quick brown fox jumped over the lazy dog"; final String mediaType = "text/plain"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -84,24 +84,25 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(content, response.getContentAsString()); - Assert.assertEquals(mediaType, response.getMediaType()); - Assert.assertNull(response.getEncoding()); + assertEquals(200, response.getStatus()); + assertEquals(content, response.getContentAsString()); + assertEquals(mediaType, response.getMediaType()); + assertNull(response.getEncoding()); } - @Test - public void testResponseWithContentType() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testResponseWithContentType(Scenario scenario) throws Exception { final String content = "The quick brown fox jumped over the lazy dog"; final String mediaType = "text/plain"; final String encoding = "UTF-8"; final String contentType = mediaType + "; charset=" + encoding; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -113,24 +114,25 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(content, response.getContentAsString()); - Assert.assertEquals(mediaType, response.getMediaType()); - Assert.assertEquals(encoding, response.getEncoding()); + assertEquals(200, response.getStatus()); + assertEquals(content, response.getContentAsString()); + assertEquals(mediaType, response.getMediaType()); + assertEquals(encoding, response.getEncoding()); } - @Test - public void testResponseWithContentTypeWithQuotedCharset() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testResponseWithContentTypeWithQuotedCharset(Scenario scenario) throws Exception { final String content = "The quick brown fox jumped over the lazy dog"; final String mediaType = "text/plain"; final String encoding = "UTF-8"; final String contentType = mediaType + "; charset=\"" + encoding + "\""; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -142,13 +144,13 @@ public class ContentResponseTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(content, response.getContentAsString()); - Assert.assertEquals(mediaType, response.getMediaType()); - Assert.assertEquals(encoding, response.getEncoding()); + assertEquals(200, response.getStatus()); + assertEquals(content, response.getContentAsString()); + assertEquals(mediaType, response.getMediaType()); + assertEquals(encoding, response.getEncoding()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java index 7c9cf0d2e65..9105a955ad3 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ExternalSiteTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.net.Socket; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -26,32 +30,25 @@ import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.http.HttpScheme; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Ignore +@Disabled public class ExternalSiteTest { - @Rule - public final TestTracker tracker = new TestTracker(); - private HttpClient client; - @Before + @BeforeEach public void prepare() throws Exception { client = new HttpClient(new SslContextFactory()); client.start(); } - @After + @AfterEach public void dispose() throws Exception { client.stop(); @@ -76,7 +73,7 @@ public class ExternalSiteTest latch1.countDown(); } }); - Assert.assertTrue(latch1.await(10, TimeUnit.SECONDS)); + assertTrue(latch1.await(10, TimeUnit.SECONDS)); // Try again the same URI, but without specifying the port final CountDownLatch latch2 = new CountDownLatch(1); @@ -85,12 +82,12 @@ public class ExternalSiteTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isSucceeded()); - Assert.assertEquals(200, result.getResponse().getStatus()); + assertTrue(result.isSucceeded()); + assertEquals(200, result.getResponse().getStatus()); latch2.countDown(); } }); - Assert.assertTrue(latch2.await(10, TimeUnit.SECONDS)); + assertTrue(latch2.await(10, TimeUnit.SECONDS)); } @Test @@ -116,7 +113,7 @@ public class ExternalSiteTest latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -151,11 +148,11 @@ public class ExternalSiteTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); latch.countDown(); } }); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); } } @@ -172,7 +169,7 @@ public class ExternalSiteTest .scheme(HttpScheme.HTTPS.asString()) .path("/twitter") .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } protected void assumeCanConnectTo(String host, int port) @@ -183,7 +180,7 @@ public class ExternalSiteTest } catch (Throwable x) { - Assume.assumeNoException(x); + assumeTrue(x == null, "Unable to connect"); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/GZIPContentDecoderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/GZIPContentDecoderTest.java index 245bad4853d..333ff8c1c51 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/GZIPContentDecoderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/GZIPContentDecoderTest.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -29,16 +29,11 @@ import java.nio.charset.StandardCharsets; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import org.eclipse.jetty.toolchain.test.TestTracker; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; @Deprecated public class GZIPContentDecoderTest { - @Rule - public final TestTracker tracker = new TestTracker(); - @Test public void testStreamNoBlocks() throws Exception { diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java index b54e75923f0..985ff01473d 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HostnameVerificationTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.IOException; import java.security.cert.CertificateException; import java.util.concurrent.ExecutionException; @@ -35,17 +39,17 @@ import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * This test class runs tests to make sure that hostname verification (http://www.ietf.org/rfc/rfc2818.txt * section 3.1) is configurable in SslContextFactory and works as expected. */ -@Ignore +@Disabled public class HostnameVerificationTest { private SslContextFactory clientSslContextFactory = new SslContextFactory(); @@ -53,7 +57,7 @@ public class HostnameVerificationTest private HttpClient client; private NetworkConnector connector; - @Before + @BeforeEach public void setUp() throws Exception { QueuedThreadPool serverThreads = new QueuedThreadPool(); @@ -87,7 +91,7 @@ public class HostnameVerificationTest client.start(); } - @After + @AfterEach public void tearDown() throws Exception { client.stop(); @@ -107,18 +111,14 @@ public class HostnameVerificationTest { clientSslContextFactory.setEndpointIdentificationAlgorithm("HTTPS"); String uri = "https://localhost:" + connector.getLocalPort() + "/"; - try - { + + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.GET(uri); - Assert.fail("sending request to client should have failed with an Exception!"); - } - catch (ExecutionException x) - { - Throwable cause = x.getCause(); - Assert.assertThat(cause, Matchers.instanceOf(SSLHandshakeException.class)); - Throwable root = cause.getCause().getCause(); - Assert.assertThat(root, Matchers.instanceOf(CertificateException.class)); - } + }); + Throwable cause = x.getCause(); + assertThat(cause, Matchers.instanceOf(SSLHandshakeException.class)); + Throwable root = cause.getCause().getCause(); + assertThat(root, Matchers.instanceOf(CertificateException.class)); } /** @@ -139,7 +139,7 @@ public class HostnameVerificationTest } catch (ExecutionException e) { - Assert.fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage()); + fail("SSLHandshake should work just fine as hostname verification is disabled!", e); } } @@ -160,7 +160,7 @@ public class HostnameVerificationTest } catch (ExecutionException e) { - Assert.fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage()); + fail("SSLHandshake should work just fine as hostname verification is disabled!", e); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java index f4b3b5858c5..071e3614638 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpAuthenticationStoreTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.net.URI; import org.eclipse.jetty.client.api.Authentication; @@ -25,8 +27,8 @@ import org.eclipse.jetty.client.api.AuthenticationStore; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.util.BasicAuthentication; import org.eclipse.jetty.client.util.DigestAuthentication; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HttpAuthenticationStoreTest { @@ -41,7 +43,7 @@ public class HttpAuthenticationStoreTest store.addAuthentication(new BasicAuthentication(uri1, realm, "user", "password")); Authentication result = store.findAuthentication("Basic", uri2, realm); - Assert.assertNotNull(result); + assertNotNull(result); store.clearAuthentications(); @@ -50,7 +52,7 @@ public class HttpAuthenticationStoreTest uri2 = URI.create("https://server:443/path"); store.addAuthentication(new DigestAuthentication(uri1, realm, "user", "password")); result = store.findAuthentication("Digest", uri2, realm); - Assert.assertNotNull(result); + assertNotNull(result); } @Test @@ -74,7 +76,7 @@ public class HttpAuthenticationStoreTest URI uri2 = URI.create("http://host"); Authentication.Result result = store.findAuthenticationResult(uri2); - Assert.assertNotNull(result); + assertNotNull(result); store.clearAuthenticationResults(); @@ -95,6 +97,6 @@ public class HttpAuthenticationStoreTest uri2 = URI.create("https://server:443/path"); result = store.findAuthenticationResult(uri2); - Assert.assertNotNull(result); + assertNotNull(result); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java index 050e22b124f..8663ba4c999 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAsyncContentTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; @@ -35,21 +38,16 @@ import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest { - public HttpClientAsyncContentTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSmallAsyncContent(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testSmallAsyncContent() throws Exception - { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -66,7 +64,7 @@ public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest final AtomicReference contentLatch = new AtomicReference<>(new CountDownLatch(1)); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseContentAsync(new Response.AsyncContentListener() { @Override @@ -86,34 +84,34 @@ public class HttpClientAsyncContentTest extends AbstractHttpClientServerTest } }); - Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); Callback callback = callbackRef.get(); // Wait a while to be sure that the parsing does not proceed. TimeUnit.MILLISECONDS.sleep(1000); - Assert.assertEquals(1, contentCount.get()); + assertEquals(1, contentCount.get()); // Succeed the content callback to proceed with parsing. callbackRef.set(null); contentLatch.set(new CountDownLatch(1)); callback.succeeded(); - Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); callback = callbackRef.get(); // Wait a while to be sure that the parsing does not proceed. TimeUnit.MILLISECONDS.sleep(1000); - Assert.assertEquals(2, contentCount.get()); - Assert.assertEquals(1, completeLatch.getCount()); + assertEquals(2, contentCount.get()); + assertEquals(1, completeLatch.getCount()); // Succeed the content callback to proceed with parsing. callbackRef.set(null); contentLatch.set(new CountDownLatch(1)); callback.succeeded(); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(2, contentCount.get()); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertEquals(2, contentCount.get()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java index 095c858e681..12a02716450 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientAuthenticationTest.java @@ -18,6 +18,13 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.IOException; import java.net.URI; @@ -63,31 +70,25 @@ import org.eclipse.jetty.util.Attributes; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.security.Constraint; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest { private String realm = "TestRealm"; - public HttpClientAuthenticationTest(SslContextFactory sslContextFactory) + public void startBasic(final Scenario scenario, Handler handler) throws Exception { - super(sslContextFactory); + start(scenario, new BasicAuthenticator(), handler); } - public void startBasic(Handler handler) throws Exception + public void startDigest(final Scenario scenario, Handler handler) throws Exception { - start(new BasicAuthenticator(), handler); + start(scenario, new DigestAuthenticator(), handler); } - public void startDigest(Handler handler) throws Exception - { - start(new DigestAuthenticator(), handler); - } - - private void start(Authenticator authenticator, Handler handler) throws Exception + private void start(final Scenario scenario, Authenticator authenticator, Handler handler) throws Exception { server = new Server(); File realmFile = MavenTestingUtils.getTestResourceFile("realm.properties"); @@ -108,51 +109,56 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest securityHandler.setLoginService(loginService); securityHandler.setHandler(handler); - start(securityHandler); + start(scenario, securityHandler); } - @Test - public void test_BasicAuthentication() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BasicAuthentication(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); - test_Authentication(new BasicAuthentication(uri, realm, "basic", "basic")); + startBasic(scenario, new EmptyServerHandler()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); + test_Authentication(scenario, new BasicAuthentication(uri, realm, "basic", "basic")); } - @Test - public void test_BasicEmptyRealm() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BasicEmptyRealm(Scenario scenario) throws Exception { realm = ""; - startBasic(new EmptyServerHandler()); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); - test_Authentication(new BasicAuthentication(uri, realm, "basic", "basic")); + startBasic(scenario, new EmptyServerHandler()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); + test_Authentication(scenario, new BasicAuthentication(uri, realm, "basic", "basic")); } - @Test - public void test_BasicAnyRealm() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BasicAnyRealm(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); - test_Authentication(new BasicAuthentication(uri, Authentication.ANY_REALM, "basic", "basic")); + startBasic(scenario, new EmptyServerHandler()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); + test_Authentication(scenario, new BasicAuthentication(uri, Authentication.ANY_REALM, "basic", "basic")); } - @Test - public void test_DigestAuthentication() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_DigestAuthentication(Scenario scenario) throws Exception { - startDigest(new EmptyServerHandler()); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); - test_Authentication(new DigestAuthentication(uri, realm, "digest", "digest")); + startDigest(scenario, new EmptyServerHandler()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); + test_Authentication(scenario, new DigestAuthentication(uri, realm, "digest", "digest")); } - @Test - public void test_DigestAnyRealm() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_DigestAnyRealm(Scenario scenario) throws Exception { - startDigest(new EmptyServerHandler()); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); - test_Authentication(new DigestAuthentication(uri, Authentication.ANY_REALM, "digest", "digest")); + startDigest(scenario, new EmptyServerHandler()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); + test_Authentication(scenario, new DigestAuthentication(uri, Authentication.ANY_REALM, "digest", "digest")); } - private void test_Authentication(Authentication authentication) throws Exception + private void test_Authentication(final Scenario scenario, Authentication authentication) throws Exception { AuthenticationStore authenticationStore = client.getAuthenticationStore(); @@ -168,11 +174,11 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); // Request without Authentication causes a 401 - Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(401, response.getStatus()); - Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(401, response.getStatus()); + assertTrue(requests.get().await(5, TimeUnit.SECONDS)); client.getRequestListeners().remove(requestListener); authenticationStore.addAuthentication(authentication); @@ -189,11 +195,11 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); // Request with authentication causes a 401 (no previous successful authentication) + 200 - request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertTrue(requests.get().await(5, TimeUnit.SECONDS)); client.getRequestListeners().remove(requestListener); requests.set(new CountDownLatch(1)); @@ -209,18 +215,19 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest // Further requests do not trigger 401 because there is a previous successful authentication // Remove existing header to be sure it's added by the implementation - request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertTrue(requests.get().await(5, TimeUnit.SECONDS)); client.getRequestListeners().remove(requestListener); } - @Test - public void test_BasicAuthentication_ThenRedirect() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BasicAuthentication_ThenRedirect(Scenario scenario) throws Exception { - startBasic(new AbstractHandler() + startBasic(scenario, new AbstractHandler() { private final AtomicInteger requests = new AtomicInteger(); @@ -229,11 +236,11 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest { baseRequest.setHandled(true); if (requests.incrementAndGet() == 1) - response.sendRedirect(URIUtil.newURI(scheme, request.getServerName(), request.getServerPort(), request.getRequestURI(), null)); + response.sendRedirect(URIUtil.newURI(scenario.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI(), null)); } }); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, "basic", "basic")); final CountDownLatch requests = new CountDownLatch(3); @@ -248,31 +255,32 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/secure") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(requests.await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertTrue(requests.await(5, TimeUnit.SECONDS)); client.getRequestListeners().remove(requestListener); } - @Test - public void test_Redirect_ThenBasicAuthentication() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_Redirect_ThenBasicAuthentication(Scenario scenario) throws Exception { - startBasic(new AbstractHandler() + startBasic(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); if (request.getRequestURI().endsWith("/redirect")) - response.sendRedirect(URIUtil.newURI(scheme, request.getServerName(), request.getServerPort(), "/secure", null)); + response.sendRedirect(URIUtil.newURI(scenario.getScheme(), request.getServerName(), request.getServerPort(), "/secure", null)); } }); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, "basic", "basic")); final CountDownLatch requests = new CountDownLatch(3); @@ -287,20 +295,21 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/redirect") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(requests.await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertTrue(requests.await(5, TimeUnit.SECONDS)); client.getRequestListeners().remove(requestListener); } - @Test - public void test_BasicAuthentication_WithAuthenticationRemoved() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BasicAuthentication_WithAuthenticationRemoved(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); + startBasic(scenario, new EmptyServerHandler()); final AtomicReference requests = new AtomicReference<>(new CountDownLatch(2)); Request.Listener.Adapter requestListener = new Request.Listener.Adapter() @@ -314,57 +323,59 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest client.getRequestListeners().add(requestListener); AuthenticationStore authenticationStore = client.getAuthenticationStore(); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic"); authenticationStore.addAuthentication(authentication); - Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertTrue(requests.get().await(5, TimeUnit.SECONDS)); authenticationStore.removeAuthentication(authentication); requests.set(new CountDownLatch(1)); - request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertTrue(requests.get().await(5, TimeUnit.SECONDS)); Authentication.Result result = authenticationStore.findAuthenticationResult(request.getURI()); - Assert.assertNotNull(result); + assertNotNull(result); authenticationStore.removeAuthenticationResult(result); requests.set(new CountDownLatch(1)); - request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(401, response.getStatus()); - Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS)); + assertNotNull(response); + assertEquals(401, response.getStatus()); + assertTrue(requests.get().await(5, TimeUnit.SECONDS)); } - @Test - public void test_BasicAuthentication_WithWrongPassword() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BasicAuthentication_WithWrongPassword(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); + startBasic(scenario, new EmptyServerHandler()); AuthenticationStore authenticationStore = client.getAuthenticationStore(); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "wrong"); authenticationStore.addAuthentication(authentication); - Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure"); + Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scenario.getScheme()).path("/secure"); ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send(); - Assert.assertNotNull(response); - Assert.assertEquals(401, response.getStatus()); + assertNotNull(response); + assertEquals(401, response.getStatus()); } - @Test - public void test_Authentication_ThrowsException() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_Authentication_ThrowsException(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); + startBasic(scenario, new EmptyServerHandler()); // Request without Authentication would cause a 401, // but the client will throw an exception trying to @@ -387,7 +398,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/secure") .timeout(5, TimeUnit.SECONDS) .send(new Response.CompleteListener() @@ -395,22 +406,23 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isFailed()); - Assert.assertEquals(cause, result.getFailure().getMessage()); + assertTrue(result.isFailed()); + assertEquals(cause, result.getFailure().getMessage()); latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void test_PreemptedAuthentication() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PreemptedAuthentication(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); + startBasic(scenario, new EmptyServerHandler()); AuthenticationStore authenticationStore = client.getAuthenticationStore(); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); authenticationStore.addAuthenticationResult(new BasicAuthentication.BasicResult(uri, "basic", "basic")); AtomicInteger requests = new AtomicInteger(); @@ -424,22 +436,23 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/secure") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(1, requests.get()); + assertEquals(200, response.getStatus()); + assertEquals(1, requests.get()); } - @Test - public void test_NonReproducibleContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_NonReproducibleContent(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler()); + startBasic(scenario, new EmptyServerHandler()); AuthenticationStore authenticationStore = client.getAuthenticationStore(); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic"); authenticationStore.addAuthentication(authentication); @@ -464,14 +477,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest content.close(); - Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); } - @Test - public void test_RequestFailsAfterResponse() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_RequestFailsAfterResponse(Scenario scenario) throws Exception { - startBasic(new EmptyServerHandler() + startBasic(scenario, new EmptyServerHandler() { @Override protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, @@ -507,7 +521,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }); AuthenticationStore authenticationStore = client.getAuthenticationStore(); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort()); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic"); authenticationStore.addAuthentication(authentication); @@ -546,7 +560,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }); CountDownLatch resultLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/secure") .content(content) .onResponseSuccess(r->authLatch.countDown()) @@ -556,7 +570,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest resultLatch.countDown(); }); - Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); } private static class GeneratingContentProvider implements ContentProvider @@ -615,121 +629,130 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest }; } } - + @Test public void testTestHeaderInfoParsing() { AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client); - + HeaderInfo headerInfo = aph.getHeaderInfo("Digest realm=\"thermostat\", qop=\"auth\", nonce=\"1523430383\"").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfo.getParameter("qop").equals("auth")); - Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat")); - Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfo.getParameter("qop").equals("auth")); + assertTrue(headerInfo.getParameter("realm").equals("thermostat")); + assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); + headerInfo = aph.getHeaderInfo("Digest qop=\"auth\", realm=\"thermostat\", nonce=\"1523430383\"").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfo.getParameter("qop").equals("auth")); - Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat")); - Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfo.getParameter("qop").equals("auth")); + assertTrue(headerInfo.getParameter("realm").equals("thermostat")); + assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); + headerInfo = aph.getHeaderInfo("Digest qop=\"auth\", nonce=\"1523430383\", realm=\"thermostat\"").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfo.getParameter("qop").equals("auth")); - Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat")); - Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfo.getParameter("qop").equals("auth")); + assertTrue(headerInfo.getParameter("realm").equals("thermostat")); + assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); + headerInfo = aph.getHeaderInfo("Digest qop=\"auth\", nonce=\"1523430383\"").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfo.getParameter("qop").equals("auth")); - Assert.assertTrue(headerInfo.getParameter("realm") == null); - Assert.assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); - - + assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfo.getParameter("qop").equals("auth")); + assertTrue(headerInfo.getParameter("realm") == null); + assertTrue(headerInfo.getParameter("nonce").equals("1523430383")); + + // test multiple authentications List headerInfoList = aph.getHeaderInfo("Digest qop=\"auth\", realm=\"thermostat\", nonce=\"1523430383\", " + "Digest realm=\"thermostat2\", qop=\"auth2\", nonce=\"4522530354\", " + "Digest qop=\"auth3\", nonce=\"9523570528\", realm=\"thermostat3\", " + "Digest qop=\"auth4\", nonce=\"3526435321\""); - - Assert.assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(0).getParameter("qop").equals("auth")); - Assert.assertTrue(headerInfoList.get(0).getParameter("realm").equals("thermostat")); - Assert.assertTrue(headerInfoList.get(0).getParameter("nonce").equals("1523430383")); - - Assert.assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(1).getParameter("qop").equals("auth2")); - Assert.assertTrue(headerInfoList.get(1).getParameter("realm").equals("thermostat2")); - Assert.assertTrue(headerInfoList.get(1).getParameter("nonce").equals("4522530354")); - - Assert.assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3")); - Assert.assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3")); - Assert.assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528")); - - Assert.assertTrue(headerInfoList.get(3).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(3).getParameter("qop").equals("auth4")); - Assert.assertTrue(headerInfoList.get(3).getParameter("realm") == null); - Assert.assertTrue(headerInfoList.get(3).getParameter("nonce").equals("3526435321")); - + + assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(0).getParameter("qop").equals("auth")); + assertTrue(headerInfoList.get(0).getParameter("realm").equals("thermostat")); + assertTrue(headerInfoList.get(0).getParameter("nonce").equals("1523430383")); + + assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(1).getParameter("qop").equals("auth2")); + assertTrue(headerInfoList.get(1).getParameter("realm").equals("thermostat2")); + assertTrue(headerInfoList.get(1).getParameter("nonce").equals("4522530354")); + + assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3")); + assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3")); + assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528")); + + assertTrue(headerInfoList.get(3).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(3).getParameter("qop").equals("auth4")); + assertTrue(headerInfoList.get(3).getParameter("realm") == null); + assertTrue(headerInfoList.get(3).getParameter("nonce").equals("3526435321")); + List headerInfos = aph.getHeaderInfo("Newauth realm=\"apps\", type=1, title=\"Login to \\\"apps\\\"\", Basic realm=\"simple\""); - Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Newauth")); - Assert.assertTrue(headerInfos.get(0).getParameter("realm").equals("apps")); - Assert.assertTrue(headerInfos.get(0).getParameter("type").equals("1")); - Assert.assertThat(headerInfos.get(0).getParameter("title"), Matchers.equalTo("Login to \"apps\"")); - Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Basic")); - Assert.assertTrue(headerInfos.get(1).getParameter("realm").equals("simple")); + assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Newauth")); + assertTrue(headerInfos.get(0).getParameter("realm").equals("apps")); + assertTrue(headerInfos.get(0).getParameter("type").equals("1")); + + assertEquals(headerInfos.get(0).getParameter("title"),"Login to \"apps\""); + + assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Basic")); + assertTrue(headerInfos.get(1).getParameter("realm").equals("simple")); } - + @Test public void testTestHeaderInfoParsingUnusualCases() { AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client); - + HeaderInfo headerInfo = aph.getHeaderInfo("Scheme").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme")); - Assert.assertTrue(headerInfo.getParameter("realm") == null); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme")); + assertTrue(headerInfo.getParameter("realm") == null); + List headerInfos = aph.getHeaderInfo("Scheme1 , Scheme2 , Scheme3"); - Assert.assertEquals(3, headerInfos.size()); - Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme1")); - Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2")); - Assert.assertTrue(headerInfos.get(2).getType().equalsIgnoreCase("Scheme3")); - + assertEquals(3, headerInfos.size()); + assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme1")); + assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2")); + assertTrue(headerInfos.get(2).getType().equalsIgnoreCase("Scheme3")); + headerInfo = aph.getHeaderInfo("Scheme name=\"value\", other=\"value2\"").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme")); - Assert.assertTrue(headerInfo.getParameter("name").equals("value")); - Assert.assertTrue(headerInfo.getParameter("other").equals("value2")); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme")); + assertTrue(headerInfo.getParameter("name").equals("value")); + assertTrue(headerInfo.getParameter("other").equals("value2")); + headerInfo = aph.getHeaderInfo("Scheme name = value , other = \"value2\" ").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme")); - Assert.assertTrue(headerInfo.getParameter("name").equals("value")); - Assert.assertTrue(headerInfo.getParameter("other").equals("value2")); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Scheme")); + assertTrue(headerInfo.getParameter("name").equals("value")); + assertTrue(headerInfo.getParameter("other").equals("value2")); + headerInfos = aph.getHeaderInfo(", , , , ,,,Scheme name=value, ,,Scheme2 name=value2,, ,,"); - Assert.assertEquals(headerInfos.size(), 2); - Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme")); - Assert.assertTrue(headerInfos.get(0).getParameter("nAmE").equals("value")); - Assert.assertThat(headerInfos.get(1).getType(), Matchers.equalToIgnoringCase("Scheme2")); - Assert.assertTrue(headerInfos.get(1).getParameter("nAmE").equals("value2")); - + assertEquals(headerInfos.size(), 2); + assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme")); + assertTrue(headerInfos.get(0).getParameter("nAmE").equals("value")); + assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2")); + + headerInfos = aph.getHeaderInfo("Scheme name=value, Scheme2 name=value2"); + assertEquals(headerInfos.size(), 2); + assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme")); + assertTrue(headerInfos.get(0).getParameter("nAmE").equals("value")); + assertThat(headerInfos.get(1).getType(), equalToIgnoringCase("Scheme2")); + + assertTrue(headerInfos.get(1).getParameter("nAmE").equals("value2")); + headerInfos = aph.getHeaderInfo("Scheme , ,, ,, name=value, Scheme2 name=value2"); - Assert.assertEquals(headerInfos.size(), 2); - Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme")); - Assert.assertTrue(headerInfos.get(0).getParameter("name").equals("value")); - Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2")); - Assert.assertTrue(headerInfos.get(1).getParameter("name").equals("value2")); - + assertEquals(headerInfos.size(), 2); + assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Scheme")); + assertTrue(headerInfos.get(0).getParameter("name").equals("value")); + assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Scheme2")); + assertTrue(headerInfos.get(1).getParameter("name").equals("value2")); + //Negotiate with base64 Content headerInfo = aph.getHeaderInfo("Negotiate TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw==").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Negotiate")); - Assert.assertTrue(headerInfo.getBase64().equals("TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw==")); - + assertTrue(headerInfo.getType().equalsIgnoreCase("Negotiate")); + assertTrue(headerInfo.getBase64().equals("TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFAs4OAAAADw==")); + headerInfos = aph.getHeaderInfo("Negotiate TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw==, " + "Negotiate YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi="); - Assert.assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Negotiate")); - Assert.assertTrue(headerInfos.get(0).getBase64().equals("TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw==")); - - Assert.assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Negotiate")); - Assert.assertTrue(headerInfos.get(1).getBase64().equals("YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi=")); + assertTrue(headerInfos.get(0).getType().equalsIgnoreCase("Negotiate")); + assertTrue(headerInfos.get(0).getBase64().equals("TlRMTVNTUAABAAAAAAAAAFAs4OAAAADw==")); + + assertTrue(headerInfos.get(1).getType().equalsIgnoreCase("Negotiate")); + assertTrue(headerInfos.get(1).getBase64().equals("YIIJvwYGKwYBBQUCoIIJszCCCa+gJDAi=")); } @@ -741,10 +764,10 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest HeaderInfo headerInfo; headerInfo = aph.getHeaderInfo("Digest realm=\"=the=rmo=stat=\", qop=\"=a=u=t=h=\", nonce=\"=1523430383=\"").get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfo.getParameter("qop").equals("=a=u=t=h=")); - Assert.assertTrue(headerInfo.getParameter("realm").equals("=the=rmo=stat=")); - Assert.assertTrue(headerInfo.getParameter("nonce").equals("=1523430383=")); + assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfo.getParameter("qop").equals("=a=u=t=h=")); + assertTrue(headerInfo.getParameter("realm").equals("=the=rmo=stat=")); + assertTrue(headerInfo.getParameter("nonce").equals("=1523430383=")); // test multiple authentications @@ -752,20 +775,20 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest + "Digest realm=\"=thermostat2\", qop=\"=auth2\", nonce=\"=4522530354\", " + "Digest qop=\"auth3=\", nonce=\"9523570528=\", realm=\"thermostat3=\", "); - Assert.assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(0).getParameter("qop").equals("=au=th=")); - Assert.assertTrue(headerInfoList.get(0).getParameter("realm").equals("=ther=mostat=")); - Assert.assertTrue(headerInfoList.get(0).getParameter("nonce").equals("=152343=0383=")); + assertTrue(headerInfoList.get(0).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(0).getParameter("qop").equals("=au=th=")); + assertTrue(headerInfoList.get(0).getParameter("realm").equals("=ther=mostat=")); + assertTrue(headerInfoList.get(0).getParameter("nonce").equals("=152343=0383=")); - Assert.assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(1).getParameter("qop").equals("=auth2")); - Assert.assertTrue(headerInfoList.get(1).getParameter("realm").equals("=thermostat2")); - Assert.assertTrue(headerInfoList.get(1).getParameter("nonce").equals("=4522530354")); + assertTrue(headerInfoList.get(1).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(1).getParameter("qop").equals("=auth2")); + assertTrue(headerInfoList.get(1).getParameter("realm").equals("=thermostat2")); + assertTrue(headerInfoList.get(1).getParameter("nonce").equals("=4522530354")); - Assert.assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3=")); - Assert.assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3=")); - Assert.assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528=")); + assertTrue(headerInfoList.get(2).getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfoList.get(2).getParameter("qop").equals("auth3=")); + assertTrue(headerInfoList.get(2).getParameter("realm").equals("thermostat3=")); + assertTrue(headerInfoList.get(2).getParameter("nonce").equals("9523570528=")); } @Test @@ -773,17 +796,15 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest { AuthenticationProtocolHandler aph = new WWWAuthenticationProtocolHandler(client); List headerInfoList = aph.getHeaderInfo("Digest param=\",f \""); - Assert.assertEquals(1, headerInfoList.size()); - - + assertEquals(1, headerInfoList.size()); headerInfoList = aph.getHeaderInfo("Digest realm=\"thermostat\", qop=\",Digest realm=hello\", nonce=\"1523430383=\""); - Assert.assertEquals(1, headerInfoList.size()); + assertEquals(1, headerInfoList.size()); HeaderInfo headerInfo = headerInfoList.get(0); - Assert.assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); - Assert.assertTrue(headerInfo.getParameter("qop").equals(",Digest realm=hello")); - Assert.assertTrue(headerInfo.getParameter("realm").equals("thermostat")); - Assert.assertThat(headerInfo.getParameter("nonce"), Matchers.is("1523430383=")); + assertTrue(headerInfo.getType().equalsIgnoreCase("Digest")); + assertTrue(headerInfo.getParameter("qop").equals(",Digest realm=hello")); + assertTrue(headerInfo.getParameter("realm").equals("thermostat")); + assertEquals(headerInfo.getParameter("nonce"), "1523430383="); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java index d1d217bbe69..3704f0c5f03 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientChunkedContentTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -34,20 +37,14 @@ import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.client.util.FutureResponseListener; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class HttpClientChunkedContentTest { - @Rule - public final TestTracker tracker = new TestTracker(); private HttpClient client; private void startClient() throws Exception @@ -59,7 +56,7 @@ public class HttpClientChunkedContentTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -113,7 +110,7 @@ public class HttpClientChunkedContentTest Result result = resultRef.get(); assertTrue(result.isSucceeded()); Response response = result.getResponse(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } } } @@ -181,7 +178,7 @@ public class HttpClientChunkedContentTest assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); Result result = resultRef.get(); assertTrue(result.isSucceeded()); - Assert.assertEquals(200, result.getResponse().getStatus()); + assertEquals(200, result.getResponse().getStatus()); // Issue another request to be sure the connection is sane. Request request = client.newRequest("localhost", server.getLocalPort()) @@ -193,7 +190,7 @@ public class HttpClientChunkedContentTest output.write(response.getBytes(StandardCharsets.UTF_8)); output.flush(); - Assert.assertEquals(200, listener.get(5, TimeUnit.SECONDS).getStatus()); + assertEquals(200, listener.get(5, TimeUnit.SECONDS).getStatus()); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java index 7505f9ed472..5380befd7c6 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientCustomProxyTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; @@ -45,9 +48,9 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class HttpClientCustomProxyTest { @@ -72,7 +75,7 @@ public class HttpClientCustomProxyTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -108,7 +111,7 @@ public class HttpClientCustomProxyTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response.getStatus()); + assertEquals(status, response.getStatus()); } private class CAFEBABEProxy extends ProxyConfiguration.Proxy @@ -182,8 +185,8 @@ public class HttpClientCustomProxyTest { ByteBuffer buffer = BufferUtil.allocate(4); int filled = getEndPoint().fill(buffer); - Assert.assertEquals(4, filled); - Assert.assertArrayEquals(CAFE_BABE, buffer.array()); + assertEquals(4, filled); + assertArrayEquals(CAFE_BABE, buffer.array()); // We are good, upgrade the connection getEndPoint().upgrade(connectionFactory.newConnection(getEndPoint(), context)); @@ -239,8 +242,8 @@ public class HttpClientCustomProxyTest { ByteBuffer buffer = BufferUtil.allocate(4); int filled = getEndPoint().fill(buffer); - Assert.assertEquals(4, filled); - Assert.assertArrayEquals(CAFE_BABE, buffer.array()); + assertEquals(4, filled); + assertArrayEquals(CAFE_BABE, buffer.array()); getEndPoint().write(this, buffer); } catch (Throwable x) diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java index 5ef311be305..fe70713c688 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientExplicitConnectionTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -30,57 +35,53 @@ import org.eclipse.jetty.client.http.HttpDestinationOverHTTP; import org.eclipse.jetty.client.util.FutureResponseListener; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.util.FuturePromise; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTest { - public HttpClientExplicitConnectionTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testExplicitConnection(Scenario scenario) throws Exception { - super(sslContextFactory); - } + start(scenario, new EmptyServerHandler()); - @Test - public void testExplicitConnection() throws Exception - { - start(new EmptyServerHandler()); - - Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort()); + Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); FuturePromise futureConnection = new FuturePromise<>(); destination.newConnection(futureConnection); try (Connection connection = futureConnection.get(5, TimeUnit.SECONDS)) { - Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme); + Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scenario.getScheme()); FutureResponseListener listener = new FutureResponseListener(request); connection.send(request, listener); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); HttpDestinationOverHTTP httpDestination = (HttpDestinationOverHTTP)destination; DuplexConnectionPool connectionPool = (DuplexConnectionPool)httpDestination.getConnectionPool(); - Assert.assertTrue(connectionPool.getActiveConnections().isEmpty()); - Assert.assertTrue(connectionPool.getIdleConnections().isEmpty()); + assertTrue(connectionPool.getActiveConnections().isEmpty()); + assertTrue(connectionPool.getIdleConnections().isEmpty()); } } - @Test - public void testExplicitConnectionIsClosedOnRemoteClose() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testExplicitConnectionIsClosedOnRemoteClose(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); - Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort()); + Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); FuturePromise futureConnection = new FuturePromise<>(); destination.newConnection(futureConnection); Connection connection = futureConnection.get(5, TimeUnit.SECONDS); - Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme); + Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scenario.getScheme()); FutureResponseListener listener = new FutureResponseListener(request); connection.send(request, listener); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // Wait some time to have the client is an idle state. TimeUnit.SECONDS.sleep(1); @@ -91,33 +92,34 @@ public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTe TimeUnit.SECONDS.sleep(1); HttpConnectionOverHTTP httpConnection = (HttpConnectionOverHTTP)connection; - Assert.assertFalse(httpConnection.getEndPoint().isOpen()); + assertFalse(httpConnection.getEndPoint().isOpen()); HttpDestinationOverHTTP httpDestination = (HttpDestinationOverHTTP)destination; DuplexConnectionPool connectionPool = (DuplexConnectionPool)httpDestination.getConnectionPool(); - Assert.assertTrue(connectionPool.getActiveConnections().isEmpty()); - Assert.assertTrue(connectionPool.getIdleConnections().isEmpty()); + assertTrue(connectionPool.getActiveConnections().isEmpty()); + assertTrue(connectionPool.getIdleConnections().isEmpty()); } - @Test - public void testExplicitConnectionResponseListeners() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testExplicitConnectionResponseListeners(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); - Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort()); + Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); FuturePromise futureConnection = new FuturePromise<>(); destination.newConnection(futureConnection); Connection connection = futureConnection.get(5, TimeUnit.SECONDS); CountDownLatch responseLatch = new CountDownLatch(1); Request request = client.newRequest(destination.getHost(), destination.getPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseSuccess(response -> responseLatch.countDown()); FutureResponseListener listener = new FutureResponseListener(request); connection.send(request, listener); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java index 6ccd6b71609..cc92cff52fd 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientFailureTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -35,9 +39,9 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class HttpClientFailureTest { @@ -56,7 +60,7 @@ public class HttpClientFailureTest server.start(); } - @After + @AfterEach public void dispose() throws Exception { if (server != null) @@ -83,23 +87,17 @@ public class HttpClientFailureTest }, null); client.start(); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .onRequestHeaders(request -> connectionRef.get().getEndPoint().close()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected. - } + }); DuplexConnectionPool connectionPool = (DuplexConnectionPool)connectionRef.get().getHttpDestination().getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } @Test @@ -137,7 +135,7 @@ public class HttpClientFailureTest completeLatch.countDown(); }); - Assert.assertTrue(commitLatch.await(5, TimeUnit.SECONDS)); + assertTrue(commitLatch.await(5, TimeUnit.SECONDS)); final CountDownLatch contentLatch = new CountDownLatch(1); content.offer(ByteBuffer.allocate(1024), new Callback() { @@ -148,14 +146,14 @@ public class HttpClientFailureTest } }); - Assert.assertTrue(commitLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(commitLatch.await(5, TimeUnit.SECONDS)); + assertTrue(contentLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); DuplexConnectionPool connectionPool = (DuplexConnectionPool)connectionRef.get().getHttpDestination().getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } /* @Test @@ -217,7 +215,7 @@ public class HttpClientFailureTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -248,7 +246,7 @@ public class HttpClientFailureTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } */ } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java index c4f203211ed..0c4d5b1f5f4 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientGZIPTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InterruptedIOException; @@ -34,22 +38,17 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientGZIPTest extends AbstractHttpClientServerTest { - public HttpClientGZIPTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - - @Test - public void testGZIPContentEncoding() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testGZIPContentEncoding(Scenario scenario) throws Exception { final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -63,19 +62,20 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } - @Test - public void testGZIPContentOneByteAtATime() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testGZIPContentOneByteAtATime(Scenario scenario) throws Exception { final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -100,18 +100,19 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } - @Test - public void testGZIPContentSentTwiceInOneWrite() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testGZIPContentSentTwiceInOneWrite(Scenario scenario) throws Exception { final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -134,34 +135,36 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); byte[] expected = Arrays.copyOf(data, 2 * data.length); System.arraycopy(data, 0, expected, data.length, data.length); - Assert.assertArrayEquals(expected, response.getContent()); + assertArrayEquals(expected, response.getContent()); } - @Test - public void testGZIPContentFragmentedBeforeTrailer() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testGZIPContentFragmentedBeforeTrailer(Scenario scenario) throws Exception { // There are 8 trailer bytes to gzip encoding. - testGZIPContentFragmented(9); + testGZIPContentFragmented(scenario, 9); } - @Test - public void testGZIPContentFragmentedAtTrailer() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testGZIPContentFragmentedAtTrailer(Scenario scenario) throws Exception { // There are 8 trailer bytes to gzip encoding. - testGZIPContentFragmented(1); + testGZIPContentFragmented(scenario, 1); } - private void testGZIPContentFragmented(final int fragment) throws Exception + private void testGZIPContentFragmented(Scenario scenario, final int fragment) throws Exception { final byte[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -190,17 +193,18 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } - @Test - public void testGZIPContentCorrupted() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testGZIPContentCorrupted(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -214,14 +218,14 @@ public class HttpClientGZIPTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(result -> { if (result.isFailed()) latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } private static void sleep(long ms) throws IOException diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java index b5af743a9dc..042ead500a9 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientProxyTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -36,24 +38,18 @@ import org.eclipse.jetty.http.HttpScheme; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.B64Code; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientProxyTest extends AbstractHttpClientServerTest { - public HttpClientProxyTest(SslContextFactory sslContextFactory) - { - // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests - super(null); - } - - @Test - public void testProxiedRequest() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests + public void testProxiedRequest(Scenario scenario) throws Exception { final String serverHost = "server"; final int status = HttpStatus.NO_CONTENT_204; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -73,15 +69,16 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest client.getProxyConfiguration().getProxies().add(new HttpProxy("localhost", proxyPort)); ContentResponse response = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response.getStatus()); + assertEquals(status, response.getStatus()); } - @Test - public void testProxyAuthentication() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests + public void testProxyAuthentication(Scenario scenario) throws Exception { final String user = "foo"; final String password = "bar"; @@ -89,7 +86,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest final String serverHost = "server"; final String realm = "test_realm"; final int status = HttpStatus.NO_CONTENT_204; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -120,15 +117,15 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort)); ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); // No Authentication available => 407 - Assert.assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus()); + assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus()); // Add authentication... - URI uri = URI.create(scheme + "://" + proxyHost + ":" + proxyPort); + URI uri = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, user, password)); final AtomicInteger requests = new AtomicInteger(); client.getRequestListeners().add(new Request.Listener.Adapter() @@ -141,36 +138,37 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // ...and perform the request again => 407 + 204 ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response2.getStatus()); - Assert.assertEquals(2, requests.get()); + assertEquals(status, response2.getStatus()); + assertEquals(2, requests.get()); // Now the authentication result is cached => 204 requests.set(0); ContentResponse response3 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response3.getStatus()); - Assert.assertEquals(1, requests.get()); + assertEquals(status, response3.getStatus()); + assertEquals(1, requests.get()); } - @Test - public void testProxyAuthenticationWithRedirect() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests + public void testProxyAuthenticationWithRedirect(Scenario scenario) throws Exception { String user = "foo"; String password = "bar"; String credentials = B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1); String proxyHost = "localhost"; String serverHost = "server"; - int serverPort = HttpScheme.HTTP.is(scheme) ? 80 : 443; + int serverPort = HttpScheme.HTTP.is(scenario.getScheme()) ? 80 : 443; String realm = "test_realm"; int status = HttpStatus.NO_CONTENT_204; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -193,7 +191,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest if (credentials.equals(attempt)) { // Change also the host, to verify that proxy authentication works in this case too. - response.sendRedirect(scheme + "://127.0.0.1:" + serverPort + "/server"); + response.sendRedirect(scenario.getScheme() + "://127.0.0.1:" + serverPort + "/server"); } } } @@ -213,16 +211,16 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort)); ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/proxy") .timeout(5, TimeUnit.SECONDS) .send(); // No Authentication available => 407. - Assert.assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus()); + assertEquals(HttpStatus.PROXY_AUTHENTICATION_REQUIRED_407, response1.getStatus()); // Add authentication... - URI uri = URI.create(scheme + "://" + proxyHost + ":" + proxyPort); + URI uri = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, realm, user, password)); final AtomicInteger requests = new AtomicInteger(); client.getRequestListeners().add(new Request.Listener.Adapter() @@ -235,33 +233,34 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // ...and perform the request again => 407 + 302 + 204. ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/proxy") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response2.getStatus()); - Assert.assertEquals(3, requests.get()); + assertEquals(status, response2.getStatus()); + assertEquals(3, requests.get()); // Now the authentication result is cached => 204. requests.set(0); ContentResponse response3 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/server") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response3.getStatus()); - Assert.assertEquals(1, requests.get()); + assertEquals(status, response3.getStatus()); + assertEquals(1, requests.get()); } - @Test - public void testProxyAuthenticationWithServerAuthentication() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests + public void testProxyAuthenticationWithServerAuthentication(Scenario scenario) throws Exception { String proxyRealm = "proxyRealm"; String serverRealm = "serverRealm"; int status = HttpStatus.NO_CONTENT_204; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -293,9 +292,9 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest int proxyPort = connector.getLocalPort(); String serverHost = "server"; int serverPort = proxyPort + 1; - URI proxyURI = URI.create(scheme + "://" + proxyHost + ":" + proxyPort); + URI proxyURI = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(proxyURI, proxyRealm, "proxyUser", "proxyPassword")); - URI serverURI = URI.create(scheme + "://" + serverHost + ":" + serverPort); + URI serverURI = URI.create(scenario.getScheme() + "://" + serverHost + ":" + serverPort); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(serverURI, serverRealm, "serverUser", "serverPassword")); client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort)); final AtomicInteger requests = new AtomicInteger(); @@ -309,31 +308,32 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // Make a request, expect 407 + 401 + 204. ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response1.getStatus()); - Assert.assertEquals(3, requests.get()); + assertEquals(status, response1.getStatus()); + assertEquals(3, requests.get()); // Make again the request, authentication is cached, expect 204. requests.set(0); ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response2.getStatus()); - Assert.assertEquals(1, requests.get()); + assertEquals(status, response2.getStatus()); + assertEquals(1, requests.get()); } - @Test - public void testProxyAuthenticationWithExplicitAuthorizationHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) // Avoid TLS otherwise CONNECT requests are sent instead of proxied requests + public void testProxyAuthenticationWithExplicitAuthorizationHeader(Scenario scenario) throws Exception { String proxyRealm = "proxyRealm"; String serverRealm = "serverRealm"; int status = HttpStatus.NO_CONTENT_204; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -365,7 +365,7 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest int proxyPort = connector.getLocalPort(); String serverHost = "server"; int serverPort = proxyPort + 1; - URI proxyURI = URI.create(scheme + "://" + proxyHost + ":" + proxyPort); + URI proxyURI = URI.create(scenario.getScheme() + "://" + proxyHost + ":" + proxyPort); client.getAuthenticationStore().addAuthentication(new BasicAuthentication(proxyURI, proxyRealm, "proxyUser", "proxyPassword")); client.getProxyConfiguration().getProxies().add(new HttpProxy(proxyHost, proxyPort)); final AtomicInteger requests = new AtomicInteger(); @@ -379,23 +379,23 @@ public class HttpClientProxyTest extends AbstractHttpClientServerTest }); // Make a request, expect 407 + 204. ContentResponse response1 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.AUTHORIZATION, "Basic foobar") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response1.getStatus()); - Assert.assertEquals(2, requests.get()); + assertEquals(status, response1.getStatus()); + assertEquals(2, requests.get()); // Make again the request, authentication is cached, expect 204. requests.set(0); ContentResponse response2 = client.newRequest(serverHost, serverPort) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.AUTHORIZATION, "Basic foobar") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(status, response2.getStatus()); - Assert.assertEquals(1, requests.get()); + assertEquals(status, response2.getStatus()); + assertEquals(1, requests.get()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java index b59ab5f7ca5..fbcac8d2d3a 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientRedirectTest.java @@ -18,6 +18,14 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.net.URLDecoder; import java.nio.ByteBuffer; @@ -42,229 +50,226 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.IO; -import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientRedirectTest extends AbstractHttpClientServerTest { - public HttpClientRedirectTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_303(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void test_303() throws Exception - { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void test_303_302() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_303_302(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/302/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void test_303_302_OnDifferentDestinations() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_303_302_OnDifferentDestinations(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/127.0.0.1/302/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void test_301() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_301(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.HEAD) .path("/301/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void test_301_WithWrongMethod() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_301_WithWrongMethod(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); - try - { + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.DELETE) .path("/301/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - HttpResponseException xx = (HttpResponseException)x.getCause(); - Response response = xx.getResponse(); - Assert.assertNotNull(response); - Assert.assertEquals(301, response.getStatus()); - Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); - } + }); + HttpResponseException xx = (HttpResponseException)x.getCause(); + Response response = xx.getResponse(); + assertNotNull(response); + assertEquals(301, response.getStatus()); + assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void test_307_WithRequestContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_307_WithRequestContent(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6, 7}; ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .path("/307/localhost/done") .content(new ByteBufferContentProvider(ByteBuffer.wrap(data))) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); - Assert.assertArrayEquals(data, response.getContent()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertArrayEquals(data, response.getContent()); } - @Test - public void testMaxRedirections() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testMaxRedirections(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); client.setMaxRedirects(1); - try - { + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/302/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - HttpResponseException xx = (HttpResponseException)x.getCause(); - Response response = xx.getResponse(); - Assert.assertNotNull(response); - Assert.assertEquals(302, response.getStatus()); - Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); - } + }); + HttpResponseException xx = (HttpResponseException)x.getCause(); + Response response = xx.getResponse(); + assertNotNull(response); + assertEquals(302, response.getStatus()); + assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void test_303_WithConnectionClose_WithBigRequest() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_303_WithConnectionClose_WithBigRequest(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/done?close=true") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void testDontFollowRedirects() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testDontFollowRedirects(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .followRedirects(false) .path("/303/localhost/done?close=true") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(303, response.getStatus()); - Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(303, response.getStatus()); + assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void testRelativeLocation() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRelativeLocation(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/done?relative=true") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void testAbsoluteURIPathWithSpaces() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbsoluteURIPathWithSpaces(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/a+space?decode=true") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void testRelativeURIPathWithSpaces() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRelativeURIPathWithSpaces(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/a+space?relative=true&decode=true") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString())); } - @Test - public void testRedirectWithWrongScheme() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRedirectWithWrongScheme(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -277,149 +282,164 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/path") .timeout(5, TimeUnit.SECONDS) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - @Ignore - public void testRedirectFailed() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + @Disabled + public void testRedirectFailed(Scenario scenario) throws Exception { // TODO this test is failing with timout after an ISP upgrade?? DNS dependent? - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); try { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/doesNotExist/done") .timeout(5, TimeUnit.SECONDS) .send(); } catch (ExecutionException x) { - Assert.assertThat(x.getCause(), Matchers.instanceOf(UnresolvedAddressException.class)); + assertThat(x.getCause(), Matchers.instanceOf(UnresolvedAddressException.class)); } } - @Test - public void test_HEAD_301() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_HEAD_301(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.MOVED_PERMANENTLY_301); + testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.MOVED_PERMANENTLY_301); } - @Test - public void test_POST_301() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_301(Scenario scenario) throws Exception { - testGETRedirect(HttpMethod.POST, HttpStatus.MOVED_PERMANENTLY_301); + testGETRedirect(scenario, HttpMethod.POST, HttpStatus.MOVED_PERMANENTLY_301); } - @Test - public void test_PUT_301() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PUT_301(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.PUT, HttpStatus.MOVED_PERMANENTLY_301); + testSameMethodRedirect(scenario, HttpMethod.PUT, HttpStatus.MOVED_PERMANENTLY_301); } - @Test - public void test_HEAD_302() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_HEAD_302(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.FOUND_302); + testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.FOUND_302); } - @Test - public void test_POST_302() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_302(Scenario scenario) throws Exception { - testGETRedirect(HttpMethod.POST, HttpStatus.FOUND_302); + testGETRedirect(scenario, HttpMethod.POST, HttpStatus.FOUND_302); } - @Test - public void test_PUT_302() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PUT_302(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.PUT, HttpStatus.FOUND_302); + testSameMethodRedirect(scenario, HttpMethod.PUT, HttpStatus.FOUND_302); } - @Test - public void test_HEAD_303() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_HEAD_303(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.SEE_OTHER_303); + testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.SEE_OTHER_303); } - @Test - public void test_POST_303() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_303(Scenario scenario) throws Exception { - testGETRedirect(HttpMethod.POST, HttpStatus.SEE_OTHER_303); + testGETRedirect(scenario, HttpMethod.POST, HttpStatus.SEE_OTHER_303); } - @Test - public void test_PUT_303() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PUT_303(Scenario scenario) throws Exception { - testGETRedirect(HttpMethod.PUT, HttpStatus.SEE_OTHER_303); + testGETRedirect(scenario, HttpMethod.PUT, HttpStatus.SEE_OTHER_303); } - @Test - public void test_HEAD_307() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_HEAD_307(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.HEAD, HttpStatus.TEMPORARY_REDIRECT_307); + testSameMethodRedirect(scenario, HttpMethod.HEAD, HttpStatus.TEMPORARY_REDIRECT_307); } - @Test - public void test_POST_307() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_307(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.POST, HttpStatus.TEMPORARY_REDIRECT_307); + testSameMethodRedirect(scenario, HttpMethod.POST, HttpStatus.TEMPORARY_REDIRECT_307); } - @Test - public void test_PUT_307() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PUT_307(Scenario scenario) throws Exception { - testSameMethodRedirect(HttpMethod.PUT, HttpStatus.TEMPORARY_REDIRECT_307); + testSameMethodRedirect(scenario, HttpMethod.PUT, HttpStatus.TEMPORARY_REDIRECT_307); } - @Test - public void testHttpRedirector() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHttpRedirector(Scenario scenario) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); final HttpRedirector redirector = new HttpRedirector(client); org.eclipse.jetty.client.api.Request request1 = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/303/localhost/302/localhost/done") .timeout(5, TimeUnit.SECONDS) .followRedirects(false); ContentResponse response1 = request1.send(); - Assert.assertEquals(303, response1.getStatus()); - Assert.assertTrue(redirector.isRedirect(response1)); + assertEquals(303, response1.getStatus()); + assertTrue(redirector.isRedirect(response1)); Result result = redirector.redirect(request1, response1); org.eclipse.jetty.client.api.Request request2 = result.getRequest(); Response response2 = result.getResponse(); - Assert.assertEquals(302, response2.getStatus()); - Assert.assertTrue(redirector.isRedirect(response2)); + assertEquals(302, response2.getStatus()); + assertTrue(redirector.isRedirect(response2)); final CountDownLatch latch = new CountDownLatch(1); redirector.redirect(request2, response2, r -> { Response response3 = r.getResponse(); - Assert.assertEquals(200, response3.getStatus()); - Assert.assertFalse(redirector.isRedirect(response3)); + assertEquals(200, response3.getStatus()); + assertFalse(redirector.isRedirect(response3)); latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testRedirectWithCorruptedBody() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRedirectWithCorruptedBody(Scenario scenario) throws Exception { byte[] bytes = "ok".getBytes(StandardCharsets.UTF_8); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -428,7 +448,7 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest if (target.startsWith("/redirect")) { response.setStatus(HttpStatus.SEE_OTHER_303); - response.setHeader(HttpHeader.LOCATION.asString(), scheme + "://localhost:" + connector.getLocalPort() + "/ok"); + response.setHeader(HttpHeader.LOCATION.asString(), scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/ok"); // Say that we send gzipped content, but actually don't. response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip"); response.getOutputStream().write("redirect".getBytes(StandardCharsets.UTF_8)); @@ -442,28 +462,28 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/redirect") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(bytes, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(bytes, response.getContent()); } - private void testSameMethodRedirect(final HttpMethod method, int redirectCode) throws Exception + private void testSameMethodRedirect(final Scenario scenario, final HttpMethod method, int redirectCode) throws Exception { - testMethodRedirect(method, method, redirectCode); + testMethodRedirect(scenario, method, method, redirectCode); } - private void testGETRedirect(final HttpMethod method, int redirectCode) throws Exception + private void testGETRedirect(final Scenario scenario, final HttpMethod method, int redirectCode) throws Exception { - testMethodRedirect(method, HttpMethod.GET, redirectCode); + testMethodRedirect(scenario, method, HttpMethod.GET, redirectCode); } - private void testMethodRedirect(final HttpMethod requestMethod, final HttpMethod redirectMethod, int redirectCode) throws Exception + private void testMethodRedirect(final Scenario scenario, final HttpMethod requestMethod, final HttpMethod redirectMethod, int redirectCode) throws Exception { - start(new RedirectHandler()); + start(scenario, new RedirectHandler()); final AtomicInteger passes = new AtomicInteger(); client.getRequestListeners().add(new org.eclipse.jetty.client.api.Request.Listener.Adapter() @@ -490,13 +510,13 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(requestMethod) .path("/" + redirectCode + "/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } private class RedirectHandler extends AbstractHandler diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java index 4c8ae816d9e..2aafbe1b783 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientSynchronizationTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.ConnectException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -25,25 +29,20 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; -import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; /** * Verifies that synchronization performed from outside HttpClient does not cause deadlocks */ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest { - public HttpClientSynchronizationTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSynchronizationOnException(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testSynchronizationOnException() throws Exception - { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); int port = connector.getLocalPort(); server.stop(); @@ -52,7 +51,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest for (int i = 0; i < count; ++i) { Request request = client.newRequest("localhost", port) - .scheme(scheme); + .scheme(scenario.getScheme()); synchronized (this) { @@ -63,7 +62,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest { synchronized (HttpClientSynchronizationTest.this) { - Assert.assertThat(failure, Matchers.instanceOf(ConnectException.class)); + assertThat(failure, Matchers.instanceOf(ConnectException.class)); latch.countDown(); } } @@ -71,20 +70,21 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest } } - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testSynchronizationOnComplete() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSynchronizationOnComplete(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); int count = 10; final CountDownLatch latch = new CountDownLatch(count); for (int i = 0; i < count; ++i) { Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme); + .scheme(scenario.getScheme()); synchronized (this) { @@ -95,7 +95,7 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest { synchronized (HttpClientSynchronizationTest.this) { - Assert.assertFalse(result.isFailed()); + assertFalse(result.isFailed()); latch.countDown(); } } @@ -103,6 +103,6 @@ public class HttpClientSynchronizationTest extends AbstractHttpClientServerTest } } - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java index 741b5582ff2..076d923a816 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTLSTest.java @@ -18,6 +18,15 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; @@ -49,10 +58,11 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.ExecutorThreadPool; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnJre; +import org.junit.jupiter.api.condition.JRE; public class HttpClientTLSTest { @@ -91,7 +101,7 @@ public class HttpClientTLSTest return sslContextFactory; } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -131,21 +141,15 @@ public class HttpClientTLSTest } }); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected. - } + }); - Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); } @Test @@ -179,21 +183,15 @@ public class HttpClientTLSTest } }); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected. - } + }); - Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); } @Test @@ -228,29 +226,23 @@ public class HttpClientTLSTest } }); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected. - } + }); - Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); } + // In JDK 11, a mismatch on the client does not generate any bytes towards + // the server, while in TLS 1.2 the client sends to the server the close_notify. + @DisabledOnJre( JRE.JAVA_11 ) @Test public void testMismatchBetweenTLSProtocolAndTLSCiphersOnClient() throws Exception { - // In JDK 11, a mismatch on the client does not generate any bytes towards - // the server, while in TLS 1.2 the client sends to the server the close_notify. - Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11)); SslContextFactory serverTLSFactory = createSslContextFactory(); startServer(serverTLSFactory, new EmptyServerHandler()); @@ -281,21 +273,15 @@ public class HttpClientTLSTest } }); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .scheme(HttpScheme.HTTPS.asString()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected. - } + }); - Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); } @Test @@ -328,17 +314,17 @@ public class HttpClientTLSTest }); ContentResponse response = client.GET("https://localhost:" + connector.getLocalPort()); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); } + // Excluded because of a bug in JDK 11+27 where session resumption does not work. + @DisabledOnJre( JRE.JAVA_11 ) @Test public void testHandshakeSucceededWithSessionResumption() throws Exception { - // Excluded because of a bug in JDK 11+27 where session resumption does not work. - Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11)); SslContextFactory serverTLSFactory = createSslContextFactory(); startServer(serverTLSFactory, new EmptyServerHandler()); @@ -372,10 +358,10 @@ public class HttpClientTLSTest .header(HttpHeader.CONNECTION, "close") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertNotNull(serverSession.get()); - Assert.assertNotNull(clientSession.get()); + assertNotNull(serverSession.get()); + assertNotNull(clientSession.get()); connector.removeBean(connector.getBean(SslHandshakeListener.class)); client.removeBean(client.getBean(SslHandshakeListener.class)); @@ -408,17 +394,17 @@ public class HttpClientTLSTest .header(HttpHeader.CONNECTION, "close") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(1, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(1, TimeUnit.SECONDS)); } + // Excluded because of a bug in JDK 11+27 where session resumption does not work. + @DisabledOnJre( JRE.JAVA_11 ) @Test public void testClientRawCloseDoesNotInvalidateSession() throws Exception { - // Excluded because of a bug in JDK 11+27 where session resumption does not work. - Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11)); SslContextFactory serverTLSFactory = createSslContextFactory(); startServer(serverTLSFactory, new EmptyServerHandler()); @@ -438,7 +424,7 @@ public class HttpClientTLSTest handshakeLatch1.countDown(); }); sslSocket.startHandshake(); - Assert.assertTrue(handshakeLatch1.await(5, TimeUnit.SECONDS)); + assertTrue(handshakeLatch1.await(5, TimeUnit.SECONDS)); // In TLS 1.3 the server sends a NewSessionTicket post-handshake message // to enable session resumption and without a read, the message is not processed. @@ -465,9 +451,9 @@ public class HttpClientTLSTest handshakeLatch2.countDown(); }); sslSocket.startHandshake(); - Assert.assertTrue(handshakeLatch2.await(5, TimeUnit.SECONDS)); + assertTrue(handshakeLatch2.await(5, TimeUnit.SECONDS)); - Assert.assertArrayEquals(session1.get(), session2.get()); + assertArrayEquals(session1.get(), session2.get()); sslSocket.close(); } @@ -499,7 +485,7 @@ public class HttpClientTLSTest .scheme(HttpScheme.HTTPS.asString()) .send(result -> { - Assert.assertThat(result.getResponseFailure(), Matchers.instanceOf(SSLException.class)); + assertThat(result.getResponseFailure(), instanceOf(SSLException.class)); latch.countDown(); }); @@ -538,7 +524,7 @@ public class HttpClientTLSTest // the socket in the try-with-resources block end. } - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java index 10f55a6be33..9afbf8c32fa 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java @@ -18,6 +18,16 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -76,47 +86,44 @@ import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.http.HttpScheme; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.io.AbstractConnection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.TestingDir; -import org.eclipse.jetty.toolchain.test.annotation.Slow; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.SocketAddressResolver; import org.eclipse.jetty.util.log.StacklessLogging; -import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +@ExtendWith(WorkDirExtension.class) public class HttpClientTest extends AbstractHttpClientServerTest { - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; - public HttpClientTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testStoppingClosesConnections(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testStoppingClosesConnections() throws Exception - { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); String path = "/"; - Response response = client.GET(scheme + "://" + host + ":" + port + path); - Assert.assertEquals(200, response.getStatus()); + Response response = client.GET(scenario.getScheme() + "://" + host + ":" + port + path); + assertEquals(200, response.getStatus()); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); long start = System.nanoTime(); @@ -126,54 +133,57 @@ public class HttpClientTest extends AbstractHttpClientServerTest connection = (HttpConnectionOverHTTP)connectionPool.getIdleConnections().peek(); TimeUnit.MILLISECONDS.sleep(10); } - Assert.assertNotNull(connection); + assertNotNull(connection); String uri = destination.getScheme() + "://" + destination.getHost() + ":" + destination.getPort(); client.getCookieStore().add(URI.create(uri), new HttpCookie("foo", "bar")); client.stop(); - Assert.assertEquals(0, client.getDestinations().size()); - Assert.assertEquals(0, connectionPool.getIdleConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnectionCount()); - Assert.assertFalse(connection.getEndPoint().isOpen()); + assertEquals(0, client.getDestinations().size()); + assertEquals(0, connectionPool.getIdleConnectionCount()); + assertEquals(0, connectionPool.getActiveConnectionCount()); + assertFalse(connection.getEndPoint().isOpen()); } - @Test - public void test_DestinationCount() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_DestinationCount(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - client.GET(scheme + "://" + host + ":" + port); + client.GET(scenario.getScheme() + "://" + host + ":" + port); List destinations = client.getDestinations(); - Assert.assertNotNull(destinations); - Assert.assertEquals(1, destinations.size()); + assertNotNull(destinations); + assertEquals(1, destinations.size()); Destination destination = destinations.get(0); - Assert.assertNotNull(destination); - Assert.assertEquals(scheme, destination.getScheme()); - Assert.assertEquals(host, destination.getHost()); - Assert.assertEquals(port, destination.getPort()); + assertNotNull(destination); + assertEquals(scenario.getScheme(), destination.getScheme()); + assertEquals(host, destination.getHost()); + assertEquals(port, destination.getPort()); } - @Test - public void test_GET_ResponseWithoutContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_GET_ResponseWithoutContent(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); - Response response = client.GET(scheme + "://localhost:" + connector.getLocalPort()); + Response response = client.GET(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } - @Test - public void test_GET_ResponseWithContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_GET_ResponseWithContent(Scenario scenario) throws Exception { final byte[] data = new byte[]{0, 1, 2, 3, 4, 5, 6, 7}; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -184,20 +194,21 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); client.setConnectBlocking(true); - ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort()); + ContentResponse response = client.GET(scenario.getScheme() + "://localhost:" + connector.getLocalPort()); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); byte[] content = response.getContent(); - Assert.assertArrayEquals(data, content); + assertArrayEquals(data, content); } - @Test - public void test_GET_WithParameters_ResponseWithContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_GET_WithParameters_ResponseWithContent(Scenario scenario) throws Exception { final String paramName1 = "a"; final String paramName2 = "b"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -207,7 +218,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest String paramValue1 = request.getParameter(paramName1); output.write(paramValue1.getBytes(StandardCharsets.UTF_8)); String paramValue2 = request.getParameter(paramName2); - Assert.assertEquals("", paramValue2); + assertEquals("", paramValue2); output.write("empty".getBytes(StandardCharsets.UTF_8)); baseRequest.setHandled(true); } @@ -216,20 +227,21 @@ public class HttpClientTest extends AbstractHttpClientServerTest String value1 = "\u20AC"; String paramValue1 = URLEncoder.encode(value1, "UTF-8"); String query = paramName1 + "=" + paramValue1 + "&" + paramName2; - ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query); + ContentResponse response = client.GET(scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/?" + query); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); String content = new String(response.getContent(), StandardCharsets.UTF_8); - Assert.assertEquals(value1 + "empty", content); + assertEquals(value1 + "empty", content); } - @Test - public void test_GET_WithParametersMultiValued_ResponseWithContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_GET_WithParametersMultiValued_ResponseWithContent(Scenario scenario) throws Exception { final String paramName1 = "a"; final String paramName2 = "b"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -252,20 +264,21 @@ public class HttpClientTest extends AbstractHttpClientServerTest String paramValue12 = URLEncoder.encode(value12, "UTF-8"); String paramValue2 = URLEncoder.encode(value2, "UTF-8"); String query = paramName1 + "=" + paramValue11 + "&" + paramName1 + "=" + paramValue12 + "&" + paramName2 + "=" + paramValue2; - ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query); + ContentResponse response = client.GET(scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/?" + query); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); String content = new String(response.getContent(), StandardCharsets.UTF_8); - Assert.assertEquals(value11 + value12 + value2, content); + assertEquals(value11 + value12 + value2, content); } - @Test - public void test_POST_WithParameters() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_WithParameters(Scenario scenario) throws Exception { final String paramName = "a"; final String paramValue = "\u20AC"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -281,23 +294,24 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()) + ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort()) .param(paramName, paramValue) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(paramValue, new String(response.getContent(), StandardCharsets.UTF_8)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(paramValue, new String(response.getContent(), StandardCharsets.UTF_8)); } - @Test - public void test_PUT_WithParameters() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PUT_WithParameters(Scenario scenario) throws Exception { final String paramName = "a"; final String paramValue = "\u20AC"; final String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8"); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -313,24 +327,25 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort() + "/path?" + paramName + "=" + encodedParamValue); + URI uri = URI.create(scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/path?" + paramName + "=" + encodedParamValue); ContentResponse response = client.newRequest(uri) .method(HttpMethod.PUT) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(paramValue, new String(response.getContent(), StandardCharsets.UTF_8)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(paramValue, new String(response.getContent(), StandardCharsets.UTF_8)); } - @Test - public void test_POST_WithParameters_WithContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_WithParameters_WithContent(Scenario scenario) throws Exception { final byte[] content = {0, 1, 2, 3}; final String paramName = "a"; final String paramValue = "\u20AC"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -347,21 +362,22 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort() + "/?b=1") + ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/?b=1") .param(paramName, paramValue) .content(new BytesContentProvider(content)) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(content, response.getContent()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertArrayEquals(content, response.getContent()); } - @Test - public void test_POST_WithContent_NotifiesRequestContentListener() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_WithContent_NotifiesRequestContentListener(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -372,7 +388,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); final byte[] content = {0, 1, 2, 3}; - ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()) + ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort()) .onRequestContent((request, buffer) -> { byte[] bytes = new byte[buffer.remaining()]; @@ -384,14 +400,15 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } - @Test - public void test_POST_WithContent_TracksProgress() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_POST_WithContent_TracksProgress(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -402,34 +419,35 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); final AtomicInteger progress = new AtomicInteger(); - ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort()) + ContentResponse response = client.POST(scenario.getScheme() + "://localhost:" + connector.getLocalPort()) .onRequestContent((request, buffer) -> { byte[] bytes = new byte[buffer.remaining()]; - Assert.assertEquals(1, bytes.length); + assertEquals(1, bytes.length); buffer.get(bytes); - Assert.assertEquals(bytes[0], progress.getAndIncrement()); + assertEquals(bytes[0], progress.getAndIncrement()); }) .content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{2}, new byte[]{3}, new byte[]{4})) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(5, progress.get()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(5, progress.get()); } - @Test - public void test_QueuedRequest_IsSent_WhenPreviousRequestSucceeded() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_QueuedRequest_IsSent_WhenPreviousRequestSucceeded(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); client.setMaxConnectionsPerDestination(1); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(2); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestBegin(request -> { try @@ -446,31 +464,32 @@ public class HttpClientTest extends AbstractHttpClientServerTest @Override public void onSuccess(Response response) { - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); successLatch.countDown(); } }); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestQueued(request -> latch.countDown()) .send(new Response.Listener.Adapter() { @Override public void onSuccess(Response response) { - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); successLatch.countDown(); } }); - Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); + assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } - @Test - public void test_QueuedRequest_IsSent_WhenPreviousRequestClosedConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_QueuedRequest_IsSent_WhenPreviousRequestClosedConnection(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -488,29 +507,30 @@ public class HttpClientTest extends AbstractHttpClientServerTest { final CountDownLatch latch = new CountDownLatch(2); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/one") .onResponseFailure((response, failure) -> latch.countDown()) .send(null); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/two") .onResponseSuccess(response -> { - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); latch.countDown(); }) .send(null); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } - @Test - public void test_ExchangeIsComplete_OnlyWhenBothRequestAndResponseAreComplete() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ExchangeIsComplete_OnlyWhenBothRequestAndResponseAreComplete(Scenario scenario) throws Exception { - start(new AbstractHandler.ErrorDispatchHandler() + start(scenario,new AbstractHandler.ErrorDispatchHandler() { @Override protected void doNonErrorHandle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException @@ -547,34 +567,34 @@ public class HttpClientTest extends AbstractHttpClientServerTest final AtomicLong requestTime = new AtomicLong(); final AtomicLong responseTime = new AtomicLong(); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .file(file) - .onRequestSuccess(request -> + .scheme(scenario.getScheme()) + .file(file) + .onRequestSuccess(request -> + { + requestTime.set(System.nanoTime()); + latch.countDown(); + }) + .send(new Response.Listener.Adapter() + { + @Override + public void onSuccess(Response response) { - requestTime.set(System.nanoTime()); + responseTime.set(System.nanoTime()); latch.countDown(); - }) - .send(new Response.Listener.Adapter() + } + + @Override + public void onComplete(Result result) { - @Override - public void onSuccess(Response response) - { - responseTime.set(System.nanoTime()); - latch.countDown(); - } + exchangeTime.set(System.nanoTime()); + latch.countDown(); + } + }); - @Override - public void onComplete(Result result) - { - exchangeTime.set(System.nanoTime()); - latch.countDown(); - } - }); + assertTrue(latch.await(10, TimeUnit.SECONDS)); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); - - Assert.assertTrue(requestTime.get() <= exchangeTime.get()); - Assert.assertTrue(responseTime.get() <= exchangeTime.get()); + assertTrue(requestTime.get() <= exchangeTime.get()); + assertTrue(responseTime.get() <= exchangeTime.get()); // Give some time to the server to consume the request content // This is just to avoid exception traces in the test output @@ -583,10 +603,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest Files.delete(file); } - @Test - public void test_ExchangeIsComplete_WhenRequestFailsMidway_WithResponse() throws Exception + + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ExchangeIsComplete_WhenRequestFailsMidway_WithResponse(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -598,7 +620,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) // The second ByteBuffer set to null will throw an exception .content(new ContentProvider() { @@ -642,22 +664,23 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void test_ExchangeIsComplete_WhenRequestFails_WithNoResponse() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ExchangeIsComplete_WhenRequestFails_WithNoResponse(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final CountDownLatch latch = new CountDownLatch(1); final String host = "localhost"; final int port = connector.getLocalPort(); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestBegin(request -> { - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); connectionPool.getActiveConnections().iterator().next().close(); }) @@ -670,15 +693,16 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Slow - @Test - public void test_Request_IdleTimeout() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review + public void test_Request_IdleTimeout(Scenario scenario) throws Exception { final long idleTimeout = 1000; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -697,48 +721,45 @@ public class HttpClientTest extends AbstractHttpClientServerTest final String host = "localhost"; final int port = connector.getLocalPort(); - try - { + assertThrows(TimeoutException.class, ()->{ client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.fail(); - } - catch (TimeoutException expected) - { - } + }); // Make another request without specifying the idle timeout, should not fail ContentResponse response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } - @Test - public void testSendToIPv6Address() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSendToIPv6Address(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); ContentResponse response = client.newRequest("[::1]", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } - @Test - public void testHeaderProcessing() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHeaderProcessing(Scenario scenario) throws Exception { final String headerName = "X-Header-Test"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -749,27 +770,28 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseHeader((response1, field) -> !field.getName().equals(headerName)) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertFalse(response.getHeaders().containsKey(headerName)); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertFalse(response.getHeaders().containsKey(headerName)); } - @Test - public void testAllHeadersDiscarded() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAllHeadersDiscarded(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); int count = 10; final CountDownLatch latch = new CountDownLatch(count); for (int i = 0; i < count; ++i) { client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(new Response.Listener.Adapter() { @Override @@ -787,14 +809,15 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); } - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); } - @Test - public void test_HEAD_With_ResponseContentLength() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_HEAD_With_ResponseContentLength(Scenario scenario) throws Exception { final int length = 1024; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -807,60 +830,57 @@ public class HttpClientTest extends AbstractHttpClientServerTest // HEAD requests receive a Content-Length header, but do not // receive the content so they must handle this case properly ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.HEAD) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(0, response.getContent().length); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(0, response.getContent().length); // Perform a normal GET request to be sure the content is now read response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(length, response.getContent().length); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(length, response.getContent().length); } - @Test - public void testConnectThrowsUnknownHostException() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testConnectThrowsUnknownHostException(Scenario scenario) throws Exception { String host = "idontexist"; int port = 80; - try - { + assertThrows(IOException.class, ()->{ Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), 1000); - Assume.assumeTrue("Host must not be resolvable", false); - } - catch (IOException ignored) - { - } + }, "Host must not be resolvable"); - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final CountDownLatch latch = new CountDownLatch(1); client.newRequest(host, port) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); Throwable failure = result.getFailure(); - Assert.assertTrue(failure instanceof UnknownHostException); + assertTrue(failure instanceof UnknownHostException); latch.countDown(); }); - Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS)); } - @Test - public void testConnectHostWithMultipleAddresses() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testConnectHostWithMultipleAddresses(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); client.setSocketAddressResolver(new SocketAddressResolver.Async(client.getExecutor(), client.getScheduler(), client.getConnectTimeout()) { @@ -889,49 +909,51 @@ public class HttpClientTest extends AbstractHttpClientServerTest // If no exceptions the test passes. client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, "close") .send(); } - @Test - public void testCustomUserAgent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testCustomUserAgent(Scenario scenario) throws Exception { final String userAgent = "Test/1.0"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); ArrayList userAgents = Collections.list(request.getHeaders("User-Agent")); - Assert.assertEquals(1, userAgents.size()); - Assert.assertEquals(userAgent, userAgents.get(0)); + assertEquals(1, userAgents.size()); + assertEquals(userAgent, userAgents.get(0)); } }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .agent(userAgent) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.USER_AGENT, null) .header(HttpHeader.USER_AGENT, userAgent) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testUserAgentCanBeRemoved() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testUserAgentCanBeRemoved(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -939,44 +961,45 @@ public class HttpClientTest extends AbstractHttpClientServerTest baseRequest.setHandled(true); ArrayList userAgents = Collections.list(request.getHeaders("User-Agent")); if ("/ua".equals(target)) - Assert.assertEquals(1, userAgents.size()); + assertEquals(1, userAgents.size()); else - Assert.assertEquals(0, userAgents.size()); + assertEquals(0, userAgents.size()); } }); // User agent not specified, use default. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/ua") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // User agent explicitly removed. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .agent(null) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // User agent explicitly removed. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.USER_AGENT, null) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testRequestListenerForMultipleEventsIsInvokedOncePerEvent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRequestListenerForMultipleEventsIsInvokedOncePerEvent(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final AtomicInteger counter = new AtomicInteger(); Request.Listener listener = new Request.Listener() @@ -1026,7 +1049,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }; ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestQueued(listener) .onRequestBegin(listener) .onRequestHeaders(listener) @@ -1037,17 +1060,18 @@ public class HttpClientTest extends AbstractHttpClientServerTest .listener(listener) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); int expectedEventsTriggeredByOnRequestXXXListeners = 5; int expectedEventsTriggeredByListener = 5; int expected = expectedEventsTriggeredByOnRequestXXXListeners + expectedEventsTriggeredByListener; - Assert.assertEquals(expected, counter.get()); + assertEquals(expected, counter.get()); } - @Test - public void testResponseListenerForMultipleEventsIsInvokedOncePerEvent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testResponseListenerForMultipleEventsIsInvokedOncePerEvent(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final AtomicInteger counter = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(1); @@ -1102,13 +1126,13 @@ public class HttpClientTest extends AbstractHttpClientServerTest @Override public void onComplete(Result result) { - Assert.assertEquals(200, result.getResponse().getStatus()); + assertEquals(200, result.getResponse().getStatus()); counter.incrementAndGet(); latch.countDown(); } }; client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseBegin(listener) .onResponseHeader(listener) .onResponseHeaders(listener) @@ -1118,19 +1142,20 @@ public class HttpClientTest extends AbstractHttpClientServerTest .onResponseFailure(listener) .send(listener); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); int expectedEventsTriggeredByOnResponseXXXListeners = 3; int expectedEventsTriggeredByCompletionListener = 4; int expected = expectedEventsTriggeredByOnResponseXXXListeners + expectedEventsTriggeredByCompletionListener; - Assert.assertEquals(expected, counter.get()); + assertEquals(expected, counter.get()); } - @Test - public void setOnCompleteCallbackWithBlockingSend() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void setOnCompleteCallbackWithBlockingSend(Scenario scenario) throws Exception { final byte[] content = new byte[512]; new Random().nextBytes(content); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1159,42 +1184,44 @@ public class HttpClientTest extends AbstractHttpClientServerTest client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(listener); Response response = ex.exchange(null); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(content, listener.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(content, listener.getContent()); } - @Test - public void testCustomHostHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testCustomHostHeader(Scenario scenario) throws Exception { final String host = "localhost"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(host, request.getServerName()); + assertEquals(host, request.getServerName()); } }); ContentResponse response = client.newRequest("http://127.0.0.1:" + connector.getLocalPort() + "/path") - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.HOST, host) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testHTTP10WithKeepAliveAndContentLength() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHTTP10WithKeepAliveAndContentLength(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1208,20 +1235,21 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .version(HttpVersion.HTTP_1_0) .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(response.getHeaders().contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())); + assertEquals(200, response.getStatus()); + assertTrue(response.getHeaders().contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())); } - @Test - public void testHTTP10WithKeepAliveAndNoContentLength() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHTTP10WithKeepAliveAndNoContentLength(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1233,7 +1261,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); FuturePromise promise = new FuturePromise<>(); - Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort()); + Destination destination = client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); destination.newConnection(promise); try (Connection connection = promise.get(5, TimeUnit.SECONDS)) { @@ -1248,36 +1276,38 @@ public class HttpClientTest extends AbstractHttpClientServerTest connection.send(request, listener); ContentResponse response = listener.get(2 * timeout, TimeUnit.MILLISECONDS); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // The parser notifies end-of-content and therefore the CompleteListener // before closing the connection, so we need to wait before checking // that the connection is closed to avoid races. Thread.sleep(1000); - Assert.assertTrue(connection.isClosed()); + assertTrue(connection.isClosed()); } } - @Test - public void testHTTP10WithKeepAliveAndNoContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHTTP10WithKeepAliveAndNoContent(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .version(HttpVersion.HTTP_1_0) .header(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(response.getHeaders().contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())); + assertEquals(200, response.getStatus()); + assertTrue(response.getHeaders().contains(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.asString())); } - @Test - public void testLongPollIsAbortedWhenClientIsStopped() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testLongPollIsAbortedWhenClientIsStopped(Scenario scenario) throws Exception { final CountDownLatch latch = new CountDownLatch(1); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1290,73 +1320,73 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(result -> { if (result.isFailed()) completeLatch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // Stop the client, the complete listener must be invoked. client.stop(); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); } - @Test - public void testSmallContentDelimitedByEOFWithSlowRequestHTTP10() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSmallContentDelimitedByEOFWithSlowRequestHTTP10(Scenario scenario) throws Exception { - try - { - testContentDelimitedByEOFWithSlowRequest(HttpVersion.HTTP_1_0, 1024); - } - catch(ExecutionException e) - { - Assert.assertThat(e.getCause(), Matchers.instanceOf(BadMessageException.class)); - Assert.assertThat(e.getCause().getMessage(), Matchers.containsString("Unknown content")); - } + Assumptions.assumeTrue(HttpScheme.HTTP.is(scenario.getScheme())); + + ExecutionException e = assertThrows(ExecutionException.class, ()->{ + testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_0, 1024); + }); + + assertThat(e.getCause(), instanceOf(BadMessageException.class)); + assertThat(e.getCause().getMessage(), containsString("Unknown content")); } - @Test - public void testBigContentDelimitedByEOFWithSlowRequestHTTP10() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) + public void testBigContentDelimitedByEOFWithSlowRequestHTTP10(Scenario scenario) throws Exception { - try - { - testContentDelimitedByEOFWithSlowRequest(HttpVersion.HTTP_1_0, 128 * 1024); - } - catch(ExecutionException e) - { - Assert.assertThat(e.getCause(), Matchers.instanceOf(BadMessageException.class)); - Assert.assertThat(e.getCause().getMessage(), Matchers.containsString("Unknown content")); - } + ExecutionException e = assertThrows(ExecutionException.class, ()->{ + testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_0, 128 * 1024); + }); + + assertThat(e.getCause(), instanceOf(BadMessageException.class)); + assertThat(e.getCause().getMessage(), containsString("Unknown content")); } - @Test - public void testSmallContentDelimitedByEOFWithSlowRequestHTTP11() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) + public void testSmallContentDelimitedByEOFWithSlowRequestHTTP11(Scenario scenario) throws Exception { - testContentDelimitedByEOFWithSlowRequest(HttpVersion.HTTP_1_1, 1024); + testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_1, 1024); } - @Test - public void testBigContentDelimitedByEOFWithSlowRequestHTTP11() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) + public void testBigContentDelimitedByEOFWithSlowRequestHTTP11(Scenario scenario) throws Exception { - testContentDelimitedByEOFWithSlowRequest(HttpVersion.HTTP_1_1, 128 * 1024); + testContentDelimitedByEOFWithSlowRequest(scenario, HttpVersion.HTTP_1_1, 128 * 1024); } - private void testContentDelimitedByEOFWithSlowRequest(final HttpVersion version, int length) throws Exception + private void testContentDelimitedByEOFWithSlowRequest(final Scenario scenario, final HttpVersion version, int length) throws Exception { // This test is crafted in a way that the response completes before the request is fully written. // With SSL, the response coming down will close the SSLEngine so it would not be possible to // write the last chunk of the request content, and the request will be failed, failing also the // test, which is not what we want. // This is a limit of Java's SSL implementation that does not allow half closes. - Assume.assumeTrue(sslContextFactory == null); + Assumptions.assumeTrue(HttpScheme.HTTP.is(scenario.getScheme())); final byte[] data = new byte[length]; new Random().nextBytes(data); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1371,7 +1401,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.wrap(new byte[]{0})); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .version(version) .content(content); FutureResponseListener listener = new FutureResponseListener(request); @@ -1382,16 +1412,17 @@ public class HttpClientTest extends AbstractHttpClientServerTest ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } - @Test - public void testRequestRetries() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRequestRetries(Scenario scenario) throws Exception { final int maxRetries = 3; final AtomicInteger requests = new AtomicInteger(); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1404,7 +1435,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest }); final CountDownLatch latch = new CountDownLatch(1); - new RetryListener(client, scheme, "localhost", connector.getLocalPort(), maxRetries) + new RetryListener(client, scenario.getScheme(), "localhost", connector.getLocalPort(), maxRetries) { @Override protected void completed(Result result) @@ -1413,13 +1444,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }.perform(); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testCompleteNotInvokedUntilContentConsumed() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testCompleteNotInvokedUntilContentConsumed(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1434,7 +1466,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest final CountDownLatch contentLatch = new CountDownLatch(1); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(new Response.Listener.Adapter() { @Override @@ -1453,22 +1485,23 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS)); + assertTrue(contentLatch.await(5, TimeUnit.SECONDS)); // Make sure the complete event is not emitted. - Assert.assertFalse(completeLatch.await(1, TimeUnit.SECONDS)); + assertFalse(completeLatch.await(1, TimeUnit.SECONDS)); // Consume the content. callbackRef.get().succeeded(); // Now the complete event is emitted. - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); } - @Test - public void testRequestSentOnlyAfterConnectionOpen() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRequestSentOnlyAfterConnectionOpen(Scenario scenario) throws Exception { - startServer(new AbstractHandler() + startServer(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1493,15 +1526,15 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }; } - }, sslContextFactory); + }, scenario.newSslContextFactory()); client.start(); final CountDownLatch latch = new CountDownLatch(2); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestBegin(request -> { - Assert.assertTrue(open.get()); + assertTrue(open.get()); latch.countDown(); }) .send(result -> @@ -1510,15 +1543,16 @@ public class HttpClientTest extends AbstractHttpClientServerTest latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testCONNECTWithHTTP10() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testCONNECTWithHTTP10(Scenario scenario) throws Exception { try (ServerSocket server = new ServerSocket(0)) { - startClient(); + startClient(scenario); String host = "localhost"; int port = server.getLocalPort(); @@ -1546,7 +1580,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest output.flush(); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // Because the tunnel was successful, this connection will be // upgraded to an SslConnection, so it will not be fill interested. @@ -1572,10 +1606,11 @@ public class HttpClientTest extends AbstractHttpClientServerTest } } - @Test - public void test_IPv6_Host() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_IPv6_Host(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -1586,21 +1621,22 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - URI uri = URI.create(scheme + "://[::1]:" + connector.getLocalPort() + "/path"); + URI uri = URI.create(scenario.getScheme() + "://[::1]:" + connector.getLocalPort() + "/path"); ContentResponse response = client.newRequest(uri) .method(HttpMethod.PUT) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1),Matchers.startsWith("[::1]:")); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertThat(new String(response.getContent(), StandardCharsets.ISO_8859_1),Matchers.startsWith("[::1]:")); } - @Test - public void testCopyRequest() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testCopyRequest(Scenario scenario) throws Exception { - startClient(); + startClient(scenario); assertCopyRequest(client.newRequest("http://example.com/some/url") .method(HttpMethod.HEAD) @@ -1645,43 +1681,45 @@ public class HttpClientTest extends AbstractHttpClientServerTest .header("X-Custom-Header-2", "value")); } - @Test - public void testHostWithHTTP10() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHostWithHTTP10(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertThat(request.getHeader("Host"), Matchers.notNullValue()); + assertThat(request.getHeader("Host"), Matchers.notNullValue()); } }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .version(HttpVersion.HTTP_1_0) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void test204WithContent() throws Exception + @ParameterizedTest + @ArgumentsSource(NonSslScenarioProvider.class) + public void test204WithContent(Scenario scenario) throws Exception { // This test only works with clear-text HTTP. - Assume.assumeTrue(sslContextFactory == null); + Assumptions.assumeTrue(HttpScheme.HTTP.is(scenario.getScheme())); try (ServerSocket server = new ServerSocket(0)) { - startClient(); + startClient(scenario); client.setMaxConnectionsPerDestination(1); int idleTimeout = 2000; client.setIdleTimeout(idleTimeout); Request request = client.newRequest("localhost", server.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS); FutureResponseListener listener = new FutureResponseListener(request); request.send(listener); @@ -1703,15 +1741,15 @@ public class HttpClientTest extends AbstractHttpClientServerTest output.flush(); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(204, response.getStatus()); + assertEquals(204, response.getStatus()); byte[] responseContent = response.getContent(); - Assert.assertNotNull(responseContent); - Assert.assertEquals(0, responseContent.length); + assertNotNull(responseContent); + assertEquals(0, responseContent.length); // Send another request to verify we have handled the wrong response correctly. request = client.newRequest("localhost", server.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS); listener = new FutureResponseListener(request); request.send(listener); @@ -1726,7 +1764,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest output.flush(); response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } } } @@ -1734,14 +1772,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest private void assertCopyRequest(Request original) { Request copy = client.copyRequest((HttpRequest) original, original.getURI()); - Assert.assertEquals(original.getURI(), copy.getURI()); - Assert.assertEquals(original.getMethod(), copy.getMethod()); - Assert.assertEquals(original.getVersion(), copy.getVersion()); - Assert.assertEquals(original.getContent(), copy.getContent()); - Assert.assertEquals(original.getIdleTimeout(), copy.getIdleTimeout()); - Assert.assertEquals(original.getTimeout(), copy.getTimeout()); - Assert.assertEquals(original.isFollowRedirects(), copy.isFollowRedirects()); - Assert.assertEquals(original.getHeaders(), copy.getHeaders()); + assertEquals(original.getURI(), copy.getURI()); + assertEquals(original.getMethod(), copy.getMethod()); + assertEquals(original.getVersion(), copy.getVersion()); + assertEquals(original.getContent(), copy.getContent()); + assertEquals(original.getIdleTimeout(), copy.getIdleTimeout()); + assertEquals(original.getTimeout(), copy.getTimeout()); + assertEquals(original.isFollowRedirects(), copy.isFollowRedirects()); + assertEquals(original.getHeaders(), copy.getHeaders()); } private void consume(InputStream input, boolean eof) throws IOException diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java index ef7a470ed38..bd4a567381c 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientURITest.java @@ -18,7 +18,12 @@ package org.eclipse.jetty.client; -import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.IOException; @@ -47,54 +52,47 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.Fields; import org.eclipse.jetty.util.URIUtil; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpClientURITest extends AbstractHttpClientServerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - public HttpClientURITest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testIPv6Host(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testIPv6Host() throws Exception - { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "::1"; Request request = client.newRequest(host, connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS); - Assert.assertEquals(host, request.getHost()); + assertEquals(host, request.getHost()); StringBuilder uri = new StringBuilder(); - URIUtil.appendSchemeHostPort(uri, scheme, host, connector.getLocalPort()); - Assert.assertEquals(uri.toString(), request.getURI().toString()); + URIUtil.appendSchemeHostPort(uri, scenario.getScheme(), host, connector.getLocalPort()); + assertEquals(uri.toString(), request.getURI().toString()); - Assert.assertEquals(HttpStatus.OK_200, request.send().getStatus()); + assertEquals(HttpStatus.OK_200, request.send().getStatus()); } - @Test - public void testIDNHost() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testIDNHost(Scenario scenario) throws Exception { - startClient(); - expectedException.expect(IllegalArgumentException.class); - client.newRequest(scheme + "://пример.рф"); // example.com-like host in IDN domain + startClient(scenario); + assertThrows(IllegalArgumentException.class, ()-> { + client.newRequest(scenario.getScheme() + "://пример.рф"); // example.com-like host in IDN domain + }); } - @Test - public void testIDNRedirect() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testIDNRedirect(Scenario scenario) throws Exception { // Internationalized Domain Name. // String exampleHost = scheme + "://пример.рф"; - String exampleHost = scheme + "://\uD0BF\uD180\uD0B8\uD0BC\uD0B5\uD180.\uD180\uD184"; + String exampleHost = scenario.getScheme() + "://\uD0BF\uD180\uD0B8\uD0BC\uD0B5\uD180.\uD180\uD184"; String incorrectlyDecoded = new String(exampleHost.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); // Simple server that only parses clear-text HTTP/1.1. @@ -103,7 +101,7 @@ public class HttpClientURITest extends AbstractHttpClientServerTest try { - startClient(); + startClient(scenario); ContentResponse response = client.newRequest("localhost", server.getLocalPort()) .timeout(5, TimeUnit.SECONDS) @@ -111,14 +109,15 @@ public class HttpClientURITest extends AbstractHttpClientServerTest .send(); HttpField location = response.getHeaders().getField(HttpHeader.LOCATION); - Assert.assertEquals(incorrectlyDecoded, location.getValue()); + assertEquals(incorrectlyDecoded, location.getValue()); - expectedException.expect(ExecutionException.class); - expectedException.expectCause(instanceOf(IllegalArgumentException.class)); - client.newRequest("localhost", server.getLocalPort()) - .timeout(5, TimeUnit.SECONDS) - .followRedirects(true) - .send(); + ExecutionException x = assertThrows(ExecutionException.class, ()-> { + client.newRequest("localhost", server.getLocalPort()) + .timeout(5, TimeUnit.SECONDS) + .followRedirects(true) + .send(); + }); + assertThat(x.getCause(), instanceOf(IllegalArgumentException.class)); } finally { @@ -126,111 +125,115 @@ public class HttpClientURITest extends AbstractHttpClientServerTest } } - @Test - public void testPath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testPath(Scenario scenario) throws Exception { final String path = "/path"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); + assertEquals(path, request.getRequestURI()); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(path); - Assert.assertEquals(path, request.getPath()); - Assert.assertNull(request.getQuery()); + assertEquals(path, request.getPath()); + assertNull(request.getQuery()); Fields params = request.getParams(); - Assert.assertEquals(0, params.getSize()); - Assert.assertTrue(request.getURI().toString().endsWith(path)); + assertEquals(0, params.getSize()); + assertTrue(request.getURI().toString().endsWith(path)); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testPathWithQuery() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testPathWithQuery(Scenario scenario) throws Exception { String name = "a"; String value = "1"; final String query = name + "=" + value; final String path = "/path"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); String pathQuery = path + "?" + query; Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(pathQuery); - Assert.assertEquals(path, request.getPath()); - Assert.assertEquals(query, request.getQuery()); - Assert.assertTrue(request.getURI().toString().endsWith(pathQuery)); + assertEquals(path, request.getPath()); + assertEquals(query, request.getQuery()); + assertTrue(request.getURI().toString().endsWith(pathQuery)); Fields params = request.getParams(); - Assert.assertEquals(1, params.getSize()); - Assert.assertEquals(value, params.get(name).getValue()); + assertEquals(1, params.getSize()); + assertEquals(value, params.get(name).getValue()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testPathWithParam() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testPathWithParam(Scenario scenario) throws Exception { String name = "a"; String value = "1"; final String query = name + "=" + value; final String path = "/path"; String pathQuery = path + "?" + query; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(path) .param(name, value); - Assert.assertEquals(path, request.getPath()); - Assert.assertEquals(query, request.getQuery()); - Assert.assertTrue(request.getURI().toString().endsWith(pathQuery)); + assertEquals(path, request.getPath()); + assertEquals(query, request.getQuery()); + assertTrue(request.getURI().toString().endsWith(pathQuery)); Fields params = request.getParams(); - Assert.assertEquals(1, params.getSize()); - Assert.assertEquals(value, params.get(name).getValue()); + assertEquals(1, params.getSize()); + assertEquals(value, params.get(name).getValue()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testPathWithQueryAndParam() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testPathWithQueryAndParam(Scenario scenario) throws Exception { String name1 = "a"; String value1 = "1"; @@ -239,38 +242,39 @@ public class HttpClientURITest extends AbstractHttpClientServerTest final String query = name1 + "=" + value1 + "&" + name2 + "=" + value2; final String path = "/path"; String pathQuery = path + "?" + query; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(path + "?" + name1 + "=" + value1) .param(name2, value2); - Assert.assertEquals(path, request.getPath()); - Assert.assertEquals(query, request.getQuery()); - Assert.assertTrue(request.getURI().toString().endsWith(pathQuery)); + assertEquals(path, request.getPath()); + assertEquals(query, request.getQuery()); + assertTrue(request.getURI().toString().endsWith(pathQuery)); Fields params = request.getParams(); - Assert.assertEquals(2, params.getSize()); - Assert.assertEquals(value1, params.get(name1).getValue()); - Assert.assertEquals(value2, params.get(name2).getValue()); + assertEquals(2, params.getSize()); + assertEquals(value1, params.get(name1).getValue()); + assertEquals(value2, params.get(name2).getValue()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testPathWithQueryAndParamValueEncoded() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testPathWithQueryAndParamValueEncoded(Scenario scenario) throws Exception { final String name1 = "a"; final String value1 = "\u20AC"; @@ -281,189 +285,195 @@ public class HttpClientURITest extends AbstractHttpClientServerTest final String query = name1 + "=" + encodedValue1 + "&" + name2 + "=" + encodedValue2; final String path = "/path"; String pathQuery = path + "?" + query; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); - Assert.assertEquals(value1, request.getParameter(name1)); - Assert.assertEquals(value2, request.getParameter(name2)); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); + assertEquals(value1, request.getParameter(name1)); + assertEquals(value2, request.getParameter(name2)); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(path + "?" + name1 + "=" + encodedValue1) .param(name2, value2); - Assert.assertEquals(path, request.getPath()); - Assert.assertEquals(query, request.getQuery()); - Assert.assertTrue(request.getURI().toString().endsWith(pathQuery)); + assertEquals(path, request.getPath()); + assertEquals(query, request.getQuery()); + assertTrue(request.getURI().toString().endsWith(pathQuery)); Fields params = request.getParams(); - Assert.assertEquals(2, params.getSize()); - Assert.assertEquals(value1, params.get(name1).getValue()); - Assert.assertEquals(value2, params.get(name2).getValue()); + assertEquals(2, params.getSize()); + assertEquals(value1, params.get(name1).getValue()); + assertEquals(value2, params.get(name2).getValue()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testNoParameterNameNoParameterValue() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testNoParameterNameNoParameterValue(Scenario scenario) throws Exception { final String path = "/path"; final String query = "="; // Bogus query String pathQuery = path + "?" + query; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(pathQuery); - Assert.assertEquals(path, request.getPath()); - Assert.assertEquals(query, request.getQuery()); - Assert.assertTrue(request.getURI().toString().endsWith(pathQuery)); + assertEquals(path, request.getPath()); + assertEquals(query, request.getQuery()); + assertTrue(request.getURI().toString().endsWith(pathQuery)); Fields params = request.getParams(); - Assert.assertEquals(0, params.getSize()); + assertEquals(0, params.getSize()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testNoParameterNameWithParameterValue() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testNoParameterNameWithParameterValue(Scenario scenario) throws Exception { final String path = "/path"; final String query = "=1"; // Bogus query String pathQuery = path + "?" + query; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .path(pathQuery); - Assert.assertEquals(path, request.getPath()); - Assert.assertEquals(query, request.getQuery()); - Assert.assertTrue(request.getURI().toString().endsWith(pathQuery)); + assertEquals(path, request.getPath()); + assertEquals(query, request.getQuery()); + assertTrue(request.getURI().toString().endsWith(pathQuery)); Fields params = request.getParams(); - Assert.assertEquals(0, params.getSize()); + assertEquals(0, params.getSize()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testCaseSensitiveParameterName() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testCaseSensitiveParameterName(Scenario scenario) throws Exception { final String name1 = "a"; final String name2 = "A"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(name1, request.getParameter(name1)); - Assert.assertEquals(name2, request.getParameter(name2)); + assertEquals(name1, request.getParameter(name1)); + assertEquals(name2, request.getParameter(name2)); } }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/path?" + name1 + "=" + name1) .param(name2, name2) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testRawQueryIsPreservedInURI() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRawQueryIsPreservedInURI(Scenario scenario) throws Exception { final String name = "a"; final String rawValue = "Hello%20World"; final String rawQuery = name + "=" + rawValue; final String value = "Hello World"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(rawQuery, request.getQueryString()); - Assert.assertEquals(value, request.getParameter(name)); + assertEquals(rawQuery, request.getQueryString()); + assertEquals(value, request.getParameter(name)); } }); - String uri = scheme + "://localhost:" + connector.getLocalPort() + "/path?" + rawQuery; + String uri = scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/path?" + rawQuery; Request request = client.newRequest(uri) .timeout(5, TimeUnit.SECONDS); - Assert.assertEquals(rawQuery, request.getQuery()); + assertEquals(rawQuery, request.getQuery()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testRawQueryIsPreservedInPath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRawQueryIsPreservedInPath(Scenario scenario) throws Exception { final String name = "a"; final String rawValue = "Hello%20World"; final String rawQuery = name + "=" + rawValue; final String value = "Hello World"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(rawQuery, request.getQueryString()); - Assert.assertEquals(value, request.getParameter(name)); + assertEquals(rawQuery, request.getQueryString()); + assertEquals(value, request.getParameter(name)); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/path?" + rawQuery) .timeout(5, TimeUnit.SECONDS); - Assert.assertEquals(rawQuery, request.getQuery()); + assertEquals(rawQuery, request.getQuery()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testRawQueryIsPreservedWithParam() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRawQueryIsPreservedWithParam(Scenario scenario) throws Exception { final String name1 = "a"; final String name2 = "b"; @@ -473,34 +483,35 @@ public class HttpClientURITest extends AbstractHttpClientServerTest final String value2 = "alfa omega"; final String encodedQuery2 = name2 + "=" + URLEncoder.encode(value2, "UTF-8"); final String query = rawQuery1 + "&" + encodedQuery2; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(query, request.getQueryString()); - Assert.assertEquals(value1, request.getParameter(name1)); - Assert.assertEquals(value2, request.getParameter(name2)); + assertEquals(query, request.getQueryString()); + assertEquals(value1, request.getParameter(name1)); + assertEquals(value2, request.getParameter(name2)); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/path?" + rawQuery1) .param(name2, value2) .timeout(5, TimeUnit.SECONDS); - Assert.assertEquals(query, request.getQuery()); + assertEquals(query, request.getQuery()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testSchemeIsCaseInsensitive() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSchemeIsCaseInsensitive(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -510,17 +521,18 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme.toUpperCase(Locale.ENGLISH)) + .scheme(scenario.getScheme().toUpperCase(Locale.ENGLISH)) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testHostIsCaseInsensitive() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testHostIsCaseInsensitive(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -530,42 +542,43 @@ public class HttpClientURITest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("LOCALHOST", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } - @Test - public void testAsteriskFormTarget() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAsteriskFormTarget(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals("*", target); - Assert.assertEquals("*", request.getPathInfo()); + assertEquals("*", target); + assertEquals("*", request.getPathInfo()); } }); Request request = client.newRequest("localhost", connector.getLocalPort()) .method(HttpMethod.OPTIONS) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("*") .timeout(5, TimeUnit.SECONDS); - Assert.assertEquals("*", request.getPath()); - Assert.assertNull(request.getQuery()); + assertEquals("*", request.getPath()); + assertNull(request.getQuery()); Fields params = request.getParams(); - Assert.assertEquals(0, params.getSize()); - Assert.assertNull(request.getURI()); + assertEquals(0, params.getSize()); + assertNull(request.getURI()); ContentResponse response = request.send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } private static class IDNRedirectServer implements Runnable diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java index 41ba8e3fe7d..73804840b3e 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientUploadDuringServerShutdown.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InputStream; import java.util.Random; @@ -43,8 +46,8 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HttpClientUploadDuringServerShutdown { @@ -216,7 +219,7 @@ public class HttpClientUploadDuringServerShutdown // Create one connection. client.newRequest("localhost", connector.getLocalPort()).send(); - Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); afterSetup.set(true); Thread.sleep(1000); @@ -228,7 +231,7 @@ public class HttpClientUploadDuringServerShutdown // Wait for close() so that the connection that // is being closed is used to send the request. - Assert.assertTrue(sendLatch.await(5, TimeUnit.SECONDS)); + assertTrue(sendLatch.await(5, TimeUnit.SECONDS)); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) @@ -247,12 +250,12 @@ public class HttpClientUploadDuringServerShutdown }) .send(result -> completeLatch.countDown()); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination("http", "localhost", connector.getLocalPort()); DuplexConnectionPool pool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, pool.getConnectionCount()); - Assert.assertEquals(0, pool.getIdleConnections().size()); - Assert.assertEquals(0, pool.getActiveConnections().size()); + assertEquals(0, pool.getConnectionCount()); + assertEquals(0, pool.getIdleConnections().size()); + assertEquals(0, pool.getActiveConnections().size()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java index b6335b81168..243303f5345 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpConnectionLifecycleTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; @@ -41,52 +45,48 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.StacklessLogging; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest { - public HttpConnectionLifecycleTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - @Override - public void start(Handler handler) throws Exception + public void start(Scenario scenario, Handler handler) throws Exception { - super.start(handler); + super.start(scenario, handler); client.setStrictEventOrdering(false); } - @Test - public void test_SuccessfulRequest_ReturnsConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SuccessfulRequest_ReturnsConnection(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); final CountDownLatch headersLatch = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestSuccess(request -> successLatch.countDown()) .onResponseHeaders(response -> { - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(1, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(1, activeConnections.size()); headersLatch.countDown(); }) .send(new Response.Listener.Adapter() @@ -100,37 +100,38 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest @Override public void onComplete(Result result) { - Assert.assertFalse(result.isFailed()); + assertFalse(result.isFailed()); successLatch.countDown(); } }); - Assert.assertTrue(headersLatch.await(30, TimeUnit.SECONDS)); - Assert.assertTrue(successLatch.await(30, TimeUnit.SECONDS)); + assertTrue(headersLatch.await(30, TimeUnit.SECONDS)); + assertTrue(successLatch.await(30, TimeUnit.SECONDS)); - Assert.assertEquals(1, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(1, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Test - public void test_FailedRequest_RemovesConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_FailedRequest_RemovesConnection(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); final CountDownLatch beginLatch = new CountDownLatch(1); final CountDownLatch failureLatch = new CountDownLatch(2); - client.newRequest(host, port).scheme(scheme).listener(new Request.Listener.Adapter() + client.newRequest(host, port).scheme(scenario.getScheme()).listener(new Request.Listener.Adapter() { @Override public void onBegin(Request request) @@ -149,39 +150,40 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isFailed()); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertTrue(result.isFailed()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); failureLatch.countDown(); } }); - Assert.assertTrue(beginLatch.await(30, TimeUnit.SECONDS)); - Assert.assertTrue(failureLatch.await(30, TimeUnit.SECONDS)); + assertTrue(beginLatch.await(30, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(30, TimeUnit.SECONDS)); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Test - public void test_BadRequest_RemovesConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BadRequest_RemovesConnection(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Queue idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .listener(new Request.Listener.Adapter() { @Override @@ -202,7 +204,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest @Override public void onSuccess(Response response) { - Assert.assertEquals(400, response.getStatus()); + assertEquals(400, response.getStatus()); // 400 response also come with a Connection: close, // so the connection is closed and removed successLatch.countDown(); @@ -211,38 +213,40 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest @Override public void onComplete(Result result) { - Assert.assertFalse(result.isFailed()); + assertFalse(result.isFailed()); successLatch.countDown(); } }); - Assert.assertTrue(successLatch.await(30, TimeUnit.SECONDS)); + assertTrue(successLatch.await(30, TimeUnit.SECONDS)); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Slow - @Test - public void test_BadRequest_WithSlowRequest_RemovesConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + @Tag("Slow") + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review + public void test_BadRequest_WithSlowRequest_RemovesConnection(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); final long delay = 1000; final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .listener(new Request.Listener.Adapter() { @Override @@ -276,7 +280,7 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest @Override public void onSuccess(Response response) { - Assert.assertEquals(400, response.getStatus()); + assertEquals(400, response.getStatus()); // 400 response also come with a Connection: close, // so the connection is closed and removed successLatch.countDown(); @@ -285,55 +289,57 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest @Override public void onComplete(Result result) { - Assert.assertFalse(result.isFailed()); + assertFalse(result.isFailed()); successLatch.countDown(); } }); - Assert.assertTrue(successLatch.await(delay * 30, TimeUnit.MILLISECONDS)); + assertTrue(successLatch.await(delay * 30, TimeUnit.MILLISECONDS)); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Test - public void test_ConnectionFailure_RemovesConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ConnectionFailure_RemovesConnection(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); server.stop(); final CountDownLatch failureLatch = new CountDownLatch(2); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestFailure((request, failure) -> failureLatch.countDown()) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); failureLatch.countDown(); }); - Assert.assertTrue(failureLatch.await(30, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(30, TimeUnit.SECONDS)); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Test - public void test_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_ResponseWithConnectionCloseHeader_RemovesConnection(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -345,42 +351,43 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); final CountDownLatch latch = new CountDownLatch(1); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(new Response.Listener.Adapter() { @Override public void onComplete(Result result) { - Assert.assertFalse(result.isFailed()); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertFalse(result.isFailed()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); latch.countDown(); } }); - Assert.assertTrue(latch.await(30, TimeUnit.SECONDS)); + assertTrue(latch.await(30, TimeUnit.SECONDS)); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Test - public void test_BigRequestContent_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_BigRequestContent_ResponseWithConnectionCloseHeader_RemovesConnection(Scenario scenario) throws Exception { - try (StacklessLogging stackless = new StacklessLogging(HttpConnection.class)) + try (StacklessLogging ignore = new StacklessLogging(HttpConnection.class)) { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -393,14 +400,14 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); Log.getLogger(HttpConnection.class).info("Expecting java.lang.IllegalStateException: HttpParser{s=CLOSED,..."); @@ -408,81 +415,84 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest ByteBuffer buffer = ByteBuffer.allocate(16 * 1024 * 1024); Arrays.fill(buffer.array(),(byte)'x'); client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .content(new ByteBufferContentProvider(buffer)) .send(new Response.Listener.Adapter() { @Override public void onComplete(Result result) { - Assert.assertEquals(1, latch.getCount()); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(1, latch.getCount()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); latch.countDown(); } }); - Assert.assertTrue(latch.await(30, TimeUnit.SECONDS)); + assertTrue(latch.await(30, TimeUnit.SECONDS)); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); server.stop(); } } - @Slow - @Test - public void test_IdleConnection_IsClosed_OnRemoteClose() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + @Tag("Slow") + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review + public void test_IdleConnection_IsClosed_OnRemoteClose(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); ContentResponse response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(30, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); connector.stop(); // Give the connection some time to process the remote close TimeUnit.SECONDS.sleep(1); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } - @Test - public void testConnectionForHTTP10ResponseIsRemoved() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testConnectionForHTTP10ResponseIsRemoved(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, host, port); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), host, port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); final Collection idleConnections = connectionPool.getIdleConnections(); - Assert.assertEquals(0, idleConnections.size()); + assertEquals(0, idleConnections.size()); final Collection activeConnections = connectionPool.getActiveConnections(); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, activeConnections.size()); client.setStrictEventOrdering(false); ContentResponse response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseBegin(response1 -> { // Simulate a HTTP 1.0 response has been received. @@ -490,9 +500,9 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest }) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); - Assert.assertEquals(0, idleConnections.size()); - Assert.assertEquals(0, activeConnections.size()); + assertEquals(0, idleConnections.size()); + assertEquals(0, activeConnections.size()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java index bffe2456a2a..d61b159d9f8 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpCookieTest.java @@ -18,6 +18,13 @@ package org.eclipse.jetty.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.IOException; import java.net.HttpCookie; import java.net.URI; @@ -37,26 +44,20 @@ import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpCookieTest extends AbstractHttpClientServerTest { private static final Cookie[] EMPTY_COOKIES = new Cookie[0]; - public HttpCookieTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - - @Test - public void test_CookieIsStored() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_CookieIsStored(Scenario scenario) throws Exception { final String name = "foo"; final String value = "bar"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -68,52 +69,54 @@ public class HttpCookieTest extends AbstractHttpClientServerTest String host = "localhost"; int port = connector.getLocalPort(); String path = "/path"; - String uri = scheme + "://" + host + ":" + port + path; + String uri = scenario.getScheme() + "://" + host + ":" + port + path; Response response = client.GET(uri); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); List cookies = client.getCookieStore().get(URI.create(uri)); - Assert.assertNotNull(cookies); - Assert.assertEquals(1, cookies.size()); + assertNotNull(cookies); + assertEquals(1, cookies.size()); HttpCookie cookie = cookies.get(0); - Assert.assertEquals(name, cookie.getName()); - Assert.assertEquals(value, cookie.getValue()); + assertEquals(name, cookie.getName()); + assertEquals(value, cookie.getValue()); } - @Test - public void test_CookieIsSent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_CookieIsSent(Scenario scenario) throws Exception { final String name = "foo"; final String value = "bar"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Cookie[] cookies = request.getCookies(); - Assert.assertNotNull(cookies); - Assert.assertEquals(1, cookies.length); + assertNotNull(cookies); + assertEquals(1, cookies.length); Cookie cookie = cookies[0]; - Assert.assertEquals(name, cookie.getName()); - Assert.assertEquals(value, cookie.getValue()); + assertEquals(name, cookie.getName()); + assertEquals(value, cookie.getValue()); } }); String host = "localhost"; int port = connector.getLocalPort(); String path = "/path"; - String uri = scheme + "://" + host + ":" + port; + String uri = scenario.getScheme() + "://" + host + ":" + port; HttpCookie cookie = new HttpCookie(name, value); client.getCookieStore().add(URI.create(uri), cookie); - Response response = client.GET(scheme + "://" + host + ":" + port + path); - Assert.assertEquals(200, response.getStatus()); + Response response = client.GET(scenario.getScheme() + "://" + host + ":" + port + path); + assertEquals(200, response.getStatus()); } - @Test - public void test_CookieWithoutValue() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_CookieWithoutValue(Scenario scenario) throws Exception { - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -123,46 +126,48 @@ public class HttpCookieTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue(client.getCookieStore().getCookies().isEmpty()); + assertEquals(200, response.getStatus()); + assertTrue(client.getCookieStore().getCookies().isEmpty()); } - @Test - public void test_PerRequestCookieIsSent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_PerRequestCookieIsSent(Scenario scenario) throws Exception { final String name = "foo"; final String value = "bar"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Cookie[] cookies = request.getCookies(); - Assert.assertNotNull(cookies); - Assert.assertEquals(1, cookies.length); + assertNotNull(cookies); + assertEquals(1, cookies.length); Cookie cookie = cookies[0]; - Assert.assertEquals(name, cookie.getName()); - Assert.assertEquals(value, cookie.getValue()); + assertEquals(name, cookie.getName()); + assertEquals(value, cookie.getValue()); } }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .cookie(new HttpCookie(name, value)) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void test_SetCookieWithoutPath_RequestURIWithOneSegment() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SetCookieWithoutPath_RequestURIWithOneSegment(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue = "1"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -181,43 +186,44 @@ public class HttpCookieTest extends AbstractHttpClientServerTest case "/": case "/foo": case "/foo/bar": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue, cookie.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_SetCookieWithoutPath_RequestURIWithTwoSegments() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SetCookieWithoutPath_RequestURIWithTwoSegments(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue = "1"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -236,48 +242,49 @@ public class HttpCookieTest extends AbstractHttpClientServerTest case "/": case "/foo": case "/foobar": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo/": case "/foo/bar": case "/foo/bar/baz": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue, cookie.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo/bar") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar", "/foo/bar/baz").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_SetCookieWithLongerPath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SetCookieWithLongerPath(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue = "1"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -297,47 +304,48 @@ public class HttpCookieTest extends AbstractHttpClientServerTest case "/": case "/foo": case "/foo/barbaz": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo/bar": case "/foo/bar/": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue, cookie.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar", "/foo/bar/", "/foo/barbaz").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_SetCookieWithShorterPath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SetCookieWithShorterPath(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue = "1"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -356,49 +364,50 @@ public class HttpCookieTest extends AbstractHttpClientServerTest { case "/": case "/foobar": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo": case "/foo/": case "/foo/bar": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue, cookie.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo/bar") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_TwoSetCookieWithSameNameSamePath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_TwoSetCookieWithSameNameSamePath(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue1 = "1"; String cookieValue2 = "2"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -419,48 +428,49 @@ public class HttpCookieTest extends AbstractHttpClientServerTest switch (target) { case "/": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo": case "/foo/bar": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue2, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue2, cookie.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_TwoSetCookieWithSameNameDifferentPath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_TwoSetCookieWithSameNameDifferentPath(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue1 = "1"; String cookieValue2 = "2"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -481,55 +491,56 @@ public class HttpCookieTest extends AbstractHttpClientServerTest switch (target) { case "/": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo": case "/foo/bar": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie1 = cookies[0]; - Assert.assertEquals(target, cookieName, cookie1.getName()); - Assert.assertEquals(target, cookieValue1, cookie1.getValue()); + assertEquals(cookieName, cookie1.getName(), target); + assertEquals(cookieValue1, cookie1.getValue(), target); break; case "/bar": case "/bar/foo": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie2 = cookies[0]; - Assert.assertEquals(target, cookieName, cookie2.getName()); - Assert.assertEquals(target, cookieValue2, cookie2.getValue()); + assertEquals(cookieName, cookie2.getName(), target); + assertEquals(cookieValue2, cookie2.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar", "/bar", "/bar/foo").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_TwoSetCookieWithSameNamePath1PrefixOfPath2() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_TwoSetCookieWithSameNamePath1PrefixOfPath2(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue1 = "1"; String cookieValue2 = "2"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -550,57 +561,58 @@ public class HttpCookieTest extends AbstractHttpClientServerTest switch (target) { case "/": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue1, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue1, cookie.getValue(), target); break; case "/foo/bar": - Assert.assertEquals(target, 2, cookies.length); + assertEquals(2, cookies.length, target); Cookie cookie1 = cookies[0]; Cookie cookie2 = cookies[1]; - Assert.assertEquals(target, cookieName, cookie1.getName()); - Assert.assertEquals(target, cookieName, cookie2.getName()); + assertEquals(cookieName, cookie1.getName(), target); + assertEquals(cookieName, cookie2.getName(), target); Set values = new HashSet<>(); values.add(cookie1.getValue()); values.add(cookie2.getValue()); - Assert.assertThat(target, values, Matchers.containsInAnyOrder(cookieValue1, cookieValue2)); + assertThat(target, values, containsInAnyOrder(cookieValue1, cookieValue2)); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } - @Test - public void test_CookiePathWithTrailingSlash() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_CookiePathWithTrailingSlash(Scenario scenario) throws Exception { String headerName = "X-Request"; String cookieName = "a"; String cookieValue = "1"; - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -620,37 +632,37 @@ public class HttpCookieTest extends AbstractHttpClientServerTest case "/": case "/foo": case "/foobar": - Assert.assertEquals(target, 0, cookies.length); + assertEquals(0, cookies.length, target); break; case "/foo/": case "/foo/bar": - Assert.assertEquals(target, 1, cookies.length); + assertEquals(1, cookies.length, target); Cookie cookie = cookies[0]; - Assert.assertEquals(target, cookieName, cookie.getName()); - Assert.assertEquals(target, cookieValue, cookie.getValue()); + assertEquals(cookieName, cookie.getName(), target); + assertEquals(cookieValue, cookie.getValue(), target); break; default: - Assert.fail(); + fail("Unrecognized Target: " + target); } } } }); ContentResponse response = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/foo/bar") .header(headerName, "0") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); Arrays.asList("/", "/foo", "/foo/", "/foobar", "/foo/bar").forEach(path -> { ContentResponse r = send(client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path(path) .header(headerName, "1") .timeout(5, TimeUnit.SECONDS)); - Assert.assertEquals(HttpStatus.OK_200, r.getStatus()); + assertEquals(HttpStatus.OK_200, r.getStatus()); }); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java index 2cb17894e85..4a63f1089d5 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpRequestAbortTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; @@ -38,57 +44,50 @@ import org.eclipse.jetty.client.util.ByteBufferContentProvider; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.StacklessLogging; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpRequestAbortTest extends AbstractHttpClientServerTest { - public HttpRequestAbortTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortBeforeQueued(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testAbortBeforeQueued() throws Exception - { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); Exception failure = new Exception("oops"); - try - { + + ExecutionException x = assertThrows(ExecutionException.class, ()->{ Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(5, TimeUnit.SECONDS); request.abort(failure); request.send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertSame(failure, x.getCause()); - // Make sure the pool is in a sane state. - HttpDestination destination = (HttpDestination)client.getDestination(scheme, "localhost", connector.getLocalPort()); - DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(1, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(1, connectionPool.getIdleConnections().size()); - } + }); + + assertSame(failure, x.getCause()); + // Make sure the pool is in a sane state. + HttpDestination destination = (HttpDestination)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); + DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); + assertEquals(1, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(1, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortOnQueued() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnQueued(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean begin = new AtomicBoolean(); - try - { + + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .listener(new Request.Listener.Adapter() { @Override @@ -106,36 +105,34 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - Assert.assertFalse(begin.get()); - } + }); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, x.getCause()); + assertFalse(begin.get()); + + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortOnBegin() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnBegin(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch committed = new CountDownLatch(1); - try - { + + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .listener(new Request.Listener.Adapter() { @Override @@ -153,36 +150,33 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - Assert.assertFalse(committed.await(1, TimeUnit.SECONDS)); - } + }); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, x.getCause()); + assertFalse(committed.await(1, TimeUnit.SECONDS)); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortOnHeaders() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnHeaders(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch committed = new CountDownLatch(1); - try - { + + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .listener(new Request.Listener.Adapter() { @Override @@ -200,27 +194,24 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - Assert.assertFalse(committed.await(1, TimeUnit.SECONDS)); - } + }); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, x.getCause()); + assertFalse(committed.await(1, TimeUnit.SECONDS)); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortOnCommit() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnCommit(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); // Test can behave in 2 ways: // A) the request is failed before the response arrived @@ -229,10 +220,9 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - try - { + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestCommit(request -> { aborted.set(request.abort(cause)); @@ -240,27 +230,24 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - } + }); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, x.getCause()); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortOnCommitWithContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnCommitWithContent(Scenario scenario) throws Exception { final AtomicReference failure = new AtomicReference<>(); - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -282,10 +269,10 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - try - { + + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestCommit(request -> { aborted.set(request.abort(cause)); @@ -301,30 +288,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - } + }); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, x.getCause()); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortOnContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnContent(Scenario scenario) throws Exception { - try (StacklessLogging suppressor = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class)) + try (StacklessLogging ignore = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class)) { CountDownLatch serverLatch = new CountDownLatch(1); - start(new EmptyServerHandler() + start(scenario, new EmptyServerHandler() { @Override protected void service(String target, org.eclipse.jetty.server.Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -344,10 +328,9 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(1); - try - { + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onRequestContent((request, content) -> { aborted.set(request.abort(cause)); @@ -363,30 +346,27 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - } + }); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, x.getCause()); - Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } } - @Test(expected = InterruptedException.class) - public void testInterrupt() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testInterrupt(Scenario scenario) throws Exception { final long delay = 1000; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -406,7 +386,7 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest Request request = client.newRequest("localhost", connector.getLocalPort()) .timeout(3 * delay, TimeUnit.MILLISECONDS) - .scheme(scheme); + .scheme(scenario.getScheme()); final Thread thread = Thread.currentThread(); new Thread(() -> @@ -422,14 +402,15 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest } }).start(); - request.send(); + assertThrows(InterruptedException.class, ()->request.send()); } - @Test - public void testAbortLongPoll() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortLongPoll(Scenario scenario) throws Exception { final long delay = 1000; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -449,7 +430,7 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Request request = client.newRequest("localhost", connector.getLocalPort()) .timeout(3 * delay, TimeUnit.MILLISECONDS) - .scheme(scheme); + .scheme(scenario.getScheme()); final Throwable cause = new Exception(); final AtomicBoolean aborted = new AtomicBoolean(); @@ -474,23 +455,24 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest } catch (ExecutionException x) { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); if (aborted.get()) - Assert.assertSame(cause, x.getCause()); + assertSame(cause, x.getCause()); } - HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scheme, "localhost", connector.getLocalPort()); + HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination(scenario.getScheme(), "localhost", connector.getLocalPort()); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnections().size()); - Assert.assertEquals(0, connectionPool.getIdleConnections().size()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getActiveConnections().size()); + assertEquals(0, connectionPool.getIdleConnections().size()); } - @Test - public void testAbortLongPollAsync() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortLongPollAsync(Scenario scenario) throws Exception { final long delay = 1000; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -511,12 +493,12 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest final Throwable cause = new Exception(); final CountDownLatch latch = new CountDownLatch(1); Request request = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .timeout(3 * delay, TimeUnit.MILLISECONDS); request.send(result -> { - Assert.assertTrue(result.isFailed()); - Assert.assertSame(cause, result.getFailure()); + assertTrue(result.isFailed()); + assertSame(cause, result.getFailure()); latch.countDown(); }); @@ -524,13 +506,14 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest request.abort(cause); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testAbortConversation() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortConversation(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -565,20 +548,15 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest } }); - try - { + ExecutionException e = assertThrows(ExecutionException.class,()->{ client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/redirect") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - if (aborted.get()) - Assert.assertSame(cause, x.getCause()); - } + }); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + if (aborted.get()) + assertSame(cause, e.getCause()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java index c195cc8f3d0..2f13fb4f776 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseAbortTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; @@ -32,42 +35,38 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.util.DeferredContentProvider; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpResponseAbortTest extends AbstractHttpClientServerTest { - public HttpResponseAbortTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnBegin(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testAbortOnBegin() throws Exception - { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseBegin(response -> response.abort(new Exception())) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testAbortOnHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnHeader(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseHeader((response, field) -> { response.abort(new Exception()); @@ -75,33 +74,35 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest }) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testAbortOnHeaders() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnHeaders(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseHeaders(response -> response.abort(new Exception())) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testAbortOnContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnContent(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -124,20 +125,21 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final CountDownLatch latch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseContent((response, content) -> response.abort(new Exception())) .send(result -> { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Test - public void testAbortOnContentBeforeRequestTermination() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnContentBeforeRequestTermination(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -162,7 +164,7 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest final AtomicInteger completes = new AtomicInteger(); final CountDownLatch completeLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .content(contentProvider) .onResponseContent((response, content) -> { @@ -181,14 +183,14 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest .send(result -> { completes.incrementAndGet(); - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); completeLatch.countDown(); }); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); // Wait to be sure that the complete event is only notified once. Thread.sleep(1000); - Assert.assertEquals(1, completes.get()); + assertEquals(1, completes.get()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java index 8e39334f6e3..f03e8a3f8e7 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/HttpResponseConcurrentAbortTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; @@ -34,9 +36,8 @@ import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTest { @@ -46,18 +47,14 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes private final AtomicBoolean failureWasAsync = new AtomicBoolean(); private final AtomicBoolean completeWasSync = new AtomicBoolean(); - public HttpResponseConcurrentAbortTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnBegin(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testAbortOnBegin() throws Exception - { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseBegin(new Response.BeginListener() { @Override @@ -67,19 +64,20 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes } }) .send(new TestResponseListener()); - Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(failureWasAsync.get()); - Assert.assertTrue(completeWasSync.get()); + assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureWasAsync.get()); + assertTrue(completeWasSync.get()); } - @Test - public void testAbortOnHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnHeader(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseHeader(new Response.HeaderListener() { @Override @@ -90,19 +88,20 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes } }) .send(new TestResponseListener()); - Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(failureWasAsync.get()); - Assert.assertTrue(completeWasSync.get()); + assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureWasAsync.get()); + assertTrue(completeWasSync.get()); } - @Test - public void testAbortOnHeaders() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnHeaders(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseHeaders(new Response.HeadersListener() { @Override @@ -112,16 +111,17 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes } }) .send(new TestResponseListener()); - Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(failureWasAsync.get()); - Assert.assertTrue(completeWasSync.get()); + assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureWasAsync.get()); + assertTrue(completeWasSync.get()); } - @Test - public void testAbortOnContent() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testAbortOnContent(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -134,7 +134,7 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes }); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .onResponseContent(new Response.ContentListener() { @Override @@ -144,10 +144,10 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes } }) .send(new TestResponseListener()); - Assert.assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(failureWasAsync.get()); - Assert.assertTrue(completeWasSync.get()); + assertTrue(callbackLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureWasAsync.get()); + assertTrue(completeWasSync.get()); } private void abort(final Response response) @@ -192,7 +192,7 @@ public class HttpResponseConcurrentAbortTest extends AbstractHttpClientServerTes @Override public void onComplete(Result result) { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); completeLatch.countDown(); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/InsufficientThreadsDetectionTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/InsufficientThreadsDetectionTest.java index 0cd49f58e65..4b0ec5fbbe5 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/InsufficientThreadsDetectionTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/InsufficientThreadsDetectionTest.java @@ -18,20 +18,24 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class InsufficientThreadsDetectionTest { - @Test(expected = IllegalStateException.class) - public void testInsufficientThreads() throws Exception + @Test + public void testInsufficientThreads() { QueuedThreadPool clientThreads = new QueuedThreadPool(1); HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP(1), null); httpClient.setExecutor(clientThreads); - httpClient.start(); + assertThrows(IllegalStateException.class, ()->{ + httpClient.start(); + }); } @Test @@ -42,17 +46,11 @@ public class InsufficientThreadsDetectionTest httpClient1.setExecutor(clientThreads); httpClient1.start(); - try - { + assertThrows(IllegalStateException.class, ()->{ // Share the same thread pool with another instance. HttpClient httpClient2 = new HttpClient(new HttpClientTransportOverHTTP(1), null); httpClient2.setExecutor(clientThreads); httpClient2.start(); - Assert.fail(); - } - catch (IllegalStateException expected) - { - // Expected. - } + }); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java index aa359c69b80..c32c9396d20 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/LivelockTest.java @@ -18,12 +18,13 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.channels.Selector; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Stream; import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.http.HttpStatus; @@ -35,39 +36,30 @@ import org.eclipse.jetty.util.SocketAddressResolver; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class LivelockTest { - @Parameterized.Parameters(name = "server={0}, client={1}") - public static List data() + public static Stream modes() { - List data = new ArrayList<>(); - // Server-live-lock, Client-live-lock - data.add(new Object[] { true, true }); - data.add(new Object[] { true, false }); - data.add(new Object[] { false, true }); - data.add(new Object[] { false, false }); - return data; + return Stream.of( + // Server-live-lock, Client-live-lock + Arguments.of(true, true), + Arguments.of(true, false), + Arguments.of(false, true), + Arguments.of(false, false) + ); } - @Parameterized.Parameter(0) - public boolean serverLiveLock; - - @Parameterized.Parameter(1) - public boolean clientLiveLock; - private Server server; private ServerConnector connector; private HttpClient client; - @Before + @BeforeEach public void before() throws Exception { Handler handler = new EmptyServerHandler(); @@ -80,7 +72,7 @@ public class LivelockTest server.start(); } - @After + @AfterEach public void after() throws Exception { if (client != null) @@ -89,8 +81,9 @@ public class LivelockTest server.stop(); } - @Test - public void testLivelock() throws Exception + @ParameterizedTest(name = "{index} ==> serverLiveLock={0}, clientLiveLock={1}") + @MethodSource("modes") + public void testLivelock(boolean serverLiveLock, boolean clientLiveLock) throws Exception { // This test applies a moderate connect/request load (5/s) over 5 seconds, // with a connect timeout of 1000, so any delayed connects will be detected. @@ -147,7 +140,7 @@ public class LivelockTest }); sleep(pause); } - Assert.assertTrue(latch.await(2 * pause * count, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(2 * pause * count, TimeUnit.MILLISECONDS)); // Exit the livelocks. busy.set(false); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ProxyConfigurationTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ProxyConfigurationTest.java index 2a7e926a3ad..fb773855878 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ProxyConfigurationTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ProxyConfigurationTest.java @@ -18,8 +18,11 @@ package org.eclipse.jetty.client; -import org.junit.Assert; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; public class ProxyConfigurationTest { @@ -27,7 +30,7 @@ public class ProxyConfigurationTest public void testProxyMatchesWithoutIncludesWithoutExcludes() throws Exception { HttpProxy proxy = new HttpProxy("host", 0); - Assert.assertTrue(proxy.matches(new Origin("http", "any", 0))); + assertTrue(proxy.matches(new Origin("http", "any", 0))); } @Test @@ -36,9 +39,9 @@ public class ProxyConfigurationTest HttpProxy proxy = new HttpProxy("host", 0); proxy.getExcludedAddresses().add("1.2.3.4:5"); - Assert.assertTrue(proxy.matches(new Origin("http", "any", 0))); - Assert.assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0))); - Assert.assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5))); + assertTrue(proxy.matches(new Origin("http", "any", 0))); + assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0))); + assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5))); } @Test @@ -47,9 +50,9 @@ public class ProxyConfigurationTest HttpProxy proxy = new HttpProxy("host", 0); proxy.getIncludedAddresses().add("1.2.3.4:5"); - Assert.assertFalse(proxy.matches(new Origin("http", "any", 0))); - Assert.assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 0))); - Assert.assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 5))); + assertFalse(proxy.matches(new Origin("http", "any", 0))); + assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 0))); + assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 5))); } @Test @@ -59,9 +62,9 @@ public class ProxyConfigurationTest proxy.getIncludedAddresses().add("1.2.3.4"); proxy.getExcludedAddresses().add("1.2.3.4:5"); - Assert.assertFalse(proxy.matches(new Origin("http", "any", 0))); - Assert.assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0))); - Assert.assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5))); + assertFalse(proxy.matches(new Origin("http", "any", 0))); + assertTrue(proxy.matches(new Origin("http", "1.2.3.4", 0))); + assertFalse(proxy.matches(new Origin("http", "1.2.3.4", 5))); } @Test @@ -71,8 +74,8 @@ public class ProxyConfigurationTest proxy.getIncludedAddresses().add("[1::2:3:4]"); proxy.getExcludedAddresses().add("[1::2:3:4]:5"); - Assert.assertFalse(proxy.matches(new Origin("http", "any", 0))); - Assert.assertTrue(proxy.matches(new Origin("http", "[1::2:3:4]", 0))); - Assert.assertFalse(proxy.matches(new Origin("http", "[1::2:3:4]", 5))); + assertFalse(proxy.matches(new Origin("http", "any", 0))); + assertTrue(proxy.matches(new Origin("http", "[1::2:3:4]", 0))); + assertFalse(proxy.matches(new Origin("http", "[1::2:3:4]", 5))); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java index 5712d0cc6d2..118ecd3af36 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ServerConnectionCloseTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -31,17 +33,13 @@ import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.client.http.HttpDestinationOverHTTP; import org.eclipse.jetty.client.util.FutureResponseListener; import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class ServerConnectionCloseTest { - @Rule - public final TestTracker tracker = new TestTracker(); private HttpClient client; private void startClient() throws Exception @@ -53,7 +51,7 @@ public class ServerConnectionCloseTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -145,7 +143,7 @@ public class ServerConnectionCloseTest socket.shutdownOutput(); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); // Give some time to process the connection. Thread.sleep(1000); @@ -153,9 +151,9 @@ public class ServerConnectionCloseTest // Connection should have been removed from pool. HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination("http", "localhost", port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getIdleConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnectionCount()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getIdleConnectionCount()); + assertEquals(0, connectionPool.getActiveConnectionCount()); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java index 754bd6aa97e..41243ec8cec 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/Socks4ProxyTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; @@ -26,17 +29,17 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class Socks4ProxyTest { private ServerSocketChannel server; private HttpClient client; - @Before + @BeforeEach public void prepare() throws Exception { server = ServerSocketChannel.open(); @@ -46,7 +49,7 @@ public class Socks4ProxyTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { client.stop(); @@ -84,24 +87,24 @@ public class Socks4ProxyTest int socks4MessageLength = 9; ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength); int read = channel.read(buffer); - Assert.assertEquals(socks4MessageLength, read); - Assert.assertEquals(4, buffer.get(0) & 0xFF); - Assert.assertEquals(1, buffer.get(1) & 0xFF); - Assert.assertEquals(serverPort, buffer.getShort(2) & 0xFFFF); - Assert.assertEquals(ip1, buffer.get(4) & 0xFF); - Assert.assertEquals(ip2, buffer.get(5) & 0xFF); - Assert.assertEquals(ip3, buffer.get(6) & 0xFF); - Assert.assertEquals(ip4, buffer.get(7) & 0xFF); - Assert.assertEquals(0, buffer.get(8) & 0xFF); + assertEquals(socks4MessageLength, read); + assertEquals(4, buffer.get(0) & 0xFF); + assertEquals(1, buffer.get(1) & 0xFF); + assertEquals(serverPort, buffer.getShort(2) & 0xFFFF); + assertEquals(ip1, buffer.get(4) & 0xFF); + assertEquals(ip2, buffer.get(5) & 0xFF); + assertEquals(ip3, buffer.get(6) & 0xFF); + assertEquals(ip4, buffer.get(7) & 0xFF); + assertEquals(0, buffer.get(8) & 0xFF); // Socks4 response. channel.write(ByteBuffer.wrap(new byte[]{0, 0x5A, 0, 0, 0, 0, 0, 0})); buffer = ByteBuffer.allocate(method.length() + 1 + path.length()); read = channel.read(buffer); - Assert.assertEquals(buffer.capacity(), read); + assertEquals(buffer.capacity(), read); buffer.flip(); - Assert.assertEquals(method + " " + path, StandardCharsets.UTF_8.decode(buffer).toString()); + assertEquals(method + " " + path, StandardCharsets.UTF_8.decode(buffer).toString()); // Response String response = "" + @@ -111,7 +114,7 @@ public class Socks4ProxyTest "\r\n"; channel.write(ByteBuffer.wrap(response.getBytes("UTF-8"))); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } @@ -143,7 +146,7 @@ public class Socks4ProxyTest int socks4MessageLength = 9; ByteBuffer buffer = ByteBuffer.allocate(socks4MessageLength); int read = channel.read(buffer); - Assert.assertEquals(socks4MessageLength, read); + assertEquals(socks4MessageLength, read); // Socks4 response, with split bytes. byte[] chunk1 = new byte[]{0, 0x5A, 0}; @@ -157,9 +160,9 @@ public class Socks4ProxyTest buffer = ByteBuffer.allocate(method.length()); read = channel.read(buffer); - Assert.assertEquals(buffer.capacity(), read); + assertEquals(buffer.capacity(), read); buffer.flip(); - Assert.assertEquals(method, StandardCharsets.UTF_8.decode(buffer).toString()); + assertEquals(method, StandardCharsets.UTF_8.decode(buffer).toString()); // Response String response = "" + @@ -169,7 +172,7 @@ public class Socks4ProxyTest "\r\n"; channel.write(ByteBuffer.wrap(response.getBytes("UTF-8"))); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java index c6678d1c75f..8575d5563bd 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/TLSServerConnectionCloseTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -34,34 +36,15 @@ import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; import org.eclipse.jetty.client.http.HttpDestinationOverHTTP; import org.eclipse.jetty.client.util.FutureResponseListener; import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; -@RunWith(Parameterized.class) public class TLSServerConnectionCloseTest { - @Parameterized.Parameters(name = "CloseMode: {0}") - public static Object[] parameters() - { - return new Object[]{CloseMode.NONE, CloseMode.CLOSE, CloseMode.ABRUPT}; - } - - @Rule - public final TestTracker tracker = new TestTracker(); private HttpClient client; - private final CloseMode closeMode; - - public TLSServerConnectionCloseTest(CloseMode closeMode) - { - this.closeMode = closeMode; - } private void startClient() throws Exception { @@ -77,32 +60,35 @@ public class TLSServerConnectionCloseTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) client.stop(); } - @Test - public void testServerSendsConnectionCloseWithoutContent() throws Exception + @ParameterizedTest + @EnumSource(CloseMode.class) + public void testServerSendsConnectionCloseWithoutContent(CloseMode closeMode) throws Exception { - testServerSendsConnectionClose(false, ""); + testServerSendsConnectionClose(closeMode, false, ""); } - @Test - public void testServerSendsConnectionCloseWithContent() throws Exception + @ParameterizedTest + @EnumSource(CloseMode.class) + public void testServerSendsConnectionCloseWithContent(CloseMode closeMode) throws Exception { - testServerSendsConnectionClose(false, "data"); + testServerSendsConnectionClose(closeMode, false, "data"); } - @Test - public void testServerSendsConnectionCloseWithChunkedContent() throws Exception + @ParameterizedTest + @EnumSource(CloseMode.class) + public void testServerSendsConnectionCloseWithChunkedContent(CloseMode closeMode) throws Exception { - testServerSendsConnectionClose(true, "data"); + testServerSendsConnectionClose(closeMode, true, "data"); } - private void testServerSendsConnectionClose(boolean chunked, String content) throws Exception + private void testServerSendsConnectionClose(final CloseMode closeMode, boolean chunked, String content) throws Exception { try (ServerSocket server = new ServerSocket(0)) { @@ -176,7 +162,7 @@ public class TLSServerConnectionCloseTest } ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); // Give some time to process the connection. Thread.sleep(1000); @@ -184,9 +170,9 @@ public class TLSServerConnectionCloseTest // Connection should have been removed from pool. HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP)client.getDestination("http", "localhost", port); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(0, connectionPool.getConnectionCount()); - Assert.assertEquals(0, connectionPool.getIdleConnectionCount()); - Assert.assertEquals(0, connectionPool.getActiveConnectionCount()); + assertEquals(0, connectionPool.getConnectionCount()); + assertEquals(0, connectionPool.getIdleConnectionCount()); + assertEquals(0, connectionPool.getActiveConnectionCount()); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java index b5cc4bb98d0..aa9a8381e1c 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ValidatingConnectionPoolTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -35,50 +37,46 @@ import org.eclipse.jetty.http.HttpHeaderValue; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest { - public ValidatingConnectionPoolTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - @Override - protected void startClient() throws Exception + protected void startClient(final Scenario scenario) throws Exception { long timeout = 1000; HttpClientTransportOverHTTP transport = new HttpClientTransportOverHTTP(1); transport.setConnectionPoolFactory(destination -> new ValidatingConnectionPool(destination, destination.getHttpClient().getMaxConnectionsPerDestination(), destination, destination.getHttpClient().getScheduler(), timeout)); - startClient(transport); + startClient(scenario, transport); } - @Test - public void testRequestAfterValidation() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testRequestAfterValidation(Scenario scenario) throws Exception { - start(new EmptyServerHandler()); + start(scenario, new EmptyServerHandler()); client.setMaxConnectionsPerDestination(1); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // The second request should be sent after the validating timeout. response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testServerClosesConnectionAfterRedirectWithoutConnectionCloseHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testServerClosesConnectionAfterRedirectWithoutConnectionCloseHeader(Scenario scenario) throws Exception { - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -88,7 +86,7 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest { response.setStatus(HttpStatus.TEMPORARY_REDIRECT_307); response.setContentLength(0); - response.setHeader(HttpHeader.LOCATION.asString(), scheme + "://localhost:" + connector.getLocalPort() + "/"); + response.setHeader(HttpHeader.LOCATION.asString(), scenario.getScheme() + "://localhost:" + connector.getLocalPort() + "/"); response.flushBuffer(); baseRequest.getHttpChannel().getEndPoint().shutdownOutput(); } @@ -102,16 +100,17 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/redirect") .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithConnectionCloseHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithConnectionCloseHeader(Scenario scenario) throws Exception { - testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(new AbstractHandler() + testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -124,10 +123,11 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest }); } - @Test - public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithoutConnectionCloseHeader() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnectionsWithoutConnectionCloseHeader(Scenario scenario) throws Exception { - testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(new AbstractHandler() + testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(scenario, new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException @@ -141,14 +141,14 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest }); } - private void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(Handler handler) throws Exception + private void testServerClosesConnectionAfterResponseWithQueuedRequestWithMaxConnections(final Scenario scenario, Handler handler) throws Exception { - start(handler); + start(scenario, handler); client.setMaxConnectionsPerDestination(1); final CountDownLatch latch = new CountDownLatch(1); Request request1 = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/one") .onRequestBegin(r -> { @@ -165,7 +165,7 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest request1.send(listener1); Request request2 = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .path("/two"); FutureResponseListener listener2 = new FutureResponseListener(request2); request2.send(listener2); @@ -175,9 +175,9 @@ public class ValidatingConnectionPoolTest extends AbstractHttpClientServerTest latch.countDown(); ContentResponse response1 = listener1.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response1.getStatus()); + assertEquals(200, response1.getStatus()); ContentResponse response2 = listener2.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response2.getStatus()); + assertEquals(200, response2.getStatus()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java b/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java index 4663ca0086b..8d2d53530f0 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/api/Usage.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client.api; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; @@ -41,11 +45,11 @@ import org.eclipse.jetty.client.util.OutputStreamContentProvider; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.util.FuturePromise; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -@Ignore +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled public class Usage { @Test @@ -58,7 +62,7 @@ public class Usage ContentResponse response = client.GET("http://localhost:8080/foo"); // Verify response status code - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // Access headers response.getHeaders().get("Content-Length"); @@ -83,7 +87,7 @@ public class Usage .timeout(20, TimeUnit.SECONDS); ContentResponse response = request.send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -110,10 +114,10 @@ public class Usage } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); Response response = responseRef.get(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } @Test @@ -141,7 +145,7 @@ public class Usage { } }).send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -163,8 +167,8 @@ public class Usage // Wait for the response on the listener Response response = listener.get(5, TimeUnit.SECONDS); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } } @@ -177,7 +181,7 @@ public class Usage // One liner to upload files Response response = client.newRequest("localhost", 8080).file(Paths.get("file_to_upload.txt")).send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -192,7 +196,7 @@ public class Usage // Send a request for the cookie's domain Response response = client.newRequest("host", 8080).send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -209,7 +213,7 @@ public class Usage // One liner to send the request ContentResponse response = client.newRequest(uri).timeout(5, TimeUnit.SECONDS).send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -227,7 +231,7 @@ public class Usage .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -277,7 +281,7 @@ public class Usage .content(new InputStreamContentProvider(input)) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Test @@ -296,7 +300,7 @@ public class Usage @Override public void onComplete(Result result) { - Assert.assertEquals(200, result.getResponse().getStatus()); + assertEquals(200, result.getResponse().getStatus()); } }); diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java index a0b3033c096..74790daf37f 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpDestinationOverHTTPTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; @@ -35,29 +38,20 @@ import org.eclipse.jetty.client.api.Destination; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpHeaderValue; -import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { - public HttpDestinationOverHTTPTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_FirstAcquire_WithEmptyQueue(Scenario scenario) throws Exception { - super(sslContextFactory); - } + start(scenario, new EmptyServerHandler()); - @Before - public void init() throws Exception - { - start(new EmptyServerHandler()); - } - - @Test - public void test_FirstAcquire_WithEmptyQueue() throws Exception - { - try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))) + try(HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); @@ -67,14 +61,17 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest // There are no queued requests, so the newly created connection will be idle connection = pollIdleConnection(connectionPool, 5, TimeUnit.SECONDS); } - Assert.assertNotNull(connection); + assertNotNull(connection); } } - @Test - public void test_SecondAcquire_AfterFirstAcquire_WithEmptyQueue_ReturnsSameConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SecondAcquire_AfterFirstAcquire_WithEmptyQueue_ReturnsSameConnection(Scenario scenario) throws Exception { - try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))) + start(scenario, new EmptyServerHandler()); + + try(HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); @@ -84,21 +81,23 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { // There are no queued requests, so the newly created connection will be idle connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS); - Assert.assertNotNull(connection1); + assertNotNull(connection1); Connection connection2 = connectionPool.acquire(); - Assert.assertSame(connection1, connection2); + assertSame(connection1, connection2); } } } - @Test - public void test_SecondAcquire_ConcurrentWithFirstAcquire_WithEmptyQueue_CreatesTwoConnections() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_SecondAcquire_ConcurrentWithFirstAcquire_WithEmptyQueue_CreatesTwoConnections(Scenario scenario) throws Exception { - CountDownLatch idleLatch = new CountDownLatch(1); - CountDownLatch latch = new CountDownLatch(1); + start(scenario, new EmptyServerHandler()); - try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())) + final CountDownLatch idleLatch = new CountDownLatch(1); + final CountDownLatch latch = new CountDownLatch(1); + HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort())) { @Override protected ConnectionPool newConnectionPool(HttpClient client) @@ -121,37 +120,40 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest } }; } - }) + }; { destination.start(); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); Connection connection1 = connectionPool.acquire(); // Make sure we entered idleCreated(). - Assert.assertTrue(idleLatch.await(5, TimeUnit.SECONDS)); + assertTrue(idleLatch.await(5, TimeUnit.SECONDS)); // There are no available existing connections, so acquire() // returns null because we delayed idleCreated() above - Assert.assertNull(connection1); + assertNull(connection1); // Second attempt also returns null because we delayed idleCreated() above. Connection connection2 = connectionPool.acquire(); - Assert.assertNull(connection2); + assertNull(connection2); latch.countDown(); // There must be 2 idle connections. Connection connection = pollIdleConnection(connectionPool, 5, TimeUnit.SECONDS); - Assert.assertNotNull(connection); + assertNotNull(connection); connection = pollIdleConnection(connectionPool, 5, TimeUnit.SECONDS); - Assert.assertNotNull(connection); + assertNotNull(connection); } } - @Test - public void test_Acquire_Process_Release_Acquire_ReturnsSameConnection() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_Acquire_Process_Release_Acquire_ReturnsSameConnection(Scenario scenario) throws Exception { - try (HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))) + start(scenario, new EmptyServerHandler()); + + try(HttpDestinationOverHTTP destination = new HttpDestinationOverHTTP(client, new Origin("http", "localhost", connector.getLocalPort()))) { destination.start(); DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool(); @@ -159,22 +161,25 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest if (connection1 == null) { connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS); - Assert.assertNotNull(connection1); + assertNotNull(connection1); // Acquire the connection to make it active. - Assert.assertSame("From idle", connection1, connectionPool.acquire()); + assertSame(connection1, connectionPool.acquire(),"From idle"); } destination.process(connection1); destination.release(connection1); Connection connection2 = connectionPool.acquire(); - Assert.assertSame("After release", connection1, connection2); + assertSame(connection1, connection2,"After release"); } } - @Test - public void test_IdleConnection_IdleTimeout() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_IdleConnection_IdleTimeout(Scenario scenario) throws Exception { + start(scenario, new EmptyServerHandler()); + long idleTimeout = 1000; client.setIdleTimeout(idleTimeout); @@ -187,19 +192,22 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { connection1 = peekIdleConnection(connectionPool, 5, TimeUnit.SECONDS); - Assert.assertNotNull(connection1); + assertNotNull(connection1); TimeUnit.MILLISECONDS.sleep(2 * idleTimeout); connection1 = connectionPool.getIdleConnections().poll(); - Assert.assertNull(connection1); + assertNull(connection1); } } } - @Test - public void test_Request_Failed_If_MaxRequestsQueuedPerDestination_Exceeded() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void test_Request_Failed_If_MaxRequestsQueuedPerDestination_Exceeded(Scenario scenario) throws Exception { + start(scenario, new EmptyServerHandler()); + String scheme = scenario.getScheme(); int maxQueued = 1; client.setMaxRequestsQueuedPerDestination(maxQueued); client.setMaxConnectionsPerDestination(1); @@ -208,7 +216,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scheme) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); // Send another request that is sent immediately CountDownLatch successLatch = new CountDownLatch(1); @@ -224,8 +232,8 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest .path("/two") .send(result -> { - Assert.assertTrue(result.isFailed()); - Assert.assertThat(result.getRequestFailure(), Matchers.instanceOf(RejectedExecutionException.class)); + assertTrue(result.isFailed()); + assertThat(result.getRequestFailure(), Matchers.instanceOf(RejectedExecutionException.class)); failureLatch.countDown(); }); }) @@ -235,54 +243,60 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest successLatch.countDown(); }); - Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } - @Test - public void testDestinationIsRemoved() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testDestinationIsRemoved(Scenario scenario) throws Exception { + start(scenario, new EmptyServerHandler()); + String host = "localhost"; int port = connector.getLocalPort(); - Destination destinationBefore = client.getDestination(scheme, host, port); + Destination destinationBefore = client.getDestination(scenario.getScheme(), host, port); ContentResponse response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); - Destination destinationAfter = client.getDestination(scheme, host, port); - Assert.assertSame(destinationBefore, destinationAfter); + Destination destinationAfter = client.getDestination(scenario.getScheme(), host, port); + assertSame(destinationBefore, destinationAfter); client.setRemoveIdleDestinations(true); response = client.newRequest(host, port) - .scheme(scheme) + .scheme(scenario.getScheme()) .header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); - destinationAfter = client.getDestination(scheme, host, port); - Assert.assertNotSame(destinationBefore, destinationAfter); + destinationAfter = client.getDestination(scenario.getScheme(), host, port); + assertNotSame(destinationBefore, destinationAfter); } - @Test - public void testDestinationIsRemovedAfterConnectionError() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testDestinationIsRemovedAfterConnectionError(Scenario scenario) throws Exception { + start(scenario, new EmptyServerHandler()); + String host = "localhost"; int port = connector.getLocalPort(); client.setRemoveIdleDestinations(true); - Assert.assertTrue("Destinations of a fresh client must be empty", client.getDestinations().isEmpty()); + assertTrue(client.getDestinations().isEmpty(), "Destinations of a fresh client must be empty"); server.stop(); - Request request = client.newRequest(host, port).scheme(this.scheme); + Request request = client.newRequest(host, port).scheme(scenario.getScheme()); try { request.send(); - Assert.fail("Request to a closed port must fail"); + fail("Request to a closed port must fail"); } catch (Exception expected) { @@ -293,7 +307,7 @@ public class HttpDestinationOverHTTPTest extends AbstractHttpClientServerTest { Thread.sleep(10); } - Assert.assertTrue("Destination must be removed after connection error", client.getDestinations().isEmpty()); + assertTrue(client.getDestinations().isEmpty(), "Destination must be removed after connection error"); } private Connection pollIdleConnection(DuplexConnectionPool connectionPool, long time, TimeUnit unit) throws InterruptedException diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java index d131c02f6b1..3c66cbfea36 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpReceiverOverHTTPTest.java @@ -18,14 +18,22 @@ package org.eclipse.jetty.client.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.EOFException; import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.stream.Stream; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpExchange; @@ -39,42 +47,29 @@ import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.io.ByteArrayEndPoint; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.Promise; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class HttpReceiverOverHTTPTest { - @Rule - public final TestTracker tracker = new TestTracker(); - - @Parameterized.Parameter(0) - public HttpCompliance compliance; - private HttpClient client; private HttpDestinationOverHTTP destination; private ByteArrayEndPoint endPoint; private HttpConnectionOverHTTP connection; - @Parameterized.Parameters - public static Collection parameters() throws Exception + public static Stream complianceModes() throws Exception { - return Arrays.asList( - new Object[] { HttpCompliance.LEGACY }, - new Object[] { HttpCompliance.RFC2616_LEGACY }, - new Object[] { HttpCompliance.RFC7230_LEGACY } - ); + return Stream.of( + HttpCompliance.LEGACY, + HttpCompliance.RFC2616_LEGACY, + HttpCompliance.RFC7230_LEGACY + ).map(Arguments::of); } - @Before - public void init() throws Exception + public void init(HttpCompliance compliance) throws Exception { client = new HttpClient(); client.setHttpCompliance(compliance); @@ -86,7 +81,7 @@ public class HttpReceiverOverHTTPTest endPoint.setConnection(connection); } - @After + @AfterEach public void destroy() throws Exception { client.stop(); @@ -98,15 +93,17 @@ public class HttpReceiverOverHTTPTest FutureResponseListener listener = new FutureResponseListener(request); HttpExchange exchange = new HttpExchange(destination, request, Collections.singletonList(listener)); boolean associated = connection.getHttpChannel().associate(exchange); - Assert.assertTrue(associated); + assertTrue(associated); exchange.requestComplete(null); exchange.terminateRequest(); return exchange; } - @Test - public void test_Receive_NoResponseContent() throws Exception + @ParameterizedTest + @MethodSource("complianceModes") + public void test_Receive_NoResponseContent(HttpCompliance compliance) throws Exception { + init(compliance); endPoint.addInput("" + "HTTP/1.1 200 OK\r\n" + "Content-length: 0\r\n" + @@ -116,19 +113,21 @@ public class HttpReceiverOverHTTPTest connection.getHttpChannel().receive(); Response response = listener.get(5, TimeUnit.SECONDS); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals("OK", response.getReason()); - Assert.assertSame(HttpVersion.HTTP_1_1, response.getVersion()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals("OK", response.getReason()); + assertSame(HttpVersion.HTTP_1_1, response.getVersion()); HttpFields headers = response.getHeaders(); - Assert.assertNotNull(headers); - Assert.assertEquals(1, headers.size()); - Assert.assertEquals("0", headers.get(HttpHeader.CONTENT_LENGTH)); + assertNotNull(headers); + assertEquals(1, headers.size()); + assertEquals("0", headers.get(HttpHeader.CONTENT_LENGTH)); } - @Test - public void test_Receive_ResponseContent() throws Exception + @ParameterizedTest + @MethodSource("complianceModes") + public void test_Receive_ResponseContent(HttpCompliance compliance) throws Exception { + init(compliance); String content = "0123456789ABCDEF"; endPoint.addInput("" + "HTTP/1.1 200 OK\r\n" + @@ -140,21 +139,23 @@ public class HttpReceiverOverHTTPTest connection.getHttpChannel().receive(); Response response = listener.get(5, TimeUnit.SECONDS); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals("OK", response.getReason()); - Assert.assertSame(HttpVersion.HTTP_1_1, response.getVersion()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals("OK", response.getReason()); + assertSame(HttpVersion.HTTP_1_1, response.getVersion()); HttpFields headers = response.getHeaders(); - Assert.assertNotNull(headers); - Assert.assertEquals(1, headers.size()); - Assert.assertEquals(String.valueOf(content.length()), headers.get(HttpHeader.CONTENT_LENGTH)); + assertNotNull(headers); + assertEquals(1, headers.size()); + assertEquals(String.valueOf(content.length()), headers.get(HttpHeader.CONTENT_LENGTH)); String received = listener.getContentAsString(StandardCharsets.UTF_8); - Assert.assertEquals(content, received); + assertEquals(content, received); } - @Test - public void test_Receive_ResponseContent_EarlyEOF() throws Exception + @ParameterizedTest + @MethodSource("complianceModes") + public void test_Receive_ResponseContent_EarlyEOF(HttpCompliance compliance) throws Exception { + init(compliance); String content1 = "0123456789"; String content2 = "ABCDEF"; endPoint.addInput("" + @@ -168,20 +169,15 @@ public class HttpReceiverOverHTTPTest endPoint.addInputEOF(); connection.getHttpChannel().receive(); - try - { - listener.get(5, TimeUnit.SECONDS); - Assert.fail(); - } - catch (ExecutionException e) - { - Assert.assertTrue(e.getCause() instanceof EOFException); - } + ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS)); + assertThat(e.getCause(), instanceOf(EOFException.class)); } - @Test - public void test_Receive_ResponseContent_IdleTimeout() throws Exception + @ParameterizedTest + @MethodSource("complianceModes") + public void test_Receive_ResponseContent_IdleTimeout(HttpCompliance compliance) throws Exception { + init(compliance); endPoint.addInput("" + "HTTP/1.1 200 OK\r\n" + "Content-length: 1\r\n" + @@ -194,20 +190,15 @@ public class HttpReceiverOverHTTPTest Thread.sleep(100); connection.onIdleExpired(); - try - { - listener.get(5, TimeUnit.SECONDS); - Assert.fail(); - } - catch (ExecutionException e) - { - Assert.assertTrue(e.getCause() instanceof TimeoutException); - } + ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS)); + assertThat(e.getCause(), instanceOf(TimeoutException.class)); } - @Test - public void test_Receive_BadResponse() throws Exception + @ParameterizedTest + @MethodSource("complianceModes") + public void test_Receive_BadResponse(HttpCompliance compliance) throws Exception { + init(compliance); endPoint.addInput("" + "HTTP/1.1 200 OK\r\n" + "Content-length: A\r\n" + @@ -216,20 +207,15 @@ public class HttpReceiverOverHTTPTest FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0); connection.getHttpChannel().receive(); - try - { - listener.get(5, TimeUnit.SECONDS); - Assert.fail(); - } - catch (ExecutionException e) - { - Assert.assertTrue(e.getCause() instanceof HttpResponseException); - } + ExecutionException e = assertThrows(ExecutionException.class, ()->listener.get(5, TimeUnit.SECONDS)); + assertThat(e.getCause(), instanceOf(HttpResponseException.class)); } - @Test - public void test_FillInterested_RacingWith_BufferRelease() throws Exception + @ParameterizedTest + @MethodSource("complianceModes") + public void test_FillInterested_RacingWith_BufferRelease(HttpCompliance compliance) throws Exception { + init(compliance); connection = new HttpConnectionOverHTTP(endPoint, destination, new Promise.Adapter<>()) { @Override @@ -247,7 +233,7 @@ public class HttpReceiverOverHTTPTest { // Verify that the buffer has been released // before fillInterested() is called. - Assert.assertNull(getResponseBuffer()); + assertNull(getResponseBuffer()); // Fill the endpoint so receive is called again. endPoint.addInput("X"); super.fillInterested(); @@ -270,7 +256,7 @@ public class HttpReceiverOverHTTPTest connection.getHttpChannel().receive(); Response response = listener.get(5, TimeUnit.SECONDS); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java index c848437a906..7abe61bbfe6 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/http/HttpSenderOverHTTPTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.client.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -33,31 +36,26 @@ import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.client.util.ByteBufferContentProvider; import org.eclipse.jetty.io.ByteArrayEndPoint; -import org.eclipse.jetty.toolchain.test.TestTracker; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.Promise; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; public class HttpSenderOverHTTPTest { - @Rule - public final TestTracker tracker = new TestTracker(); - private HttpClient client; - @Before + @BeforeEach public void init() throws Exception { client = new HttpClient(); client.start(); } - @After + @AfterEach public void destroy() throws Exception { client.stop(); @@ -90,14 +88,14 @@ public class HttpSenderOverHTTPTest connection.send(request, null); String requestString = endPoint.takeOutputString(); - Assert.assertTrue(requestString.startsWith("GET ")); - Assert.assertTrue(requestString.endsWith("\r\n\r\n")); - Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); + assertTrue(requestString.startsWith("GET ")); + assertTrue(requestString.endsWith("\r\n\r\n")); + assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); + assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } - @Slow @Test + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void test_Send_NoRequestContent_IncompleteFlush() throws Exception { ByteArrayEndPoint endPoint = new ByteArrayEndPoint("", 16); @@ -121,8 +119,8 @@ public class HttpSenderOverHTTPTest } String requestString = builder.toString(); - Assert.assertTrue(requestString.startsWith("GET ")); - Assert.assertTrue(requestString.endsWith("\r\n\r\n")); + assertTrue(requestString.startsWith("GET ")); + assertTrue(requestString.endsWith("\r\n\r\n")); } @Test @@ -149,12 +147,12 @@ public class HttpSenderOverHTTPTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); failureLatch.countDown(); } }); - Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -179,7 +177,7 @@ public class HttpSenderOverHTTPTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isFailed()); + assertTrue(result.isFailed()); failureLatch.countDown(); } }); @@ -190,7 +188,7 @@ public class HttpSenderOverHTTPTest // although it will fail because we shut down the output endPoint.takeOutputString(); - Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -222,10 +220,10 @@ public class HttpSenderOverHTTPTest connection.send(request, null); String requestString = endPoint.takeOutputString(); - Assert.assertTrue(requestString.startsWith("GET ")); - Assert.assertTrue(requestString.endsWith("\r\n\r\n" + content)); - Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); + assertTrue(requestString.startsWith("GET ")); + assertTrue(requestString.endsWith("\r\n\r\n" + content)); + assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); + assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -258,10 +256,10 @@ public class HttpSenderOverHTTPTest connection.send(request, null); String requestString = endPoint.takeOutputString(); - Assert.assertTrue(requestString.startsWith("GET ")); - Assert.assertThat(requestString,Matchers.endsWith("\r\n\r\n" + content1 + content2)); - Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); + assertTrue(requestString.startsWith("GET ")); + assertThat(requestString,Matchers.endsWith("\r\n\r\n" + content1 + content2)); + assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); + assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -301,12 +299,12 @@ public class HttpSenderOverHTTPTest connection.send(request, null); String requestString = endPoint.takeOutputString(); - Assert.assertTrue(requestString.startsWith("GET ")); + assertTrue(requestString.startsWith("GET ")); String content = Integer.toHexString(content1.length()).toUpperCase(Locale.ENGLISH) + "\r\n" + content1 + "\r\n"; content += Integer.toHexString(content2.length()).toUpperCase(Locale.ENGLISH) + "\r\n" + content2 + "\r\n"; content += "0\r\n\r\n"; - Assert.assertTrue(requestString.endsWith("\r\n\r\n" + content)); - Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); + assertTrue(requestString.endsWith("\r\n\r\n" + content)); + assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); + assertTrue(successLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java index bb6869bece5..e03afecd792 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/jmx/HttpClientJMXTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client.jmx; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.lang.management.ManagementFactory; import java.util.Locale; import java.util.Set; @@ -28,8 +30,8 @@ import javax.management.ObjectName; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.io.SelectorManager; import org.eclipse.jetty.jmx.MBeanContainer; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HttpClientJMXTest { @@ -51,16 +53,16 @@ public class HttpClientJMXTest String domain = HttpClient.class.getPackage().getName(); ObjectName pattern = new ObjectName(domain + ":type=" + HttpClient.class.getSimpleName().toLowerCase(Locale.ENGLISH) + ",*"); Set objectNames = mbeanServer.queryNames(pattern, null); - Assert.assertEquals(1, objectNames.size()); + assertEquals(1, objectNames.size()); ObjectName objectName = objectNames.iterator().next(); - Assert.assertEquals(name, objectName.getKeyProperty("context")); + assertEquals(name, objectName.getKeyProperty("context")); // Verify that the context is inherited by the descendant components. domain = SelectorManager.class.getPackage().getName(); pattern = new ObjectName(domain + ":*"); objectNames = mbeanServer.queryNames(pattern, null); for (ObjectName oName : objectNames) - Assert.assertEquals(name, oName.getKeyProperty("context")); + assertEquals(name, oName.getKeyProperty("context")); } finally { diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java index 9ecb42b04da..12aca96fec7 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/NeedWantClientAuthTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.client.ssl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.security.cert.Certificate; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -37,9 +42,9 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; /** * In order to work, client authentication needs a certificate @@ -85,7 +90,7 @@ public class NeedWantClientAuthTest return sslContextFactory; } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -108,7 +113,7 @@ public class NeedWantClientAuthTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test @@ -127,8 +132,8 @@ public class NeedWantClientAuthTest { SSLSession session = event.getSSLEngine().getSession(); Certificate[] clientCerts = session.getPeerCertificates(); - Assert.assertNotNull(clientCerts); - Assert.assertThat(clientCerts.length, Matchers.greaterThan(0)); + assertNotNull(clientCerts); + assertThat(clientCerts.length, Matchers.greaterThan(0)); handshakeLatch.countDown(); } catch (Throwable x) @@ -147,8 +152,8 @@ public class NeedWantClientAuthTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -180,7 +185,7 @@ public class NeedWantClientAuthTest @Override public void handshakeFailed(Event event, Throwable failure) { - Assert.assertThat(failure, Matchers.instanceOf(SSLHandshakeException.class)); + assertThat(failure, Matchers.instanceOf(SSLHandshakeException.class)); handshakeLatch.countDown(); } }); @@ -198,8 +203,8 @@ public class NeedWantClientAuthTest } }); - Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -218,8 +223,8 @@ public class NeedWantClientAuthTest { SSLSession session = event.getSSLEngine().getSession(); Certificate[] clientCerts = session.getPeerCertificates(); - Assert.assertNotNull(clientCerts); - Assert.assertThat(clientCerts.length, Matchers.greaterThan(0)); + assertNotNull(clientCerts); + assertThat(clientCerts.length, Matchers.greaterThan(0)); handshakeLatch.countDown(); } catch (Throwable x) @@ -238,7 +243,7 @@ public class NeedWantClientAuthTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java index d9a08b5d5dc..327901ac342 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesClientTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.client.ssl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import java.io.BufferedReader; import java.io.File; import java.io.InputStream; @@ -44,12 +50,13 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.JavaVersion; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnJre; +import org.junit.jupiter.api.condition.JRE; public class SslBytesClientTest extends SslBytesTest { @@ -59,12 +66,11 @@ public class SslBytesClientTest extends SslBytesTest private SSLServerSocket acceptor; private SimpleProxy proxy; - @Before + // This whole test is very specific to how TLS < 1.3 works. + @DisabledOnJre( JRE.JAVA_11 ) + @BeforeEach public void init() throws Exception { - // This whole test is very specific to how TLS < 1.3 works. - Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11)); - threadPool = Executors.newCachedThreadPool(); sslContextFactory = new SslContextFactory(true); @@ -85,7 +91,7 @@ public class SslBytesClientTest extends SslBytesTest logger.info(":{} <==> :{}", proxy.getPort(), serverPort); } - @After + @AfterEach public void destroy() throws Exception { if (acceptor != null) @@ -105,7 +111,7 @@ public class SslBytesClientTest extends SslBytesTest FutureResponseListener listener = new FutureResponseListener(request); request.scheme(HttpScheme.HTTPS.asString()).send(listener); - Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); + assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); try (SSLSocket server = (SSLSocket)acceptor.accept()) { @@ -119,46 +125,46 @@ public class SslBytesClientTest extends SslBytesTest // Client Hello TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); // Server Hello + Certificate + Server Done record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Client Key Exchange record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); // Change Cipher Spec record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToServer(record); // Client Done record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); // Change Cipher Spec record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToClient(record); // Server Done record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); - Assert.assertNull(handshake.get(5, TimeUnit.SECONDS)); + assertNull(handshake.get(5, TimeUnit.SECONDS)); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); // Read request BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.startsWith("GET")); + assertTrue(line.startsWith("GET")); while (line.length() > 0) line = reader.readLine(); @@ -168,10 +174,10 @@ public class SslBytesClientTest extends SslBytesTest "Content-Length: 0\r\n" + "\r\n").getBytes(StandardCharsets.UTF_8)); output.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } } @@ -182,7 +188,7 @@ public class SslBytesClientTest extends SslBytesTest FutureResponseListener listener = new FutureResponseListener(request); request.scheme(HttpScheme.HTTPS.asString()).send(listener); - Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); + assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); try (SSLSocket server = (SSLSocket)acceptor.accept()) { @@ -195,13 +201,13 @@ public class SslBytesClientTest extends SslBytesTest }); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); - Assert.assertNull(handshake.get(5, TimeUnit.SECONDS)); + assertNull(handshake.get(5, TimeUnit.SECONDS)); // Read request InputStream serverInput = server.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(serverInput, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.startsWith("GET")); + assertTrue(line.startsWith("GET")); while (line.length() > 0) line = reader.readLine(); @@ -219,7 +225,7 @@ public class SslBytesClientTest extends SslBytesTest "\r\n" + content1).getBytes(StandardCharsets.UTF_8)); serverOutput.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Renegotiate Future renegotiation = threadPool.submit(() -> @@ -230,62 +236,54 @@ public class SslBytesClientTest extends SslBytesTest // Renegotiation Handshake TLSRecord record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Renegotiation Handshake record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); // Trigger a read to have the server write the final renegotiation steps server.setSoTimeout(100); - try - { - serverInput.read(); - Assert.fail(); - } - catch (SocketTimeoutException x) - { - // Expected - } + assertThrows(SocketTimeoutException.class, ()->serverInput.read()); // Renegotiation Handshake record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Renegotiation Change Cipher record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToClient(record); // Renegotiation Handshake record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Renegotiation Change Cipher record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToServer(record); // Renegotiation Handshake record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); - Assert.assertNull(renegotiation.get(5, TimeUnit.SECONDS)); + assertNull(renegotiation.get(5, TimeUnit.SECONDS)); // Complete the response automaticProxyFlow = proxy.startAutomaticFlow(); serverOutput.write(data2); serverOutput.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertEquals(data1.length + data2.length, response.getContent().length); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(data1.length + data2.length, response.getContent().length); } } @@ -298,7 +296,7 @@ public class SslBytesClientTest extends SslBytesTest FutureResponseListener listener = new FutureResponseListener(request); request.scheme(HttpScheme.HTTPS.asString()).send(listener); - Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); + assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); try (SSLSocket server = (SSLSocket)acceptor.accept()) { @@ -311,13 +309,13 @@ public class SslBytesClientTest extends SslBytesTest }); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); - Assert.assertNull(handshake.get(5, TimeUnit.SECONDS)); + assertNull(handshake.get(5, TimeUnit.SECONDS)); // Read request InputStream serverInput = server.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(serverInput, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.startsWith("GET")); + assertTrue(line.startsWith("GET")); while (line.length() > 0) line = reader.readLine(); @@ -335,7 +333,7 @@ public class SslBytesClientTest extends SslBytesTest "\r\n" + content1).getBytes(StandardCharsets.UTF_8)); serverOutput.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Renegotiate threadPool.submit(() -> @@ -346,14 +344,14 @@ public class SslBytesClientTest extends SslBytesTest // Renegotiation Handshake TLSRecord record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Client sends close alert. record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.ALERT, record.getType()); + assertEquals(TLSRecord.Type.ALERT, record.getType()); record = proxy.readFromClient(); - Assert.assertNull(record); + assertNull(record); } } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java index f891e712896..92c3ff6ef8c 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesServerTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.client.ssl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.condition.OS.LINUX; +import static org.junit.jupiter.api.condition.OS.WINDOWS; + import java.io.BufferedReader; import java.io.EOFException; import java.io.File; @@ -66,16 +72,19 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.OS; import org.eclipse.jetty.util.JavaVersion; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnJre; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.JRE; public class SslBytesServerTest extends SslBytesTest { @@ -92,11 +101,11 @@ public class SslBytesServerTest extends SslBytesTest private SimpleProxy proxy; private Runnable idleHook; - @Before + // This whole test is very specific to how TLS < 1.3 works. + @DisabledOnJre( JRE.JAVA_11 ) + @BeforeEach public void init() throws Exception { - // This whole test is very specific to how TLS < 1.3 works. - Assume.assumeThat(JavaVersion.VERSION.getPlatform(), Matchers.lessThan(11)); threadPool = Executors.newCachedThreadPool(); server = new Server(); @@ -232,7 +241,7 @@ public class SslBytesServerTest extends SslBytesTest logger.info("proxy:{} <==> server:{}", proxy.getPort(), serverPort); } - @After + @AfterEach public void destroy() throws Exception { if (proxy != null) @@ -243,7 +252,7 @@ public class SslBytesServerTest extends SslBytesTest threadPool.shutdownNow(); } - @Test(timeout=10000) + @Test public void testHandshake() throws Exception { final SSLSocket client = newClient(); @@ -256,51 +265,51 @@ public class SslBytesServerTest extends SslBytesTest // Client Hello TLSRecord record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToServer(record); // Server Hello + Certificate + Server Done record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); // Client Key Exchange record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToServer(record); // Change Cipher Spec record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToServer(record); // Client Done record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToServer(record); // Change Cipher Spec record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); // Server Done record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); - Assert.assertNull(handshake.get(5, TimeUnit.SECONDS)); + assertNull(handshake.get(5, TimeUnit.SECONDS)); // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); closeClient(client); } - @Test(timeout=60000) + @Test public void testHandshakeWithResumedSessionThenClose() throws Exception { // First socket will establish the SSL session @@ -308,7 +317,7 @@ public class SslBytesServerTest extends SslBytesTest SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client1.startHandshake(); client1.close(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); int proxyPort = proxy.getPort(); proxy.stop(); @@ -326,35 +335,35 @@ public class SslBytesServerTest extends SslBytesTest // Client Hello with SessionID TLSRecord record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToServer(record); // Server Hello record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); // Change Cipher Spec record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); // Server Done record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); // Client Key Exchange record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); // Client Done TLSRecord doneRecord = proxy.readFromClient(); - Assert.assertNotNull(doneRecord); + assertNotNull(doneRecord); // Close client2.close(); TLSRecord closeRecord = proxy.readFromClient(); - Assert.assertNotNull(closeRecord); - Assert.assertEquals(TLSRecord.Type.ALERT, closeRecord.getType()); + assertNotNull(closeRecord); + assertEquals(TLSRecord.Type.ALERT, closeRecord.getType()); // Flush to server Client Key Exchange + Client Done + Close in one chunk byte[] recordBytes = record.getBytes(); byte[] doneBytes = doneRecord.getBytes(); @@ -369,19 +378,19 @@ public class SslBytesServerTest extends SslBytesTest // Expect the server to send a TLS Alert. record = proxy.readFromServer(); - Assert.assertNotNull(record); - Assert.assertEquals(TLSRecord.Type.ALERT, record.getType()); + assertNotNull(record); + assertEquals(TLSRecord.Type.ALERT, record.getType()); record = proxy.readFromServer(); - Assert.assertNull(record); + assertNull(record); // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); } - @Test(timeout=60000) + @Test public void testHandshakeWithSplitBoundary() throws Exception { final SSLSocket client = newClient(); @@ -438,21 +447,21 @@ public class SslBytesServerTest extends SslBytesTest // Change Cipher Spec record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); // Server Done record = proxy.readFromServer(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToClient(record); - Assert.assertNull(handshake.get(5, TimeUnit.SECONDS)); + assertNull(handshake.get(5, TimeUnit.SECONDS)); // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(40)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(40)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); @@ -467,22 +476,22 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(100, chunk2); // Socket close record = proxy.readFromClient(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); proxy.flushToServer(record); // Socket close record = proxy.readFromServer(); if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } } - @Test(timeout=60000) + @Test public void testClientHelloIncompleteThenReset() throws Exception { final SSLSocket client = newClient(); @@ -504,14 +513,14 @@ public class SslBytesServerTest extends SslBytesTest // Wait a while to detect spinning TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test public void testClientHelloThenReset() throws Exception { final SSLSocket client = newClient(); @@ -524,48 +533,48 @@ public class SslBytesServerTest extends SslBytesTest // Client Hello TLSRecord record = proxy.readFromClient(); - Assert.assertNotNull(record); + assertNotNull(record); proxy.flushToServer(record); proxy.sendRSTToServer(); // Wait a while to detect spinning TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test public void testHandshakeThenReset() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); proxy.sendRSTToServer(); // Wait a while to detect spinning TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test public void testRequestIncompleteThenReset() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); threadPool.submit(() -> { @@ -589,21 +598,21 @@ public class SslBytesServerTest extends SslBytesTest // Wait a while to detect spinning TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test public void testRequestResponse() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -619,17 +628,17 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord record = proxy.readFromClient(); proxy.flushToServer(record); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // Application data record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -638,14 +647,14 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); closeClient(client); } - @Test(timeout=60000) + @Test public void testHandshakeAndRequestOneByteAtATime() throws Exception { final SSLSocket client = newClient(); @@ -688,7 +697,7 @@ public class SslBytesServerTest extends SslBytesTest record = proxy.readFromServer(); proxy.flushToClient(record); - Assert.assertNull(handshake.get(1, TimeUnit.SECONDS)); + assertNull(handshake.get(1, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -705,17 +714,17 @@ public class SslBytesServerTest extends SslBytesTest record = proxy.readFromClient(); for (byte b : record.getBytes()) proxy.flushToServer(5, b); - Assert.assertNull(request.get(1, TimeUnit.SECONDS)); + assertNull(request.get(1, TimeUnit.SECONDS)); // Application data record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -724,11 +733,11 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(1000); - Assert.assertThat(sslFills.get(), Matchers.lessThan(2000)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(2000)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); // An average of 958 httpParses is seen in standard Oracle JDK's // An average of 1183 httpParses is seen in OpenJDK JVMs. - Assert.assertThat(httpParses.get(), Matchers.lessThan(2000)); + assertThat(httpParses.get(), Matchers.lessThan(2000)); client.close(); @@ -738,7 +747,7 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(5, b); // Socket close record = proxy.readFromClient(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); proxy.flushToServer(record); // Socket close @@ -746,25 +755,23 @@ public class SslBytesServerTest extends SslBytesTest // Raw close or alert if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } } - @Test(timeout=60000) + @Test + @EnabledOnOs(LINUX) // See next test on why we only run in Linux public void testRequestWithCloseAlertAndShutdown() throws Exception { - // See next test on why we only run in Linux - Assume.assumeTrue(OS.IS_LINUX); - final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -780,7 +787,7 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord record = proxy.readFromClient(); proxy.flushToServer(record); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); client.close(); @@ -789,36 +796,37 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(record); // Socket close record = proxy.readFromClient(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); proxy.flushToServer(record); // Expect response from server // SSLSocket is limited and we cannot read the response, but we make sure // it is application data and not a close alert record = proxy.readFromServer(); - Assert.assertNotNull(record); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertNotNull(record); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); // Socket close record = proxy.readFromServer(); if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); } - @Test(timeout=60000) + @Test + @EnabledOnOs(LINUX) public void testRequestWithCloseAlert() throws Exception { // Currently we are ignoring this test on anything other then linux @@ -829,13 +837,12 @@ public class SslBytesServerTest extends SslBytesTest // and close down the connection immediately, discarding any pending writes. It is not // required for the initiator of the close to wait for the responding // close_notify alert before closing the read side of the connection. - Assume.assumeTrue(OS.IS_LINUX); final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -850,15 +857,15 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); client.close(); // Close Alert record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.ALERT, record.getType()); + assertEquals(TLSRecord.Type.ALERT, record.getType()); proxy.flushToServer(record); // Do not close the raw socket yet @@ -867,41 +874,41 @@ public class SslBytesServerTest extends SslBytesTest // SSLSocket is limited and we cannot read the response, but we make sure // it is application data and not a close alert record = proxy.readFromServer(); - Assert.assertNotNull(record); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertNotNull(record); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); // Socket close record = proxy.readFromServer(); if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); // Socket close record = proxy.readFromClient(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); proxy.flushToServer(record); } - @Test(timeout=60000) + @Test public void testRequestWithRawClose() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -916,13 +923,13 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // Application data record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); // Close the raw socket, this generates a truncation attack @@ -933,30 +940,30 @@ public class SslBytesServerTest extends SslBytesTest // TODO check that this is OK? if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test public void testRequestWithImmediateRawClose() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -971,48 +978,46 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record, 0); // Close the raw socket, this generates a truncation attack proxy.flushToServer(null); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // Application data record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); // Expect raw close from server record = proxy.readFromServer(); if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test + @DisabledOnOs(WINDOWS) // Don't run on Windows (buggy JVM) public void testRequestWithBigContentWriteBlockedThenReset() throws Exception { - // Don't run on Windows (buggy JVM) - Assume.assumeTrue(!OS.IS_WINDOWS); - final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); byte[] data = new byte[128 * 1024]; Arrays.fill(data, (byte)'X'); @@ -1035,10 +1040,10 @@ public class SslBytesServerTest extends SslBytesTest { // Application data TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record, 0); } - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // We asked the server to echo back the data we sent // but we do not read it, thus causing a write interest @@ -1052,24 +1057,22 @@ public class SslBytesServerTest extends SslBytesTest // Wait a while to detect spinning TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(40)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(40)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(50)); + assertThat(sslFills.get(), Matchers.lessThan(40)); + assertThat(sslFlushes.get(), Matchers.lessThan(40)); + assertThat(httpParses.get(), Matchers.lessThan(50)); client.close(); } - @Test(timeout=60000) + @Test + @DisabledOnOs(WINDOWS) // Don't run on Windows (buggy JVM) public void testRequestWithBigContentReadBlockedThenReset() throws Exception { - // Don't run on Windows (buggy JVM) - Assume.assumeTrue(!OS.IS_WINDOWS); - final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); byte[] data = new byte[128 * 1024]; Arrays.fill(data, (byte)'X'); @@ -1093,10 +1096,10 @@ public class SslBytesServerTest extends SslBytesTest { // Application data TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record, 0); } - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // The server should be read blocked, and we send a RST TimeUnit.MILLISECONDS.sleep(500); @@ -1104,35 +1107,32 @@ public class SslBytesServerTest extends SslBytesTest // Wait a while to detect spinning TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(40)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(40)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(50)); + assertThat(sslFills.get(), Matchers.lessThan(40)); + assertThat(sslFlushes.get(), Matchers.lessThan(40)); + assertThat(httpParses.get(), Matchers.lessThan(50)); client.close(); } - @Test(timeout=60000) + @Test + @EnabledOnOs(LINUX) // see message below public void testRequestWithCloseAlertWithSplitBoundary() throws Exception { - if (!OS.IS_LINUX) - { - // currently we are ignoring this test on anything other then linux + // currently we are ignoring this test on anything other then linux - //http://tools.ietf.org/html/rfc2246#section-7.2.1 + // http://tools.ietf.org/html/rfc2246#section-7.2.1 - // TODO (react to this portion which seems to allow win/mac behavior) - //It is required that the other party respond with a close_notify alert of its own - //and close down the connection immediately, discarding any pending writes. It is not - //required for the initiator of the close to wait for the responding - //close_notify alert before closing the read side of the connection. - return; - } + // TODO (react to this portion which seems to allow win/mac behavior) + //It is required that the other party respond with a close_notify alert of its own + //and close down the connection immediately, discarding any pending writes. It is not + //required for the initiator of the close to wait for the responding + //close_notify alert before closing the read side of the connection. final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); Future request = threadPool.submit(() -> { @@ -1147,7 +1147,7 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord dataRecord = proxy.readFromClient(); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); client.close(); @@ -1173,36 +1173,36 @@ public class SslBytesServerTest extends SslBytesTest // SSLSocket is limited and we cannot read the response, but we make sure // it is application data and not a close alert TLSRecord record = proxy.readFromServer(); - Assert.assertNotNull(record); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertNotNull(record); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); // Socket close record = proxy.readFromServer(); if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); // Now should be a raw close record = proxy.readFromServer(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); } // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); } - @Test(timeout=60000) + @Test public void testRequestWithContentWithSplitBoundary() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); final String content = "0123456789ABCDEF"; @@ -1222,7 +1222,7 @@ public class SslBytesServerTest extends SslBytesTest // Application data TLSRecord record = proxy.readFromClient(); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); byte[] chunk1 = new byte[2 * record.getBytes().length / 3]; System.arraycopy(record.getBytes(), 0, chunk1, 0, chunk1.length); proxy.flushToServer(100, chunk1); @@ -1232,13 +1232,13 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(100, chunk2); record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -1247,21 +1247,21 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); closeClient(client); } - @Test(timeout=60000) + @Test public void testRequestWithBigContentWithSplitBoundary() throws Exception { final SSLSocket client = newClient(); SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Use a content that is larger than the TLS record which is 2^14 (around 16k) byte[] data = new byte[128 * 1024]; @@ -1298,20 +1298,20 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(100)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(50)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(100)); + assertThat(sslFills.get(), Matchers.lessThan(100)); + assertThat(sslFlushes.get(), Matchers.lessThan(50)); + assertThat(httpParses.get(), Matchers.lessThan(100)); - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); TLSRecord record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -1320,14 +1320,14 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(100)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(50)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(100)); + assertThat(sslFills.get(), Matchers.lessThan(100)); + assertThat(sslFlushes.get(), Matchers.lessThan(50)); + assertThat(httpParses.get(), Matchers.lessThan(100)); closeClient(client); } - - @Test(timeout=60000) + + @Test public void testRequestWithContentWithRenegotiationInMiddleOfContentWhenRenegotiationIsForbidden() throws Exception { assumeJavaVersionSupportsTLSRenegotiations(); @@ -1339,7 +1339,7 @@ public class SslBytesServerTest extends SslBytesTest SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); byte[] data1 = new byte[1024]; Arrays.fill(data1, (byte)'X'); @@ -1358,7 +1358,7 @@ public class SslBytesServerTest extends SslBytesTest "\r\n" + content1).getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Renegotiate threadPool.submit(() -> @@ -1369,7 +1369,7 @@ public class SslBytesServerTest extends SslBytesTest // Renegotiation Handshake TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); // Renegotiation not allowed, server has closed @@ -1381,29 +1381,29 @@ public class SslBytesServerTest extends SslBytesTest switch(record.getType()) { case APPLICATION: - Assert.fail("application data not allows after renegotiate"); + fail("application data not allows after renegotiate"); case ALERT: break loop; default: continue; } } - Assert.assertEquals(TLSRecord.Type.ALERT, record.getType()); + assertEquals(TLSRecord.Type.ALERT, record.getType()); proxy.flushToClient(record); record = proxy.readFromServer(); - Assert.assertNull(record); + assertNull(record); // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(50)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(50)); + assertThat(sslFills.get(), Matchers.lessThan(50)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(50)); client.close(); } - @Test(timeout=60000) + @Test public void testRequestWithBigContentWithRenegotiationInMiddleOfContent() throws Exception { assumeJavaVersionSupportsTLSRenegotiations(); @@ -1413,7 +1413,7 @@ public class SslBytesServerTest extends SslBytesTest SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Use a content that is larger than the TLS record which is 2^14 (around 16k) byte[] data1 = new byte[80 * 1024]; @@ -1433,7 +1433,7 @@ public class SslBytesServerTest extends SslBytesTest "\r\n" + content1).getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Renegotiate Future renegotiation = threadPool.submit(() -> @@ -1444,47 +1444,40 @@ public class SslBytesServerTest extends SslBytesTest // Renegotiation Handshake TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); // Renegotiation Handshake record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Renegotiation Change Cipher record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToClient(record); // Renegotiation Handshake record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Trigger a read to have the client write the final renegotiation steps client.setSoTimeout(100); - try - { - client.getInputStream().read(); - Assert.fail(); - } - catch (SocketTimeoutException x) - { - // Expected - } + + assertThrows(SocketTimeoutException.class, ()->client.getInputStream().read()); // Renegotiation Change Cipher record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToServer(record); // Renegotiation Handshake record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToServer(record); - Assert.assertNull(renegotiation.get(5, TimeUnit.SECONDS)); + assertNull(renegotiation.get(5, TimeUnit.SECONDS)); // Write the rest of the request Future request = threadPool.submit(() -> @@ -1502,18 +1495,18 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(record); } - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // Read response // Application Data record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -1522,14 +1515,14 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(50)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(50)); + assertThat(sslFills.get(), Matchers.lessThan(50)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(50)); closeClient(client); } - @Test(timeout=10000) + @Test public void testRequestWithBigContentWithRenegotiationInMiddleOfContentWithSplitBoundary() throws Exception { assumeJavaVersionSupportsTLSRenegotiations(); @@ -1539,7 +1532,7 @@ public class SslBytesServerTest extends SslBytesTest SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Use a content that is larger than the TLS record which is 2^14 (around 16k) byte[] data1 = new byte[80 * 1024]; @@ -1559,7 +1552,7 @@ public class SslBytesServerTest extends SslBytesTest "\r\n" + content1).getBytes(StandardCharsets.UTF_8)); clientOutput.flush(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Renegotiate Future renegotiation = threadPool.submit(() -> @@ -1570,7 +1563,7 @@ public class SslBytesServerTest extends SslBytesTest // Renegotiation Handshake TLSRecord record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); byte[] bytes = record.getBytes(); byte[] chunk1 = new byte[2 * bytes.length / 3]; System.arraycopy(bytes, 0, chunk1, 0, chunk1.length); @@ -1581,34 +1574,27 @@ public class SslBytesServerTest extends SslBytesTest // Renegotiation Handshake record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Renegotiation Change Cipher record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); proxy.flushToClient(record); // Renegotiation Handshake record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); proxy.flushToClient(record); // Trigger a read to have the client write the final renegotiation steps client.setSoTimeout(100); - try - { - client.getInputStream().read(); - Assert.fail(); - } - catch (SocketTimeoutException x) - { - // Expected - } + + assertThrows(SocketTimeoutException.class, ()->client.getInputStream().read()); // Renegotiation Change Cipher record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); + assertEquals(TLSRecord.Type.CHANGE_CIPHER_SPEC, record.getType()); bytes = record.getBytes(); chunk1 = new byte[2 * bytes.length / 3]; System.arraycopy(bytes, 0, chunk1, 0, chunk1.length); @@ -1619,7 +1605,7 @@ public class SslBytesServerTest extends SslBytesTest // Renegotiation Handshake record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); + assertEquals(TLSRecord.Type.HANDSHAKE, record.getType()); bytes = record.getBytes(); chunk1 = new byte[2 * bytes.length / 3]; System.arraycopy(bytes, 0, chunk1, 0, chunk1.length); @@ -1628,7 +1614,7 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(100, chunk1); // Do not write the second chunk now, but merge it with content, see below - Assert.assertNull(renegotiation.get(5, TimeUnit.SECONDS)); + assertNull(renegotiation.get(5, TimeUnit.SECONDS)); // Write the rest of the request Future request = threadPool.submit(() -> @@ -1641,7 +1627,7 @@ public class SslBytesServerTest extends SslBytesTest // Three TLSRecords will be generated for the remainder of the content // Merge the last chunk of the renegotiation with the first data record record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); byte[] dataBytes = record.getBytes(); byte[] mergedBytes = new byte[chunk2.length + dataBytes.length]; System.arraycopy(chunk2, 0, mergedBytes, 0, chunk2.length); @@ -1652,22 +1638,22 @@ public class SslBytesServerTest extends SslBytesTest { // Application data record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record); } - Assert.assertNull(request.get(5, TimeUnit.SECONDS)); + assertNull(request.get(5, TimeUnit.SECONDS)); // Read response // Application Data record = proxy.readFromServer(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToClient(record); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -1676,14 +1662,14 @@ public class SslBytesServerTest extends SslBytesTest // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(50)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(100)); + assertThat(sslFills.get(), Matchers.lessThan(50)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(100)); closeClient(client); } - @Test(timeout=60000) + @Test public void testServerShutdownOutputClientDoesNotCloseServerCloses() throws Exception { final SSLSocket client = newClient(); @@ -1691,7 +1677,7 @@ public class SslBytesServerTest extends SslBytesTest SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); byte[] data = new byte[3 * 1024]; Arrays.fill(data, (byte)'Y'); @@ -1709,35 +1695,35 @@ public class SslBytesServerTest extends SslBytesTest BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertNotNull(line); - Assert.assertTrue(line.startsWith("HTTP/1.1 200 ")); + assertNotNull(line); + assertTrue(line.startsWith("HTTP/1.1 200 ")); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) break; } - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); // Check client is at EOF - Assert.assertEquals(-1, client.getInputStream().read()); + assertEquals(-1, client.getInputStream().read()); // Client should close the socket, but let's hold it open. // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); // The server has shutdown the output since the client sent a Connection: close // but the client does not close, so the server must idle timeout the endPoint. TimeUnit.MILLISECONDS.sleep(idleTimeout + idleTimeout / 2); - Assert.assertFalse(serverEndPoint.get().isOpen()); + assertFalse(serverEndPoint.get().isOpen()); } - @Test(timeout=60000) + @Test public void testPlainText() throws Exception { final SSLSocket client = newClient(); @@ -1753,21 +1739,21 @@ public class SslBytesServerTest extends SslBytesTest // We expect that the server sends the TLS Alert. TLSRecord record = proxy.readFromServer(); - Assert.assertNotNull(record); - Assert.assertEquals(TLSRecord.Type.ALERT, record.getType()); + assertNotNull(record); + assertEquals(TLSRecord.Type.ALERT, record.getType()); record = proxy.readFromServer(); - Assert.assertNull(record); + assertNull(record); // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(20)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(20)); client.close(); } - @Test(timeout=60000) + @Test public void testRequestConcurrentWithIdleExpiration() throws Exception { final SSLSocket client = newClient(); @@ -1797,34 +1783,35 @@ public class SslBytesServerTest extends SslBytesTest SimpleProxy.AutomaticFlow automaticProxyFlow = proxy.startAutomaticFlow(); client.startHandshake(); - Assert.assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); + assertTrue(automaticProxyFlow.stop(5, TimeUnit.SECONDS)); - Assert.assertTrue(latch.await(idleTimeout * 2, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(idleTimeout * 2, TimeUnit.MILLISECONDS)); // Be sure that the server sent a SSL close alert TLSRecord record = proxy.readFromServer(); - Assert.assertNotNull(record); - Assert.assertEquals(TLSRecord.Type.ALERT, record.getType()); + assertNotNull(record); + assertEquals(TLSRecord.Type.ALERT, record.getType()); // Write the request to the server, to simulate a request // concurrent with the SSL close alert record = proxy.readFromClient(); - Assert.assertEquals(TLSRecord.Type.APPLICATION, record.getType()); + assertEquals(TLSRecord.Type.APPLICATION, record.getType()); proxy.flushToServer(record, 0); // Check that we did not spin TimeUnit.MILLISECONDS.sleep(500); - Assert.assertThat(sslFills.get(), Matchers.lessThan(20)); - Assert.assertThat(sslFlushes.get(), Matchers.lessThan(20)); - Assert.assertThat(httpParses.get(), Matchers.lessThan(50)); + assertThat(sslFills.get(), Matchers.lessThan(20)); + assertThat(sslFlushes.get(), Matchers.lessThan(20)); + assertThat(httpParses.get(), Matchers.lessThan(50)); record = proxy.readFromServer(); - Assert.assertNull(record); + assertNull(record); TimeUnit.MILLISECONDS.sleep(200); - Assert.assertThat(((Dumpable)server.getConnectors()[0]).dump(), Matchers.not(Matchers.containsString("SCEP@"))); + assertThat(((Dumpable)server.getConnectors()[0]).dump(), Matchers.not(Matchers.containsString("SCEP@"))); } + // TODO: Remove? We are on JDK 1.8+ now. private void assumeJavaVersionSupportsTLSRenegotiations() { // Due to a security bug, TLS renegotiations were disabled in JDK 1.6.0_19-21 @@ -1835,7 +1822,7 @@ public class SslBytesServerTest extends SslBytesTest if (matcher.matches()) { String nano = matcher.group(1); - Assume.assumeThat(Integer.parseInt(nano), Matchers.greaterThan(21)); + Assumptions.assumeTrue(Integer.parseInt(nano) > 21); } } @@ -1848,7 +1835,7 @@ public class SslBytesServerTest extends SslBytesTest { SSLSocket client = (SSLSocket)sslContext.getSocketFactory().createSocket("localhost", proxy.getPort()); client.setUseClientMode(true); - Assert.assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); + assertTrue(proxy.awaitClient(5, TimeUnit.SECONDS)); return client; } @@ -1861,16 +1848,16 @@ public class SslBytesServerTest extends SslBytesTest proxy.flushToServer(record); // Socket close record = proxy.readFromClient(); - Assert.assertNull(String.valueOf(record), record); + assertNull(record, String.valueOf(record)); proxy.flushToServer(record); // Socket close record = proxy.readFromServer(); if (record!=null) { - Assert.assertEquals(record.getType(),Type.ALERT); + assertEquals(record.getType(),Type.ALERT); record = proxy.readFromServer(); } - Assert.assertNull(record); + assertNull(record); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java index 0da45dd88e6..8e3de549a35 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslBytesTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client.ssl; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -33,17 +35,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.junit.Assert; -import org.junit.Rule; + public abstract class SslBytesTest { - @Rule - public TestTracker tracker = new TestTracker(); - protected final Logger logger = Log.getLogger(getClass()); public static class TLSRecord @@ -340,7 +337,7 @@ public abstract class SslBytesTest logger.debug("Automatic flow C <-- S finished"); } }); - Assert.assertTrue(startLatch.await(5, TimeUnit.SECONDS)); + assertTrue(startLatch.await(5, TimeUnit.SECONDS)); return new SslBytesServerTest.SimpleProxy.AutomaticFlow(stopLatch, clientToServer, serverToClient); } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java index 5c4a5a16aae..4293b831c6b 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/ssl/SslConnectionTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.client.ssl; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.File; import java.nio.ByteBuffer; @@ -34,8 +36,8 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class SslConnectionTest { @@ -81,14 +83,6 @@ public class SslConnectionTest // We want SSLHandshakeException to be thrown instead, because it is // handled better (it is an IOException) by the Connection code that // reads from the EndPoint. - try - { - sslEndPoint.fill(BufferUtil.EMPTY_BUFFER); - Assert.fail(); - } - catch (SSLHandshakeException x) - { - // Expected. - } + assertThrows(SSLHandshakeException.class, ()->sslEndPoint.fill(BufferUtil.EMPTY_BUFFER)); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java index b0855119e1e..9d3e42c5e0d 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/DeferredContentProviderTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client.util; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.Iterator; import java.util.NoSuchElementException; @@ -29,22 +33,21 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.eclipse.jetty.util.Callback; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class DeferredContentProviderTest { private ExecutorService executor; - @Before + @BeforeEach public void prepare() throws Exception { executor = Executors.newCachedThreadPool(); } - @After + @AfterEach public void dispose() throws Exception { executor.shutdownNow(); @@ -65,7 +68,7 @@ public class DeferredContentProviderTest } }); - Assert.assertTrue(await(task, 5, TimeUnit.SECONDS)); + assertTrue(await(task, 5, TimeUnit.SECONDS)); } @Test @@ -87,14 +90,14 @@ public class DeferredContentProviderTest }); // Wait until flush() blocks. - Assert.assertFalse(await(task, 1, TimeUnit.SECONDS)); + assertFalse(await(task, 1, TimeUnit.SECONDS)); // Consume the content and succeed the callback. iterator.next(); ((Callback)iterator).succeeded(); // Flush should return. - Assert.assertTrue(await(task, 5, TimeUnit.SECONDS)); + assertTrue(await(task, 5, TimeUnit.SECONDS)); } @Test @@ -115,7 +118,7 @@ public class DeferredContentProviderTest }); // Wait until flush() blocks. - Assert.assertTrue(await(task, 5, TimeUnit.SECONDS)); + assertTrue(await(task, 5, TimeUnit.SECONDS)); } @Test @@ -126,19 +129,11 @@ public class DeferredContentProviderTest provider.close(); - Assert.assertFalse(iterator.hasNext()); + assertFalse(iterator.hasNext()); - try - { - iterator.next(); - Assert.fail(); - } - catch (NoSuchElementException x) - { - // Expected - } + assertThrows(NoSuchElementException.class, ()->iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertFalse(iterator.hasNext()); } private boolean await(Future task, long time, TimeUnit unit) throws Exception diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java index cc55a1d78e3..b2e232cff41 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/InputStreamContentProviderTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.client.util; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -26,8 +31,8 @@ import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class InputStreamContentProviderTest { @@ -54,20 +59,13 @@ public class InputStreamContentProviderTest InputStreamContentProvider provider = new InputStreamContentProvider(stream); Iterator iterator = provider.iterator(); - Assert.assertNotNull(iterator); - Assert.assertFalse(iterator.hasNext()); + assertNotNull(iterator); + assertFalse(iterator.hasNext()); - try - { - iterator.next(); - Assert.fail(); - } - catch (NoSuchElementException expected) - { - } + assertThrows(NoSuchElementException.class, () -> iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertTrue(closed.get()); + assertFalse(iterator.hasNext()); + assertTrue(closed.get()); } @Test @@ -87,23 +85,16 @@ public class InputStreamContentProviderTest InputStreamContentProvider provider = new InputStreamContentProvider(stream); Iterator iterator = provider.iterator(); - Assert.assertNotNull(iterator); + assertNotNull(iterator); ByteBuffer buffer = iterator.next(); - Assert.assertNotNull(buffer); + assertNotNull(buffer); - try - { - iterator.next(); - Assert.fail(); - } - catch (NoSuchElementException expected) - { - } + assertThrows(NoSuchElementException.class, ()->iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertTrue(closed.get()); + assertFalse(iterator.hasNext()); + assertTrue(closed.get()); } @Test @@ -129,19 +120,12 @@ public class InputStreamContentProviderTest InputStreamContentProvider provider = new InputStreamContentProvider(stream); Iterator iterator = provider.iterator(); - Assert.assertNotNull(iterator); + assertNotNull(iterator); - try - { - iterator.next(); - Assert.fail(); - } - catch (NoSuchElementException expected) - { - } + assertThrows(NoSuchElementException.class, ()->iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertTrue(closed.get()); + assertFalse(iterator.hasNext()); + assertTrue(closed.get()); } @Test @@ -167,19 +151,12 @@ public class InputStreamContentProviderTest InputStreamContentProvider provider = new InputStreamContentProvider(stream); Iterator iterator = provider.iterator(); - Assert.assertNotNull(iterator); - Assert.assertTrue(iterator.hasNext()); + assertNotNull(iterator); + assertTrue(iterator.hasNext()); - try - { - iterator.next(); - Assert.fail(); - } - catch (NoSuchElementException expected) - { - } + assertThrows(NoSuchElementException.class, ()->iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertTrue(closed.get()); + assertFalse(iterator.hasNext()); + assertTrue(closed.get()); } } diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java index a0ca65696b0..d8c89eb0532 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/MultiPartContentProviderTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.client.util; +import static org.eclipse.jetty.toolchain.test.StackUtils.supply; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; @@ -51,56 +57,52 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class MultiPartContentProviderTest extends AbstractHttpClientServerTest { - public MultiPartContentProviderTest(SslContextFactory sslContextFactory) + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testEmptyMultiPart(Scenario scenario) throws Exception { - super(sslContextFactory); - } - - @Test - public void testEmptyMultiPart() throws Exception - { - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection parts = request.getParts(); - Assert.assertEquals(0, parts.size()); + assertEquals(0, parts.size()); } }); MultiPartContentProvider multiPart = new MultiPartContentProvider(); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testSimpleField() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testSimpleField(Scenario scenario) throws Exception { String name = "field"; String value = "value"; - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection parts = request.getParts(); - Assert.assertEquals(1, parts.size()); + assertEquals(1, parts.size()); Part part = parts.iterator().next(); - Assert.assertEquals(name, part.getName()); - Assert.assertEquals(value, IO.toString(part.getInputStream())); + assertEquals(name, part.getName()); + assertEquals(value, IO.toString(part.getInputStream())); } }); @@ -108,35 +110,36 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFieldPart(name, new StringContentProvider(value), null); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testFieldWithOverridenContentType() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFieldWithOverridenContentType(Scenario scenario) throws Exception { String name = "field"; String value = "\u00e8"; Charset encoding = StandardCharsets.ISO_8859_1; - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection parts = request.getParts(); - Assert.assertEquals(1, parts.size()); + assertEquals(1, parts.size()); Part part = parts.iterator().next(); - Assert.assertEquals(name, part.getName()); + assertEquals(name, part.getName()); String contentType = part.getContentType(); - Assert.assertNotNull(contentType); + assertNotNull(contentType); int equal = contentType.lastIndexOf('='); Charset charset = Charset.forName(contentType.substring(equal + 1)); - Assert.assertEquals(encoding, charset); - Assert.assertEquals(value, IO.toString(part.getInputStream(), charset)); + assertEquals(encoding, charset); + assertEquals(value, IO.toString(part.getInputStream(), charset)); } }); @@ -147,30 +150,31 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFieldPart(name, content, fields); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testFieldDeferred() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFieldDeferred(Scenario scenario) throws Exception { String name = "field"; byte[] data = "Hello, World".getBytes(StandardCharsets.US_ASCII); - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection parts = request.getParts(); - Assert.assertEquals(1, parts.size()); + assertEquals(1, parts.size()); Part part = parts.iterator().next(); - Assert.assertEquals(name, part.getName()); - Assert.assertEquals("text/plain", part.getContentType()); - Assert.assertArrayEquals(data, IO.readBytes(part.getInputStream())); + assertEquals(name, part.getName()); + assertEquals("text/plain", part.getContentType()); + assertArrayEquals(data, IO.readBytes(part.getInputStream())); } }); @@ -180,13 +184,13 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.close(); CountDownLatch responseLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(result -> { - Assert.assertTrue(String.valueOf(result.getFailure()), result.isSucceeded()); - Assert.assertEquals(200, result.getResponse().getStatus()); + assertTrue(result.isSucceeded(),supply(result.getFailure())); + assertEquals(200, result.getResponse().getStatus()); responseLatch.countDown(); }); @@ -197,30 +201,31 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest content.offer(ByteBuffer.wrap(data)); content.close(); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } - @Test - public void testFileFromInputStream() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFileFromInputStream(Scenario scenario) throws Exception { String name = "file"; String fileName = "upload.png"; String contentType = "image/png"; byte[] data = new byte[512]; new Random().nextBytes(data); - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection parts = request.getParts(); - Assert.assertEquals(1, parts.size()); + assertEquals(1, parts.size()); Part part = parts.iterator().next(); - Assert.assertEquals(name, part.getName()); - Assert.assertEquals(contentType, part.getContentType()); - Assert.assertEquals(fileName, part.getSubmittedFileName()); - Assert.assertEquals(data.length, part.getSize()); - Assert.assertArrayEquals(data, IO.readBytes(part.getInputStream())); + assertEquals(name, part.getName()); + assertEquals(contentType, part.getContentType()); + assertEquals(fileName, part.getSubmittedFileName()); + assertEquals(data.length, part.getSize()); + assertArrayEquals(data, IO.readBytes(part.getInputStream())); } }); @@ -240,17 +245,18 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart(name, fileName, content, fields); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(200, response.getStatus()); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertEquals(200, response.getStatus()); } - @Test - public void testFileFromPath() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFileFromPath(Scenario scenario) throws Exception { // Prepare a file to upload. String data = "multipart_test_\u20ac"; @@ -264,19 +270,19 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest String name = "file"; String contentType = "text/plain; charset=" + encoding.name(); - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Collection parts = request.getParts(); - Assert.assertEquals(1, parts.size()); + assertEquals(1, parts.size()); Part part = parts.iterator().next(); - Assert.assertEquals(name, part.getName()); - Assert.assertEquals(contentType, part.getContentType()); - Assert.assertEquals(tmpPath.getFileName().toString(), part.getSubmittedFileName()); - Assert.assertEquals(Files.size(tmpPath), part.getSize()); - Assert.assertEquals(data, IO.toString(part.getInputStream(), encoding)); + assertEquals(name, part.getName()); + assertEquals(contentType, part.getContentType()); + assertEquals(tmpPath.getFileName().toString(), part.getSubmittedFileName()); + assertEquals(Files.size(tmpPath), part.getSize()); + assertEquals(data, IO.toString(part.getInputStream(), encoding)); } }); @@ -286,18 +292,19 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart(name, tmpPath.getFileName().toString(), content, null); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); Files.delete(tmpPath); } - @Test - public void testFieldWithFile() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFieldWithFile(Scenario scenario) throws Exception { // Prepare a file to upload. byte[] data = new byte[1024]; @@ -316,13 +323,13 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest String contentType = "text/plain;charset=" + encoding.name(); String headerName = "foo"; String headerValue = "bar"; - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List parts = new ArrayList<>(request.getParts()); - Assert.assertEquals(2, parts.size()); + assertEquals(2, parts.size()); Part fieldPart = parts.get(0); Part filePart = parts.get(1); if (!field.equals(fieldPart.getName())) @@ -332,16 +339,16 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest fieldPart = swap; } - Assert.assertEquals(field, fieldPart.getName()); - Assert.assertEquals(contentType, fieldPart.getContentType()); - Assert.assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding)); - Assert.assertEquals(headerValue, fieldPart.getHeader(headerName)); + assertEquals(field, fieldPart.getName()); + assertEquals(contentType, fieldPart.getContentType()); + assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding)); + assertEquals(headerValue, fieldPart.getHeader(headerName)); - Assert.assertEquals(fileField, filePart.getName()); - Assert.assertEquals("application/octet-stream", filePart.getContentType()); - Assert.assertEquals(tmpPath.getFileName().toString(), filePart.getSubmittedFileName()); - Assert.assertEquals(Files.size(tmpPath), filePart.getSize()); - Assert.assertArrayEquals(data, IO.readBytes(filePart.getInputStream())); + assertEquals(fileField, filePart.getName()); + assertEquals("application/octet-stream", filePart.getContentType()); + assertEquals(tmpPath.getFileName().toString(), filePart.getSubmittedFileName()); + assertEquals(Files.size(tmpPath), filePart.getSize()); + assertArrayEquals(data, IO.readBytes(filePart.getInputStream())); } }); @@ -352,30 +359,31 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart(fileField, tmpPath.getFileName().toString(), new PathContentProvider(tmpPath), null); multiPart.close(); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); Files.delete(tmpPath); } - @Test - public void testFieldDeferredAndFileDeferred() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFieldDeferredAndFileDeferred(Scenario scenario) throws Exception { String value = "text"; Charset encoding = StandardCharsets.US_ASCII; byte[] fileData = new byte[1024]; new Random().nextBytes(fileData); - start(new AbstractMultiPartHandler() + start(scenario, new AbstractMultiPartHandler() { @Override protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List parts = new ArrayList<>(request.getParts()); - Assert.assertEquals(2, parts.size()); + assertEquals(2, parts.size()); Part fieldPart = parts.get(0); Part filePart = parts.get(1); if (!"field".equals(fieldPart.getName())) @@ -385,12 +393,12 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest fieldPart = swap; } - Assert.assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding)); + assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding)); - Assert.assertEquals("file", filePart.getName()); - Assert.assertEquals("application/octet-stream", filePart.getContentType()); - Assert.assertEquals("fileName", filePart.getSubmittedFileName()); - Assert.assertArrayEquals(fileData, IO.readBytes(filePart.getInputStream())); + assertEquals("file", filePart.getName()); + assertEquals("application/octet-stream", filePart.getContentType()); + assertEquals("fileName", filePart.getSubmittedFileName()); + assertArrayEquals(fileData, IO.readBytes(filePart.getInputStream())); } }); @@ -401,13 +409,13 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.addFilePart("file", "fileName", fileContent, null); CountDownLatch responseLatch = new CountDownLatch(1); client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(multiPart) .send(result -> { - Assert.assertTrue(String.valueOf(result.getFailure()), result.isSucceeded()); - Assert.assertEquals(200, result.getResponse().getStatus()); + assertTrue(result.isSucceeded(),supply(result.getFailure())); + assertEquals(200, result.getResponse().getStatus()); responseLatch.countDown(); }); @@ -425,7 +433,7 @@ public class MultiPartContentProviderTest extends AbstractHttpClientServerTest multiPart.close(); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } private static abstract class AbstractMultiPartHandler extends AbstractHandler diff --git a/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java b/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java index a57a2977530..7bdea0f738c 100644 --- a/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java +++ b/jetty-client/src/test/java/org/eclipse/jetty/client/util/TypedContentProviderTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.client.util; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -34,20 +38,15 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.Fields; import org.eclipse.jetty.util.IO; -import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; public class TypedContentProviderTest extends AbstractHttpClientServerTest { - public TypedContentProviderTest(SslContextFactory sslContextFactory) - { - super(sslContextFactory); - } - - @Test - public void testFormContentProvider() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFormContentProvider(Scenario scenario) throws Exception { final String name1 = "a"; final String value1 = "1"; @@ -55,19 +54,19 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest final String value2 = "2"; final String value3 = "\u20AC"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals("POST", request.getMethod()); - Assert.assertEquals(MimeTypes.Type.FORM_ENCODED.asString(), request.getContentType()); - Assert.assertEquals(value1, request.getParameter(name1)); + assertEquals("POST", request.getMethod()); + assertEquals(MimeTypes.Type.FORM_ENCODED.asString(), request.getContentType()); + assertEquals(value1, request.getParameter(name1)); String[] values = request.getParameterValues(name2); - Assert.assertNotNull(values); - Assert.assertEquals(2, values.length); - Assert.assertThat(values, Matchers.arrayContainingInAnyOrder(value2, value3)); + assertNotNull(values); + assertEquals(2, values.length); + assertThat(values, Matchers.arrayContainingInAnyOrder(value2, value3)); } }); @@ -75,13 +74,14 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest fields.put(name1, value1); fields.add(name2, value2); fields.add(name2, value3); - ContentResponse response = client.FORM(scheme + "://localhost:" + connector.getLocalPort(), fields); + ContentResponse response = client.FORM(scenario.getScheme() + "://localhost:" + connector.getLocalPort(), fields); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testFormContentProviderWithDifferentContentType() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testFormContentProviderWithDifferentContentType(Scenario scenario) throws Exception { final String name1 = "a"; final String value1 = "1"; @@ -93,50 +93,51 @@ public class TypedContentProviderTest extends AbstractHttpClientServerTest final String content = FormContentProvider.convert(fields); final String contentType = "text/plain;charset=UTF-8"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals("POST", request.getMethod()); - Assert.assertEquals(contentType, request.getContentType()); - Assert.assertEquals(content, IO.toString(request.getInputStream())); + assertEquals("POST", request.getMethod()); + assertEquals(contentType, request.getContentType()); + assertEquals(content, IO.toString(request.getInputStream())); } }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .method(HttpMethod.POST) .content(new FormContentProvider(fields)) .header(HttpHeader.CONTENT_TYPE, contentType) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } - @Test - public void testTypedContentProviderWithNoContentType() throws Exception + @ParameterizedTest + @ArgumentsSource(ScenarioProvider.class) + public void testTypedContentProviderWithNoContentType(Scenario scenario) throws Exception { final String content = "data"; - start(new AbstractHandler() + start(scenario, new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals("GET", request.getMethod()); - Assert.assertNotNull(request.getContentType()); - Assert.assertEquals(content, IO.toString(request.getInputStream())); + assertEquals("GET", request.getMethod()); + assertNotNull(request.getContentType()); + assertEquals(content, IO.toString(request.getInputStream())); } }); ContentResponse response = client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) + .scheme(scenario.getScheme()) .content(new StringContentProvider(null, content, StandardCharsets.UTF_8)) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java index 0555561a29c..354ba79963c 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCyclePathCollector.java @@ -18,11 +18,13 @@ package org.eclipse.jetty.deploy; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.List; import org.eclipse.jetty.deploy.graph.Node; -import org.junit.Assert; + /** * Binds to all lifecycle nodes, and tracks the order of the lifecycle nodes for testing purposes. @@ -69,12 +71,12 @@ public class AppLifeCyclePathCollector implements AppLifeCycle.Binding System.out.println(path.getName()); } - Assert.assertEquals(msg + " / count",expectedOrder.size(),actualOrder.size()); + assertEquals(expectedOrder.size(),actualOrder.size(),msg + " / count"); } for (int i = 0, n = expectedOrder.size(); i < n; i++) { - Assert.assertEquals(msg + "[" + i + "]",expectedOrder.get(i),actualOrder.get(i).getName()); + assertEquals(expectedOrder.get(i),actualOrder.get(i).getName(),msg + "[" + i + "]"); } } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java index 0ca949c548d..3a62b1c734c 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/AppLifeCycleTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.deploy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -26,18 +29,18 @@ import java.util.List; import org.eclipse.jetty.deploy.graph.GraphOutputDot; import org.eclipse.jetty.deploy.graph.Node; import org.eclipse.jetty.deploy.graph.Path; -import org.eclipse.jetty.toolchain.test.TestingDir; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; /** * Just an overly picky test case to validate the potential paths. */ +@ExtendWith(WorkDirExtension.class) public class AppLifeCycleTest { - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; private void assertNoPath(String from, String to) { @@ -50,7 +53,7 @@ public class AppLifeCycleTest Node toNode = lifecycle.getNodeByName(to); Path actual = lifecycle.getPath(fromNode,toNode); String msg = "LifeCycle path from " + from + " to " + to; - Assert.assertNotNull(msg + " should never be null",actual); + assertNotNull(actual,msg + " should never be null"); if (expected.size() != actual.nodes()) { @@ -67,12 +70,12 @@ public class AppLifeCycleTest System.out.println(path.getName()); } - Assert.assertEquals(msg + " / count",expected.size(),actual.nodes()); + assertEquals(expected.size(),actual.nodes(),msg + " / count"); } for (int i = 0, n = expected.size(); i < n; i++) { - Assert.assertEquals(msg + "[" + i + "]",expected.get(i),actual.getNode(i).getName()); + assertEquals(expected.get(i),actual.getNode(i).getName(),msg + "[" + i + "]"); } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java index 140f0dcd72e..728c1555e08 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerLifeCyclePathTest.java @@ -27,7 +27,7 @@ import javax.management.ObjectName; import org.eclipse.jetty.jmx.MBeanContainer; import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class DeploymentManagerLifeCyclePathTest { diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java index 31e6345acff..106ab164354 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/DeploymentManagerTest.java @@ -18,20 +18,23 @@ package org.eclipse.jetty.deploy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.util.Collection; import java.util.Set; import org.eclipse.jetty.deploy.test.XmlConfiguredJetty; import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.toolchain.test.TestingDir; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +@ExtendWith(WorkDirExtension.class) public class DeploymentManagerTest { - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; @Test public void testReceiveApp() throws Exception @@ -53,13 +56,13 @@ public class DeploymentManagerTest // Test app tracking Collection apps = depman.getApps(); - Assert.assertNotNull("Should never be null",apps); - Assert.assertEquals("Expected App Count",1,apps.size()); + assertNotNull(apps, "Should never be null"); + assertEquals(1, apps.size(), "Expected App Count"); // Test app get App actual = depman.getAppByOriginId("mock-foo-webapp-1.war"); - Assert.assertNotNull("Should have gotten app (by id)",actual); - Assert.assertEquals("Should have gotten app (by id)","mock-foo-webapp-1.war",actual.getOriginId()); + assertNotNull(actual, "Should have gotten app (by id)"); + assertEquals("mock-foo-webapp-1.war", actual.getOriginId(), "Should have gotten app (by id)"); } @Test @@ -70,12 +73,12 @@ public class DeploymentManagerTest depman.addLifeCycleBinding(pathtracker); Set allbindings = depman.getLifeCycle().getBindings(); - Assert.assertNotNull("All Bindings should never be null",allbindings); - Assert.assertEquals("All Bindings.size",1,allbindings.size()); + assertNotNull(allbindings, "All Bindings should never be null"); + assertEquals(1, allbindings.size(), "All Bindings.size"); Set deploybindings = depman.getLifeCycle().getBindings("deploying"); - Assert.assertNotNull("'deploying' Bindings should not be null",deploybindings); - Assert.assertEquals("'deploying' Bindings.size",1,deploybindings.size()); + assertNotNull(deploybindings, "'deploying' Bindings should not be null"); + assertEquals(1, deploybindings.size(), "'deploying' Bindings.size"); } @Test @@ -84,7 +87,7 @@ public class DeploymentManagerTest XmlConfiguredJetty jetty = null; try { - jetty = new XmlConfiguredJetty(testdir); + jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir()); jetty.addConfiguration("jetty.xml"); jetty.addConfiguration("jetty-http.xml"); jetty.addConfiguration("jetty-deploymgr-contexts.xml"); diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java index fec526fc701..8b66fdf3b3d 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/bindings/GlobalWebappConfigBindingTest.java @@ -18,10 +18,12 @@ package org.eclipse.jetty.deploy.bindings; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.isIn; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.File; import java.util.List; @@ -31,27 +33,27 @@ import org.eclipse.jetty.deploy.test.XmlConfiguredJetty; import org.eclipse.jetty.toolchain.test.IO; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.toolchain.test.PathAssert; -import org.eclipse.jetty.toolchain.test.TestingDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.eclipse.jetty.webapp.WebAppContext; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; /** * Tests {@link ScanningAppProvider} as it starts up for the first time. */ +@ExtendWith(WorkDirExtension.class) public class GlobalWebappConfigBindingTest { - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; private static XmlConfiguredJetty jetty; - @Before + @BeforeEach public void setupEnvironment() throws Exception { - jetty = new XmlConfiguredJetty(testdir); + jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir()); jetty.addConfiguration("jetty.xml"); jetty.addConfiguration("jetty-http.xml"); @@ -61,7 +63,7 @@ public class GlobalWebappConfigBindingTest } - @After + @AfterEach public void teardownEnvironment() throws Exception { // Stop jetty. @@ -82,17 +84,17 @@ public class GlobalWebappConfigBindingTest jetty.start(); List contexts = jetty.getWebAppContexts(); - Assert.assertThat("List of Contexts", contexts, hasSize(greaterThan(0))); + assertThat("List of Contexts", contexts, hasSize(greaterThan(0))); WebAppContext context = contexts.get(0); - Assert.assertNotNull("Context should not be null",context); + assertNotNull(context, "Context should not be null"); String defaultClasses[] = context.getDefaultServerClasses(); String currentClasses[] = context.getServerClasses(); String addedClass = "org.eclipse.foo."; // What was added by the binding - Assert.assertThat("Default Server Classes",addedClass,not(isIn(defaultClasses))); - Assert.assertThat("Current Server Classes",addedClass,isIn(currentClasses)); + assertThat("Default Server Classes",addedClass,not(isIn(defaultClasses))); + assertThat("Current Server Classes",addedClass,isIn(currentClasses)); // boolean jndiPackage = false; @@ -106,6 +108,6 @@ public class GlobalWebappConfigBindingTest // } // } // - // Assert.assertFalse(jndiPackage); + // assertFalse(jndiPackage); } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java index 7afe2dcc7ba..2a4399d76a6 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/graph/GraphTest.java @@ -18,8 +18,10 @@ package org.eclipse.jetty.deploy.graph; -import org.junit.Assert; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; public class GraphTest { @@ -36,19 +38,19 @@ public class GraphTest Path path = new Path(); - Assert.assertEquals(0, path.nodes()); - Assert.assertEquals(null,path.firstNode()); - Assert.assertEquals(null,path.lastNode()); + assertEquals(0, path.nodes()); + assertEquals(null,path.firstNode()); + assertEquals(null,path.lastNode()); path.add(new Edge(nodeA ,nodeB)); - Assert.assertEquals(2,path.nodes()); - Assert.assertEquals(nodeA,path.firstNode()); - Assert.assertEquals(nodeB,path.lastNode()); + assertEquals(2,path.nodes()); + assertEquals(nodeA,path.firstNode()); + assertEquals(nodeB,path.lastNode()); path.add(new Edge(nodeB ,nodeC)); - Assert.assertEquals(3,path.nodes()); - Assert.assertEquals(nodeA,path.firstNode()); - Assert.assertEquals(nodeC,path.lastNode()); + assertEquals(3,path.nodes()); + assertEquals(nodeA,path.firstNode()); + assertEquals(nodeC,path.lastNode()); } @Test @@ -56,10 +58,10 @@ public class GraphTest { Graph graph = new Graph(); graph.addNode(nodeA); - Assert.assertEquals(1,graph.getNodes().size()); - Assert.assertEquals(0,graph.getEdges().size()); + assertEquals(1,graph.getNodes().size()); + assertEquals(0,graph.getEdges().size()); Path path = graph.getPath(nodeA,nodeA); - Assert.assertEquals(0,path.nodes()); + assertEquals(0,path.nodes()); } @Test @@ -67,10 +69,10 @@ public class GraphTest { Graph graph = new Graph(); graph.addEdge(new Edge(nodeA,nodeB)); - Assert.assertEquals(2,graph.getNodes().size()); - Assert.assertEquals(1,graph.getEdges().size()); + assertEquals(2,graph.getNodes().size()); + assertEquals(1,graph.getEdges().size()); Path path = graph.getPath(nodeA,nodeB); - Assert.assertEquals(2,path.nodes()); + assertEquals(2,path.nodes()); } @Test @@ -80,14 +82,14 @@ public class GraphTest graph.addEdge(new Edge(nodeA,nodeB)); graph.addEdge(new Edge(nodeA,nodeC)); graph.addEdge(new Edge(nodeB,nodeC)); - Assert.assertEquals(3,graph.getNodes().size()); - Assert.assertEquals(3,graph.getEdges().size()); + assertEquals(3,graph.getNodes().size()); + assertEquals(3,graph.getEdges().size()); Path path = graph.getPath(nodeA,nodeB); - Assert.assertEquals(2,path.nodes()); + assertEquals(2,path.nodes()); path = graph.getPath(nodeA,nodeC); - Assert.assertEquals(2,path.nodes()); + assertEquals(2,path.nodes()); path = graph.getPath(nodeB,nodeC); - Assert.assertEquals(2,path.nodes()); + assertEquals(2,path.nodes()); } @@ -99,13 +101,13 @@ public class GraphTest graph.addEdge(new Edge(nodeB,nodeC)); graph.addEdge(new Edge(nodeA,nodeD)); graph.addEdge(new Edge(nodeD,nodeC)); - Assert.assertEquals(4,graph.getNodes().size()); - Assert.assertEquals(4,graph.getEdges().size()); + assertEquals(4,graph.getNodes().size()); + assertEquals(4,graph.getEdges().size()); Path path = graph.getPath(nodeA,nodeC); - Assert.assertEquals(3,path.nodes()); + assertEquals(3,path.nodes()); path = graph.getPath(nodeC,nodeA); - Assert.assertEquals(null,path); + assertEquals(null,path); } @@ -117,19 +119,19 @@ public class GraphTest graph.addEdge(new Edge(nodeB,nodeC)); graph.addEdge(new Edge(nodeC,nodeD)); graph.addEdge(new Edge(nodeD,nodeA)); - Assert.assertEquals(4,graph.getNodes().size()); - Assert.assertEquals(4,graph.getEdges().size()); + assertEquals(4,graph.getNodes().size()); + assertEquals(4,graph.getEdges().size()); Path path = graph.getPath(nodeA,nodeB); - Assert.assertEquals(2,path.nodes()); + assertEquals(2,path.nodes()); path = graph.getPath(nodeA,nodeC); - Assert.assertEquals(3,path.nodes()); + assertEquals(3,path.nodes()); path = graph.getPath(nodeA,nodeD); - Assert.assertEquals(4,path.nodes()); + assertEquals(4,path.nodes()); graph.addNode(nodeE); path = graph.getPath(nodeA,nodeE); - Assert.assertEquals(null,path); + assertEquals(null,path); } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java index c18f9a8243d..5d38c2770a2 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderRuntimeUpdatesTest.java @@ -18,49 +18,47 @@ package org.eclipse.jetty.deploy.providers; +import static org.junit.jupiter.api.condition.OS.WINDOWS; + import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.jetty.deploy.AppProvider; import org.eclipse.jetty.deploy.DeploymentManager; import org.eclipse.jetty.deploy.test.XmlConfiguredJetty; -import org.eclipse.jetty.toolchain.test.OS; -import org.eclipse.jetty.toolchain.test.TestTracker; -import org.eclipse.jetty.toolchain.test.TestingDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.eclipse.jetty.util.Scanner; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.extension.ExtendWith; /** * Similar in scope to {@link ScanningAppProviderStartupTest}, except is concerned with the modification of existing * deployed webapps due to incoming changes identified by the {@link ScanningAppProvider}. */ +@ExtendWith(WorkDirExtension.class) public class ScanningAppProviderRuntimeUpdatesTest { private static final Logger LOG = Log.getLogger(ScanningAppProviderRuntimeUpdatesTest.class); - @Rule - public TestTracker tracker = new TestTracker(); - - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; private static XmlConfiguredJetty jetty; private final AtomicInteger _scans = new AtomicInteger(); private int _providers; - @Before + @BeforeEach public void setupEnvironment() throws Exception { testdir.ensureEmpty(); Resource.setDefaultUseCaches(false); - jetty = new XmlConfiguredJetty(testdir); + jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir()); jetty.addConfiguration("jetty.xml"); jetty.addConfiguration("jetty-http.xml"); jetty.addConfiguration("jetty-deploymgr-contexts.xml"); @@ -91,7 +89,7 @@ public class ScanningAppProviderRuntimeUpdatesTest } - @After + @AfterEach public void teardownEnvironment() throws Exception { // Stop jetty. @@ -160,14 +158,9 @@ public class ScanningAppProviderRuntimeUpdatesTest * @throws Exception on test failure */ @Test + @DisabledOnOs(WINDOWS) // This test will not work on Windows as second war file would, not be written over the first one because of a file lock public void testAfterStartupThenUpdateContext() throws Exception { - // This test will not work on Windows as second war file would - // not be written over the first one because of a file lock - Assume.assumeTrue(!OS.IS_WINDOWS); - Assume.assumeTrue(!OS.IS_OSX); // build server has issues with finding itself apparently - - jetty.copyWebapp("foo-webapp-1.war","foo.war"); jetty.copyWebapp("foo.xml","foo.xml"); diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderStartupTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderStartupTest.java index 7c2a756ed0b..14e01e7d146 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderStartupTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/ScanningAppProviderStartupTest.java @@ -19,25 +19,26 @@ package org.eclipse.jetty.deploy.providers; import org.eclipse.jetty.deploy.test.XmlConfiguredJetty; -import org.eclipse.jetty.toolchain.test.TestingDir; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; /** * Tests {@link ScanningAppProvider} as it starts up for the first time. */ +@ExtendWith(WorkDirExtension.class) public class ScanningAppProviderStartupTest { - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; private static XmlConfiguredJetty jetty; - @Before + @BeforeEach public void setupEnvironment() throws Exception { - jetty = new XmlConfiguredJetty(testdir); + jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir()); jetty.addConfiguration("jetty.xml"); jetty.addConfiguration("jetty-http.xml"); jetty.addConfiguration("jetty-deploymgr-contexts.xml"); @@ -53,7 +54,7 @@ public class ScanningAppProviderStartupTest jetty.start(); } - @After + @AfterEach public void teardownEnvironment() throws Exception { // Stop jetty. diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/WebAppProviderTest.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/WebAppProviderTest.java index 093ad49bd5d..7993b665644 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/WebAppProviderTest.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/providers/WebAppProviderTest.java @@ -18,8 +18,9 @@ package org.eclipse.jetty.deploy.providers; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; import java.nio.file.FileSystemException; @@ -29,26 +30,26 @@ import java.util.Arrays; import org.eclipse.jetty.deploy.test.XmlConfiguredJetty; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.TestingDir; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; -@Ignore("See issue #1200") +@Disabled("See issue #1200") +@ExtendWith(WorkDirExtension.class) public class WebAppProviderTest { - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; private static XmlConfiguredJetty jetty; private boolean symlinkSupported = false; - @Before + @BeforeEach public void setupEnvironment() throws Exception { - jetty = new XmlConfiguredJetty(testdir); + jetty = new XmlConfiguredJetty(testdir.getEmptyPathDir()); jetty.addConfiguration("jetty.xml"); jetty.addConfiguration("jetty-http.xml"); jetty.addConfiguration("jetty-deploy-wars.xml"); @@ -77,7 +78,7 @@ public class WebAppProviderTest jetty.start(); } - @After + @AfterEach public void teardownEnvironment() throws Exception { // Stop jetty. @@ -97,7 +98,7 @@ public class WebAppProviderTest assertDirNotExists("root of work directory",workDir,"jsp"); // Test for correct behaviour - assertTrue("Should have generated directory in work directory: " + workDir,hasJettyGeneratedPath(workDir,"foo.war")); + assertTrue(hasJettyGeneratedPath(workDir,"foo.war"),"Should have generated directory in work directory: " + workDir); } @Test @@ -107,15 +108,15 @@ public class WebAppProviderTest // Check for path File barLink = jetty.getJettyDir("webapps/bar.war"); - assertTrue("bar.war link exists: " + barLink.toString(), barLink.exists()); - assertTrue("bar.war link isFile: " + barLink.toString(), barLink.isFile()); + assertTrue(barLink.exists(),"bar.war link exists: " + barLink.toString()); + assertTrue(barLink.isFile(), "bar.war link isFile: " + barLink.toString()); // Check Server for expected Handlers jetty.assertWebAppContextsExists("/bar", "/foo"); // Test for expected work/temp directory behaviour File workDir = jetty.getJettyDir("workish"); - assertTrue("Should have generated directory in work directory: " + workDir,hasJettyGeneratedPath(workDir,"bar.war")); + assertTrue(hasJettyGeneratedPath(workDir,"bar.war"),"Should have generated directory in work directory: " + workDir); } private static boolean hasJettyGeneratedPath(File basedir, String expectedWarFilename) @@ -139,6 +140,6 @@ public class WebAppProviderTest public static void assertDirNotExists(String msg, File workDir, String subdir) { File dir = new File(workDir,subdir); - Assert.assertFalse("Should not have " + subdir + " in " + msg + " - " + workDir,dir.exists()); + assertFalse(dir.exists(),"Should not have " + subdir + " in " + msg + " - " + workDir); } } diff --git a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java index d01e839b661..9b5a05cf26e 100644 --- a/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java +++ b/jetty-deploy/src/test/java/org/eclipse/jetty/deploy/test/XmlConfiguredJetty.java @@ -18,7 +18,12 @@ package org.eclipse.jetty.deploy.test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileOutputStream; @@ -31,6 +36,7 @@ import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -45,13 +51,12 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.toolchain.test.PathAssert; -import org.eclipse.jetty.toolchain.test.TestingDir; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; -import org.junit.Assert; + /** * Allows for setting up a Jetty server for testing based on XML configuration files. @@ -65,12 +70,12 @@ public class XmlConfiguredJetty private String _scheme = HttpScheme.HTTP.asString(); private File _jettyHome; - public XmlConfiguredJetty(TestingDir testdir) throws IOException + public XmlConfiguredJetty(Path testdir) throws IOException { _xmlConfigurations = new ArrayList<>(); Properties properties = new Properties(); - String jettyHomeBase = testdir.getPath().toString(); + String jettyHomeBase = testdir.toString(); // Ensure we have a new (pristene) directory to work with. int idx = 0; _jettyHome = new File(jettyHomeBase + "#" + idx); @@ -156,7 +161,7 @@ public class XmlConfiguredJetty { System.err.println("WebAppContext should not exist:\n" + context); } - Assert.assertEquals("Contexts.size",0,contexts.size()); + assertEquals(0, contexts.size(), "Contexts.size"); } } @@ -181,9 +186,8 @@ public class XmlConfiguredJetty public void assertResponseContains(String path, String needle) throws IOException { - // System.err.println("Issuing request to " + path); String content = getResponse(path); - Assert.assertTrue("Content should contain <" + needle + ">, instead got <" + content + ">",content.contains(needle)); + assertThat(content, containsString(needle)); } public void assertWebAppContextsExists(String... expectedContextPaths) @@ -201,7 +205,7 @@ public class XmlConfiguredJetty { System.err.printf("%s ## %s%n",context.getContextPath(),context); } - Assert.assertEquals("Contexts.size",expectedContextPaths.length,contexts.size()); + assertEquals(expectedContextPaths.length, contexts.size(), "Contexts.size"); } for (String expectedPath : expectedContextPaths) @@ -212,11 +216,11 @@ public class XmlConfiguredJetty if (context.getContextPath().equals(expectedPath)) { found = true; - Assert.assertThat("Context[" + context.getContextPath() + "].state", context.getState(), is("STARTED")); + assertThat("Context[" + context.getContextPath() + "].state", context.getState(), is("STARTED")); break; } } - Assert.assertTrue("Did not find Expected Context Path " + expectedPath,found); + assertTrue(found,"Did not find Expected Context Path " + expectedPath); } } @@ -258,12 +262,11 @@ public class XmlConfiguredJetty if (file.isDirectory() && file.getAbsolutePath().contains("target" + File.separator)) { deleteContents(file); - Assert.assertTrue("Delete failed: " + file.getAbsolutePath(),file.delete()); + assertTrue(file.delete(),"Delete failed: " + file.getAbsolutePath()); } else { - System.err.printf("Delete (file) %s%n",file); - Assert.assertTrue("Delete failed: " + file.getAbsolutePath(),file.delete()); + assertTrue(file.delete(),"Delete failed: " + file.getAbsolutePath()); } } } @@ -358,7 +361,7 @@ public class XmlConfiguredJetty throw new Exception("Load failed to configure a " + Server.class.getName()); } - Assert.assertEquals("Server load count",1,serverCount); + assertEquals(1, serverCount, "Server load count"); this._server = foundServer; this._server.setStopTimeout(10); @@ -370,7 +373,7 @@ public class XmlConfiguredJetty File contextFile = new File(destDir,name); if (contextFile.exists()) { - Assert.assertTrue("Delete of Webapp file: " + contextFile.getAbsolutePath(),contextFile.delete()); + assertTrue(contextFile.delete(),"Delete of Webapp file: " + contextFile.getAbsolutePath()); } } @@ -386,7 +389,7 @@ public class XmlConfiguredJetty public void start() throws Exception { - Assert.assertNotNull("Server should not be null (failed load?)",_server); + assertNotNull(_server, "Server should not be null (failed load?)"); _server.start(); @@ -403,7 +406,7 @@ public class XmlConfiguredJetty } } - Assert.assertTrue("Server Port is between 1 and 65535. Actually <" + _serverPort + ">",(1 <= this._serverPort) && (this._serverPort <= 65535)); + assertTrue((1 <= this._serverPort) && (this._serverPort <= 65535),"Server Port is between 1 and 65535. Was actually <" + _serverPort + ">"); // Uncomment to have server start and continue to run (without exiting) // System.err.printf("Listening to port %d%n",this.serverPort); diff --git a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java index eb462475ba2..02fa56926ca 100644 --- a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java +++ b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/generator/ClientGeneratorTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.fcgi.generator; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; @@ -28,8 +31,8 @@ import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ClientGeneratorTest { @@ -81,24 +84,24 @@ public class ClientGeneratorTest @Override public void onHeader(int request, HttpField field) { - Assert.assertEquals(id, request); + assertEquals(id, request); switch (field.getName()) { case shortShortName: - Assert.assertEquals(shortShortValue, field.getValue()); + assertEquals(shortShortValue, field.getValue()); params.set(params.get() * primes[0]); break; case shortLongName: - Assert.assertEquals(shortLongValue, field.getValue()); + assertEquals(shortLongValue, field.getValue()); params.set(params.get() * primes[1]); break; case longShortName: - Assert.assertEquals(longShortValue, field.getValue()); + assertEquals(longShortValue, field.getValue()); params.set(params.get() * primes[2]); break; default: - Assert.assertEquals(longLongName, field.getName()); - Assert.assertEquals(longLongValue, field.getValue()); + assertEquals(longLongName, field.getName()); + assertEquals(longLongValue, field.getValue()); params.set(params.get() * primes[3]); break; } @@ -107,7 +110,7 @@ public class ClientGeneratorTest @Override public void onHeaders(int request) { - Assert.assertEquals(id, request); + assertEquals(id, request); params.set(params.get() * primes[4]); } }); @@ -115,10 +118,10 @@ public class ClientGeneratorTest for (ByteBuffer buffer : result.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } - Assert.assertEquals(value, params.get()); + assertEquals(value, params.get()); // Parse again byte by byte params.set(1); @@ -127,10 +130,10 @@ public class ClientGeneratorTest buffer.flip(); while (buffer.hasRemaining()) parser.parse(ByteBuffer.wrap(new byte[]{buffer.get()})); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } - Assert.assertEquals(value, params.get()); + assertEquals(value, params.get()); } @Test @@ -160,7 +163,7 @@ public class ClientGeneratorTest @Override public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer) { - Assert.assertEquals(id, request); + assertEquals(id, request); totalLength.addAndGet(buffer.remaining()); return false; } @@ -168,15 +171,15 @@ public class ClientGeneratorTest @Override public void onEnd(int request) { - Assert.assertEquals(id, request); - Assert.assertEquals(contentLength, totalLength.get()); + assertEquals(id, request); + assertEquals(contentLength, totalLength.get()); } }); for (ByteBuffer buffer : result.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } // Parse again one byte at a time @@ -185,7 +188,7 @@ public class ClientGeneratorTest buffer.flip(); while (buffer.hasRemaining()) parser.parse(ByteBuffer.wrap(new byte[]{buffer.get()})); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } } } diff --git a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java index 32384137300..65f4b32f4c3 100644 --- a/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java +++ b/jetty-fcgi/fcgi-client/src/test/java/org/eclipse/jetty/fcgi/parser/ClientParserTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.fcgi.parser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -29,8 +33,8 @@ import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ClientParserTest { @@ -64,19 +68,19 @@ public class ClientParserTest @Override public void onBegin(int request, int code, String reason) { - Assert.assertEquals(statusCode, code); - Assert.assertEquals(statusMessage, reason); + assertEquals(statusCode, code); + assertEquals(statusMessage, reason); params.set(params.get() * primes[0]); } @Override public void onHeader(int request, HttpField field) { - Assert.assertEquals(id, request); + assertEquals(id, request); switch (field.getName()) { case contentTypeName: - Assert.assertEquals(contentTypeValue, field.getValue()); + assertEquals(contentTypeValue, field.getValue()); params.set(params.get() * primes[1]); break; default: @@ -87,7 +91,7 @@ public class ClientParserTest @Override public void onHeaders(int request) { - Assert.assertEquals(id, request); + assertEquals(id, request); params.set(params.get() * primes[2]); } }); @@ -95,10 +99,10 @@ public class ClientParserTest for (ByteBuffer buffer : result.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } - Assert.assertEquals(value, params.get()); + assertEquals(value, params.get()); } @Test @@ -119,7 +123,7 @@ public class ClientParserTest @Override public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer) { - Assert.assertEquals(id, request); + assertEquals(id, request); verifier.addAndGet(2); return false; } @@ -127,7 +131,7 @@ public class ClientParserTest @Override public void onEnd(int request) { - Assert.assertEquals(id, request); + assertEquals(id, request); verifier.addAndGet(3); } }); @@ -135,15 +139,15 @@ public class ClientParserTest for (ByteBuffer buffer : result1.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } for (ByteBuffer buffer : result2.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } - Assert.assertEquals(3, verifier.get()); + assertEquals(3, verifier.get()); } @Test @@ -171,8 +175,8 @@ public class ClientParserTest @Override public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer) { - Assert.assertEquals(id, request); - Assert.assertEquals(contentLength, buffer.remaining()); + assertEquals(id, request); + assertEquals(contentLength, buffer.remaining()); verifier.addAndGet(2); return false; } @@ -180,7 +184,7 @@ public class ClientParserTest @Override public void onEnd(int request) { - Assert.assertEquals(id, request); + assertEquals(id, request); verifier.addAndGet(3); } }); @@ -188,15 +192,15 @@ public class ClientParserTest for (ByteBuffer buffer : result1.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } for (ByteBuffer buffer : result2.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } - Assert.assertEquals(5, verifier.get()); + assertEquals(5, verifier.get()); } @Test @@ -225,7 +229,7 @@ public class ClientParserTest @Override public boolean onContent(int request, FCGI.StreamType stream, ByteBuffer buffer) { - Assert.assertEquals(id, request); + assertEquals(id, request); totalLength.addAndGet(buffer.remaining()); return false; } @@ -233,8 +237,8 @@ public class ClientParserTest @Override public void onEnd(int request) { - Assert.assertEquals(id, request); - Assert.assertEquals(contentLength, totalLength.get()); + assertEquals(id, request); + assertEquals(contentLength, totalLength.get()); verifier.set(true); } }); @@ -242,14 +246,14 @@ public class ClientParserTest for (ByteBuffer buffer : result1.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } for (ByteBuffer buffer : result2.getByteBuffers()) { parser.parse(buffer); - Assert.assertFalse(buffer.hasRemaining()); + assertFalse(buffer.hasRemaining()); } - Assert.assertTrue(verifier.get()); + assertTrue(verifier.get()); } } diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java index f212c832a37..ab0162991ad 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/AbstractHttpClientServerTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.fcgi.server; +import static org.hamcrest.MatcherAssert.assertThat; + import java.util.concurrent.atomic.AtomicLong; import org.eclipse.jetty.client.HttpClient; @@ -32,20 +34,14 @@ import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.LeakDetector; import org.eclipse.jetty.util.ProcessorUtils; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Rule; - -import static org.junit.Assert.assertThat; +import org.junit.jupiter.api.AfterEach; public abstract class AbstractHttpClientServerTest { - @Rule - public final TestTracker tracker = new TestTracker(); private LeakTrackingByteBufferPool serverBufferPool; protected ByteBufferPool clientBufferPool; private final AtomicLong connectionLeaks = new AtomicLong(); @@ -88,7 +84,7 @@ public abstract class AbstractHttpClientServerTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { System.gc(); diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java index 1f69cb92bbf..dd1a680eebc 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/ExternalFastCGIServerTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.fcgi.server; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -27,14 +29,13 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.fcgi.client.http.HttpClientTransportOverFCGI; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class ExternalFastCGIServerTest { @Test - @Ignore("Relies on an external server") + @Disabled("Relies on an external server") public void testExternalFastCGIServer() throws Exception { // Assume a FastCGI server is listening on localhost:9000 @@ -47,7 +48,7 @@ public class ExternalFastCGIServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); Path responseFile = Paths.get(System.getProperty("java.io.tmpdir"), "fcgi_response.html"); Files.write(responseFile, response.getContent(), StandardOpenOption.CREATE, StandardOpenOption.WRITE); diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java index c11d94e05d5..bd661438d38 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/HttpClientTest.java @@ -18,6 +18,14 @@ package org.eclipse.jetty.fcgi.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.EOFException; import java.io.IOException; import java.net.URI; @@ -49,11 +57,11 @@ import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.io.MappedByteBufferPool; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.IO; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.log.StacklessLogging; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; public class HttpClientTest extends AbstractHttpClientServerTest { @@ -65,8 +73,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest for (int i = 0; i < 2; ++i) { Response response = client.GET(scheme + "://localhost:" + connector.getLocalPort()); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } } @@ -90,10 +98,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest for (int i = 0; i < maxConnections + 1; ++i) { ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort()); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); byte[] content = response.getContent(); - Assert.assertArrayEquals(data, content); + assertArrayEquals(data, content); } } @@ -120,10 +128,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest FutureResponseListener listener = new FutureResponseListener(request, data.length); request.send(listener); ContentResponse response = listener.get(15, TimeUnit.SECONDS); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); byte[] content = response.getContent(); - Assert.assertArrayEquals(data, content); + assertArrayEquals(data, content); } @Test @@ -141,7 +149,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest String paramValue1 = request.getParameter(paramName1); output.write(paramValue1.getBytes("UTF-8")); String paramValue2 = request.getParameter(paramName2); - Assert.assertEquals("", paramValue2); + assertEquals("", paramValue2); output.write("empty".getBytes("UTF-8")); baseRequest.setHandled(true); } @@ -152,10 +160,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest String query = paramName1 + "=" + paramValue1 + "&" + paramName2; ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); String content = new String(response.getContent(), "UTF-8"); - Assert.assertEquals(value1 + "empty", content); + assertEquals(value1 + "empty", content); } @Test @@ -188,10 +196,10 @@ public class HttpClientTest extends AbstractHttpClientServerTest String query = paramName1 + "=" + paramValue11 + "&" + paramName1 + "=" + paramValue12 + "&" + paramName2 + "=" + paramValue2; ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); String content = new String(response.getContent(), "UTF-8"); - Assert.assertEquals(value11 + value12 + value2, content); + assertEquals(value11 + value12 + value2, content); } @Test @@ -220,9 +228,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(paramValue, new String(response.getContent(), "UTF-8")); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(paramValue, new String(response.getContent(), "UTF-8")); } @Test @@ -252,9 +260,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(paramValue, new String(response.getContent(), "UTF-8")); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(paramValue, new String(response.getContent(), "UTF-8")); } @Test @@ -284,9 +292,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(paramValue, new String(response.getContent(), "UTF-8")); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(paramValue, new String(response.getContent(), "UTF-8")); } @Test @@ -319,9 +327,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(content, response.getContent()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertArrayEquals(content, response.getContent()); } } @@ -347,8 +355,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } @Test @@ -364,18 +372,18 @@ public class HttpClientTest extends AbstractHttpClientServerTest public void onContent(Request request, ByteBuffer buffer) { byte[] bytes = new byte[buffer.remaining()]; - Assert.assertEquals(1, bytes.length); + assertEquals(1, bytes.length); buffer.get(bytes); - Assert.assertEquals(bytes[0], progress.getAndIncrement()); + assertEquals(bytes[0], progress.getAndIncrement()); } }) .content(new BytesContentProvider(new byte[]{0}, new byte[]{1}, new byte[]{2}, new byte[]{3}, new byte[]{4})) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(5, progress.get()); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(5, progress.get()); } @Test @@ -405,12 +413,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } - @Slow @Test + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testRequestIdleTimeout() throws Exception { final long idleTimeout = 1000; @@ -433,18 +441,13 @@ public class HttpClientTest extends AbstractHttpClientServerTest final String host = "localhost"; final int port = connector.getLocalPort(); - try - { + assertThrows(TimeoutException.class, ()->{ client.newRequest(host, port) .scheme(scheme) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.fail(); - } - catch (TimeoutException expected) - { - } + }); // Make another request without specifying the idle timeout, should not fail ContentResponse response = client.newRequest(host, port) @@ -452,8 +455,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } @Test @@ -479,19 +482,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest connector.setIdleTimeout(idleTimeout); - try - { + ExecutionException x = assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .scheme(scheme) .idleTimeout(4 * idleTimeout, TimeUnit.MILLISECONDS) .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(x.getCause() instanceof EOFException); - } + }); + assertThat(x.getCause(), instanceOf(EOFException.class)); connector.setIdleTimeout(5 * idleTimeout); @@ -502,8 +500,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(3 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } @Test @@ -516,8 +514,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); + assertNotNull(response); + assertEquals(200, response.getStatus()); } @Test @@ -542,9 +540,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(0, response.getContent().length); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(0, response.getContent().length); // Perform a normal GET request to be sure the content is now read response = client.newRequest("localhost", connector.getLocalPort()) @@ -552,9 +550,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertNotNull(response); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals(length, response.getContent().length); + assertNotNull(response); + assertEquals(200, response.getStatus()); + assertEquals(length, response.getContent().length); } @Test @@ -585,12 +583,12 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // Stop the client, the complete listener must be invoked. client.stop(); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -609,17 +607,14 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - try (StacklessLogging stackless = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class)) + try (StacklessLogging ignore = new StacklessLogging(org.eclipse.jetty.server.HttpChannel.class)) { - client.newRequest("localhost", connector.getLocalPort()) - .scheme(scheme) - .timeout(60, TimeUnit.SECONDS) - .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected. + assertThrows(ExecutionException.class, () -> { + client.newRequest("localhost", connector.getLocalPort()) + .scheme(scheme) + .timeout(60, TimeUnit.SECONDS) + .send(); + }); } } @@ -662,8 +657,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest ContentResponse response = listener.get(5, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } @Test @@ -706,34 +701,34 @@ public class HttpClientTest extends AbstractHttpClientServerTest } }); - Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); Callback callback = callbackRef.get(); // Wait a while to be sure that the parsing does not proceed. TimeUnit.MILLISECONDS.sleep(1000); - Assert.assertEquals(1, contentCount.get()); + assertEquals(1, contentCount.get()); // Succeed the content callback to proceed with parsing. callbackRef.set(null); contentLatch.set(new CountDownLatch(1)); callback.succeeded(); - Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS)); callback = callbackRef.get(); // Wait a while to be sure that the parsing does not proceed. TimeUnit.MILLISECONDS.sleep(1000); - Assert.assertEquals(2, contentCount.get()); - Assert.assertEquals(1, completeLatch.getCount()); + assertEquals(2, contentCount.get()); + assertEquals(1, completeLatch.getCount()); // Succeed the content callback to proceed with parsing. callbackRef.set(null); contentLatch.set(new CountDownLatch(1)); callback.succeeded(); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(2, contentCount.get()); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertEquals(2, contentCount.get()); } } diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java index 6ecb5126abb..9361914e6ad 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServletTest.java @@ -18,9 +18,15 @@ package org.eclipse.jetty.fcgi.server.proxy; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.util.Random; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; @@ -42,34 +48,28 @@ import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class FastCGIProxyServletTest { - @Parameterized.Parameters - public static Object[] parameters() + public static Stream factories() { - return new Object[]{true, false}; + return Stream.of( + true, // send status 200 + false // don't send status 200 + ).map(Arguments::of); } - private final boolean sendStatus200; private Server server; private ServerConnector httpConnector; private ServerConnector fcgiConnector; private ServletContextHandler context; private HttpClient client; - public FastCGIProxyServletTest(boolean sendStatus200) - { - this.sendStatus200 = sendStatus200; - } - - public void prepare(HttpServlet servlet) throws Exception + public void prepare(boolean sendStatus200, HttpServlet servlet) throws Exception { QueuedThreadPool serverThreads = new QueuedThreadPool(); serverThreads.setName("server"); @@ -110,42 +110,45 @@ public class FastCGIProxyServletTest server.start(); } - @After + @AfterEach public void dispose() throws Exception { server.stop(); } - @Test - public void testGETWithSmallResponseContent() throws Exception + @ParameterizedTest(name="[{index}] sendStatus200={0}") + @MethodSource("factories") + public void testGETWithSmallResponseContent(boolean sendStatus200) throws Exception { - testGETWithResponseContent(1024, 0); + testGETWithResponseContent(sendStatus200, 1024, 0); } - @Test - public void testGETWithLargeResponseContent() throws Exception + @ParameterizedTest(name="[{index}] sendStatus200={0}") + @MethodSource("factories") + public void testGETWithLargeResponseContent(boolean sendStatus200) throws Exception { - testGETWithResponseContent(16 * 1024 * 1024, 0); + testGETWithResponseContent(sendStatus200, 16 * 1024 * 1024, 0); } - @Test - public void testGETWithLargeResponseContentWithSlowClient() throws Exception + @ParameterizedTest(name="[{index}] sendStatus200={0}") + @MethodSource("factories") + public void testGETWithLargeResponseContentWithSlowClient(boolean sendStatus200) throws Exception { - testGETWithResponseContent(16 * 1024 * 1024, 1); + testGETWithResponseContent(sendStatus200, 16 * 1024 * 1024, 1); } - private void testGETWithResponseContent(int length, final long delay) throws Exception + private void testGETWithResponseContent(boolean sendStatus200, int length, final long delay) throws Exception { final byte[] data = new byte[length]; new Random().nextBytes(data); final String path = "/foo/index.php"; - prepare(new HttpServlet() + prepare(sendStatus200, new HttpServlet() { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - Assert.assertTrue(request.getRequestURI().endsWith(path)); + assertTrue(request.getRequestURI().endsWith(path)); response.setContentLength(data.length); response.getOutputStream().write(data); } @@ -171,24 +174,25 @@ public class FastCGIProxyServletTest ContentResponse response = listener.get(30, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatus()); - Assert.assertArrayEquals(data, response.getContent()); + assertEquals(200, response.getStatus()); + assertArrayEquals(data, response.getContent()); } - @Test - public void testURIRewrite() throws Exception + @ParameterizedTest(name="[{index}] sendStatus200={0}") + @MethodSource("factories") + public void testURIRewrite(boolean sendStatus200) throws Exception { String originalPath = "/original/index.php"; String originalQuery = "foo=bar"; String remotePath = "/remote/index.php"; - prepare(new HttpServlet() + prepare(sendStatus200, new HttpServlet() { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - Assert.assertThat((String)request.getAttribute(FCGI.Headers.REQUEST_URI), Matchers.startsWith(originalPath)); - Assert.assertEquals(originalQuery, request.getAttribute(FCGI.Headers.QUERY_STRING)); - Assert.assertThat(request.getRequestURI(), Matchers.endsWith(remotePath)); + assertThat((String)request.getAttribute(FCGI.Headers.REQUEST_URI), Matchers.startsWith(originalPath)); + assertEquals(originalQuery, request.getAttribute(FCGI.Headers.QUERY_STRING)); + assertThat(request.getRequestURI(), Matchers.endsWith(remotePath)); } }); context.stop(); @@ -216,6 +220,6 @@ public class FastCGIProxyServletTest .path(remotePath) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } } diff --git a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java index e8c5955bdea..173df037ac8 100644 --- a/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java +++ b/jetty-fcgi/fcgi-server/src/test/java/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilterTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.fcgi.server.proxy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.util.EnumSet; @@ -35,9 +38,8 @@ import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class TryFilesFilterTest { @@ -76,7 +78,7 @@ public class TryFilesFilterTest server.start(); } - @After + @AfterEach public void dispose() throws Exception { server.stop(); @@ -91,10 +93,10 @@ public class TryFilesFilterTest @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - Assert.assertTrue("https".equalsIgnoreCase(req.getScheme())); - Assert.assertTrue(req.isSecure()); - Assert.assertEquals(forwardPath, req.getRequestURI()); - Assert.assertTrue(req.getQueryString().endsWith(path)); + assertTrue("https".equalsIgnoreCase(req.getScheme())); + assertTrue(req.isSecure()); + assertEquals(forwardPath, req.getRequestURI()); + assertTrue(req.getQueryString().endsWith(path)); } }); @@ -103,6 +105,6 @@ public class TryFilesFilterTest .path(path) .send(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } } diff --git a/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java b/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java index ec5748524f3..3ba4c4f31df 100644 --- a/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java +++ b/jetty-hazelcast/src/test/java/org/eclipse/jetty/hazelcast/session/TestHazelcastSessions.java @@ -29,9 +29,9 @@ import org.eclipse.jetty.server.session.DefaultSessionCache; import org.eclipse.jetty.server.session.SessionContext; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; @@ -41,7 +41,7 @@ import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class TestHazelcastSessions { @@ -101,7 +101,7 @@ public class TestHazelcastSessions String contextPath = "/"; - @Before + @BeforeEach public void initialize() throws Exception { @@ -131,7 +131,7 @@ public class TestHazelcastSessions server.start(); } - @After + @AfterEach public void shutdown() throws Exception { diff --git a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java index dc54a27634e..429c517bccd 100644 --- a/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java +++ b/jetty-http-spi/src/test/java/org/eclipse/jetty/http/spi/TestSPIServer.java @@ -25,7 +25,7 @@ import org.eclipse.jetty.client.util.BasicAuthentication; import org.eclipse.jetty.server.NetworkConnector; import org.eclipse.jetty.server.Server; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.OutputStream; @@ -45,7 +45,7 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import org.junit.Test; +import org.junit.jupiter.api.Test; diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java index e81c3af51fd..ad6c92fa230 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/GZIPContentDecoderTest.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.http; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -31,23 +31,17 @@ import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.eclipse.jetty.io.ArrayByteBufferPool; -import org.eclipse.jetty.toolchain.test.TestTracker; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class GZIPContentDecoderTest { - @Rule - public final TestTracker tracker = new TestTracker(); - - ArrayByteBufferPool pool; AtomicInteger buffers = new AtomicInteger(0); - @Before + @BeforeEach public void beforeClass() throws Exception { buffers.set(0); @@ -71,7 +65,7 @@ public class GZIPContentDecoderTest }; } - @After + @AfterEach public void afterClass() throws Exception { assertEquals(0,buffers.get()); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java index 45b1d83c9a1..64f2f76335b 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldTest.java @@ -19,16 +19,16 @@ package org.eclipse.jetty.http; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; import java.nio.ByteBuffer; import org.eclipse.jetty.util.BufferUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HttpFieldTest { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsMatchers.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsMatchers.java new file mode 100644 index 00000000000..4cb8e6cf917 --- /dev/null +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsMatchers.java @@ -0,0 +1,47 @@ +// +// ======================================================================== +// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.http; + +import org.eclipse.jetty.http.matchers.HttpFieldsContainsHeaderValue; +import org.eclipse.jetty.http.matchers.HttpFieldsContainsHeaderKey; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; + +public class HttpFieldsMatchers +{ + @Factory + public static Matcher containsHeader(String keyName) { + return new HttpFieldsContainsHeaderKey(keyName); + } + + @Factory + public static Matcher containsHeader(HttpHeader header) { + return new HttpFieldsContainsHeaderKey(header); + } + + @Factory + public static Matcher containsHeaderValue(String keyName, String value) { + return new HttpFieldsContainsHeaderValue(keyName, value); + } + + @Factory + public static Matcher containsHeaderValue(HttpHeader header, String value) { + return new HttpFieldsContainsHeaderValue(header, value); + } +} diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java index 05aa02ce287..7227c7d4776 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpFieldsTest.java @@ -18,6 +18,15 @@ package org.eclipse.jetty.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.Collections; import java.util.Enumeration; @@ -29,16 +38,7 @@ import java.util.NoSuchElementException; import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; public class HttpFieldsTest { @@ -116,13 +116,9 @@ public class HttpFieldsTest assertEquals("value0",header.getField(0).getValue()); assertEquals("value1",header.getField(1).getValue()); - try - { + assertThrows(NoSuchElementException.class, ()->{ header.getField(2); - Assert.fail(); - } - catch(NoSuchElementException e) - {} + }); } @Test @@ -177,9 +173,9 @@ public class HttpFieldsTest BufferUtil.flipToFlush(buffer,0); String out = BufferUtil.toString(buffer).toLowerCase(Locale.ENGLISH); - Assert.assertThat(out,Matchers.containsString((HttpHeader.CONNECTION+": "+HttpHeaderValue.KEEP_ALIVE).toLowerCase(Locale.ENGLISH))); - Assert.assertThat(out,Matchers.containsString((HttpHeader.TRANSFER_ENCODING+": "+HttpHeaderValue.CHUNKED).toLowerCase(Locale.ENGLISH))); - Assert.assertThat(out,Matchers.containsString((HttpHeader.CONTENT_ENCODING+": "+HttpHeaderValue.GZIP).toLowerCase(Locale.ENGLISH))); + assertThat(out,Matchers.containsString((HttpHeader.CONNECTION+": "+HttpHeaderValue.KEEP_ALIVE).toLowerCase(Locale.ENGLISH))); + assertThat(out,Matchers.containsString((HttpHeader.TRANSFER_ENCODING+": "+HttpHeaderValue.CHUNKED).toLowerCase(Locale.ENGLISH))); + assertThat(out,Matchers.containsString((HttpHeader.CONTENT_ENCODING+": "+HttpHeaderValue.GZIP).toLowerCase(Locale.ENGLISH))); } @Test @@ -396,33 +392,33 @@ public class HttpFieldsTest fields.add("name", "four, I V"); List list = fields.getCSV("name",false); - assertEquals("zero",HttpFields.valueParameters(list.get(0),null)); - assertEquals("one",HttpFields.valueParameters(list.get(1),null)); - assertEquals("1 + 1",HttpFields.valueParameters(list.get(2),null)); - assertEquals("three",HttpFields.valueParameters(list.get(3),null)); - assertEquals("four",HttpFields.valueParameters(list.get(4),null)); - assertEquals("I V",HttpFields.valueParameters(list.get(5),null)); + assertEquals(HttpFields.valueParameters(list.get(0), null), "zero"); + assertEquals(HttpFields.valueParameters(list.get(1), null), "one"); + assertEquals(HttpFields.valueParameters(list.get(2), null), "1 + 1"); + assertEquals(HttpFields.valueParameters(list.get(3), null), "three"); + assertEquals(HttpFields.valueParameters(list.get(4), null), "four"); + assertEquals(HttpFields.valueParameters(list.get(5), null), "I V"); fields.addCSV("name","six"); list = fields.getCSV("name",false); - assertEquals("zero",HttpFields.valueParameters(list.get(0),null)); - assertEquals("one",HttpFields.valueParameters(list.get(1),null)); - assertEquals("1 + 1",HttpFields.valueParameters(list.get(2),null)); - assertEquals("three",HttpFields.valueParameters(list.get(3),null)); - assertEquals("four",HttpFields.valueParameters(list.get(4),null)); - assertEquals("I V",HttpFields.valueParameters(list.get(5),null)); - assertEquals("six",HttpFields.valueParameters(list.get(6),null)); + assertEquals(HttpFields.valueParameters(list.get(0), null), "zero"); + assertEquals(HttpFields.valueParameters(list.get(1), null), "one"); + assertEquals(HttpFields.valueParameters(list.get(2), null), "1 + 1"); + assertEquals(HttpFields.valueParameters(list.get(3), null), "three"); + assertEquals(HttpFields.valueParameters(list.get(4), null), "four"); + assertEquals(HttpFields.valueParameters(list.get(5), null), "I V"); + assertEquals(HttpFields.valueParameters(list.get(6), null), "six"); fields.addCSV("name","1 + 1","7","zero"); list = fields.getCSV("name",false); - assertEquals("zero",HttpFields.valueParameters(list.get(0),null)); - assertEquals("one",HttpFields.valueParameters(list.get(1),null)); - assertEquals("1 + 1",HttpFields.valueParameters(list.get(2),null)); - assertEquals("three",HttpFields.valueParameters(list.get(3),null)); - assertEquals("four",HttpFields.valueParameters(list.get(4),null)); - assertEquals("I V",HttpFields.valueParameters(list.get(5),null)); - assertEquals("six",HttpFields.valueParameters(list.get(6),null)); - assertEquals("7",HttpFields.valueParameters(list.get(7),null)); + assertEquals(HttpFields.valueParameters(list.get(0), null), "zero"); + assertEquals(HttpFields.valueParameters(list.get(1), null), "one"); + assertEquals(HttpFields.valueParameters(list.get(2), null), "1 + 1"); + assertEquals(HttpFields.valueParameters(list.get(3), null), "three"); + assertEquals(HttpFields.valueParameters(list.get(4), null), "four"); + assertEquals(HttpFields.valueParameters(list.get(5), null), "I V"); + assertEquals(HttpFields.valueParameters(list.get(6), null), "six"); + assertEquals(HttpFields.valueParameters(list.get(7), null), "7"); } @Test @@ -440,12 +436,12 @@ public class HttpFieldsTest List list = fields.getQualityCSV("name"); - assertEquals("first",HttpFields.valueParameters(list.get(0),null)); - assertEquals("zero",HttpFields.valueParameters(list.get(1),null)); - assertEquals("one",HttpFields.valueParameters(list.get(2),null)); - assertEquals("two",HttpFields.valueParameters(list.get(3),null)); - assertEquals("three",HttpFields.valueParameters(list.get(4),null)); - assertEquals("four",HttpFields.valueParameters(list.get(5),null)); + assertEquals(HttpFields.valueParameters(list.get(0), null), "first"); + assertEquals(HttpFields.valueParameters(list.get(1), null), "zero"); + assertEquals(HttpFields.valueParameters(list.get(2), null), "one"); + assertEquals(HttpFields.valueParameters(list.get(3), null), "two"); + assertEquals(HttpFields.valueParameters(list.get(4), null), "three"); + assertEquals(HttpFields.valueParameters(list.get(5), null), "four"); } @Test @@ -463,12 +459,12 @@ public class HttpFieldsTest List list = fields.getQualityCSV(HttpHeader.ACCEPT); - assertEquals("first",HttpFields.valueParameters(list.get(0),null)); - assertEquals("zero",HttpFields.valueParameters(list.get(1),null)); - assertEquals("one",HttpFields.valueParameters(list.get(2),null)); - assertEquals("two",HttpFields.valueParameters(list.get(3),null)); - assertEquals("three",HttpFields.valueParameters(list.get(4),null)); - assertEquals("four",HttpFields.valueParameters(list.get(5),null)); + assertEquals(HttpFields.valueParameters(list.get(0), null), "first"); + assertEquals(HttpFields.valueParameters(list.get(1), null), "zero"); + assertEquals(HttpFields.valueParameters(list.get(2), null), "one"); + assertEquals(HttpFields.valueParameters(list.get(3), null), "two"); + assertEquals(HttpFields.valueParameters(list.get(4), null), "three"); + assertEquals(HttpFields.valueParameters(list.get(5), null), "four"); } @@ -616,8 +612,8 @@ public class HttpFieldsTest { assertTrue(header.containsKey("n"+i)); assertTrue(header.containsKey("N"+i)); - assertFalse(""+i,header.contains("n"+i,"xyz")); - assertEquals(""+i,i>=4,header.contains("n"+i,"def")); + assertFalse(header.contains("n"+i,"xyz"),""+i); + assertEquals(i>=4,header.contains("n"+i, "def"), ""+i); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java index f3eaa36de74..941900584ea 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorClientTest.java @@ -18,12 +18,16 @@ package org.eclipse.jetty.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HttpGeneratorClientTest { @@ -50,33 +54,33 @@ public class HttpGeneratorClientTest HttpGenerator.Result result=gen.generateRequest(null,null,null,null, true); - Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_INFO, result); + assertEquals(HttpGenerator.State.START, gen.getState()); Info info = new Info("GET","/index.html"); info.getFields().add("Host","something"); info.getFields().add("User-Agent","test"); - Assert.assertTrue(!gen.isChunking()); + assertTrue(!gen.isChunking()); result=gen.generateRequest(info,null,null,null, true); - Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + assertEquals(HttpGenerator.State.START, gen.getState()); result=gen.generateRequest(info,header,null,null, true); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertTrue(!gen.isChunking()); String out = BufferUtil.toString(header); BufferUtil.clear(header); result=gen.generateResponse(null,false,null,null, null, false); - Assert.assertEquals(HttpGenerator.Result.DONE, result); - Assert.assertEquals(HttpGenerator.State.END, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); + assertTrue(!gen.isChunking()); - Assert.assertEquals(0, gen.getContentPrepared()); - Assert.assertThat(out, Matchers.containsString("GET /index.html HTTP/1.1")); - Assert.assertThat(out, Matchers.not(Matchers.containsString("Content-Length"))); + assertEquals(0, gen.getContentPrepared()); + assertThat(out, Matchers.containsString("GET /index.html HTTP/1.1")); + assertThat(out, Matchers.not(Matchers.containsString("Content-Length"))); } @Test @@ -87,36 +91,36 @@ public class HttpGeneratorClientTest HttpGenerator.Result result=gen.generateRequest(null,null,null,null, true); - Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_INFO, result); + assertEquals(HttpGenerator.State.START, gen.getState()); Info info = new Info("GET","/index.html"); info.getFields().add("Host","something"); info.getFields().add("Null",null); info.getFields().add("Empty",""); - Assert.assertTrue(!gen.isChunking()); + assertTrue(!gen.isChunking()); result=gen.generateRequest(info,null,null,null, true); - Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + assertEquals(HttpGenerator.State.START, gen.getState()); result=gen.generateRequest(info,header,null,null, true); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertTrue(!gen.isChunking()); String out = BufferUtil.toString(header); BufferUtil.clear(header); result=gen.generateResponse(null,false,null,null, null, false); - Assert.assertEquals(HttpGenerator.Result.DONE, result); - Assert.assertEquals(HttpGenerator.State.END, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); + assertTrue(!gen.isChunking()); - Assert.assertEquals(0, gen.getContentPrepared()); - Assert.assertThat(out, Matchers.containsString("GET /index.html HTTP/1.1")); - Assert.assertThat(out, Matchers.not(Matchers.containsString("Content-Length"))); - Assert.assertThat(out, Matchers.containsString("Empty:")); - Assert.assertThat(out, Matchers.not(Matchers.containsString("Null:"))); + assertEquals(0, gen.getContentPrepared()); + assertThat(out, Matchers.containsString("GET /index.html HTTP/1.1")); + assertThat(out, Matchers.not(Matchers.containsString("Content-Length"))); + assertThat(out, Matchers.containsString("Empty:")); + assertThat(out, Matchers.not(Matchers.containsString("Null:"))); } @@ -128,33 +132,33 @@ public class HttpGeneratorClientTest HttpGenerator.Result result=gen.generateRequest(null,null,null,null, true); - Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_INFO, result); + assertEquals(HttpGenerator.State.START, gen.getState()); Info info = new Info("POST","/index.html"); info.getFields().add("Host","something"); info.getFields().add("User-Agent","test"); - Assert.assertTrue(!gen.isChunking()); + assertTrue(!gen.isChunking()); result=gen.generateRequest(info,null,null,null, true); - Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + assertEquals(HttpGenerator.State.START, gen.getState()); result=gen.generateRequest(info,header,null,null, true); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertTrue(!gen.isChunking()); String out = BufferUtil.toString(header); BufferUtil.clear(header); result=gen.generateResponse(null,false,null,null, null, false); - Assert.assertEquals(HttpGenerator.Result.DONE, result); - Assert.assertEquals(HttpGenerator.State.END, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); + assertTrue(!gen.isChunking()); - Assert.assertEquals(0, gen.getContentPrepared()); - Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); - Assert.assertThat(out, Matchers.containsString("Content-Length: 0")); + assertEquals(0, gen.getContentPrepared()); + assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); + assertThat(out, Matchers.containsString("Content-Length: 0")); } @Test @@ -167,38 +171,38 @@ public class HttpGeneratorClientTest HttpGenerator.Result result=gen.generateRequest(null,null,null,content0, true); - Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_INFO, result); + assertEquals(HttpGenerator.State.START, gen.getState()); Info info = new Info("POST","/index.html"); info.getFields().add("Host","something"); info.getFields().add("User-Agent","test"); result=gen.generateRequest(info,null,null,content0, true); - Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + assertEquals(HttpGenerator.State.START, gen.getState()); result=gen.generateRequest(info,header,null,content0, true); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertTrue(!gen.isChunking()); out = BufferUtil.toString(header); BufferUtil.clear(header); out+=BufferUtil.toString(content0); BufferUtil.clear(content0); result=gen.generateResponse(null,false,null,null, null, false); - Assert.assertEquals(HttpGenerator.Result.DONE, result); - Assert.assertEquals(HttpGenerator.State.END, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); + assertTrue(!gen.isChunking()); - Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); - Assert.assertThat(out, Matchers.containsString("Host: something")); - Assert.assertThat(out, Matchers.containsString("Content-Length: 58")); - Assert.assertThat(out, Matchers.containsString("Hello World. The quick brown fox jumped over the lazy dog.")); + assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); + assertThat(out, Matchers.containsString("Host: something")); + assertThat(out, Matchers.containsString("Content-Length: 58")); + assertThat(out, Matchers.containsString("Hello World. The quick brown fox jumped over the lazy dog.")); - Assert.assertEquals(58, gen.getContentPrepared()); + assertEquals(58, gen.getContentPrepared()); } @Test @@ -213,63 +217,63 @@ public class HttpGeneratorClientTest HttpGenerator.Result result=gen.generateRequest(null,null,null,content0, false); - Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_INFO, result); + assertEquals(HttpGenerator.State.START, gen.getState()); Info info = new Info("POST","/index.html"); info.getFields().add("Host","something"); info.getFields().add("User-Agent","test"); result=gen.generateRequest(info,null,null,content0, false); - Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + assertEquals(HttpGenerator.State.START, gen.getState()); result=gen.generateRequest(info,header,null,content0, false); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); - Assert.assertTrue(gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); + assertTrue(gen.isChunking()); out = BufferUtil.toString(header); BufferUtil.clear(header); out+=BufferUtil.toString(content0); BufferUtil.clear(content0); result=gen.generateRequest(null,header,null,content1, false); - Assert.assertEquals(HttpGenerator.Result.NEED_CHUNK, result); - Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_CHUNK, result); + assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); result=gen.generateRequest(null,null,chunk,content1, false); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); - Assert.assertTrue(gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); + assertTrue(gen.isChunking()); out+=BufferUtil.toString(chunk); BufferUtil.clear(chunk); out+=BufferUtil.toString(content1); BufferUtil.clear(content1); result=gen.generateResponse(null,false,null,chunk, null, true); - Assert.assertEquals(HttpGenerator.Result.CONTINUE, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - Assert.assertTrue(gen.isChunking()); + assertEquals(HttpGenerator.Result.CONTINUE, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertTrue(gen.isChunking()); result=gen.generateResponse(null,false,null,chunk, null, true); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); out+=BufferUtil.toString(chunk); BufferUtil.clear(chunk); - Assert.assertTrue(!gen.isChunking()); + assertTrue(!gen.isChunking()); result=gen.generateResponse(null,false,null,chunk, null, true); - Assert.assertEquals(HttpGenerator.Result.DONE, result); - Assert.assertEquals(HttpGenerator.State.END, gen.getState()); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); - Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); - Assert.assertThat(out, Matchers.containsString("Host: something")); - Assert.assertThat(out, Matchers.containsString("Transfer-Encoding: chunked")); - Assert.assertThat(out, Matchers.containsString("\r\nD\r\nHello World. \r\n")); - Assert.assertThat(out, Matchers.containsString("\r\n2D\r\nThe quick brown fox jumped over the lazy dog.\r\n")); - Assert.assertThat(out, Matchers.containsString("\r\n0\r\n\r\n")); + assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); + assertThat(out, Matchers.containsString("Host: something")); + assertThat(out, Matchers.containsString("Transfer-Encoding: chunked")); + assertThat(out, Matchers.containsString("\r\nD\r\nHello World. \r\n")); + assertThat(out, Matchers.containsString("\r\n2D\r\nThe quick brown fox jumped over the lazy dog.\r\n")); + assertThat(out, Matchers.containsString("\r\n0\r\n\r\n")); - Assert.assertEquals(58, gen.getContentPrepared()); + assertEquals(58, gen.getContentPrepared()); } @@ -285,50 +289,50 @@ public class HttpGeneratorClientTest HttpGenerator.Result result=gen.generateRequest(null,null,null,content0, false); - Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_INFO, result); + assertEquals(HttpGenerator.State.START, gen.getState()); Info info = new Info("POST","/index.html",58); info.getFields().add("Host","something"); info.getFields().add("User-Agent","test"); result=gen.generateRequest(info,null,null,content0, false); - Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result); - Assert.assertEquals(HttpGenerator.State.START, gen.getState()); + assertEquals(HttpGenerator.Result.NEED_HEADER, result); + assertEquals(HttpGenerator.State.START, gen.getState()); result=gen.generateRequest(info,header,null,content0, false); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); + assertTrue(!gen.isChunking()); out = BufferUtil.toString(header); BufferUtil.clear(header); out+=BufferUtil.toString(content0); BufferUtil.clear(content0); result=gen.generateRequest(null,null,null,content1, false); - Assert.assertEquals(HttpGenerator.Result.FLUSH, result); - Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.FLUSH, result); + assertEquals(HttpGenerator.State.COMMITTED, gen.getState()); + assertTrue(!gen.isChunking()); out+=BufferUtil.toString(content1); BufferUtil.clear(content1); result=gen.generateResponse(null,false,null,null, null, true); - Assert.assertEquals(HttpGenerator.Result.CONTINUE, result); - Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); - Assert.assertTrue(!gen.isChunking()); + assertEquals(HttpGenerator.Result.CONTINUE, result); + assertEquals(HttpGenerator.State.COMPLETING, gen.getState()); + assertTrue(!gen.isChunking()); result=gen.generateResponse(null,false,null,null, null, true); - Assert.assertEquals(HttpGenerator.Result.DONE, result); - Assert.assertEquals(HttpGenerator.State.END, gen.getState()); + assertEquals(HttpGenerator.Result.DONE, result); + assertEquals(HttpGenerator.State.END, gen.getState()); out+=BufferUtil.toString(chunk); BufferUtil.clear(chunk); - Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); - Assert.assertThat(out, Matchers.containsString("Host: something")); - Assert.assertThat(out, Matchers.containsString("Content-Length: 58")); - Assert.assertThat(out, Matchers.containsString("\r\n\r\nHello World. The quick brown fox jumped over the lazy dog.")); + assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1")); + assertThat(out, Matchers.containsString("Host: something")); + assertThat(out, Matchers.containsString("Content-Length: 58")); + assertThat(out, Matchers.containsString("\r\n\r\nHello World. The quick brown fox jumped over the lazy dog.")); - Assert.assertEquals(58, gen.getContentPrepared()); + assertEquals(58, gen.getContentPrepared()); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java index dda87a32ff1..59168afee43 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerHTTPTest.java @@ -18,41 +18,36 @@ package org.eclipse.jetty.http; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.List; - -import org.eclipse.jetty.util.BufferUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.stream.Stream; + +import org.eclipse.jetty.util.BufferUtil; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class HttpGeneratorServerHTTPTest { - @Parameter(value = 0) - public Run run; private String _content; private String _reason; - @Test - public void testHTTP() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testHTTP(Run run) throws Exception { Handler handler = new Handler(); HttpGenerator gen = new HttpGenerator(); - String t = run.toString(); + String msg = run.toString(); run.result.getHttpFields().clear(); @@ -64,19 +59,20 @@ public class HttpGeneratorServerHTTPTest parser.parseNext(BufferUtil.toBuffer(response)); if (run.result._body != null) - assertEquals(t, run.result._body, this._content); + assertEquals(run.result._body, this._content, msg); + // TODO: Break down rationale more clearly, these should be separate checks and/or assertions if (run.httpVersion == 10) - assertTrue(t, gen.isPersistent() || run.result._contentLength >= 0 || EnumSet.of(ConnectionType.CLOSE, ConnectionType.KEEP_ALIVE, ConnectionType.NONE).contains(run.connection)); + assertTrue(gen.isPersistent() || run.result._contentLength >= 0 || EnumSet.of(ConnectionType.CLOSE, ConnectionType.KEEP_ALIVE, ConnectionType.NONE).contains(run.connection), msg); else - assertTrue(t, gen.isPersistent() || EnumSet.of(ConnectionType.CLOSE, ConnectionType.TE_CLOSE).contains(run.connection)); + assertTrue(gen.isPersistent() || EnumSet.of(ConnectionType.CLOSE, ConnectionType.TE_CLOSE).contains(run.connection), msg); assertEquals("OK??Test", _reason); if (_content == null) - assertTrue(t, run.result._body == null); + assertTrue(run.result._body == null, msg); else - assertThat(t, run.result._contentLength, either(equalTo(_content.length())).or(equalTo(-1))); + assertThat(msg, run.result._contentLength, either(equalTo(_content.length())).or(equalTo(-1))); } private static class Result @@ -276,21 +272,19 @@ public class HttpGeneratorServerHTTPTest private static class Run { - public static Run[] as(Result result, int ver, int chunks, ConnectionType connection) - { - Run run = new Run(); - run.result = result; - run.httpVersion = ver; - run.chunks = chunks; - run.connection = connection; - return new Run[]{run}; - } - private Result result; private ConnectionType connection; private int httpVersion; private int chunks; + public Run(Result result, int ver, int chunks, ConnectionType connection) + { + this.result = result; + this.httpVersion = ver; + this.chunks = chunks; + this.connection = connection; + } + @Override public String toString() { @@ -327,8 +321,8 @@ public class HttpGeneratorServerHTTPTest } } - @Parameters(name = "{0}") - public static Collection data() + + public static Stream data() { Result[] results = { new Result(200, null, -1, null, false), @@ -341,7 +335,7 @@ public class HttpGeneratorServerHTTPTest new Result(200, "text/html", CONTENT.length(), CONTENT, false) }; - List data = new ArrayList<>(); + ArrayList data = new ArrayList<>(); // For each test result for (Result result : results) @@ -357,12 +351,13 @@ public class HttpGeneratorServerHTTPTest { if (connection.isSupportedByHttp(v)) { - data.add(Run.as(result, v, chunks, connection)); + data.add(Arguments.of(new Run(result, v, chunks, connection))); } } } } } - return data; + + return data.stream(); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java index a7687991ec3..a1d5aaebe4b 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpGeneratorServerTest.java @@ -18,20 +18,20 @@ package org.eclipse.jetty.http; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.nio.ByteBuffer; import java.util.function.Supplier; import org.eclipse.jetty.util.BufferUtil; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HttpGeneratorServerTest { @@ -249,15 +249,10 @@ public class HttpGeneratorServerTest result = gen.generateResponse(info, false, null, null, null, true); assertEquals(HttpGenerator.Result.NEED_HEADER, result); - try - { + BadMessageException e = assertThrows(BadMessageException.class, ()->{ gen.generateResponse(info, false, header, null, null, true); - Assert.fail(); - } - catch(BadMessageException e) - { - assertEquals(e._code,500); - } + }); + assertEquals(500, e._code); } @Test @@ -833,9 +828,9 @@ public class HttpGeneratorServerTest MetaData.Response info = new MetaData.Response(HttpVersion.HTTP_1_0, 200, "OK", fields, -1); ByteBuffer header = BufferUtil.allocate(4096); HttpGenerator.Result result = generator.generateResponse(info, false, header, null, null, true); - Assert.assertSame(HttpGenerator.Result.FLUSH, result); + assertSame(HttpGenerator.Result.FLUSH, result); String headers = BufferUtil.toString(header); - Assert.assertTrue(headers.contains(HttpHeaderValue.KEEP_ALIVE.asString())); - Assert.assertTrue(headers.contains(customValue)); + assertThat(headers, containsString(HttpHeaderValue.KEEP_ALIVE.asString())); + assertThat(headers, containsString(customValue)); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java index 48f13e70933..cb96bef18a7 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpParserTest.java @@ -18,6 +18,17 @@ package org.eclipse.jetty.http; +import static org.eclipse.jetty.http.HttpComplianceSection.NO_FIELD_FOLDING; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -28,12 +39,8 @@ import org.eclipse.jetty.http.HttpParser.State; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.eclipse.jetty.http.HttpComplianceSection.NO_FIELD_FOLDING; -import static org.hamcrest.Matchers.contains; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class HttpParserTest { @@ -72,19 +79,19 @@ public class HttpParserTest @Test public void HttpMethodTest() { - Assert.assertNull(HttpMethod.lookAheadGet(BufferUtil.toBuffer("Wibble "))); - Assert.assertNull(HttpMethod.lookAheadGet(BufferUtil.toBuffer("GET"))); - Assert.assertNull(HttpMethod.lookAheadGet(BufferUtil.toBuffer("MO"))); + assertNull(HttpMethod.lookAheadGet(BufferUtil.toBuffer("Wibble "))); + assertNull(HttpMethod.lookAheadGet(BufferUtil.toBuffer("GET"))); + assertNull(HttpMethod.lookAheadGet(BufferUtil.toBuffer("MO"))); - Assert.assertEquals(HttpMethod.GET, HttpMethod.lookAheadGet(BufferUtil.toBuffer("GET "))); - Assert.assertEquals(HttpMethod.MOVE, HttpMethod.lookAheadGet(BufferUtil.toBuffer("MOVE "))); + assertEquals(HttpMethod.GET, HttpMethod.lookAheadGet(BufferUtil.toBuffer("GET "))); + assertEquals(HttpMethod.MOVE, HttpMethod.lookAheadGet(BufferUtil.toBuffer("MOVE "))); ByteBuffer b = BufferUtil.allocateDirect(128); BufferUtil.append(b, BufferUtil.toBuffer("GET")); - Assert.assertNull(HttpMethod.lookAheadGet(b)); + assertNull(HttpMethod.lookAheadGet(b)); BufferUtil.append(b, BufferUtil.toBuffer(" ")); - Assert.assertEquals(HttpMethod.GET, HttpMethod.lookAheadGet(b)); + assertEquals(HttpMethod.GET, HttpMethod.lookAheadGet(b)); } @Test @@ -95,10 +102,10 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("POST", _methodOrVersion); - Assert.assertEquals("/mock/127.0.0.1", _uriOrStatus); - Assert.assertEquals("HTTP/1.1", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("POST", _methodOrVersion); + assertEquals("/mock/127.0.0.1", _uriOrStatus); + assertEquals("HTTP/1.1", _versionOrReason); + assertEquals(-1, _headers); } @Test @@ -109,10 +116,10 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("POST", _methodOrVersion); - Assert.assertEquals("/foo", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("POST", _methodOrVersion); + assertEquals("/foo", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals(-1, _headers); } @Test @@ -124,12 +131,12 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, HttpCompliance.RFC2616_LEGACY); parseAll(parser, buffer); - Assert.assertNull(_bad); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/999", _uriOrStatus); - Assert.assertEquals("HTTP/0.9", _versionOrReason); - Assert.assertEquals(-1, _headers); - Assert.assertThat(_complianceViolation, contains(HttpComplianceSection.NO_HTTP_0_9)); + assertNull(_bad); + assertEquals("GET", _methodOrVersion); + assertEquals("/999", _uriOrStatus); + assertEquals("HTTP/0.9", _versionOrReason); + assertEquals(-1, _headers); + assertThat(_complianceViolation, contains(HttpComplianceSection.NO_HTTP_0_9)); } @Test @@ -140,8 +147,8 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("HTTP/0.9 not supported", _bad); - Assert.assertThat(_complianceViolation,Matchers.empty()); + assertEquals("HTTP/0.9 not supported", _bad); + assertThat(_complianceViolation,Matchers.empty()); } @Test @@ -153,12 +160,12 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, HttpCompliance.RFC2616_LEGACY); parseAll(parser, buffer); - Assert.assertNull(_bad); - Assert.assertEquals("POST", _methodOrVersion); - Assert.assertEquals("/222", _uriOrStatus); - Assert.assertEquals("HTTP/0.9", _versionOrReason); - Assert.assertEquals(-1, _headers); - Assert.assertThat(_complianceViolation, contains(HttpComplianceSection.NO_HTTP_0_9)); + assertNull(_bad); + assertEquals("POST", _methodOrVersion); + assertEquals("/222", _uriOrStatus); + assertEquals("HTTP/0.9", _versionOrReason); + assertEquals(-1, _headers); + assertThat(_complianceViolation, contains(HttpComplianceSection.NO_HTTP_0_9)); } @Test @@ -170,8 +177,8 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("HTTP/0.9 not supported", _bad); - Assert.assertThat(_complianceViolation,Matchers.empty()); + assertEquals("HTTP/0.9 not supported", _bad); + assertThat(_complianceViolation,Matchers.empty()); } @Test @@ -182,10 +189,10 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("POST", _methodOrVersion); - Assert.assertEquals("/fo\u0690", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("POST", _methodOrVersion); + assertEquals("/fo\u0690", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals(-1, _headers); } @Test @@ -196,10 +203,10 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("POST", _methodOrVersion); - Assert.assertEquals("/foo?param=\u0690", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("POST", _methodOrVersion); + assertEquals("/foo?param=\u0690", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals(-1, _headers); } @Test @@ -210,10 +217,10 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("POST", _methodOrVersion); - Assert.assertEquals("/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("POST", _methodOrVersion); + assertEquals("/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/123456789abcdef/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals(-1, _headers); } @Test @@ -224,12 +231,12 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser= new HttpParser(handler); parseAll(parser,buffer); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals(-1, _headers); } - + @Test public void testDisallowedLinePreamble() throws Exception { @@ -238,9 +245,9 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser= new HttpParser(handler); parseAll(parser,buffer); - Assert.assertEquals("Illegal character SPACE=' '", _bad); + assertEquals("Illegal character SPACE=' '", _bad); } - + @Test public void testConnect() throws Exception { @@ -248,10 +255,10 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("CONNECT", _methodOrVersion); - Assert.assertEquals("192.168.1.2:80", _uriOrStatus); - Assert.assertEquals("HTTP/1.1", _versionOrReason); - Assert.assertEquals(-1, _headers); + assertEquals("CONNECT", _methodOrVersion); + assertEquals("192.168.1.2:80", _uriOrStatus); + assertEquals("HTTP/1.1", _versionOrReason); + assertEquals(-1, _headers); } @Test @@ -267,16 +274,16 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertTrue(_headerCompleted); - Assert.assertTrue(_messageCompleted); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Host", _hdr[0]); - Assert.assertEquals("localhost", _val[0]); - Assert.assertEquals("Connection", _hdr[1]); - Assert.assertEquals("close", _val[1]); - Assert.assertEquals(1, _headers); + assertTrue(_headerCompleted); + assertTrue(_messageCompleted); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Host", _hdr[0]); + assertEquals("localhost", _val[0]); + assertEquals("Connection", _hdr[1]); + assertEquals("close", _val[1]); + assertEquals(1, _headers); } @Test @@ -295,15 +302,15 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, HttpCompliance.RFC2616_LEGACY); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.nullValue()); - Assert.assertEquals("Host", _hdr[0]); - Assert.assertEquals("localhost", _val[0]); - Assert.assertEquals(2, _headers); - Assert.assertEquals("Name", _hdr[1]); - Assert.assertEquals("value extra", _val[1]); - Assert.assertEquals("Name2", _hdr[2]); - Assert.assertEquals("value2", _val[2]); - Assert.assertThat(_complianceViolation, contains(NO_FIELD_FOLDING,NO_FIELD_FOLDING)); + assertThat(_bad, Matchers.nullValue()); + assertEquals("Host", _hdr[0]); + assertEquals("localhost", _val[0]); + assertEquals(2, _headers); + assertEquals("Name", _hdr[1]); + assertEquals("value extra", _val[1]); + assertEquals("Name2", _hdr[2]); + assertEquals("value2", _val[2]); + assertThat(_complianceViolation, contains(NO_FIELD_FOLDING,NO_FIELD_FOLDING)); } @Test @@ -320,9 +327,9 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, 4096, HttpCompliance.RFC7230_LEGACY); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.notNullValue()); - Assert.assertThat(_bad, Matchers.containsString("Header Folding")); - Assert.assertThat(_complianceViolation,Matchers.empty()); + assertThat(_bad, Matchers.notNullValue()); + assertThat(_bad, containsString("Header Folding")); + assertThat(_complianceViolation,Matchers.empty()); } @Test @@ -338,8 +345,8 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, 4096, HttpCompliance.RFC7230_LEGACY); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.notNullValue()); - Assert.assertThat(_bad, Matchers.containsString("Illegal character")); + assertThat(_bad, Matchers.notNullValue()); + assertThat(_bad, containsString("Illegal character")); } @Test @@ -355,19 +362,19 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, 4096, HttpCompliance.RFC7230_LEGACY); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.notNullValue()); - Assert.assertThat(_bad, Matchers.containsString("Illegal character")); + assertThat(_bad, Matchers.notNullValue()); + assertThat(_bad, containsString("Illegal character")); } - @Test + @Test // TODO: Parameterize Test public void testWhiteSpaceBeforeRequest() { HttpCompliance[] compliances = new HttpCompliance[] { HttpCompliance.RFC7230, HttpCompliance.RFC2616 }; - - String whitespaces[][] = new String[][] + + String whitespaces[][] = new String[][] { { " ", "Illegal character SPACE" }, { "\t", "Illegal character HTAB" }, @@ -388,7 +395,7 @@ public class HttpParserTest for (int i = 0; i < compliances.length; i++) { HttpCompliance compliance = compliances[i]; - + for (int j = 0; j < whitespaces.length; j++) { String request = @@ -408,9 +415,9 @@ public class HttpParserTest String test = "whitespace.[" + compliance + "].[" + j + "]"; String expected = whitespaces[j][1]; if (expected==null) - Assert.assertNull(test, _bad); + assertThat(test, _bad, is(nullValue())); else - Assert.assertThat(test, _bad, Matchers.containsString(expected)); + assertThat(test, _bad, containsString(expected)); } } } @@ -429,18 +436,18 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertTrue(_headerCompleted); - Assert.assertTrue(_messageCompleted); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Host", _hdr[0]); - Assert.assertEquals("localhost", _val[0]); - Assert.assertEquals("Name0", _hdr[1]); - Assert.assertEquals("", _val[1]); - Assert.assertEquals("Name1", _hdr[2]); - Assert.assertEquals("", _val[2]); - Assert.assertEquals(2, _headers); + assertTrue(_headerCompleted); + assertTrue(_messageCompleted); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Host", _hdr[0]); + assertEquals("localhost", _val[0]); + assertEquals("Name0", _hdr[1]); + assertEquals("", _val[1]); + assertEquals("Name1", _hdr[2]); + assertEquals("", _val[2]); + assertEquals(2, _headers); } @Test @@ -457,8 +464,8 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler,HttpCompliance.CUSTOM0); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.containsString("Illegal character")); - Assert.assertThat(_complianceViolation,contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME)); + assertThat(_bad, containsString("Illegal character")); + assertThat(_complianceViolation,contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME)); } @Test @@ -475,8 +482,8 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler,HttpCompliance.CUSTOM0); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.containsString("Illegal character")); - Assert.assertThat(_complianceViolation,contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME)); + assertThat(_bad, containsString("Illegal character")); + assertThat(_complianceViolation,contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME)); } @Test @@ -492,23 +499,23 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler, -1, HttpCompliance.CUSTOM0); parseAll(parser, buffer); - Assert.assertTrue(_headerCompleted); - Assert.assertTrue(_messageCompleted); + assertTrue(_headerCompleted); + assertTrue(_messageCompleted); - Assert.assertEquals("HTTP/1.1", _methodOrVersion); - Assert.assertEquals("204", _uriOrStatus); - Assert.assertEquals("No Content", _versionOrReason); - Assert.assertEquals(null, _content); + assertEquals("HTTP/1.1", _methodOrVersion); + assertEquals("204", _uriOrStatus); + assertEquals("No Content", _versionOrReason); + assertEquals(null, _content); - Assert.assertEquals(1, _headers); + assertEquals(1, _headers); System.out.println(Arrays.asList(_hdr)); System.out.println(Arrays.asList(_val)); - Assert.assertEquals("Access-Control-Allow-Headers", _hdr[0]); - Assert.assertEquals("Origin", _val[0]); - Assert.assertEquals("Other", _hdr[1]); - Assert.assertEquals("value", _val[1]); + assertEquals("Access-Control-Allow-Headers", _hdr[0]); + assertEquals("Origin", _val[0]); + assertEquals("Other", _hdr[1]); + assertEquals("value", _val[1]); - Assert.assertThat(_complianceViolation, contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME,HttpComplianceSection.NO_WS_AFTER_FIELD_NAME)); + assertThat(_complianceViolation, contains(HttpComplianceSection.NO_WS_AFTER_FIELD_NAME,HttpComplianceSection.NO_WS_AFTER_FIELD_NAME)); } @Test @@ -524,10 +531,10 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("HTTP/1.1", _methodOrVersion); - Assert.assertEquals("204", _uriOrStatus); - Assert.assertEquals("No Content", _versionOrReason); - Assert.assertThat(_bad, Matchers.containsString("Illegal character ")); + assertEquals("HTTP/1.1", _methodOrVersion); + assertEquals("204", _uriOrStatus); + assertEquals("No Content", _versionOrReason); + assertThat(_bad, containsString("Illegal character ")); } @Test @@ -542,8 +549,8 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler,HttpCompliance.RFC7230_LEGACY); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.containsString("Illegal character")); - Assert.assertThat(_complianceViolation,Matchers.empty()); + assertThat(_bad, containsString("Illegal character")); + assertThat(_complianceViolation,Matchers.empty()); } @@ -572,30 +579,30 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Host", _hdr[0]); - Assert.assertEquals("localhost", _val[0]); - Assert.assertEquals("Header1", _hdr[1]); - Assert.assertEquals("value1", _val[1]); - Assert.assertEquals("Header2", _hdr[2]); - Assert.assertEquals("value 2a", _val[2]); - Assert.assertEquals("Header3", _hdr[3]); - Assert.assertEquals("3", _val[3]); - Assert.assertEquals("Header4", _hdr[4]); - Assert.assertEquals("value4", _val[4]); - Assert.assertEquals("Server5", _hdr[5]); - Assert.assertEquals("notServer", _val[5]); - Assert.assertEquals("HostHeader", _hdr[6]); - Assert.assertEquals("notHost", _val[6]); - Assert.assertEquals("Connection", _hdr[7]); - Assert.assertEquals("close", _val[7]); - Assert.assertEquals("Accept-Encoding", _hdr[8]); - Assert.assertEquals("gzip, deflated", _val[8]); - Assert.assertEquals("Accept", _hdr[9]); - Assert.assertEquals("unknown", _val[9]); - Assert.assertEquals(9, _headers); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Host", _hdr[0]); + assertEquals("localhost", _val[0]); + assertEquals("Header1", _hdr[1]); + assertEquals("value1", _val[1]); + assertEquals("Header2", _hdr[2]); + assertEquals("value 2a", _val[2]); + assertEquals("Header3", _hdr[3]); + assertEquals("3", _val[3]); + assertEquals("Header4", _hdr[4]); + assertEquals("value4", _val[4]); + assertEquals("Server5", _hdr[5]); + assertEquals("notServer", _val[5]); + assertEquals("HostHeader", _hdr[6]); + assertEquals("notHost", _val[6]); + assertEquals("Connection", _hdr[7]); + assertEquals("close", _val[7]); + assertEquals("Accept-Encoding", _hdr[8]); + assertEquals("gzip, deflated", _val[8]); + assertEquals("Accept", _hdr[9]); + assertEquals("unknown", _val[9]); + assertEquals(9, _headers); } @Test @@ -618,30 +625,30 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Host", _hdr[0]); - Assert.assertEquals("localhost", _val[0]); - Assert.assertEquals("Header1", _hdr[1]); - Assert.assertEquals("value1", _val[1]); - Assert.assertEquals("Header2", _hdr[2]); - Assert.assertEquals("value 2a", _val[2]); - Assert.assertEquals("Header3", _hdr[3]); - Assert.assertEquals("3", _val[3]); - Assert.assertEquals("Header4", _hdr[4]); - Assert.assertEquals("value4", _val[4]); - Assert.assertEquals("Server5", _hdr[5]); - Assert.assertEquals("notServer", _val[5]); - Assert.assertEquals("HostHeader", _hdr[6]); - Assert.assertEquals("notHost", _val[6]); - Assert.assertEquals("Connection", _hdr[7]); - Assert.assertEquals("close", _val[7]); - Assert.assertEquals("Accept-Encoding", _hdr[8]); - Assert.assertEquals("gzip, deflated", _val[8]); - Assert.assertEquals("Accept", _hdr[9]); - Assert.assertEquals("unknown", _val[9]); - Assert.assertEquals(9, _headers); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Host", _hdr[0]); + assertEquals("localhost", _val[0]); + assertEquals("Header1", _hdr[1]); + assertEquals("value1", _val[1]); + assertEquals("Header2", _hdr[2]); + assertEquals("value 2a", _val[2]); + assertEquals("Header3", _hdr[3]); + assertEquals("3", _val[3]); + assertEquals("Header4", _hdr[4]); + assertEquals("value4", _val[4]); + assertEquals("Server5", _hdr[5]); + assertEquals("notServer", _val[5]); + assertEquals("HostHeader", _hdr[6]); + assertEquals("notHost", _val[6]); + assertEquals("Connection", _hdr[7]); + assertEquals("close", _val[7]); + assertEquals("Accept-Encoding", _hdr[8]); + assertEquals("gzip, deflated", _val[8]); + assertEquals("Accept", _hdr[9]); + assertEquals("unknown", _val[9]); + assertEquals(9, _headers); } @Test @@ -664,30 +671,30 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Host", _hdr[0]); - Assert.assertEquals("localhost", _val[0]); - Assert.assertEquals("Header1", _hdr[1]); - Assert.assertEquals("value1", _val[1]); - Assert.assertEquals("Header2", _hdr[2]); - Assert.assertEquals("value 2a value 2b", _val[2]); - Assert.assertEquals("Header3", _hdr[3]); - Assert.assertEquals("3", _val[3]); - Assert.assertEquals("Header4", _hdr[4]); - Assert.assertEquals("value4", _val[4]); - Assert.assertEquals("Server5", _hdr[5]); - Assert.assertEquals("notServer", _val[5]); - Assert.assertEquals("HostHeader", _hdr[6]); - Assert.assertEquals("notHost", _val[6]); - Assert.assertEquals("Connection", _hdr[7]); - Assert.assertEquals("close", _val[7]); - Assert.assertEquals("Accept-Encoding", _hdr[8]); - Assert.assertEquals("gzip, deflated", _val[8]); - Assert.assertEquals("Accept", _hdr[9]); - Assert.assertEquals("unknown", _val[9]); - Assert.assertEquals(9, _headers); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Host", _hdr[0]); + assertEquals("localhost", _val[0]); + assertEquals("Header1", _hdr[1]); + assertEquals("value1", _val[1]); + assertEquals("Header2", _hdr[2]); + assertEquals("value 2a value 2b", _val[2]); + assertEquals("Header3", _hdr[3]); + assertEquals("3", _val[3]); + assertEquals("Header4", _hdr[4]); + assertEquals("value4", _val[4]); + assertEquals("Server5", _hdr[5]); + assertEquals("notServer", _val[5]); + assertEquals("HostHeader", _hdr[6]); + assertEquals("notHost", _val[6]); + assertEquals("Connection", _hdr[7]); + assertEquals("close", _val[7]); + assertEquals("Accept-Encoding", _hdr[8]); + assertEquals("gzip, deflated", _val[8]); + assertEquals("Accept", _hdr[9]); + assertEquals("unknown", _val[9]); + assertEquals(9, _headers); } @Test @@ -703,16 +710,16 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Name0", _hdr[0]); - Assert.assertEquals("\"value0\"", _val[0]); - Assert.assertEquals("Name1", _hdr[1]); - Assert.assertEquals("\"value\t1\"", _val[1]); - Assert.assertEquals("Name2", _hdr[2]); - Assert.assertEquals("\"value\t2A\",\"value,2B\"", _val[2]); - Assert.assertEquals(2, _headers); + assertEquals("GET", _methodOrVersion); + assertEquals("/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Name0", _hdr[0]); + assertEquals("\"value0\"", _val[0]); + assertEquals("Name1", _hdr[1]); + assertEquals("\"value\t1\"", _val[1]); + assertEquals("Name2", _hdr[2]); + assertEquals("\"value\t2A\",\"value,2B\"", _val[2]); + assertEquals(2, _headers); } @Test @@ -734,15 +741,15 @@ public class HttpParserTest HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertEquals("GET", _methodOrVersion); - Assert.assertEquals("/foo/\u0690/", _uriOrStatus); - Assert.assertEquals("HTTP/1.0", _versionOrReason); - Assert.assertEquals("Header1", _hdr[0]); - Assert.assertEquals("\u00e6 \u00e6", _val[0]); - Assert.assertEquals("Header2", _hdr[1]); - Assert.assertEquals(""+(char)255, _val[1]); - Assert.assertEquals(1, _headers); - Assert.assertEquals(null, _bad); + assertEquals("GET", _methodOrVersion); + assertEquals("/foo/\u0690/", _uriOrStatus); + assertEquals("HTTP/1.0", _versionOrReason); + assertEquals("Header1", _hdr[0]); + assertEquals("\u00e6 \u00e6", _val[0]); + assertEquals("Header2", _hdr[1]); + assertEquals(""+(char)255, _val[1]); + assertEquals(1, _headers); + assertEquals(null, _bad); } @Test @@ -764,7 +771,7 @@ public class HttpParserTest parser.parseNext(buffer); } - Assert.assertThat(BufferUtil.toUTF8String(buffer), Matchers.is("FOOGRADE")); + assertThat(BufferUtil.toUTF8String(buffer), Matchers.is("FOOGRADE")); } @Test @@ -776,7 +783,7 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.notNullValue()); + assertThat(_bad, Matchers.notNullValue()); } @Test @@ -788,7 +795,7 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.notNullValue()); + assertThat(_bad, Matchers.notNullValue()); } @Test @@ -802,13 +809,13 @@ public class HttpParserTest HttpParser.RequestHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parseAll(parser, buffer); - Assert.assertThat(_bad, Matchers.notNullValue()); + assertThat(_bad, Matchers.notNullValue()); } - - @Test + + @Test // TODO: Parameterize Test public void testBadHeaderNames() throws Exception { - String[] bad = new String[] + String[] bad = new String[] { "Foo\\Bar: value\r\n", "Foo@Bar: value\r\n", @@ -826,7 +833,7 @@ public class HttpParserTest "Foo]Bar: value\r\n", "Foo[Bar: value\r\n", }; - + for (int i=0; i data() + public static Stream data() { - String[][] tests = { + return Stream.of( - // Nothing but path - {"path",null,null,"-1","path",null,null,null}, - {"path/path",null,null,"-1","path/path",null,null,null}, - {"%65ncoded/path",null,null,"-1","%65ncoded/path",null,null,null}, + // Nothing but path + Arguments.of("path",null,null,"-1","path",null,null,null), + Arguments.of("path/path",null,null,"-1","path/path",null,null,null), + Arguments.of("%65ncoded/path",null,null,"-1","%65ncoded/path",null,null,null), // Basic path reference - {"/path/to/context",null,null,"-1","/path/to/context",null,null,null}, + Arguments.of("/path/to/context",null,null,"-1","/path/to/context",null,null,null), // Basic with encoded query - {"http://example.com/path/to/context;param?query=%22value%22#fragment","http","example.com","-1","/path/to/context;param","param","query=%22value%22","fragment"}, - {"http://[::1]/path/to/context;param?query=%22value%22#fragment","http","[::1]","-1","/path/to/context;param","param","query=%22value%22","fragment"}, + Arguments.of("http://example.com/path/to/context;param?query=%22value%22#fragment","http","example.com","-1","/path/to/context;param","param","query=%22value%22","fragment"), + Arguments.of("http://[::1]/path/to/context;param?query=%22value%22#fragment","http","[::1]","-1","/path/to/context;param","param","query=%22value%22","fragment"), // Basic with parameters and query - {"http://example.com:8080/path/to/context;param?query=%22value%22#fragment","http","example.com","8080","/path/to/context;param","param","query=%22value%22","fragment"}, - {"http://[::1]:8080/path/to/context;param?query=%22value%22#fragment","http","[::1]","8080","/path/to/context;param","param","query=%22value%22","fragment"}, + Arguments.of("http://example.com:8080/path/to/context;param?query=%22value%22#fragment","http","example.com","8080","/path/to/context;param","param","query=%22value%22","fragment"), + Arguments.of("http://[::1]:8080/path/to/context;param?query=%22value%22#fragment","http","[::1]","8080","/path/to/context;param","param","query=%22value%22","fragment"), // Path References - {"/path/info",null,null,null,"/path/info",null,null,null}, - {"/path/info#fragment",null,null,null,"/path/info",null,null,"fragment"}, - {"/path/info?query",null,null,null,"/path/info",null,"query",null}, - {"/path/info?query#fragment",null,null,null,"/path/info",null,"query","fragment"}, - {"/path/info;param",null,null,null,"/path/info;param","param",null,null}, - {"/path/info;param#fragment",null,null,null,"/path/info;param","param",null,"fragment"}, - {"/path/info;param?query",null,null,null,"/path/info;param","param","query",null}, - {"/path/info;param?query#fragment",null,null,null,"/path/info;param","param","query","fragment"}, - {"/path/info;a=b/foo;c=d",null,null,null,"/path/info;a=b/foo;c=d","c=d",null,null}, // TODO #405 + Arguments.of("/path/info",null,null,null,"/path/info",null,null,null), + Arguments.of("/path/info#fragment",null,null,null,"/path/info",null,null,"fragment"), + Arguments.of("/path/info?query",null,null,null,"/path/info",null,"query",null), + Arguments.of("/path/info?query#fragment",null,null,null,"/path/info",null,"query","fragment"), + Arguments.of("/path/info;param",null,null,null,"/path/info;param","param",null,null), + Arguments.of("/path/info;param#fragment",null,null,null,"/path/info;param","param",null,"fragment"), + Arguments.of("/path/info;param?query",null,null,null,"/path/info;param","param","query",null), + Arguments.of("/path/info;param?query#fragment",null,null,null,"/path/info;param","param","query","fragment"), + Arguments.of("/path/info;a=b/foo;c=d",null,null,null,"/path/info;a=b/foo;c=d","c=d",null,null), // TODO #405 // Protocol Less (aka scheme-less) URIs - {"//host/path/info",null,"host",null,"/path/info",null,null,null}, - {"//user@host/path/info",null,"host",null,"/path/info",null,null,null}, - {"//user@host:8080/path/info",null,"host","8080","/path/info",null,null,null}, - {"//host:8080/path/info",null,"host","8080","/path/info",null,null,null}, + Arguments.of("//host/path/info",null,"host",null,"/path/info",null,null,null), + Arguments.of("//user@host/path/info",null,"host",null,"/path/info",null,null,null), + Arguments.of("//user@host:8080/path/info",null,"host","8080","/path/info",null,null,null), + Arguments.of("//host:8080/path/info",null,"host","8080","/path/info",null,null,null), // Host Less - {"http:/path/info","http",null,null,"/path/info",null,null,null}, - {"http:/path/info#fragment","http",null,null,"/path/info",null,null,"fragment"}, - {"http:/path/info?query","http",null,null,"/path/info",null,"query",null}, - {"http:/path/info?query#fragment","http",null,null,"/path/info",null,"query","fragment"}, - {"http:/path/info;param","http",null,null,"/path/info;param","param",null,null}, - {"http:/path/info;param#fragment","http",null,null,"/path/info;param","param",null,"fragment"}, - {"http:/path/info;param?query","http",null,null,"/path/info;param","param","query",null}, - {"http:/path/info;param?query#fragment","http",null,null,"/path/info;param","param","query","fragment"}, + Arguments.of("http:/path/info","http",null,null,"/path/info",null,null,null), + Arguments.of("http:/path/info#fragment","http",null,null,"/path/info",null,null,"fragment"), + Arguments.of("http:/path/info?query","http",null,null,"/path/info",null,"query",null), + Arguments.of("http:/path/info?query#fragment","http",null,null,"/path/info",null,"query","fragment"), + Arguments.of("http:/path/info;param","http",null,null,"/path/info;param","param",null,null), + Arguments.of("http:/path/info;param#fragment","http",null,null,"/path/info;param","param",null,"fragment"), + Arguments.of("http:/path/info;param?query","http",null,null,"/path/info;param","param","query",null), + Arguments.of("http:/path/info;param?query#fragment","http",null,null,"/path/info;param","param","query","fragment"), // Everything and the kitchen sink - {"http://user@host:8080/path/info;param?query#fragment","http","host","8080","/path/info;param","param","query","fragment"}, - {"xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","host","8080","/path/info;param","param","query","fragment"}, + Arguments.of("http://user@host:8080/path/info;param?query#fragment","http","host","8080","/path/info;param","param","query","fragment"), + Arguments.of("xxxxx://user@host:8080/path/info;param?query#fragment","xxxxx","host","8080","/path/info;param","param","query","fragment"), // No host, parameter with no content - {"http:///;?#","http",null,null,"/;","","",""}, + Arguments.of("http:///;?#","http",null,null,"/;","","",""), // Path with query that has no value - {"/path/info?a=?query",null,null,null,"/path/info",null,"a=?query",null}, + Arguments.of("/path/info?a=?query",null,null,null,"/path/info",null,"a=?query",null), // Path with query alt syntax - {"/path/info?a=;query",null,null,null,"/path/info",null,"a=;query",null}, + Arguments.of("/path/info?a=;query",null,null,null,"/path/info",null,"a=;query",null), // URI with host character - {"/@path/info",null,null,null,"/@path/info",null,null,null}, - {"/user@path/info",null,null,null,"/user@path/info",null,null,null}, - {"//user@host/info",null,"host",null,"/info",null,null,null}, - {"//@host/info",null,"host",null,"/info",null,null,null}, - {"@host/info",null,null,null,"@host/info",null,null,null}, + Arguments.of("/@path/info",null,null,null,"/@path/info",null,null,null), + Arguments.of("/user@path/info",null,null,null,"/user@path/info",null,null,null), + Arguments.of("//user@host/info",null,"host",null,"/info",null,null,null), + Arguments.of("//@host/info",null,"host",null,"/info",null,null,null), + Arguments.of("@host/info",null,null,null,"@host/info",null,null,null), // Scheme-less, with host and port (overlapping with path) - {"//host:8080//",null,"host","8080","//",null,null,null}, + Arguments.of("//host:8080//",null,"host","8080","//",null,null,null), // File reference - {"file:///path/info","file",null,null,"/path/info",null,null,null}, - {"file:/path/info","file",null,null,"/path/info",null,null,null}, + Arguments.of("file:///path/info","file",null,null,"/path/info",null,null,null), + Arguments.of("file:/path/info","file",null,null,"/path/info",null,null,null), // Bad URI (no scheme, no host, no path) - {"//",null,null,null,null,null,null,null}, + Arguments.of("//",null,null,null,null,null,null,null), // Simple localhost references - {"http://localhost/","http","localhost",null,"/",null,null,null}, - {"http://localhost:8080/", "http", "localhost","8080","/", null, null,null}, - {"http://localhost/?x=y", "http", "localhost",null,"/", null,"x=y",null}, + Arguments.of("http://localhost/","http","localhost",null,"/",null,null,null), + Arguments.of("http://localhost:8080/", "http", "localhost","8080","/", null, null,null), + Arguments.of("http://localhost/?x=y", "http", "localhost",null,"/", null,"x=y",null), // Simple path with parameter - {"/;param",null, null,null,"/;param", "param",null,null}, - {";param",null, null,null,";param", "param",null,null}, + Arguments.of("/;param",null, null,null,"/;param", "param",null,null), + Arguments.of(";param",null, null,null,";param", "param",null,null), // Simple path with query - {"/?x=y",null, null,null,"/", null,"x=y",null}, - {"/?abc=test",null, null,null,"/", null,"abc=test",null}, + Arguments.of("/?x=y",null, null,null,"/", null,"x=y",null), + Arguments.of("/?abc=test",null, null,null,"/", null,"abc=test",null), // Simple path with fragment - {"/#fragment",null, null,null,"/", null,null,"fragment"}, + Arguments.of("/#fragment",null, null,null,"/", null,null,"fragment"), // Simple IPv4 host with port (default path) - {"http://192.0.0.1:8080/","http","192.0.0.1","8080","/",null,null,null}, + Arguments.of("http://192.0.0.1:8080/","http","192.0.0.1","8080","/",null,null,null), // Simple IPv6 host with port (default path) - {"http://[2001:db8::1]:8080/","http","[2001:db8::1]","8080","/",null,null,null}, + Arguments.of("http://[2001:db8::1]:8080/","http","[2001:db8::1]","8080","/",null,null,null), // IPv6 authenticated host with port (default path) - {"http://user@[2001:db8::1]:8080/","http","[2001:db8::1]","8080","/",null,null,null}, + Arguments.of("http://user@[2001:db8::1]:8080/","http","[2001:db8::1]","8080","/",null,null,null), // Simple IPv6 host no port (default path) - {"http://[2001:db8::1]/","http","[2001:db8::1]",null,"/",null,null,null}, + Arguments.of("http://[2001:db8::1]/","http","[2001:db8::1]",null,"/",null,null,null), // Scheme-less IPv6, host with port (default path) - {"//[2001:db8::1]:8080/",null,"[2001:db8::1]","8080","/",null,null,null}, + Arguments.of("//[2001:db8::1]:8080/",null,"[2001:db8::1]","8080","/",null,null,null), // Interpreted as relative path of "*" (no host/port/scheme/query/fragment) - {"*",null,null,null,"*",null, null,null}, + Arguments.of("*",null,null,null,"*",null, null,null), // Path detection Tests (seen from JSP/JSTL and use) - {"http://host:8080/path/info?q1=v1&q2=v2","http","host","8080","/path/info",null,"q1=v1&q2=v2",null}, - {"/path/info?q1=v1&q2=v2",null,null,null,"/path/info",null,"q1=v1&q2=v2",null}, - {"/info?q1=v1&q2=v2",null,null,null,"/info",null,"q1=v1&q2=v2",null}, - {"info?q1=v1&q2=v2",null,null,null,"info",null,"q1=v1&q2=v2",null}, - {"info;q1=v1?q2=v2",null,null,null,"info;q1=v1","q1=v1","q2=v2",null}, + Arguments.of("http://host:8080/path/info?q1=v1&q2=v2","http","host","8080","/path/info",null,"q1=v1&q2=v2",null), + Arguments.of("/path/info?q1=v1&q2=v2",null,null,null,"/path/info",null,"q1=v1&q2=v2",null), + Arguments.of("/info?q1=v1&q2=v2",null,null,null,"/info",null,"q1=v1&q2=v2",null), + Arguments.of("info?q1=v1&q2=v2",null,null,null,"info",null,"q1=v1&q2=v2",null), + Arguments.of("info;q1=v1?q2=v2",null,null,null,"info;q1=v1","q1=v1","q2=v2",null), // Path-less, query only (seen from JSP/JSTL and use) - {"?q1=v1&q2=v2",null,null,null,"",null,"q1=v1&q2=v2",null} - }; - - return Arrays.asList(tests); + Arguments.of("?q1=v1&q2=v2",null,null,null,"",null,"q1=v1&q2=v2",null) + ); } - @Parameter(0) - public String input; - - @Parameter(1) - public String scheme; - - @Parameter(2) - public String host; - - @Parameter(3) - public String port; - - @Parameter(4) - public String path; - - @Parameter(5) - public String param; - - @Parameter(6) - public String query; - - @Parameter(7) - public String fragment; - - @Test - public void testParseString() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testParseString(String input, String scheme, String host, Integer port, String path, String param, String query, String fragment) throws Exception { HttpURI httpUri = new HttpURI(input); @@ -208,7 +176,7 @@ public class HttpURIParseTest // Assert expectations assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(scheme)); assertThat("[" + input + "] .host",httpUri.getHost(),is(host)); - assertThat("[" + input + "] .port",httpUri.getPort(),is(port == null ? -1 : Integer.parseInt(port))); + assertThat("[" + input + "] .port",httpUri.getPort(),is(port == null ? -1 : port)); assertThat("[" + input + "] .path",httpUri.getPath(),is(path)); assertThat("[" + input + "] .param",httpUri.getParam(),is(param)); assertThat("[" + input + "] .query",httpUri.getQuery(),is(query)); @@ -227,27 +195,27 @@ public class HttpURIParseTest assertThat("[" + input + "] .fragment",httpUri.getFragment(),is(nullValue())); } } - - @Test - public void testParseURI() throws Exception + + @ParameterizedTest + @MethodSource("data") + public void testParseURI(String input, String scheme, String host, Integer port, String path, String param, String query, String fragment) throws Exception { URI javaUri = null; try { javaUri = new URI(input); - assumeNotNull(javaUri); } - catch (URISyntaxException e) + catch (URISyntaxException ignore) { // Ignore, as URI is invalid anyway - assumeNoException(e); } - + assumeTrue(javaUri != null, "Skipping, not a valid input URI"); + HttpURI httpUri = new HttpURI(javaUri); assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(scheme)); assertThat("[" + input + "] .host",httpUri.getHost(),is(host)); - assertThat("[" + input + "] .port",httpUri.getPort(),is(port == null ? -1 : Integer.parseInt(port))); + assertThat("[" + input + "] .port",httpUri.getPort(),is(port == null ? -1 : port)); assertThat("[" + input + "] .path",httpUri.getPath(),is(path)); assertThat("[" + input + "] .param",httpUri.getParam(),is(param)); assertThat("[" + input + "] .query",httpUri.getQuery(),is(query)); @@ -255,22 +223,22 @@ public class HttpURIParseTest assertThat("[" + input + "] .toString",httpUri.toString(),is(input)); } - - @Test - public void testCompareToJavaNetURI() throws Exception + + @ParameterizedTest + @MethodSource("data") + public void testCompareToJavaNetURI(String input, String scheme, String host, Integer port, String path, String param, String query, String fragment) throws Exception { URI javaUri = null; try { javaUri = new URI(input); - assumeNotNull(javaUri); } - catch (URISyntaxException e) + catch (URISyntaxException ignore) { // Ignore, as URI is invalid anyway - assumeNoException(e); } - + assumeTrue(javaUri != null, "Skipping, not a valid input URI"); + HttpURI httpUri = new HttpURI(javaUri); assertThat("[" + input + "] .scheme",httpUri.getScheme(),is(javaUri.getScheme())); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java index 000d35a35c1..b9f93871d4a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/HttpURITest.java @@ -21,16 +21,16 @@ package org.eclipse.jetty.http; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import org.eclipse.jetty.util.MultiMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class HttpURITest { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java index 3370199d231..a27ff28f876 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MimeTypesTest.java @@ -19,12 +19,12 @@ package org.eclipse.jetty.http; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.hamcrest.MatcherAssert.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MimeTypesTest { @@ -74,8 +74,8 @@ public class MimeTypesTest MimeTypes mimetypes = new MimeTypes(); String contentType = mimetypes.getMimeByExtension(filename); String prefix = "MimeTypes.getMimeByExtension(" + filename + ")"; - assertNotNull(prefix,contentType); - assertEquals(prefix,expectedMimeType,contentType); + assertNotNull(contentType,prefix); + assertEquals(expectedMimeType,contentType,prefix); } private void assertCharsetFromContentType(String contentType, String expectedCharset) diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java index 030ace1131b..8715794d88e 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartCaptureTest.java @@ -19,10 +19,10 @@ package org.eclipse.jetty.http; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; import java.io.BufferedReader; import java.io.IOException; @@ -38,145 +38,137 @@ import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.function.Function; +import java.util.stream.Stream; import javax.servlet.MultipartConfigElement; import javax.servlet.http.Part; import org.eclipse.jetty.toolchain.test.Hex; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.TestingDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.QuotedStringTokenizer; import org.eclipse.jetty.util.StringUtil; import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) +@ExtendWith(WorkDirExtension.class) public class MultiPartCaptureTest { - public static final int MAX_FILE_SIZE = 2 * 1024 * 1024; public static final int MAX_REQUEST_SIZE = MAX_FILE_SIZE + (60 * 1024); public static final int FILE_SIZE_THRESHOLD = 50; - @Parameterized.Parameters(name = "{0}") - public static List data() + public static Stream data() { - List ret = new ArrayList<>(); + return Stream.of( + // == Arbitrary / Non-Standard Examples == - // == Arbitrary / Non-Standard Examples == + "multipart-uppercase", + // "multipart-base64", // base64 transfer encoding deprecated + // "multipart-base64-long", // base64 transfer encoding deprecated - ret.add(new String[]{"multipart-uppercase"}); - // ret.add(new String[]{"multipart-base64"}); // base64 transfer encoding deprecated - // ret.add(new String[]{"multipart-base64-long"}); // base64 transfer encoding deprecated + // == Capture of raw request body contents from Apache HttpClient 4.5.5 == - // == Capture of raw request body contents from Apache HttpClient 4.5.5 == + "browser-capture-company-urlencoded-apache-httpcomp", + "browser-capture-complex-apache-httpcomp", + "browser-capture-duplicate-names-apache-httpcomp", + "browser-capture-encoding-mess-apache-httpcomp", + "browser-capture-nested-apache-httpcomp", + "browser-capture-nested-binary-apache-httpcomp", + "browser-capture-number-only2-apache-httpcomp", + "browser-capture-number-only-apache-httpcomp", + "browser-capture-sjis-apache-httpcomp", + "browser-capture-strange-quoting-apache-httpcomp", + "browser-capture-text-files-apache-httpcomp", + "browser-capture-unicode-names-apache-httpcomp", + "browser-capture-zalgo-text-plain-apache-httpcomp", - ret.add(new String[]{"browser-capture-company-urlencoded-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-complex-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-duplicate-names-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-encoding-mess-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-nested-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-nested-binary-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-number-only2-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-number-only-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-sjis-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-strange-quoting-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-text-files-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-unicode-names-apache-httpcomp"}); - ret.add(new String[]{"browser-capture-zalgo-text-plain-apache-httpcomp"}); + // == Capture of raw request body contents from Eclipse Jetty Http Client 9.4.9 == - // == Capture of raw request body contents from Eclipse Jetty Http Client 9.4.9 == + "browser-capture-complex-jetty-client", + "browser-capture-duplicate-names-jetty-client", + "browser-capture-encoding-mess-jetty-client", + "browser-capture-nested-jetty-client", + "browser-capture-number-only-jetty-client", + "browser-capture-sjis-jetty-client", + "browser-capture-text-files-jetty-client", + "browser-capture-unicode-names-jetty-client", + "browser-capture-whitespace-only-jetty-client", - ret.add(new String[]{"browser-capture-complex-jetty-client"}); - ret.add(new String[]{"browser-capture-duplicate-names-jetty-client"}); - ret.add(new String[]{"browser-capture-encoding-mess-jetty-client"}); - ret.add(new String[]{"browser-capture-nested-jetty-client"}); - ret.add(new String[]{"browser-capture-number-only-jetty-client"}); - ret.add(new String[]{"browser-capture-sjis-jetty-client"}); - ret.add(new String[]{"browser-capture-text-files-jetty-client"}); - ret.add(new String[]{"browser-capture-unicode-names-jetty-client"}); - ret.add(new String[]{"browser-capture-whitespace-only-jetty-client"}); + // == Capture of raw request body contents from various browsers == - // == Capture of raw request body contents from various browsers == + // simple form - 2 fields + "browser-capture-form1-android-chrome", + "browser-capture-form1-android-firefox", + "browser-capture-form1-chrome", + "browser-capture-form1-edge", + "browser-capture-form1-firefox", + "browser-capture-form1-ios-safari", + "browser-capture-form1-msie", + "browser-capture-form1-osx-safari", - // simple form - 2 fields - ret.add(new String[]{"browser-capture-form1-android-chrome"}); - ret.add(new String[]{"browser-capture-form1-android-firefox"}); - ret.add(new String[]{"browser-capture-form1-chrome"}); - ret.add(new String[]{"browser-capture-form1-edge"}); - ret.add(new String[]{"browser-capture-form1-firefox"}); - ret.add(new String[]{"browser-capture-form1-ios-safari"}); - ret.add(new String[]{"browser-capture-form1-msie"}); - ret.add(new String[]{"browser-capture-form1-osx-safari"}); + // form submitted as shift-jis + "browser-capture-sjis-form-edge", + "browser-capture-sjis-form-msie", + // TODO: these might be addressable via Issue #2398 + // "browser-capture-sjis-form-android-chrome", // contains html encoded character and unspecified charset defaults to utf-8 + // "browser-capture-sjis-form-android-firefox", // contains html encoded character and unspecified charset defaults to utf-8 + // "browser-capture-sjis-form-chrome", // contains html encoded character and unspecified charset defaults to utf-8 + // "browser-capture-sjis-form-firefox", // contains html encoded character and unspecified charset defaults to utf-8 + // "browser-capture-sjis-form-ios-safari", // contains html encoded character and unspecified charset defaults to utf-8 + // "browser-capture-sjis-form-safari", // contains html encoded character and unspecified charset defaults to utf-8 - // form submitted as shift-jis - ret.add(new String[]{"browser-capture-sjis-form-edge"}); - ret.add(new String[]{"browser-capture-sjis-form-msie"}); - // TODO: these might be addressable via Issue #2398 - // ret.add(new String[]{"browser-capture-sjis-form-android-chrome"}); // contains html encoded character and unspecified charset defaults to utf-8 - // ret.add(new String[]{"browser-capture-sjis-form-android-firefox"}); // contains html encoded character and unspecified charset defaults to utf-8 - // ret.add(new String[]{"browser-capture-sjis-form-chrome"}); // contains html encoded character and unspecified charset defaults to utf-8 - // ret.add(new String[]{"browser-capture-sjis-form-firefox"}); // contains html encoded character and unspecified charset defaults to utf-8 - // ret.add(new String[]{"browser-capture-sjis-form-ios-safari"}); // contains html encoded character and unspecified charset defaults to utf-8 - // ret.add(new String[]{"browser-capture-sjis-form-safari"}); // contains html encoded character and unspecified charset defaults to utf-8 + // form submitted as shift-jis (with HTML5 specific hidden _charset_ field) + "browser-capture-sjis-charset-form-android-chrome", // contains html encoded character + "browser-capture-sjis-charset-form-android-firefox", // contains html encoded character + "browser-capture-sjis-charset-form-chrome", // contains html encoded character + "browser-capture-sjis-charset-form-edge", + "browser-capture-sjis-charset-form-firefox", // contains html encoded character + "browser-capture-sjis-charset-form-ios-safari", // contains html encoded character + "browser-capture-sjis-charset-form-msie", + "browser-capture-sjis-charset-form-safari", // contains html encoded character - // form submitted as shift-jis (with HTML5 specific hidden _charset_ field) - ret.add(new String[]{"browser-capture-sjis-charset-form-android-chrome"}); // contains html encoded character - ret.add(new String[]{"browser-capture-sjis-charset-form-android-firefox"}); // contains html encoded character - ret.add(new String[]{"browser-capture-sjis-charset-form-chrome"}); // contains html encoded character - ret.add(new String[]{"browser-capture-sjis-charset-form-edge"}); - ret.add(new String[]{"browser-capture-sjis-charset-form-firefox"}); // contains html encoded character - ret.add(new String[]{"browser-capture-sjis-charset-form-ios-safari"}); // contains html encoded character - ret.add(new String[]{"browser-capture-sjis-charset-form-msie"}); - ret.add(new String[]{"browser-capture-sjis-charset-form-safari"}); // contains html encoded character + // form submitted with simple file upload + "browser-capture-form-fileupload-android-chrome", + "browser-capture-form-fileupload-android-firefox", + "browser-capture-form-fileupload-chrome", + "browser-capture-form-fileupload-edge", + "browser-capture-form-fileupload-firefox", + "browser-capture-form-fileupload-ios-safari", + "browser-capture-form-fileupload-msie", + "browser-capture-form-fileupload-safari", - // form submitted with simple file upload - ret.add(new String[]{"browser-capture-form-fileupload-android-chrome"}); - ret.add(new String[]{"browser-capture-form-fileupload-android-firefox"}); - ret.add(new String[]{"browser-capture-form-fileupload-chrome"}); - ret.add(new String[]{"browser-capture-form-fileupload-edge"}); - ret.add(new String[]{"browser-capture-form-fileupload-firefox"}); - ret.add(new String[]{"browser-capture-form-fileupload-ios-safari"}); - ret.add(new String[]{"browser-capture-form-fileupload-msie"}); - ret.add(new String[]{"browser-capture-form-fileupload-safari"}); - - // form submitted with 2 files (1 binary, 1 text) and 2 text fields - ret.add(new String[]{"browser-capture-form-fileupload-alt-chrome"}); - ret.add(new String[]{"browser-capture-form-fileupload-alt-edge"}); - ret.add(new String[]{"browser-capture-form-fileupload-alt-firefox"}); - ret.add(new String[]{"browser-capture-form-fileupload-alt-msie"}); - ret.add(new String[]{"browser-capture-form-fileupload-alt-safari"}); - - return ret; + // form submitted with 2 files (1 binary, 1 text) and 2 text fields + "browser-capture-form-fileupload-alt-chrome", + "browser-capture-form-fileupload-alt-edge", + "browser-capture-form-fileupload-alt-firefox", + "browser-capture-form-fileupload-alt-msie", + "browser-capture-form-fileupload-alt-safari" + ).map(Arguments::of); } - @Rule - public TestingDir testingDir = new TestingDir(); + public WorkDir testingDir; - private final Path multipartRawFile; - private final MultipartExpectations multipartExpectations; - - public MultiPartCaptureTest(String rawPrefix) throws IOException + @ParameterizedTest + @MethodSource("data") + public void testUtilParse(String rawPrefix) throws Exception { - multipartRawFile = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".raw"); + Path multipartRawFile = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".raw"); Path expectationPath = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".expected.txt"); - multipartExpectations = new MultipartExpectations(expectationPath); - } + MultipartExpectations multipartExpectations = new MultipartExpectations(expectationPath); - @Test - public void testUtilParse() throws Exception - { Path outputDir = testingDir.getEmptyPathDir(); MultipartConfigElement config = newMultipartConfigElement(outputDir); try (InputStream in = Files.newInputStream(multipartRawFile)) { org.eclipse.jetty.util.MultiPartInputStreamParser parser = new org.eclipse.jetty.util.MultiPartInputStreamParser(in,multipartExpectations.contentType,config,outputDir.toFile()); - checkParts(parser.getParts(),s-> + multipartExpectations.checkParts(parser.getParts(),s-> { try { @@ -190,16 +182,21 @@ public class MultiPartCaptureTest } } - @Test - public void testHttpParse() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testHttpParse(String rawPrefix) throws Exception { + Path multipartRawFile = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".raw"); + Path expectationPath = MavenTestingUtils.getTestResourcePathFile("multipart/" + rawPrefix + ".expected.txt"); + MultipartExpectations multipartExpectations = new MultipartExpectations(expectationPath); + Path outputDir = testingDir.getEmptyPathDir(); MultipartConfigElement config = newMultipartConfigElement(outputDir); try (InputStream in = Files.newInputStream(multipartRawFile)) { MultiPartFormInputStream parser = new MultiPartFormInputStream(in, multipartExpectations.contentType, config, outputDir.toFile()); - checkParts(parser.getParts(),s-> + multipartExpectations.checkParts(parser.getParts(),s-> { try { @@ -213,85 +210,11 @@ public class MultiPartCaptureTest } } - private void checkParts(Collection parts, Function getPart) throws Exception - { - // Evaluate Count - if (multipartExpectations.partCount >= 0) - { - assertThat("Mulitpart.parts.size", parts.size(), is(multipartExpectations.partCount)); - } - - String defaultCharset = UTF_8.toString(); - Part charSetPart = getPart.apply("_charset_"); - if(charSetPart != null) - { - defaultCharset = IO.toString(charSetPart.getInputStream()); - } - - - // Evaluate expected Contents - for (NameValue expected : multipartExpectations.partContainsContents) - { - Part part = getPart.apply(expected.name); - assertThat("Part[" + expected.name + "]", part, is(notNullValue())); - try (InputStream partInputStream = part.getInputStream()) - { - String charset = getCharsetFromContentType(part.getContentType(), defaultCharset); - String contents = IO.toString(partInputStream, charset); - assertThat("Part[" + expected.name + "].contents", contents, containsString(expected.value)); - } - } - - // Evaluate expected filenames - for (NameValue expected : multipartExpectations.partFilenames) - { - Part part = getPart.apply(expected.name); - assertThat("Part[" + expected.name + "]", part, is(notNullValue())); - assertThat("Part[" + expected.name + "]", part.getSubmittedFileName(), is(expected.value)); - } - - // Evaluate expected contents checksums - for (NameValue expected : multipartExpectations.partSha1sums) - { - Part part = getPart.apply(expected.name); - assertThat("Part[" + expected.name + "]", part, is(notNullValue())); - MessageDigest digest = MessageDigest.getInstance("SHA1"); - try (InputStream partInputStream = part.getInputStream(); - NoOpOutputStream noop = new NoOpOutputStream(); - DigestOutputStream digester = new DigestOutputStream(noop, digest)) - { - IO.copy(partInputStream, digester); - String actualSha1sum = Hex.asHex(digest.digest()).toLowerCase(Locale.US); - assertThat("Part[" + expected.name + "].sha1sum", actualSha1sum, Matchers.equalToIgnoringCase(expected.value)); - } - } - } - private MultipartConfigElement newMultipartConfigElement(Path path) { return new MultipartConfigElement(path.toString(), MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD); } - private String getCharsetFromContentType(String contentType, String defaultCharset) - { - if(StringUtil.isBlank(contentType)) - { - return defaultCharset; - } - - QuotedStringTokenizer tok = new QuotedStringTokenizer(contentType, ";", false, false); - while(tok.hasMoreTokens()) - { - String str = tok.nextToken().trim(); - if(str.startsWith("charset=")) - { - return str.substring("charset=".length()); - } - } - - return defaultCharset; - } - public static class NameValue { public String name; @@ -372,9 +295,83 @@ public class MultiPartCaptureTest this.contentType = parsedContentType; this.partCount = Integer.parseInt(parsedPartCount); } + + private void checkParts(Collection parts, Function getPart) throws Exception + { + // Evaluate Count + if (partCount >= 0) + { + assertThat("Mulitpart.parts.size", parts.size(), is(partCount)); + } + + String defaultCharset = UTF_8.toString(); + Part charSetPart = getPart.apply("_charset_"); + if(charSetPart != null) + { + defaultCharset = IO.toString(charSetPart.getInputStream()); + } + + + // Evaluate expected Contents + for (NameValue expected : partContainsContents) + { + Part part = getPart.apply(expected.name); + assertThat("Part[" + expected.name + "]", part, is(notNullValue())); + try (InputStream partInputStream = part.getInputStream()) + { + String charset = getCharsetFromContentType(part.getContentType(), defaultCharset); + String contents = IO.toString(partInputStream, charset); + assertThat("Part[" + expected.name + "].contents", contents, containsString(expected.value)); + } + } + + // Evaluate expected filenames + for (NameValue expected : partFilenames) + { + Part part = getPart.apply(expected.name); + assertThat("Part[" + expected.name + "]", part, is(notNullValue())); + assertThat("Part[" + expected.name + "]", part.getSubmittedFileName(), is(expected.value)); + } + + // Evaluate expected contents checksums + for (NameValue expected : partSha1sums) + { + Part part = getPart.apply(expected.name); + assertThat("Part[" + expected.name + "]", part, is(notNullValue())); + MessageDigest digest = MessageDigest.getInstance("SHA1"); + try (InputStream partInputStream = part.getInputStream(); + NoOpOutputStream noop = new NoOpOutputStream(); + DigestOutputStream digester = new DigestOutputStream(noop, digest)) + { + IO.copy(partInputStream, digester); + String actualSha1sum = Hex.asHex(digest.digest()).toLowerCase(Locale.US); + assertThat("Part[" + expected.name + "].sha1sum", actualSha1sum, Matchers.equalToIgnoringCase(expected.value)); + } + } + } + + private String getCharsetFromContentType(String contentType, String defaultCharset) + { + if(StringUtil.isBlank(contentType)) + { + return defaultCharset; + } + + QuotedStringTokenizer tok = new QuotedStringTokenizer(contentType, ";", false, false); + while(tok.hasMoreTokens()) + { + String str = tok.nextToken().trim(); + if(str.startsWith("charset=")) + { + return str.substring("charset=".length()); + } + } + + return defaultCharset; + } } - class NoOpOutputStream extends OutputStream + static class NoOpOutputStream extends OutputStream { @Override public void write(byte[] b) throws IOException diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java index 4689b743407..87ca092a65f 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartFormInputStreamTest.java @@ -18,17 +18,20 @@ package org.eclipse.jetty.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -46,7 +49,7 @@ import javax.servlet.http.Part; import org.eclipse.jetty.http.MultiPartFormInputStream.MultiPart; import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.IO; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * MultiPartInputStreamTest @@ -56,6 +59,7 @@ public class MultiPartFormInputStreamTest private static final String FILENAME = "stuff.txt"; protected String _contentType = "multipart/form-data, boundary=AaB03x"; protected String _multi = createMultipartRequestString(FILENAME); + // TODO: move to testing dir concept protected String _dirname = System.getProperty("java.io.tmpdir") + File.separator + "myfiles-" + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); protected File _tmpDir = new File(_dirname); @@ -76,33 +80,29 @@ public class MultiPartFormInputStreamTest "\r\n--" + boundary + "-\r\n" + "Content-Disposition: form-data; name=\"fileup\"; filename=\"test.upload\"\r\n" + "\r\n"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), "multipart/form-data, boundary=" + boundary, config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); - fail("Incomplete Multipart"); - } - catch (IOException e) - { - assertTrue(e.getMessage().startsWith("Incomplete")); - } + + IOException x = assertThrows(IOException.class, + ()-> mpis.getParts(), + "Incomplete Multipart"); + assertThat(x.getMessage(), startsWith("Incomplete")); } - - + + @Test public void testFinalBoundaryOnly() throws Exception { String delimiter = "\r\n"; final String boundary = "MockMultiPartTestBoundary"; - - + + // Malformed multipart request body containing only an arbitrary string of text, followed by the final boundary marker, delimited by empty lines. String str = delimiter + @@ -110,7 +110,7 @@ public class MultiPartFormInputStreamTest delimiter + // Two delimiter markers, which make an empty line. delimiter + "--" + boundary + "--" + delimiter; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), "multipart/form-data, boundary=" + boundary, @@ -127,11 +127,11 @@ public class MultiPartFormInputStreamTest { String delimiter = "\r\n"; final String boundary = "MockMultiPartTestBoundary"; - + String str = delimiter + "--" + boundary + "--" + delimiter; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), "multipart/form-data, boundary=" + boundary, @@ -140,7 +140,7 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); assertTrue(mpis.getParts().isEmpty()); } - + @Test public void testNoBoundaryRequest() throws Exception @@ -186,7 +186,7 @@ public class MultiPartFormInputStreamTest assertThat(fileName.getSize(), is(3L)); IO.copy(fileName.getInputStream(), baos); assertThat(baos.toString("US-ASCII"), is("abc")); - + baos = new ByteArrayOutputStream(); Part desc = mpis.getPart("desc"); assertThat(desc, notNullValue()); @@ -201,7 +201,7 @@ public class MultiPartFormInputStreamTest IO.copy(title.getInputStream(), baos); assertThat(baos.toString("US-ASCII"), is("ttt")); } - + @Test public void testNonMultiPartRequest() throws Exception @@ -214,27 +214,21 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); assertTrue(mpis.getParts().isEmpty()); } - + @Test public void testNoBody() { String body = ""; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), _contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); - fail("Missing initial multi part boundary"); - } - catch (IOException e) - { - assertTrue(e.getMessage().contains("Missing initial multi part boundary")); - } + + IOException x = assertThrows(IOException.class, ()-> mpis.getParts()); + assertThat(x.getMessage(), containsString("Missing initial multi part boundary")); } @@ -244,24 +238,24 @@ public class MultiPartFormInputStreamTest { ServletInputStream is = new ServletInputStream() { - + @Override public boolean isFinished() { return true; } - + @Override public boolean isReady() { return false; } - + @Override public void setReadListener(ReadListener readListener) { } - + @Override public int read() { @@ -280,51 +274,37 @@ public class MultiPartFormInputStreamTest assertEquals(0, parts.size()); } - + @Test public void testWhitespaceBodyWithCRLF() { String whitespace = " \n\n\n\r\n\r\n\r\n\r\n"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(whitespace.getBytes()), _contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); - fail("Missing initial multi part boundary"); - } - catch (IOException e) - { - assertTrue(e.getMessage().contains("Missing initial multi part boundary")); - } + IOException x = assertThrows(IOException.class, ()-> mpis.getParts()); + assertThat(x.getMessage(), containsString("Missing initial multi part boundary")); } - + @Test public void testWhitespaceBody() { String whitespace = " "; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(whitespace.getBytes()), _contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); - fail("Multipart missing body"); - } - catch (IOException e) - { - assertTrue(e.getMessage().startsWith("Missing initial")); - } + IOException x = assertThrows(IOException.class, ()-> mpis.getParts()); + assertThat(x.getMessage(), containsString("Missing initial")); } - + @Test public void testLeadingWhitespaceBodyWithCRLF() throws Exception @@ -340,67 +320,70 @@ public class MultiPartFormInputStreamTest "\r\n" + "aaaa" + "bbbbb" + "\r\n" + "--AaB03x--\r\n"; - - + + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), _contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - + Collection parts = mpis.getParts(); assertThat(parts, notNullValue()); assertThat(parts.size(), is(2)); - Part field1 = mpis.getPart("field1"); - assertThat(field1, notNullValue()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - IO.copy(field1.getInputStream(), baos); - assertThat(baos.toString("US-ASCII"), is("Joe Blow")); - - Part stuff = mpis.getPart("stuff"); - assertThat(stuff, notNullValue()); - baos = new ByteArrayOutputStream(); - IO.copy(stuff.getInputStream(), baos); - assertTrue(baos.toString("US-ASCII").contains("aaaa")); + + try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) + { + Part field1 = mpis.getPart("field1"); + assertThat(field1, notNullValue()); + IO.copy(field1.getInputStream(), baos); + assertThat(baos.toString("US-ASCII"), is("Joe Blow")); + } + + try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) + { + Part stuff = mpis.getPart("stuff"); + assertThat(stuff, notNullValue()); + IO.copy(stuff.getInputStream(), baos); + assertThat(baos.toString("US-ASCII"), containsString("aaaa")); + } } - + @Test - public void testLeadingWhitespaceBodyWithoutCRLF() - throws Exception + public void testLeadingWhitespaceBodyWithoutCRLF() throws Exception { - String body = " " + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"field1\"\r\n" + - "\r\n" + - "Joe Blow\r\n" + - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"stuff\"; filename=\"" + "foo.txt" + "\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + "aaaa" + - "bbbbb" + "\r\n" + + String body = " "+ + "--AaB03x\r\n"+ + "content-disposition: form-data; name=\"field1\"\r\n"+ + "\r\n"+ + "Joe Blow\r\n"+ + "--AaB03x\r\n"+ + "content-disposition: form-data; name=\"stuff\"; filename=\"" + "foo.txt" + "\"\r\n"+ + "Content-Type: text/plain\r\n"+ + "\r\n"+"aaaa"+ + "bbbbb"+"\r\n" + "--AaB03x--\r\n"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), _contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - + Collection parts = mpis.getParts(); assertThat(parts, notNullValue()); assertThat(parts.size(), is(1)); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Part stuff = mpis.getPart("stuff"); assertThat(stuff, notNullValue()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); IO.copy(stuff.getInputStream(), baos); - assertTrue(baos.toString("US-ASCII").contains("bbbbb")); + assertThat(baos.toString("US-ASCII"), containsString("bbbbb")); } - - + @Test public void testNoLimits() throws Exception @@ -414,10 +397,9 @@ public class MultiPartFormInputStreamTest Collection parts = mpis.getParts(); assertFalse(parts.isEmpty()); } - + @Test - public void testRequestTooBig() - throws Exception + public void testRequestTooBig () { MultipartConfigElement config = new MultipartConfigElement(_dirname, 60, 100, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -425,22 +407,14 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - - try - { - mpis.getParts(); - fail("Request should have exceeded maxRequestSize"); - } - catch (IllegalStateException e) - { - assertTrue(e.getMessage().startsWith("Request exceeds maxRequestSize")); - } + + IllegalStateException x = assertThrows(IllegalStateException.class, ()-> mpis.getParts()); + assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); } @Test - public void testRequestTooBigThrowsErrorOnGetParts() - throws Exception + public void testRequestTooBigThrowsErrorOnGetParts () { MultipartConfigElement config = new MultipartConfigElement(_dirname, 60, 100, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -448,33 +422,18 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - + //cause parsing - try - { - mpis.getParts(); - fail("Request should have exceeded maxRequestSize"); - } - catch (IllegalStateException e) - { - assertTrue(e.getMessage().startsWith("Request exceeds maxRequestSize")); - } - + IllegalStateException x = assertThrows(IllegalStateException.class, ()-> mpis.getParts()); + assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); + //try again - try - { - mpis.getParts(); - fail("Request should have exceeded maxRequestSize"); - } - catch (IllegalStateException e) - { - assertTrue(e.getMessage().startsWith("Request exceeds maxRequestSize")); - } + x = assertThrows(IllegalStateException.class, ()-> mpis.getParts()); + assertThat(x.getMessage(), containsString("Request exceeds maxRequestSize")); } - + @Test public void testFileTooBig() - throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 40, 1024, 30); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -482,20 +441,14 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); - fail("stuff.txt should have been larger than maxFileSize"); - } - catch (IllegalStateException e) - { - assertTrue(e.getMessage().startsWith("Multipart Mime part")); - } + IllegalStateException x = assertThrows(IllegalStateException.class, + ()-> mpis.getParts(), + "stuff.txt should have been larger than maxFileSize"); + assertThat(x.getMessage(), startsWith("Multipart Mime part")); } @Test public void testFileTooBigThrowsErrorOnGetParts() - throws Exception { MultipartConfigElement config = new MultipartConfigElement(_dirname, 40, 1024, 30); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(_multi.getBytes()), @@ -503,29 +456,19 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); //caused parsing - fail("stuff.txt should have been larger than maxFileSize"); - } - catch (Throwable e) - { - assertTrue(e.getMessage().startsWith("Multipart Mime part")); - } - + // Caused parsing + IllegalStateException x = assertThrows(IllegalStateException.class, + ()-> mpis.getParts(), + "stuff.txt should have been larger than maxFileSize"); + assertThat(x.getMessage(), startsWith("Multipart Mime part")); + //test again after the parsing - try - { - mpis.getParts(); //caused parsing - fail("stuff.txt should have been larger than maxFileSize"); - } - catch (IllegalStateException e) - { - assertTrue(e.getMessage().startsWith("Multipart Mime part")); - } + x = assertThrows(IllegalStateException.class, + ()-> mpis.getParts(), + "stuff.txt should have been larger than maxFileSize"); + assertThat(x.getMessage(), startsWith("Multipart Mime part")); } - - + @Test public void testPartFileNotDeleted() throws Exception { @@ -559,7 +502,7 @@ public class MultiPartFormInputStreamTest _tmpDir); mpis.setDeleteOnExit(true); mpis.getParts(); - + MultiPart part = (MultiPart)mpis.getPart("stuff"); File stuff = part.getFile(); assertThat(stuff, notNullValue()); // longer than 100 bytes, should already be a tmp file @@ -581,7 +524,7 @@ public class MultiPartFormInputStreamTest "\n" + "Other" + "\r\n--AaB03x--\n"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), _contentType, @@ -595,14 +538,14 @@ public class MultiPartFormInputStreamTest ByteArrayOutputStream baos = new ByteArrayOutputStream(); IO.copy(p1.getInputStream(), baos); assertThat(baos.toString("UTF-8"), is("Joe Blow")); - + Part p2 = mpis.getPart("field2"); assertThat(p2, notNullValue()); baos = new ByteArrayOutputStream(); IO.copy(p2.getInputStream(), baos); assertThat(baos.toString("UTF-8"), is("Other")); - - + + } @Test @@ -617,39 +560,20 @@ public class MultiPartFormInputStreamTest "\r" + "Other\r" + "--AaB03x--\r"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(str.getBytes()), _contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - - try - { - Collection parts = mpis.getParts(); - assertThat(parts.size(), is(2)); - - assertThat(parts.size(), is(2)); - Part p1 = mpis.getPart("field1"); - assertThat(p1, notNullValue()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - IO.copy(p1.getInputStream(), baos); - assertThat(baos.toString("UTF-8"), is("Joe Blow")); - - Part p2 = mpis.getPart("field2"); - assertThat(p2, notNullValue()); - baos = new ByteArrayOutputStream(); - IO.copy(p2.getInputStream(), baos); - assertThat(baos.toString("UTF-8"), is("Other")); - } - catch (Throwable e) - { - assertTrue(e.getMessage().contains("Bad EOL")); - } + + IllegalStateException x = assertThrows(IllegalStateException.class, + ()-> mpis.getParts(), + "Improper EOL"); + assertThat(x.getMessage(), containsString("Bad EOL")); } - + @Test public void testCRandLFMixRequest() { @@ -670,29 +594,11 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - - - try - { - Collection parts = mpis.getParts(); - assertThat(parts.size(), is(2)); - - Part p1 = mpis.getPart("field1"); - assertThat(p1, notNullValue()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - IO.copy(p1.getInputStream(), baos); - assertThat(baos.toString("UTF-8"), is("\nJoe Blow\n")); - - Part p2 = mpis.getPart("field2"); - assertThat(p2, notNullValue()); - baos = new ByteArrayOutputStream(); - IO.copy(p2.getInputStream(), baos); - assertThat(baos.toString("UTF-8"), is("Other")); - } - catch (Throwable e) - { - assertTrue(e.getMessage().contains("Bad EOL")); - } + + IllegalStateException x = assertThrows(IllegalStateException.class, + ()-> mpis.getParts(), + "Improper EOL"); + assertThat(x.getMessage(), containsString("Bad EOL")); } @Test @@ -711,16 +617,10 @@ public class MultiPartFormInputStreamTest config, _tmpDir); mpis.setDeleteOnExit(true); - try - { - mpis.getParts(); - fail("Header Line Exceeded Max Length"); - } - catch (Throwable e) - { - assertTrue(e.getMessage().startsWith("Header Line Exceeded Max Length")); - } - + IllegalStateException x = assertThrows(IllegalStateException.class, + ()-> mpis.getParts(), + "Header Line Exceeded Max Length"); + assertThat(x.getMessage(), containsString("Header Line Exceeded Max Length")); } @Test @@ -788,7 +688,7 @@ public class MultiPartFormInputStreamTest assertThat(parts.size(), is(1)); assertThat(parts.iterator().next().getSubmittedFileName(), is("c:\\this\\really\\is\\some\\path\\to\\a\\file.txt")); } - + @Test public void testCorrectlyEncodedMSFilename() throws Exception { @@ -809,13 +709,13 @@ public class MultiPartFormInputStreamTest assertThat(parts.size(), is(1)); assertThat(parts.iterator().next().getSubmittedFileName(), is("c:\\this\\really\\is\\some\\path\\to\\a\\file.txt")); } - + @Test public void testMultiWithSpaceInFilename() throws Exception { testMulti("stuff with spaces.txt"); } - + @Test public void testWriteFilesIfContentDispositionFilename() @@ -864,7 +764,7 @@ public class MultiPartFormInputStreamTest Part field1 = mpis.getPart("field1"); //field 1 too small to go into tmp file, should be in internal buffer assertThat(field1, notNullValue()); assertThat(field1.getName(), is("field1")); - + ByteArrayOutputStream os = new ByteArrayOutputStream(); try (InputStream is = field1.getInputStream()) { @@ -872,7 +772,7 @@ public class MultiPartFormInputStreamTest } assertEquals("Joe Blow", new String(os.toByteArray())); assertEquals(8, field1.getSize()); - + assertNotNull(((MultiPartFormInputStream.MultiPart)field1).getBytes());//in internal buffer field1.write("field1.txt"); assertNull(((MultiPartFormInputStream.MultiPart)field1).getBytes());//no longer in internal buffer @@ -885,7 +785,7 @@ public class MultiPartFormInputStreamTest field1.delete(); //file should be deleted assertFalse(f.exists()); //original file was renamed assertFalse(f2.exists()); //2nd written file was explicitly deleted - + MultiPart stuff = (MultiPart)mpis.getPart("stuff"); assertThat(stuff.getSubmittedFileName(), is(filename)); assertThat(stuff.getContentType(), is("text/plain")); @@ -910,11 +810,11 @@ public class MultiPartFormInputStreamTest } catch (Exception e) { - fail("Part.getInputStream() after file rename operation: " + e.getMessage()); + fail("Part.getInputStream() after file rename operation", e); } f.deleteOnExit(); //clean up after test } - + @Test public void testMultiSameNames() throws Exception @@ -930,7 +830,7 @@ public class MultiPartFormInputStreamTest "\r\n" + "110000000000000000000000000000000000000000000000000\r\n" + "--AaB03x--\r\n"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(sameNames.getBytes()), _contentType, @@ -941,13 +841,13 @@ public class MultiPartFormInputStreamTest assertEquals(2, parts.size()); for (Part p : parts) assertEquals("stuff", p.getName()); - + //if they all have the name name, then only retrieve the first one Part p = mpis.getPart("stuff"); assertNotNull(p); assertEquals(5, p.getSize()); } - + @Test public void testBase64EncodedContent() throws Exception { @@ -969,7 +869,7 @@ public class MultiPartFormInputStreamTest "\r\n" + "the end" + "\r\n" + "--AaB03x--\r\n"; - + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(contentWithEncodedPart.getBytes()), _contentType, @@ -978,13 +878,13 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertEquals(3, parts.size()); - + Part p1 = mpis.getPart("other"); assertNotNull(p1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IO.copy(p1.getInputStream(), baos); assertEquals("other", baos.toString("US-ASCII")); - + Part p2 = mpis.getPart("stuff"); assertNotNull(p2); baos = new ByteArrayOutputStream(); @@ -1022,21 +922,21 @@ public class MultiPartFormInputStreamTest mpis.setDeleteOnExit(true); Collection parts = mpis.getParts(); assertEquals(2, parts.size()); - + Part p1 = mpis.getPart("other"); assertNotNull(p1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IO.copy(p1.getInputStream(), baos); assertEquals("other", baos.toString("US-ASCII")); - + Part p2 = mpis.getPart("stuff"); assertNotNull(p2); baos = new ByteArrayOutputStream(); IO.copy(p2.getInputStream(), baos); assertEquals("truth=3Dbeauty", baos.toString("US-ASCII")); } - - + + @Test public void testGeneratedForm() throws Exception @@ -1053,15 +953,15 @@ public class MultiPartFormInputStreamTest "\r\n" + "&ᄈᄎ￙ᅱᅢO\r\n" + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW--"; - - + + MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50); MultiPartFormInputStream mpis = new MultiPartFormInputStream(new ByteArrayInputStream(body.getBytes()), contentType, config, _tmpDir); mpis.setDeleteOnExit(true); - + Collection parts = mpis.getParts(); assertThat(parts, notNullValue()); assertThat(parts.size(), is(2)); @@ -1071,7 +971,7 @@ public class MultiPartFormInputStreamTest Part part2 = mpis.getPart("part2"); assertThat(part2, notNullValue()); } - + private static String createMultipartRequestString(String filename) { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java index 2b45a16bab7..e54f17989e1 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/MultiPartParserTest.java @@ -18,10 +18,11 @@ package org.eclipse.jetty.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -31,11 +32,11 @@ import java.util.concurrent.ThreadLocalRandom; import org.eclipse.jetty.http.MultiPartParser.State; import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MultiPartParserTest { - + @Test public void testEmptyPreamble() { @@ -47,7 +48,7 @@ public class MultiPartParserTest parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); } - + @Test public void testNoPreamble() { @@ -94,7 +95,7 @@ public class MultiPartParserTest assertThat(parser.getState(), is(State.PREAMBLE)); assertThat(data.remaining(), is(0)); } - + @Test public void testPreambleCompleteBoundary() { @@ -115,7 +116,7 @@ public class MultiPartParserTest { }, "BOUNDARY"); ByteBuffer data = BufferUtil.toBuffer("This is not part of a part\r\n"); - + parser.parse(data, false); assertThat(parser.getState(), is(State.PREAMBLE)); assertThat(data.remaining(), is(0)); @@ -144,7 +145,7 @@ public class MultiPartParserTest assertThat(parser.getState(), is(State.BODY_PART)); assertThat(data.remaining(), is(0)); } - + @Test public void testFirstPartNoFields() { @@ -179,7 +180,7 @@ public class MultiPartParserTest + " 2\r\n" + "\r\n" + "Content"); - + parser.parse(data, false); assertThat(parser.getState(), is(State.FIRST_OCTETS)); assertThat(data.remaining(), is(7)); @@ -221,7 +222,7 @@ public class MultiPartParserTest assertThat(handler.content, Matchers.contains("<>")); } - + @Test public void testFirstPartContentLookingLikeNoCRLF() { @@ -242,7 +243,7 @@ public class MultiPartParserTest assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("-", "Content!")); } - + @Test public void testFirstPartPartialContent() { @@ -258,7 +259,7 @@ public class MultiPartParserTest assertThat(data.remaining(), is(0)); assertThat(handler.fields, Matchers.contains("name: value", "<>")); assertThat(handler.content, Matchers.contains("Hello")); - + data = BufferUtil.toBuffer( "Now is the time for all good ment to come to the aid of the party.\r\n" + "How now brown cow.\r\n" @@ -273,7 +274,7 @@ public class MultiPartParserTest + "The quick brown fox jumped over the lazy dog.\r\n" + "this is not a --BOUNDARY")); } - + @Test public void testFirstPartShortContent() { @@ -292,7 +293,7 @@ public class MultiPartParserTest assertThat(handler.content, Matchers.contains("Hello", "<>")); } - + @Test public void testFirstPartLongContent() { @@ -321,7 +322,7 @@ public class MultiPartParserTest { TestHandler handler = new TestHandler(); MultiPartParser parser = new MultiPartParser(handler, "BOUNDARY"); - + //boundary still requires carriage return ByteBuffer data = BufferUtil.toBuffer("--BOUNDARY\n" + "name: value\n" @@ -339,7 +340,7 @@ public class MultiPartParserTest + "How now brown cow.\n" + "The quick brown fox jumped over the lazy dog.\n", "<>")); } - + @Test public void testBinaryPart() @@ -442,7 +443,7 @@ public class MultiPartParserTest assertThat(data.remaining(), is(0)); } - + @Test public void testCrAsLineTermination() { @@ -453,7 +454,7 @@ public class MultiPartParserTest { return true; } - + @Override public boolean content(ByteBuffer buffer, boolean last) { @@ -463,47 +464,41 @@ public class MultiPartParserTest }; MultiPartParser parser = new MultiPartParser(handler, "AaB03x"); - ByteBuffer data = BufferUtil.toBuffer( - "--AaB03x\r\n" + - "content-disposition: form-data; name=\"field1\"\r\n" + - "\r" + - "Joe Blow\r\n" + - "--AaB03x--\r\n"); - - try - { - parser.parse(data, true); - fail("Invalid End of Line"); - } - catch (BadMessageException e) - { - assertTrue(e.getMessage().contains("Bad EOL")); - } + ByteBuffer data = BufferUtil.toBuffer( + "--AaB03x\r\n"+ + "content-disposition: form-data; name=\"field1\"\r\n"+ + "\r"+ + "Joe Blow\r\n"+ + "--AaB03x--\r\n"); + + BadMessageException x = assertThrows(BadMessageException.class, + ()-> parser.parse(data,true), + "Invalid EOL"); + assertThat(x.getMessage(), containsString("Bad EOL")); } - - - @Test + + @Test // TODO: Parameterize public void testBadHeaderNames() throws Exception { String[] bad = new String[] - { - "Foo\\Bar: value\r\n", - "Foo@Bar: value\r\n", - "Foo,Bar: value\r\n", - "Foo}Bar: value\r\n", - "Foo{Bar: value\r\n", - "Foo=Bar: value\r\n", - "Foo>Bar: value\r\n", - "FooBar: value\r\n", + "Foo>" , "Content-Disposition: form-data; name=\"file1\"; filename=\"a.txt\"" , "Content-Type: text/plain", "<>" @@ -635,8 +629,8 @@ public class MultiPartParserTest , "Field4: value4", "Field5: value5", "Field6: value6" , "Field7: value7", "Field8: value8", "Field9: value 9", "<>" , "Field1: value1", "<>")); - - + + assertThat(handler.contentString(), is("text default" + "<>" + "Content of a.txt.\n" + "<>" + "Content of a.html.\n" + "<>" @@ -653,13 +647,13 @@ public class MultiPartParserTest "due to their formerly liquid state, showed at a glance\n" + "how far the hard, rocky beds had once extended into\n" + "the open ocean.\n" + "<>")); - + handler.clear(); parser.reset(); } } - + @Test public void testGeneratedForm() { @@ -670,7 +664,7 @@ public class MultiPartParserTest { return true; } - + @Override public boolean content(ByteBuffer buffer, boolean last) { @@ -698,11 +692,11 @@ public class MultiPartParserTest "\r\n" + "&ᄈᄎ￙ᅱᅢO\r\n" + "--WebKitFormBoundary7MA4YWf7OaKlSxkTrZu0gW--"); - + parser.parse(data, true); assertThat(parser.getState(), is(State.END)); assertThat(handler.fields.size(), is(2)); - + } @@ -710,13 +704,13 @@ public class MultiPartParserTest { List fields = new ArrayList<>(); List content = new ArrayList<>(); - + @Override public void parsedField(String name, String value) { fields.add(name + ": " + value); } - + public String contentString() { StringBuilder sb = new StringBuilder(); @@ -724,14 +718,14 @@ public class MultiPartParserTest sb.append(s); return sb.toString(); } - + @Override public boolean headerComplete() { fields.add("<>"); return false; } - + @Override public boolean content(ByteBuffer buffer, boolean last) { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/PathMapTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/PathMapTest.java index 2687b4a20c5..b507bd8d348 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/PathMapTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/PathMapTest.java @@ -18,11 +18,11 @@ package org.eclipse.jetty.http; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @@ -70,77 +70,76 @@ public class PathMapTest for (String[] test : tests) { - assertEquals(test[0], test[1], p.getMatch(test[0]).getValue()); + assertEquals(test[1], p.getMatch(test[0]).getValue(), test[0]); } - assertEquals("Get absolute path", "1", p.get("/abs/path")); - assertEquals("Match absolute path", "/abs/path", p.getMatch("/abs/path").getKey()); - assertEquals("all matches", "[/animal/bird/*=3, /animal/*=5, *.tar.gz=6, *.gz=7, /=8]", - p.getMatches("/animal/bird/path.tar.gz").toString()); - assertEquals("Dir matches", "[/animal/fish/*=4, /animal/*=5, /=8]", p.getMatches("/animal/fish/").toString()); - assertEquals("Dir matches", "[/animal/fish/*=4, /animal/*=5, /=8]", p.getMatches("/animal/fish").toString()); - assertEquals("Root matches", "[=10, /=8]",p.getMatches("/").toString()); - assertEquals("Dir matches", "[/=8]", p.getMatches("").toString()); + assertEquals("1", p.get("/abs/path"), "Get absolute path"); + assertEquals("/abs/path", p.getMatch("/abs/path").getKey(), "Match absolute path"); + assertEquals("[/animal/bird/*=3, /animal/*=5, *.tar.gz=6, *.gz=7, /=8]", p.getMatches("/animal/bird/path.tar.gz").toString(), "all matches"); + assertEquals("[/animal/fish/*=4, /animal/*=5, /=8]", p.getMatches("/animal/fish/").toString(), "Dir matches"); + assertEquals("[/animal/fish/*=4, /animal/*=5, /=8]", p.getMatches("/animal/fish").toString(), "Dir matches"); + assertEquals("[=10, /=8]", p.getMatches("/").toString(), "Root matches"); + assertEquals("[/=8]", p.getMatches("").toString(), "Dir matches"); - assertEquals("pathMatch exact", "/Foo/bar", PathMap.pathMatch("/Foo/bar", "/Foo/bar")); - assertEquals("pathMatch prefix", "/Foo", PathMap.pathMatch("/Foo/*", "/Foo/bar")); - assertEquals("pathMatch prefix", "/Foo", PathMap.pathMatch("/Foo/*", "/Foo/")); - assertEquals("pathMatch prefix", "/Foo", PathMap.pathMatch("/Foo/*", "/Foo")); - assertEquals("pathMatch suffix", "/Foo/bar.ext", PathMap.pathMatch("*.ext", "/Foo/bar.ext")); - assertEquals("pathMatch default", "/Foo/bar.ext", PathMap.pathMatch("/", "/Foo/bar.ext")); + assertEquals("/Foo/bar", PathMap.pathMatch("/Foo/bar", "/Foo/bar"), "pathMatch exact"); + assertEquals("/Foo", PathMap.pathMatch("/Foo/*", "/Foo/bar"), "pathMatch prefix"); + assertEquals("/Foo", PathMap.pathMatch("/Foo/*", "/Foo/"), "pathMatch prefix"); + assertEquals("/Foo", PathMap.pathMatch("/Foo/*", "/Foo"), "pathMatch prefix"); + assertEquals("/Foo/bar.ext", PathMap.pathMatch("*.ext", "/Foo/bar.ext"), "pathMatch suffix"); + assertEquals("/Foo/bar.ext", PathMap.pathMatch("/", "/Foo/bar.ext"), "pathMatch default"); - assertEquals("pathInfo exact", null, PathMap.pathInfo("/Foo/bar", "/Foo/bar")); - assertEquals("pathInfo prefix", "/bar", PathMap.pathInfo("/Foo/*", "/Foo/bar")); - assertEquals("pathInfo prefix", "/*", PathMap.pathInfo("/Foo/*", "/Foo/*")); - assertEquals("pathInfo prefix", "/", PathMap.pathInfo("/Foo/*", "/Foo/")); - assertEquals("pathInfo prefix", null, PathMap.pathInfo("/Foo/*", "/Foo")); - assertEquals("pathInfo suffix", null, PathMap.pathInfo("*.ext", "/Foo/bar.ext")); - assertEquals("pathInfo default", null, PathMap.pathInfo("/", "/Foo/bar.ext")); - assertEquals("multi paths", "9", p.getMatch("/XXX").getValue()); - assertEquals("multi paths", "9", p.getMatch("/YYY").getValue()); + assertEquals(null, PathMap.pathInfo("/Foo/bar", "/Foo/bar"), "pathInfo exact"); + assertEquals("/bar", PathMap.pathInfo("/Foo/*", "/Foo/bar"), "pathInfo prefix"); + assertEquals("/*", PathMap.pathInfo("/Foo/*", "/Foo/*"), "pathInfo prefix"); + assertEquals("/", PathMap.pathInfo("/Foo/*", "/Foo/"), "pathInfo prefix"); + assertEquals(null, PathMap.pathInfo("/Foo/*", "/Foo"), "pathInfo prefix"); + assertEquals(null, PathMap.pathInfo("*.ext", "/Foo/bar.ext"), "pathInfo suffix"); + assertEquals(null, PathMap.pathInfo("/", "/Foo/bar.ext"), "pathInfo default"); + assertEquals("9", p.getMatch("/XXX").getValue(), "multi paths"); + assertEquals("9", p.getMatch("/YYY").getValue(), "multi paths"); p.put("/*", "0"); - assertEquals("Get absolute path", "1", p.get("/abs/path")); - assertEquals("Match absolute path", "/abs/path", p.getMatch("/abs/path").getKey()); - assertEquals("Match absolute path", "1", p.getMatch("/abs/path").getValue()); - assertEquals("Mismatch absolute path", "0", p.getMatch("/abs/path/xxx").getValue()); - assertEquals("Mismatch absolute path", "0", p.getMatch("/abs/pith").getValue()); - assertEquals("Match longer absolute path", "2", p.getMatch("/abs/path/longer").getValue()); - assertEquals("Not exact absolute path", "0", p.getMatch("/abs/path/").getValue()); - assertEquals("Not exact absolute path", "0", p.getMatch("/abs/path/xxx").getValue()); + assertEquals("1", p.get("/abs/path"), "Get absolute path"); + assertEquals("/abs/path", p.getMatch("/abs/path").getKey(), "Match absolute path"); + assertEquals("1", p.getMatch("/abs/path").getValue(), "Match absolute path"); + assertEquals("0", p.getMatch("/abs/path/xxx").getValue(), "Mismatch absolute path"); + assertEquals("0", p.getMatch("/abs/pith").getValue(), "Mismatch absolute path"); + assertEquals("2", p.getMatch("/abs/path/longer").getValue(), "Match longer absolute path"); + assertEquals("0", p.getMatch("/abs/path/").getValue(), "Not exact absolute path"); + assertEquals("0", p.getMatch("/abs/path/xxx").getValue(), "Not exact absolute path"); - assertEquals("Match longest prefix", "3", p.getMatch("/animal/bird/eagle/bald").getValue()); - assertEquals("Match longest prefix", "4", p.getMatch("/animal/fish/shark/grey").getValue()); - assertEquals("Match longest prefix", "5", p.getMatch("/animal/insect/bug").getValue()); - assertEquals("mismatch exact prefix", "5", p.getMatch("/animal").getValue()); - assertEquals("mismatch exact prefix", "5", p.getMatch("/animal/").getValue()); + assertEquals("3", p.getMatch("/animal/bird/eagle/bald").getValue(), "Match longest prefix"); + assertEquals("4", p.getMatch("/animal/fish/shark/grey").getValue(), "Match longest prefix"); + assertEquals("5", p.getMatch("/animal/insect/bug").getValue(), "Match longest prefix"); + assertEquals("5", p.getMatch("/animal").getValue(), "mismatch exact prefix"); + assertEquals("5", p.getMatch("/animal/").getValue(), "mismatch exact prefix"); - assertEquals("Match longest suffix", "0", p.getMatch("/suffix/path.tar.gz").getValue()); - assertEquals("Match longest suffix", "0", p.getMatch("/suffix/path.gz").getValue()); - assertEquals("prefix rather than suffix", "5", p.getMatch("/animal/path.gz").getValue()); + assertEquals("0", p.getMatch("/suffix/path.tar.gz").getValue(), "Match longest suffix"); + assertEquals("0", p.getMatch("/suffix/path.gz").getValue(), "Match longest suffix"); + assertEquals("5", p.getMatch("/animal/path.gz").getValue(), "prefix rather than suffix"); - assertEquals("default", "0", p.getMatch("/Other/path").getValue()); + assertEquals("0", p.getMatch("/Other/path").getValue(), "default"); - assertEquals("pathMatch /*", "", PathMap.pathMatch("/*", "/xxx/zzz")); - assertEquals("pathInfo /*", "/xxx/zzz", PathMap.pathInfo("/*", "/xxx/zzz")); + assertEquals("", PathMap.pathMatch("/*", "/xxx/zzz"), "pathMatch /*"); + assertEquals("/xxx/zzz", PathMap.pathInfo("/*", "/xxx/zzz"), "pathInfo /*"); - assertTrue("match /", PathMap.match("/", "/anything")); - assertTrue("match /*", PathMap.match("/*", "/anything")); - assertTrue("match /foo", PathMap.match("/foo", "/foo")); - assertTrue("!match /foo", !PathMap.match("/foo", "/bar")); - assertTrue("match /foo/*", PathMap.match("/foo/*", "/foo")); - assertTrue("match /foo/*", PathMap.match("/foo/*", "/foo/")); - assertTrue("match /foo/*", PathMap.match("/foo/*", "/foo/anything")); - assertTrue("!match /foo/*", !PathMap.match("/foo/*", "/bar")); - assertTrue("!match /foo/*", !PathMap.match("/foo/*", "/bar/")); - assertTrue("!match /foo/*", !PathMap.match("/foo/*", "/bar/anything")); - assertTrue("match *.foo", PathMap.match("*.foo", "anything.foo")); - assertTrue("!match *.foo", !PathMap.match("*.foo", "anything.bar")); + assertTrue(PathMap.match("/", "/anything"), "match /"); + assertTrue(PathMap.match("/*", "/anything"), "match /*"); + assertTrue(PathMap.match("/foo", "/foo"), "match /foo"); + assertTrue(!PathMap.match("/foo", "/bar"), "!match /foo"); + assertTrue(PathMap.match("/foo/*", "/foo"), "match /foo/*"); + assertTrue(PathMap.match("/foo/*", "/foo/"), "match /foo/*"); + assertTrue(PathMap.match("/foo/*", "/foo/anything"), "match /foo/*"); + assertTrue(!PathMap.match("/foo/*", "/bar"), "!match /foo/*"); + assertTrue(!PathMap.match("/foo/*", "/bar/"), "!match /foo/*"); + assertTrue(!PathMap.match("/foo/*", "/bar/anything"), "!match /foo/*"); + assertTrue(PathMap.match("*.foo", "anything.foo"), "match *.foo"); + assertTrue(!PathMap.match("*.foo", "anything.bar"), "!match *.foo"); - assertEquals("match / with ''", "10", p.getMatch("/").getValue()); + assertEquals("10", p.getMatch("/").getValue(), "match / with ''"); - assertTrue("match \"\"", PathMap.match("", "/")); + assertTrue(PathMap.match("", "/"),"match \"\""); } /** @@ -193,12 +192,12 @@ public class PathMapTest private void assertMatch(String spec, String path) { boolean match = PathMap.match(spec, path); - assertTrue("PathSpec '" + spec + "' should match path '" + path + "'", match); + assertTrue(match,"PathSpec '" + spec + "' should match path '" + path + "'"); } private void assertNotMatch(String spec, String path) { boolean match = PathMap.match(spec, path); - assertFalse("PathSpec '" + spec + "' should not match path '" + path + "'", match); + assertFalse(match,"PathSpec '" + spec + "' should not match path '" + path + "'"); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java index 2f1199e1d40..29b17a6ccae 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedCSVTest.java @@ -19,11 +19,11 @@ package org.eclipse.jetty.http; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class QuotedCSVTest { @@ -32,7 +32,7 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(); values.addValue(" value 0.5 ; pqy = vwz ; q =0.5 , value 1.0 , other ; param "); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value 0.5;pqy=vwz;q=0.5", "value 1.0", "other;param")); @@ -43,7 +43,7 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(); values.addValue(",aaaa, , bbbb ,,cccc,"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "aaaa", "bbbb", "cccc")); @@ -54,7 +54,7 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(); values.addValue("A;p=\"v\",B,\"C, D\""); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "A;p=\"v\"", "B", "\"C, D\"")); @@ -65,7 +65,7 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(); values.addValue("value;p=\"v"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value;p=\"v")); } @@ -74,7 +74,7 @@ public class QuotedCSVTest { QuotedCSV values = new QuotedCSV(false); values.addValue("A;p=\"v\",B,\"C, D\""); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "A;p=v", "B", "C, D")); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java index 80b4d957450..334cb5b9a87 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/QuotedQualityCSVTest.java @@ -18,15 +18,15 @@ package org.eclipse.jetty.http; + +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.List; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertThat; public class QuotedQualityCSVTest { @@ -36,7 +36,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" audio/*; q=0.2, audio/basic"); - Assert.assertThat(values,Matchers.contains("audio/basic","audio/*")); + assertThat(values,Matchers.contains("audio/basic","audio/*")); } @Test @@ -45,7 +45,7 @@ public class QuotedQualityCSVTest QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/plain; q=0.5, text/html,"); values.addValue("text/x-dvi; q=0.8, text/x-c"); - Assert.assertThat(values,Matchers.contains("text/html","text/x-c","text/x-dvi","text/plain")); + assertThat(values,Matchers.contains("text/html","text/x-c","text/x-dvi","text/plain")); } @Test @@ -55,7 +55,7 @@ public class QuotedQualityCSVTest values.addValue("text/*, text/plain, text/plain;format=flowed, */*"); // Note this sort is only on quality and not the most specific type as per 5.3.2 - Assert.assertThat(values,Matchers.contains("text/*","text/plain","text/plain;format=flowed","*/*")); + assertThat(values,Matchers.contains("text/*","text/plain","text/plain;format=flowed","*/*")); } @Test @@ -64,7 +64,7 @@ public class QuotedQualityCSVTest QuotedQualityCSV values = new QuotedQualityCSV(QuotedQualityCSV.MOST_SPECIFIC); values.addValue("text/*, text/plain, text/plain;format=flowed, */*"); - Assert.assertThat(values,Matchers.contains("text/plain;format=flowed","text/plain","text/*","*/*")); + assertThat(values,Matchers.contains("text/plain;format=flowed","text/plain","text/*","*/*")); } @Test @@ -73,7 +73,7 @@ public class QuotedQualityCSVTest QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("text/*;q=0.3, text/html;q=0.7, text/html;level=1,"); values.addValue("text/html;level=2;q=0.4, */*;q=0.5"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "text/html;level=1", "text/html", "*/*", @@ -92,7 +92,7 @@ public class QuotedQualityCSVTest values.addValue("compress;q=0.5, gzip;q=1.0"); values.addValue("gzip;q=1.0, identity; q=0.5, *;q=0"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "compress", "gzip", "*", @@ -108,7 +108,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = v ; q =0.5 , value 1.0 "); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value 1.0", "value 0.5;p=v")); } @@ -118,7 +118,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(",aaaa, , bbbb ,,cccc,"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "aaaa", "bbbb", "cccc")); @@ -129,7 +129,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = \"v ; q = \\\"0.5\\\" , value 1.0 \" "); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value 0.5;p=\"v ; q = \\\"0.5\\\" , value 1.0 \"")); } @@ -138,7 +138,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("value;p=\"v"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value;p=\"v")); } @@ -147,7 +147,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue(" value 0.5 ; p = v ; q = \"0.5\" , value 1.0 "); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value 1.0", "value 0.5;p=v")); } @@ -157,7 +157,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("value0.5;p=v;q=0.5,value1.0,valueBad;q=X"); - Assert.assertThat(values,Matchers.contains( + assertThat(values,Matchers.contains( "value1.0", "value0.5;p=v")); } @@ -302,7 +302,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("one;q=0.5,two;q=0.5,three;q=0.5"); - Assert.assertThat(values.getValues(),Matchers.contains("one","two","three")); + assertThat(values.getValues(),Matchers.contains("one","two","three")); } @Test @@ -310,7 +310,7 @@ public class QuotedQualityCSVTest { QuotedQualityCSV values = new QuotedQualityCSV(); values.addValue("one,two;,three;x=y"); - Assert.assertThat(values.getValues(),Matchers.contains("one","two","three;x=y")); + assertThat(values.getValues(),Matchers.contains("one","two","three;x=y")); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java index b0ea5b8fe07..173d3d1d548 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/SyntaxTest.java @@ -20,10 +20,10 @@ package org.eclipse.jetty.http; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SyntaxTest { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderKey.java b/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderKey.java new file mode 100644 index 00000000000..b4ef5f11e39 --- /dev/null +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderKey.java @@ -0,0 +1,58 @@ +// +// ======================================================================== +// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.http.matchers; + +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeader; +import org.hamcrest.Description; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; + +public class HttpFieldsContainsHeaderKey extends TypeSafeMatcher +{ + private final String keyName; + + public HttpFieldsContainsHeaderKey(String keyName) + { + this.keyName = keyName; + } + + public HttpFieldsContainsHeaderKey(HttpHeader header) + { + this.keyName = header.asString(); + } + + @Override + public void describeTo(Description description) + { + description.appendText("expecting http field name ").appendValue(keyName); + } + + @Override + protected boolean matchesSafely(HttpFields fields) + { + return fields.containsKey(this.keyName); + } + + @Factory + public static Matcher containsKey(String keyName) { + return new HttpFieldsContainsHeaderKey(keyName); + } +} diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderValue.java b/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderValue.java new file mode 100644 index 00000000000..1e8389089f1 --- /dev/null +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsContainsHeaderValue.java @@ -0,0 +1,75 @@ +// +// ======================================================================== +// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.http.matchers; + +import java.util.Locale; + +import org.eclipse.jetty.http.HttpField; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeader; +import org.hamcrest.Description; +import org.hamcrest.TypeSafeMatcher; + +public class HttpFieldsContainsHeaderValue extends TypeSafeMatcher +{ + private final String keyName; + private final String value; + + public HttpFieldsContainsHeaderValue(String keyName, String value) + { + this.keyName = keyName; + this.value = value; + } + + public HttpFieldsContainsHeaderValue(HttpHeader header, String value) + { + this(header.asString(), value); + } + + @Override + public void describeTo(Description description) + { + description.appendText("expecting http header ").appendValue(keyName).appendText(" with value ").appendValue(value); + } + + @Override + protected boolean matchesSafely(HttpFields fields) + { + HttpField field = fields.getField(this.keyName); + if (field == null) + return false; + + // Use HttpField.contains() logic + if (field.contains(this.value)) + return true; + + // Simple equals + if(this.value == field.getValue()) + return true; + + // Try individual value logic + String lcValue = this.value.toLowerCase(Locale.ENGLISH); + for (String value : field.getValues()) + { + if (value.toLowerCase(Locale.ENGLISH).contains(lcValue)) + return true; + } + return false; + } +} diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsMatchersTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsMatchersTest.java new file mode 100644 index 00000000000..895049a797f --- /dev/null +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/matchers/HttpFieldsMatchersTest.java @@ -0,0 +1,118 @@ +// +// ======================================================================== +// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.http.matchers; + +import static org.eclipse.jetty.http.HttpFieldsMatchers.containsHeader; +import static org.eclipse.jetty.http.HttpFieldsMatchers.containsHeaderValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeader; +import org.junit.jupiter.api.Test; + +public class HttpFieldsMatchersTest +{ + @Test + public void testContainsHeader() + { + HttpFields fields = new HttpFields(); + fields.put("a", "foo"); + fields.put("b", "bar"); + fields.put("c", "fizz"); + + assertThat(fields, containsHeader("a")); + } + + @Test + public void testNotContainsHeader() + { + HttpFields fields = new HttpFields(); + fields.put("a", "foo"); + fields.put("b", "bar"); + fields.put("c", "fizz"); + + AssertionError x = assertThrows(AssertionError.class, ()-> { + assertThat(fields, not(containsHeader("a"))); + }); + + assertThat(x.getMessage(), containsString("not expecting http field name \"a\"")); + } + + @Test + public void testContainsHeader_MisMatch() + { + HttpFields fields = new HttpFields(); + fields.put("a", "foo"); + fields.put("b", "bar"); + fields.put("c", "fizz"); + + AssertionError x = assertThrows(AssertionError.class, ()->{ + assertThat(fields, containsHeader("z")); + }); + + assertThat(x.getMessage(), containsString("expecting http field name \"z\"")); + } + + @Test + public void testContainsHeaderValue_MisMatch_NoSuchHeader() + { + HttpFields fields = new HttpFields(); + fields.put("a", "foo"); + fields.put("b", "bar"); + fields.put("c", "fizz"); + + AssertionError x = assertThrows(AssertionError.class, ()-> { + assertThat(fields, containsHeaderValue("z", "floom")); + }); + + assertThat(x.getMessage(), containsString("expecting http header \"z\" with value \"floom\"")); + } + + @Test + public void testContainsHeaderValue_MisMatch_NoSuchValue() + { + HttpFields fields = new HttpFields(); + fields.put("a", "foo"); + fields.put("b", "bar"); + fields.put("c", "fizz"); + + AssertionError x = assertThrows(AssertionError.class, ()-> { + assertThat(fields, containsHeaderValue("a", "floom")); + }); + + assertThat(x.getMessage(), containsString("expecting http header \"a\" with value \"floom\"")); + } + + @Test + public void testContainsHeaderValue() + { + HttpFields fields = new HttpFields(); + fields.put("a", "foo"); + fields.put("b", "bar"); + fields.put("c", "fizz"); + fields.put(HttpHeader.CONTENT_TYPE, "text/plain;charset=utf-8"); + + assertThat(fields, containsHeaderValue("b", "bar")); + assertThat(fields, containsHeaderValue("content-type", "text/plain")); + assertThat(fields, containsHeaderValue("content-type", "charset=UTF-8")); + } +} diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java index 77a2757adc6..6ca1022c6cf 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathMappingsTest.java @@ -18,12 +18,15 @@ package org.eclipse.jetty.http.pathmap; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; public class PathMappingsTest { @@ -31,9 +34,9 @@ public class PathMappingsTest { String msg = String.format(".getMatch(\"%s\")",path); MappedResource match = pathmap.getMatch(path); - Assert.assertThat(msg,match,notNullValue()); + assertThat(msg,match,notNullValue()); String actualMatch = match.getResource(); - Assert.assertEquals(msg,expectedValue,actualMatch); + assertEquals(expectedValue,actualMatch,msg); } public void dumpMappings(PathMappings p) @@ -175,63 +178,63 @@ public class PathMappingsTest p.put(new ServletPathSpec(""), "10"); p.put(new ServletPathSpec("/\u20ACuro/*"), "11"); - assertEquals("pathMatch exact", "/Foo/bar", new ServletPathSpec("/Foo/bar").getPathMatch("/Foo/bar")); - assertEquals("pathMatch prefix", "/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/bar")); - assertEquals("pathMatch prefix", "/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/")); - assertEquals("pathMatch prefix", "/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo")); - assertEquals("pathMatch suffix", "/Foo/bar.ext", new ServletPathSpec("*.ext").getPathMatch("/Foo/bar.ext")); - assertEquals("pathMatch default", "/Foo/bar.ext", new ServletPathSpec("/").getPathMatch("/Foo/bar.ext")); + assertEquals("/Foo/bar", new ServletPathSpec("/Foo/bar").getPathMatch("/Foo/bar"), "pathMatch exact"); + assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/bar"), "pathMatch prefix"); + assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/"), "pathMatch prefix"); + assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo"), "pathMatch prefix"); + assertEquals("/Foo/bar.ext", new ServletPathSpec("*.ext").getPathMatch("/Foo/bar.ext"), "pathMatch suffix"); + assertEquals("/Foo/bar.ext", new ServletPathSpec("/").getPathMatch("/Foo/bar.ext"), "pathMatch default"); - assertEquals("pathInfo exact", null, new ServletPathSpec("/Foo/bar").getPathInfo("/Foo/bar")); - assertEquals("pathInfo prefix", "/bar", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/bar")); - assertEquals("pathInfo prefix", "/*", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/*")); - assertEquals("pathInfo prefix", "/", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/")); - assertEquals("pathInfo prefix", null, new ServletPathSpec("/Foo/*").getPathInfo("/Foo")); - assertEquals("pathInfo suffix", null, new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext")); - assertEquals("pathInfo default", null, new ServletPathSpec("/").getPathInfo("/Foo/bar.ext")); + assertEquals(null, new ServletPathSpec("/Foo/bar").getPathInfo("/Foo/bar"), "pathInfo exact"); + assertEquals("/bar", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/bar"), "pathInfo prefix"); + assertEquals("/*", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/*"), "pathInfo prefix"); + assertEquals("/", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/"), "pathInfo prefix"); + assertEquals(null, new ServletPathSpec("/Foo/*").getPathInfo("/Foo"), "pathInfo prefix"); + assertEquals(null, new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext"), "pathInfo suffix"); + assertEquals(null, new ServletPathSpec("/").getPathInfo("/Foo/bar.ext"), "pathInfo default"); p.put(new ServletPathSpec("/*"), "0"); - // assertEquals("Get absolute path", "1", p.get("/abs/path")); - assertEquals("Match absolute path", "/abs/path", p.getMatch("/abs/path").getPathSpec().pathSpec); - assertEquals("Match absolute path", "1", p.getMatch("/abs/path").getResource()); - assertEquals("Mismatch absolute path", "0", p.getMatch("/abs/path/xxx").getResource()); - assertEquals("Mismatch absolute path", "0", p.getMatch("/abs/pith").getResource()); - assertEquals("Match longer absolute path", "2", p.getMatch("/abs/path/longer").getResource()); - assertEquals("Not exact absolute path", "0", p.getMatch("/abs/path/").getResource()); - assertEquals("Not exact absolute path", "0", p.getMatch("/abs/path/xxx").getResource()); + // assertEquals("1", p.get("/abs/path"), "Get absolute path"); + assertEquals("/abs/path", p.getMatch("/abs/path").getPathSpec().pathSpec, "Match absolute path"); + assertEquals("1", p.getMatch("/abs/path").getResource(), "Match absolute path"); + assertEquals("0", p.getMatch("/abs/path/xxx").getResource(), "Mismatch absolute path"); + assertEquals("0", p.getMatch("/abs/pith").getResource(), "Mismatch absolute path"); + assertEquals("2", p.getMatch("/abs/path/longer").getResource(), "Match longer absolute path"); + assertEquals("0", p.getMatch("/abs/path/").getResource(), "Not exact absolute path"); + assertEquals("0", p.getMatch("/abs/path/xxx").getResource(), "Not exact absolute path"); - assertEquals("Match longest prefix", "3", p.getMatch("/animal/bird/eagle/bald").getResource()); - assertEquals("Match longest prefix", "4", p.getMatch("/animal/fish/shark/grey").getResource()); - assertEquals("Match longest prefix", "5", p.getMatch("/animal/insect/bug").getResource()); - assertEquals("mismatch exact prefix", "5", p.getMatch("/animal").getResource()); - assertEquals("mismatch exact prefix", "5", p.getMatch("/animal/").getResource()); + assertEquals("3", p.getMatch("/animal/bird/eagle/bald").getResource(), "Match longest prefix"); + assertEquals("4", p.getMatch("/animal/fish/shark/grey").getResource(), "Match longest prefix"); + assertEquals("5", p.getMatch("/animal/insect/bug").getResource(), "Match longest prefix"); + assertEquals("5", p.getMatch("/animal").getResource(), "mismatch exact prefix"); + assertEquals("5", p.getMatch("/animal/").getResource(), "mismatch exact prefix"); - assertEquals("Match longest suffix", "0", p.getMatch("/suffix/path.tar.gz").getResource()); - assertEquals("Match longest suffix", "0", p.getMatch("/suffix/path.gz").getResource()); - assertEquals("prefix rather than suffix", "5", p.getMatch("/animal/path.gz").getResource()); + assertEquals("0", p.getMatch("/suffix/path.tar.gz").getResource(), "Match longest suffix"); + assertEquals("0", p.getMatch("/suffix/path.gz").getResource(), "Match longest suffix"); + assertEquals("5", p.getMatch("/animal/path.gz").getResource(), "prefix rather than suffix"); - assertEquals("default", "0", p.getMatch("/Other/path").getResource()); + assertEquals("0", p.getMatch("/Other/path").getResource(), "default"); - assertEquals("pathMatch /*", "", new ServletPathSpec("/*").getPathMatch("/xxx/zzz")); - assertEquals("pathInfo /*", "/xxx/zzz", new ServletPathSpec("/*").getPathInfo("/xxx/zzz")); + assertEquals("", new ServletPathSpec("/*").getPathMatch("/xxx/zzz"), "pathMatch /*"); + assertEquals("/xxx/zzz", new ServletPathSpec("/*").getPathInfo("/xxx/zzz"), "pathInfo /*"); - assertTrue("match /", new ServletPathSpec("/").matches("/anything")); - assertTrue("match /*", new ServletPathSpec("/*").matches("/anything")); - assertTrue("match /foo", new ServletPathSpec("/foo").matches("/foo")); - assertTrue("!match /foo", !new ServletPathSpec("/foo").matches("/bar")); - assertTrue("match /foo/*", new ServletPathSpec("/foo/*").matches("/foo")); - assertTrue("match /foo/*", new ServletPathSpec("/foo/*").matches("/foo/")); - assertTrue("match /foo/*", new ServletPathSpec("/foo/*").matches("/foo/anything")); - assertTrue("!match /foo/*", !new ServletPathSpec("/foo/*").matches("/bar")); - assertTrue("!match /foo/*", !new ServletPathSpec("/foo/*").matches("/bar/")); - assertTrue("!match /foo/*", !new ServletPathSpec("/foo/*").matches("/bar/anything")); - assertTrue("match *.foo", new ServletPathSpec("*.foo").matches("anything.foo")); - assertTrue("!match *.foo", !new ServletPathSpec("*.foo").matches("anything.bar")); + assertTrue(new ServletPathSpec("/").matches("/anything"), "match /"); + assertTrue(new ServletPathSpec("/*").matches("/anything"), "match /*"); + assertTrue(new ServletPathSpec("/foo").matches("/foo"), "match /foo"); + assertTrue(!new ServletPathSpec("/foo").matches("/bar"), "!match /foo"); + assertTrue(new ServletPathSpec("/foo/*").matches("/foo"), "match /foo/*"); + assertTrue(new ServletPathSpec("/foo/*").matches("/foo/"), "match /foo/*"); + assertTrue(new ServletPathSpec("/foo/*").matches("/foo/anything"), "match /foo/*"); + assertTrue(!new ServletPathSpec("/foo/*").matches("/bar"), "!match /foo/*"); + assertTrue(!new ServletPathSpec("/foo/*").matches("/bar/"), "!match /foo/*"); + assertTrue(!new ServletPathSpec("/foo/*").matches("/bar/anything"), "!match /foo/*"); + assertTrue(new ServletPathSpec("*.foo").matches("anything.foo"), "match *.foo"); + assertTrue(!new ServletPathSpec("*.foo").matches("anything.bar"), "!match *.foo"); - assertEquals("match / with ''", "10", p.getMatch("/").getResource()); + assertEquals("10", p.getMatch("/").getResource(), "match / with ''"); - assertTrue("match \"\"", new ServletPathSpec("").matches("/")); + assertTrue(new ServletPathSpec("").matches("/"),"match \"\""); } /** @@ -279,13 +282,18 @@ public class PathMappingsTest assertEquals("prefix",p.getMatch("/dump/gzip/something.txt").getResource()); } - @Test - public void testBadPathSpecs() + @ParameterizedTest + @ValueSource(strings = { + "*", + "/foo/*/bar", + "/foo*", + "*/foo", + "*.foo/*" + }) + public void testBadPathSpecs(String str) { - try{new ServletPathSpec("*");Assert.fail();}catch(IllegalArgumentException e){} - try{new ServletPathSpec("/foo/*/bar");Assert.fail();}catch(IllegalArgumentException e){} - try{new ServletPathSpec("/foo*");Assert.fail();}catch(IllegalArgumentException e){} - try{new ServletPathSpec("*/foo");Assert.fail();}catch(IllegalArgumentException e){} - try{new ServletPathSpec("*.foo/*");Assert.fail();}catch(IllegalArgumentException e){} + assertThrows(IllegalArgumentException.class, ()->{ + new ServletPathSpec(str); + }); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java index 731ddca947b..1770db67923 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/PathSpecAssert.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.http.pathmap; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; public class PathSpecAssert { diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java index 458bc8c5437..6771a27f300 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/RegexPathSpecTest.java @@ -19,10 +19,10 @@ package org.eclipse.jetty.http.pathmap; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RegexPathSpecTest { @@ -42,10 +42,10 @@ public class RegexPathSpecTest public void testExactSpec() { RegexPathSpec spec = new RegexPathSpec("^/a$"); - assertEquals("Spec.pathSpec","^/a$",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",1,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.EXACT,spec.group); + assertEquals("^/a$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.EXACT, spec.group, "Spec.group"); assertMatches(spec,"/a"); @@ -57,10 +57,10 @@ public class RegexPathSpecTest public void testMiddleSpec() { RegexPathSpec spec = new RegexPathSpec("^/rest/([^/]*)/list$"); - assertEquals("Spec.pathSpec","^/rest/([^/]*)/list$",spec.getDeclaration()); - assertEquals("Spec.pattern","^/rest/([^/]*)/list$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",3,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.MIDDLE_GLOB,spec.group); + assertEquals("^/rest/([^/]*)/list$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/rest/([^/]*)/list$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.group, "Spec.group"); assertMatches(spec,"/rest/api/list"); assertMatches(spec,"/rest/1.0/list"); @@ -78,10 +78,10 @@ public class RegexPathSpecTest public void testMiddleSpecNoGrouping() { RegexPathSpec spec = new RegexPathSpec("^/rest/[^/]+/list$"); - assertEquals("Spec.pathSpec","^/rest/[^/]+/list$",spec.getDeclaration()); - assertEquals("Spec.pattern","^/rest/[^/]+/list$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",3,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.MIDDLE_GLOB,spec.group); + assertEquals("^/rest/[^/]+/list$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/rest/[^/]+/list$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.group, "Spec.group"); assertMatches(spec,"/rest/api/list"); assertMatches(spec,"/rest/1.0/list"); @@ -99,10 +99,10 @@ public class RegexPathSpecTest public void testPrefixSpec() { RegexPathSpec spec = new RegexPathSpec("^/a/(.*)$"); - assertEquals("Spec.pathSpec","^/a/(.*)$",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a/(.*)$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",2,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.PREFIX_GLOB,spec.group); + assertEquals("^/a/(.*)$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a/(.*)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.PREFIX_GLOB, spec.group, "Spec.group"); assertMatches(spec,"/a/"); assertMatches(spec,"/a/b"); @@ -117,10 +117,10 @@ public class RegexPathSpecTest public void testSuffixSpec() { RegexPathSpec spec = new RegexPathSpec("^(.*).do$"); - assertEquals("Spec.pathSpec","^(.*).do$",spec.getDeclaration()); - assertEquals("Spec.pattern","^(.*).do$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",0,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.SUFFIX_GLOB,spec.group); + assertEquals("^(.*).do$", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^(.*).do$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(0, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.group, "Spec.group"); assertMatches(spec,"/a.do"); assertMatches(spec,"/a/b/c.do"); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java index 0f5dd5dd886..36079878b2c 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecMatchListTest.java @@ -18,37 +18,35 @@ package org.eclipse.jetty.http.pathmap; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import java.util.Arrays; +import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests of {@link PathMappings#getMatches(String)} */ -@RunWith(Parameterized.class) +@SuppressWarnings("Duplicates") public class ServletPathSpecMatchListTest { - @Parameters(name="{0} = {1}") - public static List testCases() + public static Stream data() { - String data[][] = new String[][] { - // From old PathMapTest - { "All matches", "/animal/bird/path.tar.gz", "[/animal/bird/*=birds, /animal/*=animals, *.tar.gz=tarball, *.gz=gzipped, /=default]"}, - { "Dir matches", "/animal/fish/", "[/animal/fish/*=fishes, /animal/*=animals, /=default]"}, - { "Dir matches", "/animal/fish", "[/animal/fish/*=fishes, /animal/*=animals, /=default]"}, - { "Root matches", "/", "[=root, /=default]"}, - { "Dir matches", "", "[/=default]"} - }; - - return Arrays.asList(data); + ArrayList data = new ArrayList<>(); + + // From old PathMapTest + data.add(Arguments.of( "All matches", "/animal/bird/path.tar.gz", "[/animal/bird/*=birds, /animal/*=animals, *.tar.gz=tarball, *.gz=gzipped, /=default]")); + data.add(Arguments.of( "Dir matches", "/animal/fish/", "[/animal/fish/*=fishes, /animal/*=animals, /=default]")); + data.add(Arguments.of( "Dir matches", "/animal/fish", "[/animal/fish/*=fishes, /animal/*=animals, /=default]")); + data.add(Arguments.of( "Root matches", "/", "[=root, /=default]")); + data.add(Arguments.of( "Dir matches", "", "[/=default]")); + + return data.stream(); } private static PathMappings mappings; @@ -70,17 +68,9 @@ public class ServletPathSpecMatchListTest mappings.put(new ServletPathSpec("/\u20ACuro/*"),"money"); // 11 } - @Parameter(0) - public String message; - - @Parameter(1) - public String inputPath; - - @Parameter(2) - public String expectedListing; - - @Test - public void testGetMatches() + @ParameterizedTest + @MethodSource("data") + public void testGetMatches(String message, String inputPath, String expectedListing) { List> matches = mappings.getMatches(inputPath); diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java index 79b745c8e5c..a1a4a370457 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecOrderTest.java @@ -18,56 +18,53 @@ package org.eclipse.jetty.http.pathmap; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import java.util.Arrays; -import java.util.List; +import java.util.ArrayList; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests of {@link PathMappings#getMatch(String)}, with a focus on correct mapping selection order */ -@RunWith(Parameterized.class) +@SuppressWarnings("Duplicates") public class ServletPathSpecOrderTest { - @Parameters(name="{0} = {1}") - public static List testCases() + public static Stream data() { - String data[][] = new String[][] { - // From old PathMapTest - {"/abs/path","abspath"}, - {"/abs/path/xxx","default"}, - {"/abs/pith","default"}, - {"/abs/path/longer","longpath"}, - {"/abs/path/","default"}, - {"/abs/path/foo","default"}, - {"/animal/bird/eagle/bald","birds"}, - {"/animal/fish/shark/hammerhead","fishes"}, - {"/animal/insect/ladybug","animals"}, - {"/animal","animals"}, - {"/animal/","animals"}, - {"/animal/other","animals"}, - {"/animal/*","animals"}, - {"/downloads/distribution.tar.gz","tarball"}, - {"/downloads/script.gz","gzipped"}, - {"/animal/arhive.gz","animals"}, - {"/Other/path","default"}, - {"/\u20ACuro/path","money"}, - {"/","root"}, - - // Extra tests - {"/downloads/readme.txt","default"}, - {"/downloads/logs.tgz","default"}, - {"/main.css","default"} - }; - - return Arrays.asList(data); + ArrayList data = new ArrayList<>(); + + // From old PathMapTest + data.add(Arguments.of("/abs/path","abspath")); + data.add(Arguments.of("/abs/path/xxx","default")); + data.add(Arguments.of("/abs/pith","default")); + data.add(Arguments.of("/abs/path/longer","longpath")); + data.add(Arguments.of("/abs/path/","default")); + data.add(Arguments.of("/abs/path/foo","default")); + data.add(Arguments.of("/animal/bird/eagle/bald","birds")); + data.add(Arguments.of("/animal/fish/shark/hammerhead","fishes")); + data.add(Arguments.of("/animal/insect/ladybug","animals")); + data.add(Arguments.of("/animal","animals")); + data.add(Arguments.of("/animal/","animals")); + data.add(Arguments.of("/animal/other","animals")); + data.add(Arguments.of("/animal/*","animals")); + data.add(Arguments.of("/downloads/distribution.tar.gz","tarball")); + data.add(Arguments.of("/downloads/script.gz","gzipped")); + data.add(Arguments.of("/animal/arhive.gz","animals")); + data.add(Arguments.of("/Other/path","default")); + data.add(Arguments.of("/\u20ACuro/path","money")); + data.add(Arguments.of("/","root")); + + // Extra tests + data.add(Arguments.of("/downloads/readme.txt","default")); + data.add(Arguments.of("/downloads/logs.tgz","default")); + data.add(Arguments.of("/main.css","default")); + + return data.stream(); } private static PathMappings mappings; @@ -89,14 +86,9 @@ public class ServletPathSpecOrderTest mappings.put(new ServletPathSpec("/\u20ACuro/*"),"money"); // 11 } - @Parameter(0) - public String inputPath; - - @Parameter(1) - public String expectedResource; - - @Test - public void testMatch() + @ParameterizedTest + @MethodSource("data") + public void testMatch(String inputPath, String expectedResource) { assertThat("Match on ["+ inputPath+ "]", mappings.getMatch(inputPath).getResource(), is(expectedResource)); } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java index 76f1bc00985..b0154e6b52c 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/ServletPathSpecTest.java @@ -19,11 +19,11 @@ package org.eclipse.jetty.http.pathmap; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.fail; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ServletPathSpecTest { @@ -87,16 +87,16 @@ public class ServletPathSpecTest public void testDefaultPathSpec() { ServletPathSpec spec = new ServletPathSpec("/"); - assertEquals("Spec.pathSpec","/",spec.getDeclaration()); - assertEquals("Spec.pathDepth",-1,spec.getPathDepth()); + assertEquals("/", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals(-1, spec.getPathDepth(), "Spec.pathDepth"); } @Test public void testExactPathSpec() { ServletPathSpec spec = new ServletPathSpec("/abs/path"); - assertEquals("Spec.pathSpec","/abs/path",spec.getDeclaration()); - assertEquals("Spec.pathDepth",2,spec.getPathDepth()); + assertEquals("/abs/path", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); assertMatches(spec,"/abs/path"); @@ -110,52 +110,52 @@ public class ServletPathSpecTest @Test public void testGetPathInfo() { - assertEquals("pathInfo exact",null,new ServletPathSpec("/Foo/bar").getPathInfo("/Foo/bar")); - assertEquals("pathInfo prefix","/bar",new ServletPathSpec("/Foo/*").getPathInfo("/Foo/bar")); - assertEquals("pathInfo prefix","/*",new ServletPathSpec("/Foo/*").getPathInfo("/Foo/*")); - assertEquals("pathInfo prefix","/",new ServletPathSpec("/Foo/*").getPathInfo("/Foo/")); - assertEquals("pathInfo prefix",null,new ServletPathSpec("/Foo/*").getPathInfo("/Foo")); - assertEquals("pathInfo suffix",null,new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext")); - assertEquals("pathInfo default",null,new ServletPathSpec("/").getPathInfo("/Foo/bar.ext")); + assertEquals(null, new ServletPathSpec("/Foo/bar").getPathInfo("/Foo/bar"), "pathInfo exact"); + assertEquals("/bar", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/bar"), "pathInfo prefix"); + assertEquals("/*", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/*"), "pathInfo prefix"); + assertEquals("/", new ServletPathSpec("/Foo/*").getPathInfo("/Foo/"), "pathInfo prefix"); + assertEquals(null, new ServletPathSpec("/Foo/*").getPathInfo("/Foo"), "pathInfo prefix"); + assertEquals(null, new ServletPathSpec("*.ext").getPathInfo("/Foo/bar.ext"), "pathInfo suffix"); + assertEquals(null, new ServletPathSpec("/").getPathInfo("/Foo/bar.ext"), "pathInfo default"); - assertEquals("pathInfo default","/xxx/zzz",new ServletPathSpec("/*").getPathInfo("/xxx/zzz")); + assertEquals("/xxx/zzz", new ServletPathSpec("/*").getPathInfo("/xxx/zzz"), "pathInfo default"); } @Test public void testNullPathSpec() { ServletPathSpec spec = new ServletPathSpec(null); - assertEquals("Spec.pathSpec","",spec.getDeclaration()); - assertEquals("Spec.pathDepth",-1,spec.getPathDepth()); + assertEquals("", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals(-1, spec.getPathDepth(), "Spec.pathDepth"); } @Test public void testRootPathSpec() { ServletPathSpec spec = new ServletPathSpec(""); - assertEquals("Spec.pathSpec","",spec.getDeclaration()); - assertEquals("Spec.pathDepth",-1,spec.getPathDepth()); + assertEquals("", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals(-1, spec.getPathDepth(), "Spec.pathDepth"); } @Test public void testPathMatch() { - assertEquals("pathMatch exact","/Foo/bar",new ServletPathSpec("/Foo/bar").getPathMatch("/Foo/bar")); - assertEquals("pathMatch prefix","/Foo",new ServletPathSpec("/Foo/*").getPathMatch("/Foo/bar")); - assertEquals("pathMatch prefix","/Foo",new ServletPathSpec("/Foo/*").getPathMatch("/Foo/")); - assertEquals("pathMatch prefix","/Foo",new ServletPathSpec("/Foo/*").getPathMatch("/Foo")); - assertEquals("pathMatch suffix","/Foo/bar.ext",new ServletPathSpec("*.ext").getPathMatch("/Foo/bar.ext")); - assertEquals("pathMatch default","/Foo/bar.ext",new ServletPathSpec("/").getPathMatch("/Foo/bar.ext")); + assertEquals("/Foo/bar", new ServletPathSpec("/Foo/bar").getPathMatch("/Foo/bar"), "pathMatch exact"); + assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/bar"), "pathMatch prefix"); + assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo/"), "pathMatch prefix"); + assertEquals("/Foo", new ServletPathSpec("/Foo/*").getPathMatch("/Foo"), "pathMatch prefix"); + assertEquals("/Foo/bar.ext", new ServletPathSpec("*.ext").getPathMatch("/Foo/bar.ext"), "pathMatch suffix"); + assertEquals("/Foo/bar.ext", new ServletPathSpec("/").getPathMatch("/Foo/bar.ext"), "pathMatch default"); - assertEquals("pathMatch default","",new ServletPathSpec("/*").getPathMatch("/xxx/zzz")); + assertEquals("", new ServletPathSpec("/*").getPathMatch("/xxx/zzz"), "pathMatch default"); } @Test public void testPrefixPathSpec() { ServletPathSpec spec = new ServletPathSpec("/downloads/*"); - assertEquals("Spec.pathSpec","/downloads/*",spec.getDeclaration()); - assertEquals("Spec.pathDepth",2,spec.getPathDepth()); + assertEquals("/downloads/*", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); assertMatches(spec,"/downloads/logo.jpg"); assertMatches(spec,"/downloads/distribution.tar.gz"); @@ -164,17 +164,17 @@ public class ServletPathSpecTest assertMatches(spec,"/downloads"); - assertEquals("Spec.pathInfo","/",spec.getPathInfo("/downloads/")); - assertEquals("Spec.pathInfo","/distribution.zip",spec.getPathInfo("/downloads/distribution.zip")); - assertEquals("Spec.pathInfo","/dist/9.0/distribution.tar.gz",spec.getPathInfo("/downloads/dist/9.0/distribution.tar.gz")); + assertEquals("/", spec.getPathInfo("/downloads/"), "Spec.pathInfo"); + assertEquals("/distribution.zip", spec.getPathInfo("/downloads/distribution.zip"), "Spec.pathInfo"); + assertEquals("/dist/9.0/distribution.tar.gz", spec.getPathInfo("/downloads/dist/9.0/distribution.tar.gz"), "Spec.pathInfo"); } @Test public void testSuffixPathSpec() { ServletPathSpec spec = new ServletPathSpec("*.gz"); - assertEquals("Spec.pathSpec","*.gz",spec.getDeclaration()); - assertEquals("Spec.pathDepth",0,spec.getPathDepth()); + assertEquals("*.gz", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals(0, spec.getPathDepth(), "Spec.pathDepth"); assertMatches(spec,"/downloads/distribution.tar.gz"); assertMatches(spec,"/downloads/jetty.log.gz"); @@ -183,6 +183,6 @@ public class ServletPathSpecTest assertNotMatches(spec,"/downloads/distribution.tgz"); assertNotMatches(spec,"/abs/path"); - assertEquals("Spec.pathInfo",null,spec.getPathInfo("/downloads/distribution.tar.gz")); + assertEquals(null, spec.getPathInfo("/downloads/distribution.tar.gz"), "Spec.pathInfo"); } } diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java index 9c1260ee721..9cdb498a06c 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecBadSpecsTest.java @@ -18,70 +18,46 @@ package org.eclipse.jetty.http.pathmap; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.stream.Stream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests for bad path specs on ServerEndpoint Path Param / URI Template */ -@RunWith(Parameterized.class) public class UriTemplatePathSpecBadSpecsTest { - private static void bad(List data, String str) + public static Stream data() { - data.add(new String[] - { str }); + String badSpecs[] = new String[]{ + "/a/b{var}", // bad syntax - variable does not encompass whole path segment + "a/{var}", // bad syntax - no start slash + "/a/{var/b}", // path segment separator in variable name + "/{var}/*", // bad syntax - no globs allowed + "/{var}.do", // bad syntax - variable does not encompass whole path segment + "/a/{var*}", // use of glob character not allowed in variable name + "/a/{}", // bad syntax - no variable name + // MIGHT BE ALLOWED "/a/{---}", // no alpha in variable name + "{var}", // bad syntax - no start slash + "/a/{my special variable}", // bad syntax - space in variable name + "/a/{var}/{var}", // variable name duplicate + // MIGHT BE ALLOWED "/a/{var}/{Var}/{vAR}", // variable name duplicated (diff case) + "/a/../../../{var}", // path navigation not allowed + "/a/./{var}", // path navigation not allowed + "/a//{var}" // bad syntax - double path slash (no path segment) + }; + + return Stream.of(badSpecs).map(Arguments::of); } - @Parameters - public static Collection data() + @ParameterizedTest(name="[{index}] {0}") + @MethodSource("data") + public void testBadPathSpec(String pathSpec) { - List data = new ArrayList<>(); - bad(data,"/a/b{var}"); // bad syntax - variable does not encompass whole path segment - bad(data,"a/{var}"); // bad syntax - no start slash - bad(data,"/a/{var/b}"); // path segment separator in variable name - bad(data,"/{var}/*"); // bad syntax - no globs allowed - bad(data,"/{var}.do"); // bad syntax - variable does not encompass whole path segment - bad(data,"/a/{var*}"); // use of glob character not allowed in variable name - bad(data,"/a/{}"); // bad syntax - no variable name - // MIGHT BE ALLOWED bad(data,"/a/{---}"); // no alpha in variable name - bad(data,"{var}"); // bad syntax - no start slash - bad(data,"/a/{my special variable}"); // bad syntax - space in variable name - bad(data,"/a/{var}/{var}"); // variable name duplicate - // MIGHT BE ALLOWED bad(data,"/a/{var}/{Var}/{vAR}"); // variable name duplicated (diff case) - bad(data,"/a/../../../{var}"); // path navigation not allowed - bad(data,"/a/./{var}"); // path navigation not allowed - bad(data,"/a//{var}"); // bad syntax - double path slash (no path segment) - return data; + assertThrows(IllegalArgumentException.class, ()-> new UriTemplatePathSpec(pathSpec)); } - - private String pathSpec; - - public UriTemplatePathSpecBadSpecsTest(String pathSpec) - { - this.pathSpec = pathSpec; - } - - @Test - public void testBadPathSpec() - { - try - { - new UriTemplatePathSpec(this.pathSpec); - fail("Expected IllegalArgumentException for a bad PathParam pathspec on: " + pathSpec); - } - catch (IllegalArgumentException e) - { - // expected path - System.out.println(e.getMessage()); - } - } -} +} \ No newline at end of file diff --git a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java index ab8f2538864..edac6c3eb7a 100644 --- a/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java +++ b/jetty-http/src/test/java/org/eclipse/jetty/http/pathmap/UriTemplatePathSpecTest.java @@ -20,12 +20,12 @@ package org.eclipse.jetty.http.pathmap; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for URI Template Path Specs @@ -35,11 +35,11 @@ public class UriTemplatePathSpecTest private void assertDetectedVars(UriTemplatePathSpec spec, String... expectedVars) { String prefix = String.format("Spec(\"%s\")",spec.getDeclaration()); - assertEquals(prefix + ".variableCount",expectedVars.length,spec.getVariableCount()); - assertEquals(prefix + ".variable.length",expectedVars.length,spec.getVariables().length); + assertEquals(expectedVars.length, spec.getVariableCount(), prefix + ".variableCount"); + assertEquals(expectedVars.length, spec.getVariables().length, prefix + ".variable.length"); for (int i = 0; i < expectedVars.length; i++) { - assertEquals(String.format("%s.variable[%d]",prefix,i),expectedVars[i],spec.getVariables()[i]); + assertThat(String.format("%s.variable[%d]",prefix,i),spec.getVariables()[i],is(expectedVars[i])); } } @@ -59,60 +59,60 @@ public class UriTemplatePathSpecTest public void testDefaultPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/"); - assertEquals("Spec.pathSpec","/",spec.getDeclaration()); - assertEquals("Spec.pattern","^/$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",1,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.EXACT,spec.getGroup()); + assertEquals("/", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.EXACT, spec.getGroup(), "Spec.group"); - assertEquals("Spec.variableCount",0,spec.getVariableCount()); - assertEquals("Spec.variable.length",0,spec.getVariables().length); + assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); + assertEquals(0, spec.getVariables().length, "Spec.variable.length"); } @Test public void testExactOnePathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/a"); - assertEquals("Spec.pathSpec","/a",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",1,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.EXACT,spec.getGroup()); + assertEquals("/a", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.EXACT, spec.getGroup(), "Spec.group"); assertMatches(spec,"/a"); assertMatches(spec,"/a?type=other"); assertNotMatches(spec,"/a/b"); assertNotMatches(spec,"/a/"); - assertEquals("Spec.variableCount",0,spec.getVariableCount()); - assertEquals("Spec.variable.length",0,spec.getVariables().length); + assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); + assertEquals(0, spec.getVariables().length, "Spec.variable.length"); } @Test public void testExactPathSpec_TestWebapp() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/deep.thought/"); - assertEquals("Spec.pathSpec","/deep.thought/",spec.getDeclaration()); - assertEquals("Spec.pattern","^/deep\\.thought/$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",1,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.EXACT,spec.getGroup()); + assertEquals("/deep.thought/", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/deep\\.thought/$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.EXACT, spec.getGroup(), "Spec.group"); assertMatches(spec,"/deep.thought/"); assertNotMatches(spec,"/deep.thought"); - assertEquals("Spec.variableCount",0,spec.getVariableCount()); - assertEquals("Spec.variable.length",0,spec.getVariables().length); + assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); + assertEquals(0, spec.getVariables().length, "Spec.variable.length"); } @Test public void testExactTwoPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/a/b"); - assertEquals("Spec.pathSpec","/a/b",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a/b$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",2,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.EXACT,spec.getGroup()); + assertEquals("/a/b", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a/b$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.EXACT, spec.getGroup(), "Spec.group"); - assertEquals("Spec.variableCount",0,spec.getVariableCount()); - assertEquals("Spec.variable.length",0,spec.getVariables().length); + assertEquals(0, spec.getVariableCount(), "Spec.variableCount"); + assertEquals(0, spec.getVariables().length, "Spec.variable.length"); assertMatches(spec,"/a/b"); @@ -125,10 +125,10 @@ public class UriTemplatePathSpecTest public void testMiddleVarPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/a/{var}/c"); - assertEquals("Spec.pathSpec","/a/{var}/c",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a/([^/]+)/c$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",3,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.MIDDLE_GLOB,spec.getGroup()); + assertEquals("/a/{var}/c", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a/([^/]+)/c$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"var"); @@ -142,17 +142,17 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a/b/c"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(1)); - assertEquals("Spec.pathParams[var]","b",mapped.get("var")); + assertEquals("b", mapped.get("var"), "Spec.pathParams[var]"); } @Test public void testOneVarPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/a/{foo}"); - assertEquals("Spec.pathSpec","/a/{foo}",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a/([^/]+)$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",2,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.PREFIX_GLOB,spec.getGroup()); + assertEquals("/a/{foo}", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a/([^/]+)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(2, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.PREFIX_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"foo"); @@ -163,17 +163,17 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a/b"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(1)); - assertEquals("Spec.pathParams[foo]","b",mapped.get("foo")); + assertEquals("b", mapped.get("foo"), "Spec.pathParams[foo]"); } @Test public void testOneVarSuffixPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/{var}/b/c"); - assertEquals("Spec.pathSpec","/{var}/b/c",spec.getDeclaration()); - assertEquals("Spec.pattern","^/([^/]+)/b/c$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",3,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.SUFFIX_GLOB,spec.getGroup()); + assertEquals("/{var}/b/c", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/([^/]+)/b/c$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.SUFFIX_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"var"); @@ -187,17 +187,17 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a/b/c"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(1)); - assertEquals("Spec.pathParams[var]","a",mapped.get("var")); + assertEquals("a", mapped.get("var"), "Spec.pathParams[var]"); } @Test public void testTwoVarComplexInnerPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/a/{var1}/c/{var2}/e"); - assertEquals("Spec.pathSpec","/a/{var1}/c/{var2}/e",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a/([^/]+)/c/([^/]+)/e$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",5,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.MIDDLE_GLOB,spec.getGroup()); + assertEquals("/a/{var1}/c/{var2}/e", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a/([^/]+)/c/([^/]+)/e$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(5, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"var1","var2"); @@ -209,18 +209,18 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a/b/c/d/e"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(2)); - assertEquals("Spec.pathParams[var1]","b",mapped.get("var1")); - assertEquals("Spec.pathParams[var2]","d",mapped.get("var2")); + assertEquals("b", mapped.get("var1"), "Spec.pathParams[var1]"); + assertEquals("d", mapped.get("var2"), "Spec.pathParams[var2]"); } @Test public void testTwoVarComplexOuterPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/{var1}/b/{var2}/{var3}"); - assertEquals("Spec.pathSpec","/{var1}/b/{var2}/{var3}",spec.getDeclaration()); - assertEquals("Spec.pattern","^/([^/]+)/b/([^/]+)/([^/]+)$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",4,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.MIDDLE_GLOB,spec.getGroup()); + assertEquals("/{var1}/b/{var2}/{var3}", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/([^/]+)/b/([^/]+)/([^/]+)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(4, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.MIDDLE_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"var1","var2","var3"); @@ -232,19 +232,19 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a/b/c/d"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(3)); - assertEquals("Spec.pathParams[var1]","a",mapped.get("var1")); - assertEquals("Spec.pathParams[var2]","c",mapped.get("var2")); - assertEquals("Spec.pathParams[var3]","d",mapped.get("var3")); + assertEquals("a", mapped.get("var1"), "Spec.pathParams[var1]"); + assertEquals("c", mapped.get("var2"), "Spec.pathParams[var2]"); + assertEquals("d", mapped.get("var3"), "Spec.pathParams[var3]"); } @Test public void testTwoVarPrefixPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/a/{var1}/{var2}"); - assertEquals("Spec.pathSpec","/a/{var1}/{var2}",spec.getDeclaration()); - assertEquals("Spec.pattern","^/a/([^/]+)/([^/]+)$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",3,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.PREFIX_GLOB,spec.getGroup()); + assertEquals("/a/{var1}/{var2}", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/a/([^/]+)/([^/]+)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(3, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.PREFIX_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"var1","var2"); @@ -256,18 +256,18 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a/b/c"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(2)); - assertEquals("Spec.pathParams[var1]","b",mapped.get("var1")); - assertEquals("Spec.pathParams[var2]","c",mapped.get("var2")); + assertEquals("b", mapped.get("var1"), "Spec.pathParams[var1]"); + assertEquals("c", mapped.get("var2"), "Spec.pathParams[var2]"); } @Test public void testVarOnlyPathSpec() { UriTemplatePathSpec spec = new UriTemplatePathSpec("/{var1}"); - assertEquals("Spec.pathSpec","/{var1}",spec.getDeclaration()); - assertEquals("Spec.pattern","^/([^/]+)$",spec.getPattern().pattern()); - assertEquals("Spec.pathDepth",1,spec.getPathDepth()); - assertEquals("Spec.group",PathSpecGroup.PREFIX_GLOB,spec.getGroup()); + assertEquals("/{var1}", spec.getDeclaration(), "Spec.pathSpec"); + assertEquals("^/([^/]+)$", spec.getPattern().pattern(), "Spec.pattern"); + assertEquals(1, spec.getPathDepth(), "Spec.pathDepth"); + assertEquals(PathSpecGroup.PREFIX_GLOB, spec.getGroup(), "Spec.group"); assertDetectedVars(spec,"var1"); @@ -279,6 +279,6 @@ public class UriTemplatePathSpecTest Map mapped = spec.getPathParams("/a"); assertThat("Spec.pathParams",mapped,notNullValue()); assertThat("Spec.pathParams.size",mapped.size(),is(1)); - assertEquals("Spec.pathParams[var1]","a",mapped.get("var1")); + assertEquals("a", mapped.get("var1"), "Spec.pathParams[var1]"); } } diff --git a/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/ALPNNegotiationTest.java b/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/ALPNNegotiationTest.java index eae336de1e2..60c859bf5ff 100644 --- a/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/ALPNNegotiationTest.java +++ b/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/ALPNNegotiationTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.http2.alpn.tests; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -36,8 +41,7 @@ import javax.net.ssl.SSLSocket; import org.eclipse.jetty.alpn.ALPN; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ALPNNegotiationTest extends AbstractALPNTest { @@ -88,7 +92,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest encrypted.clear(); int read = channel.read(encrypted); encrypted.flip(); - Assert.assertTrue(read > 0); + assertTrue(read > 0); // Cannot decrypt, as the SSLEngine has been already closed // It may happen that the read() above read both the ServerHello and the TLS Close Alert. @@ -98,9 +102,9 @@ public class ALPNNegotiationTest extends AbstractALPNTest if (read > 0) { encrypted.flip(); - Assert.assertEquals(21, encrypted.get()); + assertEquals(21, encrypted.get()); encrypted.clear(); - Assert.assertEquals(-1, channel.read(encrypted)); + assertEquals(-1, channel.read(encrypted)); } } } @@ -147,7 +151,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest encrypted.clear(); int read = channel.read(encrypted); encrypted.flip(); - Assert.assertTrue(read > 0); + assertTrue(read > 0); ByteBuffer decrypted = ByteBuffer.allocate(sslEngine.getSession().getApplicationBufferSize()); sslEngine.unwrap(encrypted, decrypted); @@ -157,12 +161,12 @@ public class ALPNNegotiationTest extends AbstractALPNTest // Now if we can read more, we should read the TLS Close Alert and then the TCP FIN. encrypted.clear(); read = channel.read(encrypted); - Assert.assertTrue(read > 0); + assertTrue(read > 0); encrypted.flip(); } - Assert.assertEquals(21, encrypted.get()); + assertEquals(21, encrypted.get()); encrypted.clear(); - Assert.assertEquals(-1, channel.read(encrypted)); + assertEquals(-1, channel.read(encrypted)); } } @@ -196,7 +200,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest @Override public void selected(String protocol) { - Assert.assertEquals("http/1.1", protocol); + assertEquals("http/1.1", protocol); } }); @@ -215,7 +219,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.contains(" 404 ")); + assertThat(line, containsString(" 404 ")); } } @@ -248,7 +252,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest @Override public void selected(String protocol) { - Assert.assertEquals("http/1.1", protocol); + assertEquals("http/1.1", protocol); } }); @@ -267,7 +271,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.contains(" 404 ")); + assertThat(line, containsString(" 404 ")); } } @@ -318,7 +322,7 @@ public class ALPNNegotiationTest extends AbstractALPNTest InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String line = reader.readLine(); - Assert.assertTrue(line.contains(" 404 ")); + assertThat(line, containsString(" 404 ")); } } } diff --git a/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/AbstractALPNTest.java b/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/AbstractALPNTest.java index ac6051ece09..59ad2d7e3c1 100644 --- a/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/AbstractALPNTest.java +++ b/jetty-http2/http2-alpn-tests/src/test/java/org/eclipse/jetty/http2/alpn/tests/AbstractALPNTest.java @@ -22,35 +22,24 @@ import java.net.InetSocketAddress; import org.eclipse.jetty.alpn.ALPN; import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory; -import org.eclipse.jetty.http2.HTTP2Cipher; import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.toolchain.test.JDK; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; +// The mandatory cipher needed to run HTTP/2 +// over TLS is only available in JDK 8. +@EnabledOnJre(JRE.JAVA_8) public class AbstractALPNTest { - @Rule - public final TestTracker tracker = new TestTracker(); protected Server server; protected ServerConnector connector; - @Before - public void before() - { - // The mandatory cipher needed to run HTTP/2 - // over TLS is only available in JDK 8. - Assume.assumeTrue(JDK.IS_8); - } - protected InetSocketAddress prepare() throws Exception { server = new Server(); @@ -84,7 +73,7 @@ public class AbstractALPNTest return sslContextFactory; } - @After + @AfterEach public void dispose() throws Exception { if (server != null) diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java index e2e162e3281..9d55e94971f 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AbstractTest.java @@ -39,16 +39,12 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; public class AbstractTest { - @Rule - public TestTracker tracker = new TestTracker(); protected ServerConnector connector; protected String servletPath = "/test"; protected HTTP2Client client; @@ -127,7 +123,7 @@ public class AbstractTest return new MetaData.Request(method, HttpScheme.HTTP, new HostPortHttpField(authority), servletPath + pathInfo, HttpVersion.HTTP_2, fields); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java index cf29ddf070d..46a15a43b12 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncIOTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; @@ -41,8 +44,8 @@ import org.eclipse.jetty.http2.frames.DataFrame; import org.eclipse.jetty.http2.frames.HeadersFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class AsyncIOTest extends AbstractTest { @@ -97,7 +100,7 @@ public class AsyncIOTest extends AbstractTest Stream stream = promise.get(5, TimeUnit.SECONDS); stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), Callback.NOOP); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -151,7 +154,7 @@ public class AsyncIOTest extends AbstractTest Thread.sleep(1000); stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), true), Callback.NOOP); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -211,9 +214,9 @@ public class AsyncIOTest extends AbstractTest Thread.sleep(1000); stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(1), true), Callback.NOOP); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // Make sure onDataAvailable() has been called twice - Assert.assertEquals(2, count.get()); + assertEquals(2, count.get()); } private static void sleep(long ms) throws InterruptedIOException diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java index 92e8f7e2f20..2ea9eb80f9d 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/AsyncServletTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Random; @@ -55,8 +60,8 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class AsyncServletTest extends AbstractTest { @@ -115,8 +120,8 @@ public class AsyncServletTest extends AbstractTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assert.assertArrayEquals(content, buffer.toByteArray()); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertArrayEquals(content, buffer.toByteArray()); } @Test @@ -149,8 +154,8 @@ public class AsyncServletTest extends AbstractTest // When the client closes, the server receives the // corresponding frame and acts by notifying the failure, // which sends back to the client the error response. - Assert.assertTrue(serverLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); - Assert.assertTrue(clientLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(serverLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(clientLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); } @Test @@ -182,8 +187,8 @@ public class AsyncServletTest extends AbstractTest // When the client resets, the server receives the // corresponding frame and acts by notifying the failure, // but the response is not sent back to the client. - Assert.assertTrue(serverLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); - Assert.assertTrue(clientLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(serverLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(clientLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); } @Test @@ -219,7 +224,7 @@ public class AsyncServletTest extends AbstractTest Stream stream = promise.get(5, TimeUnit.SECONDS); // Wait for the server to be in ASYNC_WAIT. - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); sleep(500); stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); @@ -230,17 +235,13 @@ public class AsyncServletTest extends AbstractTest AsyncContext asyncContext = asyncContextRef.get(); ServletResponse response = asyncContext.getResponse(); ServletOutputStream output = response.getOutputStream(); - try - { - // Large writes or explicit flush() must - // fail because the stream has been reset. - output.flush(); - Assert.fail(); - } - catch (IOException x) - { - // Expected - } + + assertThrows(IOException.class, + () -> { + // Large writes or explicit flush() must + // fail because the stream has been reset. + output.flush(); + }); } @Test @@ -342,8 +343,8 @@ public class AsyncServletTest extends AbstractTest // When the server idle times out, but the request has been dispatched // then the server must ignore the idle timeout as per Servlet semantic. - Assert.assertFalse(errorLatch.await(2 * timeout, TimeUnit.MILLISECONDS)); - Assert.assertTrue(clientLatch.await(2 * timeout, TimeUnit.MILLISECONDS)); + assertFalse(errorLatch.await(2 * timeout, TimeUnit.MILLISECONDS)); + assertTrue(clientLatch.await(2 * timeout, TimeUnit.MILLISECONDS)); } private void sleep(long ms) diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java index f26041942cd..c6bd653a9eb 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ConnectTimeoutTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; @@ -28,9 +32,8 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.http2.api.Session; import org.eclipse.jetty.http2.api.server.ServerSessionListener; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; public class ConnectTimeoutTest extends AbstractTest { @@ -52,12 +55,12 @@ public class ConnectTimeoutTest extends AbstractTest @Override public void failed(Throwable x) { - Assert.assertTrue(x instanceof SocketTimeoutException); + assertThat(x, instanceOf(SocketTimeoutException.class)); latch.countDown(); } }); - Assert.assertTrue(latch.await(2 * connectTimeout, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(2 * connectTimeout, TimeUnit.MILLISECONDS)); } private void assumeConnectTimeout(String host, int port, int connectTimeout) throws IOException @@ -85,6 +88,6 @@ public class ConnectTimeoutTest extends AbstractTest } // Abort the test if we can connect. - Assume.assumeTrue("Should have seen connect timeout",socketTimeout); + Assumptions.assumeTrue(socketTimeout, "Should have seen connect timeout"); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java index 5ff158a2404..2a71d1ecc9b 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStalledTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayDeque; @@ -48,20 +51,16 @@ import org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class FlowControlStalledTest { - @Rule - public TestTracker tracker = new TestTracker(); protected ServerConnector connector; protected HTTP2Client client; protected Server server; @@ -107,7 +106,7 @@ public class FlowControlStalledTest return new MetaData.Request(method, HttpScheme.HTTP, new HostPortHttpField(authority), target, HttpVersion.HTTP_2, fields); } - @After + @AfterEach public void dispose() throws Exception { // Allow WINDOW_UPDATE frames to be sent/received to avoid exception stack traces. @@ -184,7 +183,7 @@ public class FlowControlStalledTest } }); - Assert.assertTrue(stallLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(stallLatch.get().await(5, TimeUnit.SECONDS)); // First stream is now stalled, check that writing a second stream // does not result in the first be notified again of being stalled. @@ -193,7 +192,7 @@ public class FlowControlStalledTest request = newRequest("GET", "/", new HttpFields()); client.newStream(new HeadersFrame(request, null, true), new Promise.Adapter<>(), new Stream.Listener.Adapter()); - Assert.assertFalse(stallLatch.get().await(1, TimeUnit.SECONDS)); + assertFalse(stallLatch.get().await(1, TimeUnit.SECONDS)); // Consume all data. while (!latch.await(10, TimeUnit.MILLISECONDS)) @@ -204,7 +203,7 @@ public class FlowControlStalledTest } // Make sure the unstall callback is invoked. - Assert.assertTrue(unstallLatch.await(5, TimeUnit.SECONDS)); + assertTrue(unstallLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -284,7 +283,7 @@ public class FlowControlStalledTest } }); - Assert.assertTrue(stallLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(stallLatch.get().await(5, TimeUnit.SECONDS)); // The session is now stalled, check that writing a second stream // does not result in the session be notified again of being stalled. @@ -293,7 +292,7 @@ public class FlowControlStalledTest request = newRequest("GET", "/", new HttpFields()); session.newStream(new HeadersFrame(request, null, true), new Promise.Adapter<>(), new Stream.Listener.Adapter()); - Assert.assertFalse(stallLatch.get().await(1, TimeUnit.SECONDS)); + assertFalse(stallLatch.get().await(1, TimeUnit.SECONDS)); // Consume all data. while (!latch.await(10, TimeUnit.MILLISECONDS)) @@ -304,6 +303,6 @@ public class FlowControlStalledTest } // Make sure the unstall callback is invoked. - Assert.assertTrue(unstallLatch.await(5, TimeUnit.SECONDS)); + assertTrue(unstallLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java index d601f2d3b17..08b60cd0388 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlStrategyTest.java @@ -18,6 +18,13 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -61,21 +68,18 @@ import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public abstract class FlowControlStrategyTest { - @Rule - public TestTracker tracker = new TestTracker(); protected ServerConnector connector; protected HTTP2Client client; protected Server server; @@ -123,7 +127,7 @@ public abstract class FlowControlStrategyTest return new MetaData.Request(method, HttpScheme.HTTP, new HostPortHttpField(authority), "/", HttpVersion.HTTP_2, fields); } - @After + @AfterEach public void dispose() throws Exception { // Allow WINDOW_UPDATE frames to be sent/received to avoid exception stack traces. @@ -145,8 +149,8 @@ public abstract class FlowControlStrategyTest public Map onPreface(Session session) { HTTP2Session serverSession = (HTTP2Session)session; - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverSession.getSendWindow()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverSession.getRecvWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverSession.getSendWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverSession.getRecvWindow()); prefaceLatch.countDown(); return null; } @@ -157,8 +161,8 @@ public abstract class FlowControlStrategyTest for (Stream stream : session.getStreams()) { HTTP2Stream serverStream = (HTTP2Stream)stream; - Assert.assertEquals(0, serverStream.getSendWindow()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow()); + assertEquals(0, serverStream.getSendWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow()); } settingsLatch.countDown(); } @@ -170,14 +174,14 @@ public abstract class FlowControlStrategyTest MetaData.Request request = (MetaData.Request)frame.getMetaData(); if ("GET".equalsIgnoreCase(request.getMethod())) { - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getSendWindow()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getSendWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow()); stream1Latch.countDown(); } else { - Assert.assertEquals(0, serverStream.getSendWindow()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow()); + assertEquals(0, serverStream.getSendWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, serverStream.getRecvWindow()); stream2Latch.countDown(); } return null; @@ -186,18 +190,18 @@ public abstract class FlowControlStrategyTest HTTP2Session clientSession = (HTTP2Session)newClient(new Session.Listener.Adapter()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientSession.getSendWindow()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientSession.getRecvWindow()); - Assert.assertTrue(prefaceLatch.await(5, TimeUnit.SECONDS)); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientSession.getSendWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientSession.getRecvWindow()); + assertTrue(prefaceLatch.await(5, TimeUnit.SECONDS)); MetaData.Request request1 = newRequest("GET", new HttpFields()); FuturePromise promise1 = new FuturePromise<>(); clientSession.newStream(new HeadersFrame(request1, null, true), promise1, new Stream.Listener.Adapter()); HTTP2Stream clientStream1 = (HTTP2Stream)promise1.get(5, TimeUnit.SECONDS); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getSendWindow()); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getRecvWindow()); - Assert.assertTrue(stream1Latch.await(5, TimeUnit.SECONDS)); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getSendWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getRecvWindow()); + assertTrue(stream1Latch.await(5, TimeUnit.SECONDS)); // Send a SETTINGS frame that changes the window size. // This tells the server that its stream send window must be updated, @@ -209,8 +213,8 @@ public abstract class FlowControlStrategyTest clientSession.settings(frame, callback); callback.get(5, TimeUnit.SECONDS); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getSendWindow()); - Assert.assertEquals(0, clientStream1.getRecvWindow()); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream1.getSendWindow()); + assertEquals(0, clientStream1.getRecvWindow()); settingsLatch.await(5, TimeUnit.SECONDS); // Now create a new stream, it must pick up the new value. @@ -219,9 +223,9 @@ public abstract class FlowControlStrategyTest clientSession.newStream(new HeadersFrame(request2, null, true), promise2, new Stream.Listener.Adapter()); HTTP2Stream clientStream2 = (HTTP2Stream)promise2.get(5, TimeUnit.SECONDS); - Assert.assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream2.getSendWindow()); - Assert.assertEquals(0, clientStream2.getRecvWindow()); - Assert.assertTrue(stream2Latch.await(5, TimeUnit.SECONDS)); + assertEquals(FlowControlStrategy.DEFAULT_WINDOW_SIZE, clientStream2.getSendWindow()); + assertEquals(0, clientStream2.getRecvWindow()); + assertTrue(stream2Latch.await(5, TimeUnit.SECONDS)); } @Test @@ -300,12 +304,12 @@ public abstract class FlowControlStrategyTest stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(size * 2), true), Callback.NOOP); }); - Assert.assertFalse(dataLatch.await(1, TimeUnit.SECONDS)); + assertFalse(dataLatch.await(1, TimeUnit.SECONDS)); // Consume the data arrived to server, this will resume flow control on the client. callbackRef.get().succeeded(); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -346,7 +350,7 @@ public abstract class FlowControlStrategyTest session.settings(new SettingsFrame(settings, false), completable); completable.thenRun(settingsLatch::countDown); - Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); + assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); final CountDownLatch dataLatch = new CountDownLatch(1); final Exchanger exchanger = new Exchanger<>(); @@ -377,7 +381,7 @@ public abstract class FlowControlStrategyTest } else { - Assert.fail(); + fail("Unrecognized dataFrames: " + dataFrames); } } catch (InterruptedException x) @@ -399,7 +403,7 @@ public abstract class FlowControlStrategyTest // Consume the second chunk. callback.succeeded(); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -450,7 +454,7 @@ public abstract class FlowControlStrategyTest } else { - Assert.fail(); + fail("Unrecognized dataFrames: " + dataFrames); } } catch (InterruptedException x) @@ -471,7 +475,7 @@ public abstract class FlowControlStrategyTest } }); - Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); + assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); MetaData.Request metaData = newRequest("GET", new HttpFields()); HeadersFrame requestFrame = new HeadersFrame(metaData, null, false); @@ -495,20 +499,13 @@ public abstract class FlowControlStrategyTest // Consume the second chunk. callback.succeeded(); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); } private void checkThatWeAreFlowControlStalled(Exchanger exchanger) throws Exception { - try - { - exchanger.exchange(null, 1, TimeUnit.SECONDS); - Assert.fail(); - } - catch (TimeoutException x) - { - // Expected. - } + assertThrows(TimeoutException.class, + () -> exchanger.exchange(null, 1, TimeUnit.SECONDS)); } @Test @@ -563,7 +560,7 @@ public abstract class FlowControlStrategyTest prepareLatch.countDown(); } }); - Assert.assertTrue(prepareLatch.await(5, TimeUnit.SECONDS)); + assertTrue(prepareLatch.await(5, TimeUnit.SECONDS)); // Second request will consume half of the remaining the session window. MetaData.Request request2 = newRequest("GET", new HttpFields()); @@ -603,14 +600,14 @@ public abstract class FlowControlStrategyTest }); // Verify that the data does not arrive because the server session is stalled. - Assert.assertFalse(latch.await(1, TimeUnit.SECONDS)); + assertFalse(latch.await(1, TimeUnit.SECONDS)); // Consume the data of the first response. // This will open up the session window, allowing the fourth stream to send data. for (Callback callback : callbacks1) callback.succeeded(); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -658,8 +655,8 @@ public abstract class FlowControlStrategyTest } }); - Assert.assertTrue(latch.await(15, TimeUnit.SECONDS)); - Assert.assertArrayEquals(data, bytes); + assertTrue(latch.await(15, TimeUnit.SECONDS)); + assertArrayEquals(data, bytes); } @Test @@ -724,10 +721,10 @@ public abstract class FlowControlStrategyTest stream.data(dataFrame, Callback.NOOP); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); responseContent.flip(); - Assert.assertArrayEquals(requestData, responseData); + assertArrayEquals(requestData, responseData); } @Test @@ -783,7 +780,7 @@ public abstract class FlowControlStrategyTest dataLatch.countDown(); } }); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); // The following "sneaky" write may clash with the write // of the reply SETTINGS frame sent by the client in @@ -803,7 +800,7 @@ public abstract class FlowControlStrategyTest http2Session.getEndPoint().write(Callback.NOOP, buffers.toArray(new ByteBuffer[buffers.size()])); // Expect the connection to be closed. - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -867,7 +864,7 @@ public abstract class FlowControlStrategyTest dataLatch.countDown(); } }); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); // Wait for a while before doing the "sneaky" write // below, see comments in the previous test case. @@ -883,7 +880,7 @@ public abstract class FlowControlStrategyTest http2Session.getEndPoint().write(Callback.NOOP, buffers.toArray(new ByteBuffer[buffers.size()])); // Expect the connection to be closed. - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -949,8 +946,8 @@ public abstract class FlowControlStrategyTest } }); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -1014,9 +1011,9 @@ public abstract class FlowControlStrategyTest ByteBuffer data = ByteBuffer.allocate(FlowControlStrategy.DEFAULT_WINDOW_SIZE - 1); stream.data(new DataFrame(stream.getId(), data, true), Callback.NOOP); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(sessionWindowUpdates.size() > 0); - Assert.assertEquals(0, streamWindowUpdates.size()); + assertTrue(sessionWindowUpdates.size() > 0); + assertEquals(0, streamWindowUpdates.size()); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java index d28e2fb4331..ecf9e8d1331 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/FlowControlWindowsTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -42,9 +45,8 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class FlowControlWindowsTest { @@ -77,7 +79,7 @@ public class FlowControlWindowsTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -106,9 +108,9 @@ public class FlowControlWindowsTest Thread.sleep(1000); int sessionSendWindow = clientSession.updateSendWindow(0); - Assert.assertEquals(serverSessionRecvWindow, sessionSendWindow); + assertEquals(serverSessionRecvWindow, sessionSendWindow); int sessionRecvWindow = clientSession.updateRecvWindow(0); - Assert.assertEquals(clientSessionRecvWindow, sessionRecvWindow); + assertEquals(clientSessionRecvWindow, sessionRecvWindow); HostPortHttpField hostPort = new HostPortHttpField("localhost:" + connector.getLocalPort()); MetaData.Request request = new MetaData.Request(HttpMethod.GET.asString(), HttpScheme.HTTP, hostPort, "/", HttpVersion.HTTP_2, new HttpFields()); @@ -118,9 +120,9 @@ public class FlowControlWindowsTest IStream clientStream = (IStream)promise.get(5, TimeUnit.SECONDS); int streamSendWindow = clientStream.updateSendWindow(0); - Assert.assertEquals(serverStreamRecvWindow, streamSendWindow); + assertEquals(serverStreamRecvWindow, streamSendWindow); int streamRecvWindow = clientStream.updateRecvWindow(0); - Assert.assertEquals(clientStreamRecvWindow, streamRecvWindow); + assertEquals(clientStreamRecvWindow, streamRecvWindow); } @Test @@ -150,27 +152,27 @@ public class FlowControlWindowsTest ISession clientSession = newClient(new Session.Listener.Adapter()); - Assert.assertTrue(sessionLatch.await(5, TimeUnit.SECONDS)); + assertTrue(sessionLatch.await(5, TimeUnit.SECONDS)); ISession serverSession = sessionRef.get(); // Wait while client and server exchange SETTINGS and WINDOW_UPDATE frames. Thread.sleep(1000); int sessionSendWindow = serverSession.updateSendWindow(0); - Assert.assertEquals(clientSessionRecvWindow, sessionSendWindow); + assertEquals(clientSessionRecvWindow, sessionSendWindow); int sessionRecvWindow = serverSession.updateRecvWindow(0); - Assert.assertEquals(serverSessionRecvWindow, sessionRecvWindow); + assertEquals(serverSessionRecvWindow, sessionRecvWindow); HostPortHttpField hostPort = new HostPortHttpField("localhost:" + connector.getLocalPort()); MetaData.Request request = new MetaData.Request(HttpMethod.GET.asString(), HttpScheme.HTTP, hostPort, "/", HttpVersion.HTTP_2, new HttpFields()); HeadersFrame frame = new HeadersFrame(request, null, true); clientSession.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter()); - Assert.assertTrue(streamLatch.await(5, TimeUnit.SECONDS)); + assertTrue(streamLatch.await(5, TimeUnit.SECONDS)); IStream serverStream = streamRef.get(); int streamSendWindow = serverStream.updateSendWindow(0); - Assert.assertEquals(clientStreamRecvWindow, streamSendWindow); + assertEquals(clientStreamRecvWindow, streamSendWindow); int streamRecvWindow = serverStream.updateRecvWindow(0); - Assert.assertEquals(serverStreamRecvWindow, streamRecvWindow); + assertEquals(serverStreamRecvWindow, streamRecvWindow); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java index 1a3a315d095..33ef5e818a0 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/HTTP2Test.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritePendingException; @@ -57,8 +61,8 @@ import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.Jetty; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HTTP2Test extends AbstractTest { @@ -78,19 +82,19 @@ public class HTTP2Test extends AbstractTest @Override public void onHeaders(Stream stream, HeadersFrame frame) { - Assert.assertTrue(stream.getId() > 0); + assertTrue(stream.getId() > 0); - Assert.assertTrue(frame.isEndStream()); - Assert.assertEquals(stream.getId(), frame.getStreamId()); - Assert.assertTrue(frame.getMetaData().isResponse()); + assertTrue(frame.isEndStream()); + assertEquals(stream.getId(), frame.getStreamId()); + assertTrue(frame.getMetaData().isResponse()); MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -125,22 +129,22 @@ public class HTTP2Test extends AbstractTest @Override public void onHeaders(Stream stream, HeadersFrame frame) { - Assert.assertFalse(frame.isEndStream()); - Assert.assertEquals(stream.getId(), frame.getStreamId()); + assertFalse(frame.isEndStream()); + assertEquals(stream.getId(), frame.getStreamId()); MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); } @Override public void onData(Stream stream, DataFrame frame, Callback callback) { - Assert.assertTrue(frame.isEndStream()); + assertTrue(frame.isEndStream()); callback.succeeded(); latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -167,13 +171,13 @@ public class HTTP2Test extends AbstractTest @Override public void onHeaders(Stream stream, HeadersFrame frame) { - Assert.assertTrue(stream.getId() > 0); + assertTrue(stream.getId() > 0); - Assert.assertFalse(frame.isEndStream()); - Assert.assertEquals(stream.getId(), frame.getStreamId()); - Assert.assertTrue(frame.getMetaData().isResponse()); + assertFalse(frame.isEndStream()); + assertEquals(stream.getId(), frame.getStreamId()); + assertTrue(frame.getMetaData().isResponse()); MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); latch.countDown(); } @@ -181,15 +185,15 @@ public class HTTP2Test extends AbstractTest @Override public void onData(Stream stream, DataFrame frame, Callback callback) { - Assert.assertTrue(frame.isEndStream()); - Assert.assertEquals(ByteBuffer.wrap(content), frame.getData()); + assertTrue(frame.isEndStream()); + assertEquals(ByteBuffer.wrap(content), frame.getData()); callback.succeeded(); latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -232,7 +236,7 @@ public class HTTP2Test extends AbstractTest stream.data(dataFrame, Callback.NOOP); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -275,7 +279,7 @@ public class HTTP2Test extends AbstractTest }); } - Assert.assertTrue(server.dump() + System.lineSeparator() + client.dump(), latch.await(requests, TimeUnit.SECONDS)); + assertTrue(latch.await(requests, TimeUnit.SECONDS), server.dump() + System.lineSeparator() + client.dump()); } @Test @@ -302,13 +306,13 @@ public class HTTP2Test extends AbstractTest public void onHeaders(Stream stream, HeadersFrame frame) { MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(status, response.getStatus()); + assertEquals(status, response.getStatus()); if (frame.isEndStream()) latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -322,9 +326,9 @@ public class HTTP2Test extends AbstractTest @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - Assert.assertEquals(host, request.getServerName()); - Assert.assertEquals(port, request.getServerPort()); - Assert.assertEquals(authority, request.getHeader("Host")); + assertEquals(host, request.getServerName()); + assertEquals(port, request.getServerPort()); + assertEquals(authority, request.getHeader("Host")); } }); @@ -339,13 +343,13 @@ public class HTTP2Test extends AbstractTest public void onHeaders(Stream stream, HeadersFrame frame) { MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); if (frame.isEndStream()) latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -367,7 +371,7 @@ public class HTTP2Test extends AbstractTest server.stop(); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -389,7 +393,7 @@ public class HTTP2Test extends AbstractTest client.stop(); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -424,7 +428,7 @@ public class HTTP2Test extends AbstractTest settingsLatch.countDown(); } }); - Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); + assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); MetaData.Request request1 = newRequest("GET", new HttpFields()); FuturePromise promise1 = new FuturePromise<>(); @@ -467,8 +471,8 @@ public class HTTP2Test extends AbstractTest } }, new Stream.Listener.Adapter()); - Assert.assertTrue(maxStreamsLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(2, session.getStreams().size()); + assertTrue(maxStreamsLatch.await(5, TimeUnit.SECONDS)); + assertEquals(2, session.getStreams().size()); // End the second stream. stream2.data(new DataFrame(stream2.getId(), BufferUtil.EMPTY_BUFFER, true), new Callback() @@ -479,8 +483,8 @@ public class HTTP2Test extends AbstractTest exchangeLatch2.countDown(); } }); - Assert.assertTrue(exchangeLatch2.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(1, session.getStreams().size()); + assertTrue(exchangeLatch2.await(5, TimeUnit.SECONDS)); + assertEquals(1, session.getStreams().size()); // Create a fourth stream. MetaData.Request request4 = newRequest("GET", new HttpFields()); @@ -501,8 +505,8 @@ public class HTTP2Test extends AbstractTest exchangeLatch4.countDown(); } }); - Assert.assertTrue(exchangeLatch4.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(1, session.getStreams().size()); + assertTrue(exchangeLatch4.await(5, TimeUnit.SECONDS)); + assertEquals(1, session.getStreams().size()); // End the first stream. stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), new Callback() @@ -513,8 +517,8 @@ public class HTTP2Test extends AbstractTest exchangeLatch1.countDown(); } }); - Assert.assertTrue(exchangeLatch2.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, session.getStreams().size()); + assertTrue(exchangeLatch2.await(5, TimeUnit.SECONDS)); + assertEquals(0, session.getStreams().size()); } @Test @@ -608,7 +612,7 @@ public class HTTP2Test extends AbstractTest } }); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -681,7 +685,7 @@ public class HTTP2Test extends AbstractTest } }); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -722,8 +726,8 @@ public class HTTP2Test extends AbstractTest session.newStream(request, new Promise.Adapter<>(), new Stream.Listener.Adapter()); // Make sure onClose() is called. - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertFalse(failureLatch.await(1, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertFalse(failureLatch.await(1, TimeUnit.SECONDS)); } @Test @@ -785,9 +789,9 @@ public class HTTP2Test extends AbstractTest } }); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(goAwayLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(goAwayLatch.await(5, TimeUnit.SECONDS)); } private static void sleep(long time) diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java index 8c7c966ac44..297b93fd91f 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/IdleTimeoutTest.java @@ -19,6 +19,12 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; @@ -57,8 +63,8 @@ import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class IdleTimeoutTest extends AbstractTest { @@ -102,7 +108,7 @@ public class IdleTimeoutTest extends AbstractTest } }, new Stream.Listener.Adapter()); - Assert.assertTrue(latch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); } @Test @@ -141,7 +147,7 @@ public class IdleTimeoutTest extends AbstractTest } }, new Stream.Listener.Adapter()); - Assert.assertTrue(latch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); } @Test @@ -195,10 +201,10 @@ public class IdleTimeoutTest extends AbstractTest } }); - Assert.assertTrue(replyLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(replyLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); // Just make sure onClose() has never been called, but don't wait too much - Assert.assertFalse(closeLatch.await(idleTimeout / 2, TimeUnit.MILLISECONDS)); + assertFalse(closeLatch.await(idleTimeout / 2, TimeUnit.MILLISECONDS)); } @Test @@ -237,8 +243,8 @@ public class IdleTimeoutTest extends AbstractTest } }, new Stream.Listener.Adapter()); - Assert.assertTrue(closeLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); - Assert.assertTrue(session.isClosed()); + assertTrue(closeLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(session.isClosed()); } @Test @@ -274,7 +280,7 @@ public class IdleTimeoutTest extends AbstractTest } }, new Stream.Listener.Adapter()); - Assert.assertTrue(closeLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(closeLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); } @Test @@ -326,8 +332,8 @@ public class IdleTimeoutTest extends AbstractTest } }); - Assert.assertFalse(closeLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); - Assert.assertTrue(replyLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertFalse(closeLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(replyLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); } @Test @@ -368,20 +374,20 @@ public class IdleTimeoutTest extends AbstractTest @Override public boolean onIdleTimeout(Stream stream, Throwable x) { - Assert.assertThat(x, Matchers.instanceOf(TimeoutException.class)); + assertThat(x, Matchers.instanceOf(TimeoutException.class)); timeoutLatch.countDown(); return true; } }); - Assert.assertTrue(timeoutLatch.await(5, TimeUnit.SECONDS)); + assertTrue(timeoutLatch.await(5, TimeUnit.SECONDS)); // We must not receive any DATA frame. - Assert.assertFalse(dataLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertFalse(dataLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); // Stream must be gone. - Assert.assertTrue(session.getStreams().isEmpty()); + assertTrue(session.getStreams().isEmpty()); // Session must not be closed, nor disconnected. - Assert.assertFalse(session.isClosed()); - Assert.assertFalse(((HTTP2Session)session).isDisconnected()); + assertFalse(session.isClosed()); + assertFalse(((HTTP2Session)session).isDisconnected()); } @Test @@ -420,13 +426,13 @@ public class IdleTimeoutTest extends AbstractTest } }); - Assert.assertTrue(timeoutLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(timeoutLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); // Stream must be gone. - Assert.assertTrue(session.getStreams().isEmpty()); + assertTrue(session.getStreams().isEmpty()); // Session must not be closed, nor disconnected. - Assert.assertFalse(session.isClosed()); - Assert.assertFalse(((HTTP2Session)session).isDisconnected()); + assertFalse(session.isClosed()); + assertFalse(((HTTP2Session)session).isDisconnected()); } @Test @@ -481,16 +487,16 @@ public class IdleTimeoutTest extends AbstractTest public void succeeded() { // Idle timeout should not fire while the server is receiving. - Assert.assertEquals(1, timeoutLatch.getCount()); + assertEquals(1, timeoutLatch.getCount()); dataLatch.countDown(); } }); } }); - Assert.assertTrue(dataLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(dataLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS)); // The server did not send a response, so it will eventually timeout. - Assert.assertTrue(timeoutLatch.await(5 * idleTimeout, TimeUnit.SECONDS)); + assertTrue(timeoutLatch.await(5 * idleTimeout, TimeUnit.SECONDS)); } @Test @@ -544,7 +550,7 @@ public class IdleTimeoutTest extends AbstractTest stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(1), true), Callback.NOOP); }); - Assert.assertFalse(resetLatch.await(1, TimeUnit.SECONDS)); + assertFalse(resetLatch.await(1, TimeUnit.SECONDS)); } @Test @@ -595,7 +601,7 @@ public class IdleTimeoutTest extends AbstractTest ByteBuffer data = ByteBuffer.allocate(contentLength); stream.data(new DataFrame(stream.getId(), data, true), Callback.NOOP); - Assert.assertTrue(latch.await(2 * (contentLength / bufferSize + 1) * delay, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(2 * (contentLength / bufferSize + 1) * delay, TimeUnit.MILLISECONDS)); } @Test @@ -667,12 +673,12 @@ public class IdleTimeoutTest extends AbstractTest ByteBuffer data = ByteBuffer.allocate(((ISession)client).updateSendWindow(0)); stream.data(new DataFrame(stream.getId(), data, true), Callback.NOOP); - Assert.assertTrue(resetLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); + assertTrue(resetLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS)); // Wait for WINDOW_UPDATEs to be processed by the client. sleep(1000); - Assert.assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); + assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); } private void sleep(long value) @@ -683,7 +689,7 @@ public class IdleTimeoutTest extends AbstractTest } catch (InterruptedException x) { - Assert.fail(); + fail(x); } } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java index 489cc161870..a194c01b27f 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InterleavingTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -47,9 +53,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class InterleavingTest extends AbstractTest { @@ -101,7 +105,7 @@ public class InterleavingTest extends AbstractTest session.newStream(headersFrame2, streamPromise2, streamListener); streamPromise2.get(5, TimeUnit.SECONDS); - Assert.assertTrue(serverStreamsLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverStreamsLatch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); @@ -146,7 +150,7 @@ public class InterleavingTest extends AbstractTest { DataFrameCallback dataFrameCallback = dataFrames.poll(5, TimeUnit.SECONDS); if (dataFrameCallback == null) - Assert.fail(); + fail(); DataFrame dataFrame = dataFrameCallback.frame; int streamId = dataFrame.getStreamId(); @@ -161,8 +165,8 @@ public class InterleavingTest extends AbstractTest } // Verify that the content has been sent properly. - Assert.assertArrayEquals(content1, contents.get(serverStream1.getId()).toByteArray()); - Assert.assertArrayEquals(content2, contents.get(serverStream2.getId()).toByteArray()); + assertArrayEquals(content1, contents.get(serverStream1.getId()).toByteArray()); + assertArrayEquals(content2, contents.get(serverStream2.getId()).toByteArray()); // Verify that the interleaving is correct. Map> groups = new HashMap<>(); @@ -191,7 +195,7 @@ public class InterleavingTest extends AbstractTest { logger.debug("stream {} interleaved lengths = {}", stream, lengths); for (Integer length : lengths) - Assert.assertThat(length, Matchers.lessThanOrEqualTo(maxFrameSize)); + assertThat(length, lessThanOrEqualTo(maxFrameSize)); }); } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java index a56cb15c924..750f0aca457 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/InvalidServerTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; @@ -29,8 +32,7 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.http2.api.Session; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class InvalidServerTest extends AbstractTest { @@ -60,9 +62,9 @@ public class InvalidServerTest extends AbstractTest output.write("enough_junk_bytes".getBytes(StandardCharsets.UTF_8)); Session session = promise.get(5, TimeUnit.SECONDS); - Assert.assertNotNull(session); + assertNotNull(session); - Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); // Verify that the client closed the socket. InputStream input = socket.getInputStream(); diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java index be26c7a8955..c2eb22730fd 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/MaxPushedStreamsTest.java @@ -44,8 +44,10 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class MaxPushedStreamsTest extends AbstractTest { @@ -88,7 +90,7 @@ public class MaxPushedStreamsTest extends AbstractTest @Override public void onReset(Stream stream, ResetFrame frame) { - Assert.assertEquals(ErrorCode.REFUSED_STREAM_ERROR.code, frame.getError()); + assertEquals(ErrorCode.REFUSED_STREAM_ERROR.code, frame.getError()); resetLatch.countDown(); } }); @@ -124,7 +126,7 @@ public class MaxPushedStreamsTest extends AbstractTest } }); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java index f50c33874d5..7c8c8bb0569 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PingTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -26,8 +29,8 @@ import org.eclipse.jetty.http2.api.Session; import org.eclipse.jetty.http2.api.server.ServerSessionListener; import org.eclipse.jetty.http2.frames.PingFrame; import org.eclipse.jetty.util.Callback; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PingTest extends AbstractTest { @@ -44,8 +47,8 @@ public class PingTest extends AbstractTest @Override public void onPing(Session session, PingFrame frame) { - Assert.assertTrue(frame.isReply()); - Assert.assertArrayEquals(payload, frame.getPayload()); + assertTrue(frame.isReply()); + assertArrayEquals(payload, frame.getPayload()); latch.countDown(); } }); @@ -53,6 +56,6 @@ public class PingTest extends AbstractTest PingFrame frame = new PingFrame(payload, false); session.ping(frame, Callback.NOOP); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java index ba140b6de86..835db222aac 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PrefaceTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; @@ -57,8 +63,7 @@ import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class PrefaceTest extends AbstractTest { @@ -117,7 +122,7 @@ public class PrefaceTest extends AbstractTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -179,11 +184,11 @@ public class PrefaceTest extends AbstractTest parser.parse(buffer); } - Assert.assertEquals(2, settings.size()); + assertEquals(2, settings.size()); SettingsFrame frame1 = settings.poll(); - Assert.assertFalse(frame1.isReply()); + assertFalse(frame1.isReply()); SettingsFrame frame2 = settings.poll(); - Assert.assertTrue(frame2.isReply()); + assertTrue(frame2.isReply()); } } @@ -244,8 +249,8 @@ public class PrefaceTest extends AbstractTest socket.write(upgradeBuffer); // Make sure onPreface() is called on server. - Assert.assertTrue(serverPrefaceLatch.get().await(5, TimeUnit.SECONDS)); - Assert.assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(serverPrefaceLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS)); // The 101 response is the reply to the client preface SETTINGS frame. ByteBuffer buffer = byteBufferPool.acquire(1024, true); @@ -254,8 +259,7 @@ public class PrefaceTest extends AbstractTest BufferUtil.clearToFill(buffer); int read = socket.read(buffer); BufferUtil.flipToFlush(buffer, 0); - if (read < 0) - Assert.fail(); + assertThat(read, greaterThanOrEqualTo(0)); int crlfs = 0; while (buffer.hasRemaining()) @@ -285,9 +289,9 @@ public class PrefaceTest extends AbstractTest socket.write(buffers.toArray(new ByteBuffer[buffers.size()])); // However, we should not call onPreface() again. - Assert.assertFalse(serverPrefaceLatch.get().await(1, TimeUnit.SECONDS)); + assertFalse(serverPrefaceLatch.get().await(1, TimeUnit.SECONDS)); // Although we should notify of the SETTINGS frame. - Assert.assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS)); + assertTrue(serverSettingsLatch.get().await(5, TimeUnit.SECONDS)); CountDownLatch clientSettingsLatch = new CountDownLatch(1); AtomicBoolean responded = new AtomicBoolean(); @@ -298,7 +302,7 @@ public class PrefaceTest extends AbstractTest { if (frame.isReply()) return; - Assert.assertEquals(maxConcurrentStreams, frame.getSettings().get(SettingsFrame.MAX_CONCURRENT_STREAMS)); + assertEquals(maxConcurrentStreams, frame.getSettings().get(SettingsFrame.MAX_CONCURRENT_STREAMS)); clientSettingsLatch.countDown(); } @@ -321,11 +325,10 @@ public class PrefaceTest extends AbstractTest BufferUtil.clearToFill(buffer); int read = socket.read(buffer); BufferUtil.flipToFlush(buffer, 0); - if (read < 0) - Assert.fail(); + assertThat(read, greaterThanOrEqualTo(0)); } - Assert.assertTrue(clientSettingsLatch.await(5, TimeUnit.SECONDS)); + assertTrue(clientSettingsLatch.await(5, TimeUnit.SECONDS)); } } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java index c6c49c0f27a..0832264bd07 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PriorityTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -32,8 +36,8 @@ import org.eclipse.jetty.http2.frames.PriorityFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PriorityTest extends AbstractTest { @@ -54,7 +58,7 @@ public class PriorityTest extends AbstractTest Session session = newClient(new Session.Listener.Adapter()); int streamId = session.priority(new PriorityFrame(0, 13, false), Callback.NOOP); - Assert.assertTrue(streamId > 0); + assertTrue(streamId > 0); CountDownLatch latch = new CountDownLatch(2); MetaData metaData = newRequest("GET", new HttpFields()); @@ -64,7 +68,7 @@ public class PriorityTest extends AbstractTest @Override public void succeeded(Stream result) { - Assert.assertEquals(streamId, result.getId()); + assertEquals(streamId, result.getId()); latch.countDown(); } }, new Stream.Listener.Adapter() @@ -77,7 +81,7 @@ public class PriorityTest extends AbstractTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -132,14 +136,14 @@ public class PriorityTest extends AbstractTest Stream stream2 = promise2.get(5, TimeUnit.SECONDS); int streamId = session.priority(new PriorityFrame(stream1.getId(), stream2.getId(), 13, false), Callback.NOOP); - Assert.assertEquals(stream1.getId(), streamId); + assertEquals(stream1.getId(), streamId); // Give time to the PRIORITY frame to arrive to server. Thread.sleep(1000); beforeRequests.countDown(); - Assert.assertTrue(afterRequests.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(responses.await(5, TimeUnit.SECONDS)); + assertTrue(afterRequests.await(5, TimeUnit.SECONDS)); + assertTrue(responses.await(5, TimeUnit.SECONDS)); } @Test @@ -153,10 +157,10 @@ public class PriorityTest extends AbstractTest public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) { PriorityFrame priority = frame.getPriority(); - Assert.assertNotNull(priority); - Assert.assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); - Assert.assertEquals(priorityFrame.getWeight(), priority.getWeight()); - Assert.assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); + assertNotNull(priority); + assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); + assertEquals(priorityFrame.getWeight(), priority.getWeight()); + assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); latch.countDown(); MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields()); @@ -179,6 +183,6 @@ public class PriorityTest extends AbstractTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java index a5715f1ccc7..dffd55f185f 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyProtocolTest.java @@ -18,6 +18,13 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import static org.hamcrest.MatcherAssert.assertThat; + import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -50,10 +57,9 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.TypeUtil; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class ProxyProtocolTest { @@ -75,7 +81,7 @@ public class ProxyProtocolTest server.start(); } - @After + @AfterEach public void dispose() throws Exception { if (server != null) @@ -92,10 +98,10 @@ public class ProxyProtocolTest { try { - Assert.assertEquals("1.2.3.4",request.getRemoteAddr()); - Assert.assertEquals(1111,request.getRemotePort()); - Assert.assertEquals("5.6.7.8",request.getLocalAddr()); - Assert.assertEquals(2222,request.getLocalPort()); + assertEquals("1.2.3.4",request.getRemoteAddr()); + assertEquals(1111,request.getRemotePort()); + assertEquals("5.6.7.8",request.getLocalAddr()); + assertEquals(2222,request.getLocalPort()); } catch(Throwable th) { @@ -126,12 +132,12 @@ public class ProxyProtocolTest public void onHeaders(Stream stream, HeadersFrame frame) { MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); if (frame.isEndStream()) latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -144,14 +150,14 @@ public class ProxyProtocolTest { try { - Assert.assertEquals("10.0.0.4",request.getRemoteAddr()); - Assert.assertEquals(33824,request.getRemotePort()); - Assert.assertEquals("10.0.0.5",request.getLocalAddr()); - Assert.assertEquals(8888,request.getLocalPort()); + assertEquals("10.0.0.4",request.getRemoteAddr()); + assertEquals(33824,request.getRemotePort()); + assertEquals("10.0.0.5",request.getLocalAddr()); + assertEquals(8888,request.getLocalPort()); EndPoint endPoint = baseRequest.getHttpChannel().getEndPoint(); - Assert.assertThat(endPoint, Matchers.instanceOf(ProxyConnectionFactory.ProxyEndPoint.class)); + assertThat(endPoint, instanceOf(ProxyConnectionFactory.ProxyEndPoint.class)); ProxyConnectionFactory.ProxyEndPoint proxyEndPoint = (ProxyConnectionFactory.ProxyEndPoint)endPoint; - Assert.assertNotNull(proxyEndPoint.getAttribute(ProxyConnectionFactory.TLS_VERSION)); + assertNotNull(proxyEndPoint.getAttribute(ProxyConnectionFactory.TLS_VERSION)); } catch(Throwable th) { @@ -184,11 +190,11 @@ public class ProxyProtocolTest public void onHeaders(Stream stream, HeadersFrame frame) { MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); if (frame.isEndStream()) latch.countDown(); } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java index 75bb8676c7a..c5eec2e1155 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/ProxyTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; @@ -47,20 +49,15 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class ProxyTest { - @Rule - public final TestTracker tracker = new TestTracker(); private HTTP2Client client; private Server proxy; private ServerConnector proxyConnector; @@ -132,7 +129,7 @@ public class ProxyTest return new MetaData.Request(method, HttpScheme.HTTP, new HostPortHttpField(authority), path, HttpVersion.HTTP_2, fields); } - @After + @AfterEach public void dispose() throws Exception { client.stop(); @@ -190,7 +187,7 @@ public class ProxyTest } }); - Assert.assertTrue(serverLatch.await(15, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(15, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(15, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(15, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java index ee7b2821a47..a8bb32169eb 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/PushCacheFilterTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.EnumSet; @@ -52,8 +56,8 @@ import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlets.PushCacheFilter; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PushCacheFilterTest extends AbstractTest { @@ -128,7 +132,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); // Request again the primary resource, we should get the secondary resource pushed. primaryRequest = newRequest("GET", primaryResource, primaryFields); @@ -175,8 +179,8 @@ public class PushCacheFilterTest extends AbstractTest }; } }); - Assert.assertTrue(pushLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(pushLatch.await(5, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -232,7 +236,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); // Request again the primary resource, we should not get the secondary resource pushed. primaryRequest = newRequest("GET", primaryResource, primaryFields); @@ -263,8 +267,8 @@ public class PushCacheFilterTest extends AbstractTest primaryResponseLatch.countDown(); } }); - Assert.assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -318,7 +322,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); // Request again the primary resource, we should get the secondary resource pushed. primaryRequest = newRequest("GET", primaryResource, primaryFields); @@ -352,8 +356,8 @@ public class PushCacheFilterTest extends AbstractTest } }); // We should not receive pushed data that we reset. - Assert.assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); // Make sure the session is sane by requesting the secondary resource. HttpFields secondaryFields = new HttpFields(); @@ -370,7 +374,7 @@ public class PushCacheFilterTest extends AbstractTest secondaryResponseLatch.countDown(); } }); - Assert.assertTrue(secondaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(secondaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -420,7 +424,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); @@ -452,8 +456,8 @@ public class PushCacheFilterTest extends AbstractTest }; } }); - Assert.assertTrue(pushLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(pushLatch.await(5, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -543,7 +547,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); @@ -567,7 +571,7 @@ public class PushCacheFilterTest extends AbstractTest { // The stream id of the PUSH_PROMISE must // always be a client stream and therefore odd. - Assert.assertEquals(1, frame.getStreamId() & 1); + assertEquals(1, frame.getStreamId() & 1); return new Adapter() { @Override @@ -596,9 +600,9 @@ public class PushCacheFilterTest extends AbstractTest } }); - Assert.assertTrue(primaryPushesLatch.await(5, TimeUnit.SECONDS)); - Assert.assertFalse(recursiveLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(primaryPushesLatch.await(5, TimeUnit.SECONDS)); + assertFalse(recursiveLatch.await(1, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); // Make sure that explicitly requesting a secondary resource, we get the tertiary pushed. CountDownLatch secondaryResponseLatch = new CountDownLatch(1); @@ -630,8 +634,8 @@ public class PushCacheFilterTest extends AbstractTest } }); - Assert.assertTrue(secondaryPushLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(secondaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(secondaryPushLatch.await(5, TimeUnit.SECONDS)); + assertTrue(secondaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -706,7 +710,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); @@ -731,8 +735,8 @@ public class PushCacheFilterTest extends AbstractTest return null; } }); - Assert.assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -793,7 +797,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); @@ -807,9 +811,9 @@ public class PushCacheFilterTest extends AbstractTest public Stream.Listener onPush(Stream stream, PushPromiseFrame frame) { MetaData metaData = frame.getMetaData(); - Assert.assertTrue(metaData instanceof MetaData.Request); + assertTrue(metaData instanceof MetaData.Request); MetaData.Request pushedRequest = (MetaData.Request)metaData; - Assert.assertEquals(contextPath + servletPath + secondaryResource, pushedRequest.getURI().getPathQuery()); + assertEquals(contextPath + servletPath + secondaryResource, pushedRequest.getURI().getPathQuery()); return new Adapter() { @Override @@ -832,8 +836,8 @@ public class PushCacheFilterTest extends AbstractTest primaryResponseLatch.countDown(); } }); - Assert.assertTrue(pushLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(pushLatch.await(5, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -887,7 +891,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); // Request again the primary resource with POST, we should not get the secondary resource pushed. primaryRequest = newRequest("POST", primaryResource, primaryFields); @@ -918,8 +922,8 @@ public class PushCacheFilterTest extends AbstractTest primaryResponseLatch.countDown(); } }); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); - Assert.assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); } @Test @@ -982,7 +986,7 @@ public class PushCacheFilterTest extends AbstractTest } } }); - Assert.assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); + assertTrue(warmupLatch.await(5, TimeUnit.SECONDS)); // Request again the primary resource, we should not get the secondary resource pushed. primaryRequest = newRequest("GET", primaryResource, primaryFields); @@ -1005,7 +1009,7 @@ public class PushCacheFilterTest extends AbstractTest primaryResponseLatch.countDown(); } }); - Assert.assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); - Assert.assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); + assertFalse(pushLatch.await(1, TimeUnit.SECONDS)); + assertTrue(primaryResponseLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java index 26e38bc09cf..5b9f3ad3f3c 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayDeque; @@ -56,9 +59,9 @@ import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class RawHTTP2ProxyTest { @@ -92,7 +95,7 @@ public class RawHTTP2ProxyTest return client; } - @After + @AfterEach public void dispose() throws Exception { for (int i = clients.size() - 1; i >= 0; i--) @@ -223,7 +226,7 @@ public class RawHTTP2ProxyTest { if (LOGGER.isDebugEnabled()) LOGGER.debug("CLIENT received {}", frame); - Assert.assertEquals(buffer1.slice(), frame.getData()); + assertEquals(buffer1.slice(), frame.getData()); callback.succeeded(); latch1.countDown(); } @@ -259,8 +262,8 @@ public class RawHTTP2ProxyTest Stream stream2 = streamPromise2.get(5, TimeUnit.SECONDS); stream2.data(new DataFrame(stream2.getId(), buffer1.slice(), true), Callback.NOOP); - Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS)); + assertTrue(latch1.await(5, TimeUnit.SECONDS)); + assertTrue(latch2.await(5, TimeUnit.SECONDS)); } private static class ClientToProxySessionListener extends ServerSessionListener.Adapter diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java index 9b7d5b41822..f4787700a21 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SessionFailureTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; @@ -32,8 +36,7 @@ import org.eclipse.jetty.http2.api.server.ServerSessionListener; import org.eclipse.jetty.http2.frames.HeadersFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SessionFailureTest extends AbstractTest { @@ -57,7 +60,7 @@ public class SessionFailureTest extends AbstractTest output.write(0x0); output.flush(); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // The server will reply with a GOAWAY frame, and then shutdown. // Read until EOF. @@ -115,15 +118,15 @@ public class SessionFailureTest extends AbstractTest Promise promise = new Promise.Adapter<>(); session.newStream(frame, promise, null); - Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(serverFailureLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(clientFailureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverFailureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(clientFailureLatch.await(5, TimeUnit.SECONDS)); long start = System.nanoTime(); long now = System.nanoTime(); while (((HTTP2Session)session).getEndPoint().isOpen()) { - if (TimeUnit.NANOSECONDS.toSeconds(now-start)>5) - Assert.fail(); + assertThat(TimeUnit.NANOSECONDS.toSeconds(now-start), lessThanOrEqualTo(5L)); + Thread.sleep(10); now = System.nanoTime(); } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java index be35947eca5..e67928f5e4d 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/SmallThreadPoolLoadTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.Locale; @@ -52,11 +55,11 @@ import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -@Ignore +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled public class SmallThreadPoolLoadTest extends AbstractTest { private final Logger logger = Log.getLogger(SmallThreadPoolLoadTest.class); @@ -90,7 +93,7 @@ public class SmallThreadPoolLoadTest extends AbstractTest .reduce(true, (acc, res) -> acc && res)) .reduce(true, (acc, res) -> acc && res); - Assert.assertTrue(result); + assertTrue(result); } private boolean run(Session session, int iterations) @@ -119,9 +122,9 @@ public class SmallThreadPoolLoadTest extends AbstractTest ++successes; } - Assert.assertTrue(latch.await(iterations, TimeUnit.SECONDS)); + assertTrue(latch.await(iterations, TimeUnit.SECONDS)); long end = System.nanoTime(); - Assert.assertThat(successes, Matchers.greaterThan(0L)); + assertThat(successes, Matchers.greaterThan(0L)); task.cancel(); long elapsed = TimeUnit.NANOSECONDS.toMillis(end - begin); logger.info("{} requests in {} ms, {}/{} success/failure, {} req/s", diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java index 4265d5a422a..4a20cb85540 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCloseTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -41,8 +45,8 @@ import org.eclipse.jetty.http2.frames.ResetFrame; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class StreamCloseTest extends AbstractTest { @@ -55,7 +59,7 @@ public class StreamCloseTest extends AbstractTest @Override public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) { - Assert.assertTrue(((HTTP2Stream)stream).isRemotelyClosed()); + assertTrue(((HTTP2Stream)stream).isRemotelyClosed()); latch.countDown(); return null; } @@ -66,8 +70,8 @@ public class StreamCloseTest extends AbstractTest FuturePromise promise = new FuturePromise<>(); session.newStream(frame, promise, null); Stream stream = promise.get(5, TimeUnit.SECONDS); - Assert.assertTrue(((HTTP2Stream)stream).isLocallyClosed()); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(((HTTP2Stream)stream).isLocallyClosed()); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -86,8 +90,8 @@ public class StreamCloseTest extends AbstractTest @Override public void succeeded() { - Assert.assertTrue(stream.isClosed()); - Assert.assertEquals(0, stream.getSession().getStreams().size()); + assertTrue(stream.isClosed()); + assertEquals(0, stream.getSession().getStreams().size()); latch.countDown(); } }); @@ -108,8 +112,8 @@ public class StreamCloseTest extends AbstractTest } }); Stream stream = promise.get(5, TimeUnit.SECONDS); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(stream.isClosed()); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(stream.isClosed()); } @Test @@ -130,15 +134,15 @@ public class StreamCloseTest extends AbstractTest @Override public void onData(final Stream stream, DataFrame frame, final Callback callback) { - Assert.assertTrue(((HTTP2Stream)stream).isRemotelyClosed()); + assertTrue(((HTTP2Stream)stream).isRemotelyClosed()); completable.thenRun(() -> stream.data(frame, new Callback() { @Override public void succeeded() { - Assert.assertTrue(stream.isClosed()); - Assert.assertEquals(0, stream.getSession().getStreams().size()); + assertTrue(stream.isClosed()); + assertEquals(0, stream.getSession().getStreams().size()); callback.succeeded(); serverDataLatch.countDown(); } @@ -163,8 +167,8 @@ public class StreamCloseTest extends AbstractTest } }); final Stream stream = promise.get(5, TimeUnit.SECONDS); - Assert.assertFalse(stream.isClosed()); - Assert.assertFalse(((HTTP2Stream)stream).isLocallyClosed()); + assertFalse(stream.isClosed()); + assertFalse(((HTTP2Stream)stream).isLocallyClosed()); final CountDownLatch clientDataLatch = new CountDownLatch(1); stream.data(new DataFrame(stream.getId(), ByteBuffer.wrap(new byte[512]), true), new Callback() @@ -177,11 +181,11 @@ public class StreamCloseTest extends AbstractTest } }); - Assert.assertTrue(clientDataLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(serverDataLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(stream.isClosed()); - Assert.assertEquals(0, stream.getSession().getStreams().size()); + assertTrue(clientDataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverDataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(completeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(stream.isClosed()); + assertEquals(0, stream.getSession().getStreams().size()); } @Test @@ -200,14 +204,14 @@ public class StreamCloseTest extends AbstractTest public void succeeded(final Stream pushedStream) { // When created, pushed stream must be implicitly remotely closed. - Assert.assertTrue(((HTTP2Stream)pushedStream).isRemotelyClosed()); + assertTrue(((HTTP2Stream)pushedStream).isRemotelyClosed()); // Send some data with endStream = true. pushedStream.data(new DataFrame(pushedStream.getId(), ByteBuffer.allocate(16), true), new Callback() { @Override public void succeeded() { - Assert.assertTrue(pushedStream.isClosed()); + assertTrue(pushedStream.isClosed()); serverLatch.countDown(); } }); @@ -227,13 +231,13 @@ public class StreamCloseTest extends AbstractTest @Override public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame) { - Assert.assertTrue(((HTTP2Stream)pushedStream).isLocallyClosed()); + assertTrue(((HTTP2Stream)pushedStream).isLocallyClosed()); return new Adapter() { @Override public void onData(Stream pushedStream, DataFrame frame, Callback callback) { - Assert.assertTrue(pushedStream.isClosed()); + assertTrue(pushedStream.isClosed()); callback.succeeded(); clientLatch.countDown(); } @@ -241,8 +245,8 @@ public class StreamCloseTest extends AbstractTest } }); - Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -260,8 +264,8 @@ public class StreamCloseTest extends AbstractTest @Override public void onReset(Stream pushedStream, ResetFrame frame) { - Assert.assertTrue(pushedStream.isReset()); - Assert.assertTrue(pushedStream.isClosed()); + assertTrue(pushedStream.isReset()); + assertTrue(pushedStream.isClosed()); HeadersFrame response = new HeadersFrame(stream.getId(), new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields()), null, true); stream.headers(response, Callback.NOOP); serverLatch.countDown(); @@ -284,8 +288,8 @@ public class StreamCloseTest extends AbstractTest @Override public void succeeded() { - Assert.assertTrue(pushedStream.isReset()); - Assert.assertTrue(pushedStream.isClosed()); + assertTrue(pushedStream.isReset()); + assertTrue(pushedStream.isClosed()); clientLatch.countDown(); } }); @@ -299,8 +303,8 @@ public class StreamCloseTest extends AbstractTest } }); - Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -343,14 +347,14 @@ public class StreamCloseTest extends AbstractTest HeadersFrame request2 = new HeadersFrame(newRequest("GET", new HttpFields()), null, true); session.newStream(request2, new Promise.Adapter<>(), new Stream.Listener.Adapter()); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); Session serverSession = sessionRef.get(); // Wait for the server to finish the close activities. Thread.sleep(1000); - Assert.assertEquals(0, serverSession.getStreams().size()); + assertEquals(0, serverSession.getStreams().size()); for (Stream stream : streams) - Assert.assertTrue(stream.isClosed()); + assertTrue(stream.isClosed()); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java index dead8125855..9a5d22f94c0 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamCountTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.client; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -38,8 +41,8 @@ import org.eclipse.jetty.http2.frames.SettingsFrame; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class StreamCountTest extends AbstractTest { @@ -89,7 +92,7 @@ public class StreamCountTest extends AbstractTest } }); - Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); + assertTrue(settingsLatch.await(5, TimeUnit.SECONDS)); HttpFields fields = new HttpFields(); MetaData.Request metaData = newRequest("GET", fields); @@ -111,18 +114,11 @@ public class StreamCountTest extends AbstractTest FuturePromise streamPromise2 = new FuturePromise<>(); session.newStream(frame2, streamPromise2, new Stream.Listener.Adapter()); - try - { - streamPromise2.get(5, TimeUnit.SECONDS); - Assert.fail(); - } - catch (ExecutionException x) - { - // Expected - } + assertThrows(ExecutionException.class, + () -> streamPromise2.get(5, TimeUnit.SECONDS)); stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), Callback.NOOP); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -188,9 +184,9 @@ public class StreamCountTest extends AbstractTest }); streamPromise2.get(5, TimeUnit.SECONDS); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), Callback.NOOP); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java index 0d23a9eba50..bae4c00c3ad 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/StreamResetTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; @@ -73,8 +79,8 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.StacklessLogging; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class StreamResetTest extends AbstractTest { @@ -94,7 +100,7 @@ public class StreamResetTest extends AbstractTest stream.reset(resetFrame, resetCallback); resetCallback.get(5, TimeUnit.SECONDS); // After reset the stream should be gone. - Assert.assertEquals(0, client.getStreams().size()); + assertEquals(0, client.getStreams().size()); } @Test @@ -112,8 +118,8 @@ public class StreamResetTest extends AbstractTest @Override public void onReset(Stream stream, ResetFrame frame) { - Assert.assertNotNull(stream); - Assert.assertTrue(stream.isReset()); + assertNotNull(stream); + assertTrue(stream.isReset()); streamRef.set(stream); resetLatch.countDown(); } @@ -130,14 +136,14 @@ public class StreamResetTest extends AbstractTest ResetFrame resetFrame = new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code); stream.reset(resetFrame, Callback.NOOP); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); // Wait a while to let the server remove the // stream after returning from onReset(). Thread.sleep(1000); Stream serverStream = streamRef.get(); - Assert.assertEquals(0, serverStream.getSession().getStreams().size()); + assertEquals(0, serverStream.getSession().getStreams().size()); } @Test @@ -211,7 +217,7 @@ public class StreamResetTest extends AbstractTest } }); Stream stream1 = promise1.get(5, TimeUnit.SECONDS); - Assert.assertTrue(stream1HeadersLatch.await(5, TimeUnit.SECONDS)); + assertTrue(stream1HeadersLatch.await(5, TimeUnit.SECONDS)); MetaData.Request request2 = newRequest("GET", new HttpFields()); HeadersFrame requestFrame2 = new HeadersFrame(request2, null, false); @@ -231,14 +237,14 @@ public class StreamResetTest extends AbstractTest ResetFrame resetFrame = new ResetFrame(stream1.getId(), ErrorCode.CANCEL_STREAM_ERROR.code); stream1.reset(resetFrame, Callback.NOOP); - Assert.assertTrue(serverResetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverResetLatch.await(5, TimeUnit.SECONDS)); // Stream MUST NOT receive data sent by server after reset. - Assert.assertFalse(stream1DataLatch.await(1, TimeUnit.SECONDS)); + assertFalse(stream1DataLatch.await(1, TimeUnit.SECONDS)); // The other stream should still be working. stream2.data(new DataFrame(stream2.getId(), ByteBuffer.allocate(16), true), Callback.NOOP); - Assert.assertTrue(serverDataLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(stream2DataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverDataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(stream2DataLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -265,7 +271,7 @@ public class StreamResetTest extends AbstractTest try { // Wait for the reset to be sent. - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); // Wait for the reset to arrive to the server and be processed. Thread.sleep(1000); } @@ -318,7 +324,7 @@ public class StreamResetTest extends AbstractTest } }); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -345,7 +351,7 @@ public class StreamResetTest extends AbstractTest try { // Wait for the reset to happen. - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); // Wait for the reset to arrive to the server and be processed. Thread.sleep(1000); } @@ -405,7 +411,7 @@ public class StreamResetTest extends AbstractTest } }); - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -430,8 +436,8 @@ public class StreamResetTest extends AbstractTest } }); // The server does not read the data, so the flow control window should be zero. - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, ((ISession)client).updateSendWindow(0)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertEquals(0, ((ISession)client).updateSendWindow(0)); // Now reset the stream. stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); @@ -440,7 +446,7 @@ public class StreamResetTest extends AbstractTest // it, and for the client to process the window updates. Thread.sleep(1000); - Assert.assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); + assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); } @Test @@ -531,13 +537,13 @@ public class StreamResetTest extends AbstractTest // Wait for WINDOW_UPDATEs to be processed by the client. Thread.sleep(1000); - Assert.assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); + assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); latch.set(new CountDownLatch(2 * streams.size())); // Complete all streams. streams.forEach(s -> s.data(new DataFrame(s.getId(), BufferUtil.EMPTY_BUFFER, true), Callback.NOOP)); - Assert.assertTrue(latch.get().await(5, TimeUnit.SECONDS)); + assertTrue(latch.get().await(5, TimeUnit.SECONDS)); } @Test @@ -581,14 +587,14 @@ public class StreamResetTest extends AbstractTest } }); // The server does not read the data, so the flow control window should be zero. - Assert.assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(0, ((ISession)client).updateSendWindow(0)); + assertTrue(dataLatch.await(5, TimeUnit.SECONDS)); + assertEquals(0, ((ISession)client).updateSendWindow(0)); // Wait for the server process the exception, and // for the client to process the window updates. Thread.sleep(2000); - Assert.assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); + assertThat(((ISession)client).updateSendWindow(0), Matchers.greaterThan(0)); } } @@ -643,13 +649,13 @@ public class StreamResetTest extends AbstractTest } }); Stream stream = promise.get(5, TimeUnit.SECONDS); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // Reset and consume. stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); dataQueue.forEach(Callback::succeeded); - Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -690,21 +696,21 @@ public class StreamResetTest extends AbstractTest } }); Stream stream = promise.get(5, TimeUnit.SECONDS); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // Reset. stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); - Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); // Give time to the server to process the reset and drain the flusher queue. Thread.sleep(500); AbstractHTTP2ServerConnectionFactory http2 = connector.getConnectionFactory(AbstractHTTP2ServerConnectionFactory.class); Set sessions = http2.getBean(AbstractHTTP2ServerConnectionFactory.HTTP2SessionContainer.class).getSessions(); - Assert.assertEquals(1, sessions.size()); + assertEquals(1, sessions.size()); HTTP2Session session = (HTTP2Session)sessions.iterator().next(); HTTP2Flusher flusher = session.getBean(HTTP2Flusher.class); - Assert.assertEquals(0, flusher.getFrameQueueSize()); + assertEquals(0, flusher.getFrameQueueSize()); } @Test @@ -769,13 +775,13 @@ public class StreamResetTest extends AbstractTest } }); Stream stream = promise.get(5, TimeUnit.SECONDS); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); // Reset and consume. stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); dataQueue.forEach(Callback::succeeded); - Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(writeLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -818,7 +824,7 @@ public class StreamResetTest extends AbstractTest ByteBuffer content = ByteBuffer.wrap(new byte[1024]); stream.data(new DataFrame(stream.getId(), content, true), Callback.NOOP); - Assert.assertTrue(requestLatch.await(5, TimeUnit.SECONDS)); + assertTrue(requestLatch.await(5, TimeUnit.SECONDS)); stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); // Wait for the reset to arrive to the server and be processed. @@ -827,6 +833,6 @@ public class StreamResetTest extends AbstractTest // Try to read on server. readLatch.countDown(); // Read on server should fail. - Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); + assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java index e51778a653c..b2007ec6efe 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/TrailersTest.java @@ -18,6 +18,16 @@ package org.eclipse.jetty.http2.client; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -48,10 +58,10 @@ import org.eclipse.jetty.server.Response; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.Promise; + import org.eclipse.jetty.util.StringUtil; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + public class TrailersTest extends AbstractTest { @@ -65,16 +75,16 @@ public class TrailersTest extends AbstractTest public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) { MetaData.Request request = (MetaData.Request)frame.getMetaData(); - Assert.assertFalse(frame.isEndStream()); - Assert.assertTrue(request.getFields().containsKey("X-Request")); + assertFalse(frame.isEndStream()); + assertTrue(request.getFields().containsKey("X-Request")); return new Stream.Listener.Adapter() { @Override public void onHeaders(Stream stream, HeadersFrame frame) { MetaData trailer = frame.getMetaData(); - Assert.assertTrue(frame.isEndStream()); - Assert.assertTrue(trailer.getFields().containsKey("X-Trailer")); + assertTrue(frame.isEndStream()); + assertTrue(trailer.getFields().containsKey("X-Trailer")); latch.countDown(); } }; @@ -98,7 +108,7 @@ public class TrailersTest extends AbstractTest HeadersFrame trailerFrame = new HeadersFrame(stream.getId(), trailers, null, true); stream.headers(trailerFrame, Callback.NOOP); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -112,7 +122,7 @@ public class TrailersTest extends AbstractTest { Request jettyRequest = (Request)request; // No trailers yet. - Assert.assertNull(jettyRequest.getTrailers()); + assertNull(jettyRequest.getTrailers()); trailerLatch.countDown(); @@ -127,8 +137,8 @@ public class TrailersTest extends AbstractTest // Now we have the trailers. HttpFields trailers = jettyRequest.getTrailers(); - Assert.assertNotNull(trailers); - Assert.assertNotNull(trailers.get("X-Trailer")); + assertNotNull(trailers); + assertNotNull(trailers.get("X-Trailer")); } }); @@ -146,7 +156,7 @@ public class TrailersTest extends AbstractTest public void onHeaders(Stream stream, HeadersFrame frame) { MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); if (frame.isEndStream()) latch.countDown(); } @@ -157,7 +167,7 @@ public class TrailersTest extends AbstractTest Callback.Completable callback = new Callback.Completable(); stream.data(new DataFrame(stream.getId(), ByteBuffer.allocate(16), false), callback); - Assert.assertTrue(trailerLatch.await(5, TimeUnit.SECONDS)); + assertTrue(trailerLatch.await(5, TimeUnit.SECONDS)); // Send the trailers. callback.thenRun(() -> @@ -169,7 +179,7 @@ public class TrailersTest extends AbstractTest stream.headers(trailerFrame, Callback.NOOP); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -214,22 +224,22 @@ public class TrailersTest extends AbstractTest if (!responded) { MetaData.Response response = (MetaData.Response)frame.getMetaData(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(response.getFields().containsKey("X-Response")); - Assert.assertFalse(frame.isEndStream()); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertTrue(response.getFields().containsKey("X-Response")); + assertFalse(frame.isEndStream()); responded = true; } else { MetaData trailer = frame.getMetaData(); - Assert.assertTrue(trailer.getFields().containsKey("X-Trailer")); - Assert.assertTrue(frame.isEndStream()); + assertTrue(trailer.getFields().containsKey("X-Trailer")); + assertTrue(frame.isEndStream()); latch.countDown(); } } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -277,17 +287,18 @@ public class TrailersTest extends AbstractTest } }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assert.assertThat(frames.toString(), frames.size(), Matchers.is(3)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + + assertTrue( frames.size()==3, frames.toString()); HeadersFrame headers = (HeadersFrame)frames.get(0); DataFrame data = (DataFrame)frames.get(1); HeadersFrame trailers = (HeadersFrame)frames.get(2); - Assert.assertFalse(headers.isEndStream()); - Assert.assertFalse(data.isEndStream()); - Assert.assertTrue(trailers.isEndStream()); - Assert.assertThat(trailers.getMetaData().getFields().get(trailerName), Matchers.equalTo(trailerValue)); + assertFalse(headers.isEndStream()); + assertFalse(data.isEndStream()); + assertTrue(trailers.isEndStream()); + assertTrue(trailers.getMetaData().getFields().get(trailerName).equals(trailerValue)); } @Test @@ -332,7 +343,7 @@ public class TrailersTest extends AbstractTest } }); Stream stream = promise.get(5, TimeUnit.SECONDS); - ByteBuffer data = ByteBuffer.wrap(StringUtil.getUtf8Bytes("hello")); + ByteBuffer data = ByteBuffer.wrap( StringUtil.getUtf8Bytes( "hello")); Callback.Completable completable = new Callback.Completable(); stream.data(new DataFrame(stream.getId(), data, false), completable); completable.thenRun(() -> @@ -345,7 +356,8 @@ public class TrailersTest extends AbstractTest stream.headers(trailerFrame, Callback.NOOP); }); - Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); + assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); + } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java index 3f272efefd0..e1f6aba087b 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ContinuationParseTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -36,8 +40,8 @@ import org.eclipse.jetty.http2.hpack.HpackEncoder; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ContinuationParseTest { @@ -77,7 +81,7 @@ public class ContinuationParseTest generator.generateHeaders(lease, streamId, metaData, null, true); List byteBuffers = lease.getByteBuffers(); - Assert.assertEquals(2, byteBuffers.size()); + assertEquals(2, byteBuffers.size()); ByteBuffer headersBody = byteBuffers.remove(1); int start = headersBody.position(); @@ -141,20 +145,20 @@ public class ContinuationParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); HeadersFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertTrue(frame.isEndStream()); + assertEquals(streamId, frame.getStreamId()); + assertTrue(frame.isEndStream()); MetaData.Request request = (MetaData.Request)frame.getMetaData(); - Assert.assertEquals(metaData.getMethod(), request.getMethod()); - Assert.assertEquals(metaData.getURI(), request.getURI()); + assertEquals(metaData.getMethod(), request.getMethod()); + assertEquals(metaData.getURI(), request.getURI()); for (int j = 0; j < fields.size(); ++j) { HttpField field = fields.getField(j); - Assert.assertTrue(request.getFields().contains(field)); + assertTrue(request.getFields().contains(field)); } PriorityFrame priority = frame.getPriority(); - Assert.assertNull(priority); + assertNull(priority); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java index 17e26e9c0cd..097de2d32d6 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/DataGenerateParseTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -30,8 +33,8 @@ import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; import org.eclipse.jetty.util.BufferUtil; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class DataGenerateParseTest { @@ -61,11 +64,11 @@ public class DataGenerateParseTest private void testGenerateParseContent(ByteBuffer content) { List frames = testGenerateParse(content); - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); DataFrame frame = frames.get(0); - Assert.assertTrue(frame.getStreamId() != 0); - Assert.assertTrue(frame.isEndStream()); - Assert.assertEquals(content, frame.getData()); + assertTrue(frame.getStreamId() != 0); + assertTrue(frame.isEndStream()); + assertEquals(content, frame.getData()); } @Test @@ -73,17 +76,17 @@ public class DataGenerateParseTest { ByteBuffer content = ByteBuffer.wrap(largeContent); List frames = testGenerateParse(content); - Assert.assertEquals(8, frames.size()); + assertEquals(8, frames.size()); ByteBuffer aggregate = ByteBuffer.allocate(content.remaining()); for (int i = 1; i <= frames.size(); ++i) { DataFrame frame = frames.get(i - 1); - Assert.assertTrue(frame.getStreamId() != 0); - Assert.assertEquals(i == frames.size(), frame.isEndStream()); + assertTrue(frame.getStreamId() != 0); + assertEquals(i == frames.size(), frame.isEndStream()); aggregate.put(frame.getData()); } aggregate.flip(); - Assert.assertEquals(content, aggregate); + assertEquals(content, aggregate); } private List testGenerateParse(ByteBuffer data) @@ -165,7 +168,7 @@ public class DataGenerateParseTest } } - Assert.assertEquals(largeContent.length, frames.size()); + assertEquals(largeContent.length, frames.size()); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java index d9b2e386e79..36bae05839c 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/GoAwayGenerateParseTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -29,8 +33,8 @@ import org.eclipse.jetty.http2.generator.HeaderGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class GoAwayGenerateParseTest { @@ -71,11 +75,11 @@ public class GoAwayGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); GoAwayFrame frame = frames.get(0); - Assert.assertEquals(lastStreamId, frame.getLastStreamId()); - Assert.assertEquals(error, frame.getError()); - Assert.assertNull(frame.getPayload()); + assertEquals(lastStreamId, frame.getLastStreamId()); + assertEquals(error, frame.getError()); + assertNull(frame.getPayload()); } @Test @@ -114,11 +118,11 @@ public class GoAwayGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); GoAwayFrame frame = frames.get(0); - Assert.assertEquals(lastStreamId, frame.getLastStreamId()); - Assert.assertEquals(error, frame.getError()); - Assert.assertArrayEquals(payload, frame.getPayload()); + assertEquals(lastStreamId, frame.getLastStreamId()); + assertEquals(error, frame.getError()); + assertArrayEquals(payload, frame.getPayload()); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java index 7365c526bca..b5a0ba1787f 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/HeadersGenerateParseTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -35,8 +39,8 @@ import org.eclipse.jetty.http2.hpack.HpackEncoder; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HeadersGenerateParseTest { @@ -80,24 +84,24 @@ public class HeadersGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); HeadersFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertTrue(frame.isEndStream()); + assertEquals(streamId, frame.getStreamId()); + assertTrue(frame.isEndStream()); MetaData.Request request = (MetaData.Request)frame.getMetaData(); - Assert.assertEquals(metaData.getMethod(), request.getMethod()); - Assert.assertEquals(metaData.getURI(), request.getURI()); + assertEquals(metaData.getMethod(), request.getMethod()); + assertEquals(metaData.getURI(), request.getURI()); for (int j = 0; j < fields.size(); ++j) { HttpField field = fields.getField(j); - Assert.assertTrue(request.getFields().contains(field)); + assertTrue(request.getFields().contains(field)); } PriorityFrame priority = frame.getPriority(); - Assert.assertNotNull(priority); - Assert.assertEquals(priorityFrame.getStreamId(), priority.getStreamId()); - Assert.assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); - Assert.assertEquals(priorityFrame.getWeight(), priority.getWeight()); - Assert.assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); + assertNotNull(priority); + assertEquals(priorityFrame.getStreamId(), priority.getStreamId()); + assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); + assertEquals(priorityFrame.getWeight(), priority.getWeight()); + assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); } } @@ -140,24 +144,24 @@ public class HeadersGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); HeadersFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertTrue(frame.isEndStream()); + assertEquals(streamId, frame.getStreamId()); + assertTrue(frame.isEndStream()); MetaData.Request request = (MetaData.Request)frame.getMetaData(); - Assert.assertEquals(metaData.getMethod(), request.getMethod()); - Assert.assertEquals(metaData.getURI(), request.getURI()); + assertEquals(metaData.getMethod(), request.getMethod()); + assertEquals(metaData.getURI(), request.getURI()); for (int j = 0; j < fields.size(); ++j) { HttpField field = fields.getField(j); - Assert.assertTrue(request.getFields().contains(field)); + assertTrue(request.getFields().contains(field)); } PriorityFrame priority = frame.getPriority(); - Assert.assertNotNull(priority); - Assert.assertEquals(priorityFrame.getStreamId(), priority.getStreamId()); - Assert.assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); - Assert.assertEquals(priorityFrame.getWeight(), priority.getWeight()); - Assert.assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); + assertNotNull(priority); + assertEquals(priorityFrame.getStreamId(), priority.getStreamId()); + assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); + assertEquals(priorityFrame.getWeight(), priority.getWeight()); + assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java index b902c1d925c..2004b33d82a 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/MaxFrameSizeParseTest.java @@ -26,8 +26,9 @@ import org.eclipse.jetty.http2.ErrorCode; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class MaxFrameSizeParseTest { @@ -61,6 +62,6 @@ public class MaxFrameSizeParseTest parser.parse(buffer); } - Assert.assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, failure.get()); + assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, failure.get()); } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java index aac8e696ce9..45f2a69fa24 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PingGenerateParseTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -29,8 +33,8 @@ import org.eclipse.jetty.http2.generator.PingGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PingGenerateParseTest { @@ -71,10 +75,10 @@ public class PingGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PingFrame frame = frames.get(0); - Assert.assertArrayEquals(payload, frame.getPayload()); - Assert.assertTrue(frame.isReply()); + assertArrayEquals(payload, frame.getPayload()); + assertTrue(frame.isReply()); } @Test @@ -111,10 +115,10 @@ public class PingGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PingFrame frame = frames.get(0); - Assert.assertArrayEquals(payload, frame.getPayload()); - Assert.assertTrue(frame.isReply()); + assertArrayEquals(payload, frame.getPayload()); + assertTrue(frame.isReply()); } } @@ -146,9 +150,9 @@ public class PingGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PingFrame pong = frames.get(0); - Assert.assertEquals(ping.getPayloadAsLong(), pong.getPayloadAsLong()); - Assert.assertTrue(pong.isReply()); + assertEquals(ping.getPayloadAsLong(), pong.getPayloadAsLong()); + assertTrue(pong.isReply()); } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java index 5a9b9bffc4c..9aa3f5d8db6 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PriorityGenerateParseTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -28,8 +30,8 @@ import org.eclipse.jetty.http2.generator.PriorityGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PriorityGenerateParseTest { @@ -72,12 +74,12 @@ public class PriorityGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PriorityFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(parentStreamId, frame.getParentStreamId()); - Assert.assertEquals(weight, frame.getWeight()); - Assert.assertEquals(exclusive, frame.isExclusive()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(parentStreamId, frame.getParentStreamId()); + assertEquals(weight, frame.getWeight()); + assertEquals(exclusive, frame.isExclusive()); } @Test @@ -116,12 +118,12 @@ public class PriorityGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PriorityFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(parentStreamId, frame.getParentStreamId()); - Assert.assertEquals(weight, frame.getWeight()); - Assert.assertEquals(exclusive, frame.isExclusive()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(parentStreamId, frame.getParentStreamId()); + assertEquals(weight, frame.getWeight()); + assertEquals(exclusive, frame.isExclusive()); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java index 1e1c214a52f..9448d92bb17 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/PushPromiseGenerateParseTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -35,8 +38,8 @@ import org.eclipse.jetty.http2.hpack.HpackEncoder; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PushPromiseGenerateParseTest { @@ -80,17 +83,17 @@ public class PushPromiseGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PushPromiseFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(promisedStreamId, frame.getPromisedStreamId()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(promisedStreamId, frame.getPromisedStreamId()); MetaData.Request request = (MetaData.Request)frame.getMetaData(); - Assert.assertEquals(metaData.getMethod(), request.getMethod()); - Assert.assertEquals(metaData.getURI(), request.getURI()); + assertEquals(metaData.getMethod(), request.getMethod()); + assertEquals(metaData.getURI(), request.getURI()); for (int j = 0; j < fields.size(); ++j) { HttpField field = fields.getField(j); - Assert.assertTrue(request.getFields().contains(field)); + assertTrue(request.getFields().contains(field)); } } } @@ -133,17 +136,17 @@ public class PushPromiseGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); PushPromiseFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(promisedStreamId, frame.getPromisedStreamId()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(promisedStreamId, frame.getPromisedStreamId()); MetaData.Request request = (MetaData.Request)frame.getMetaData(); - Assert.assertEquals(metaData.getMethod(), request.getMethod()); - Assert.assertEquals(metaData.getURI(), request.getURI()); + assertEquals(metaData.getMethod(), request.getMethod()); + assertEquals(metaData.getURI(), request.getURI()); for (int j = 0; j < fields.size(); ++j) { HttpField field = fields.getField(j); - Assert.assertTrue(request.getFields().contains(field)); + assertTrue(request.getFields().contains(field)); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java index c61c4638b17..9d412663755 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/ResetGenerateParseTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -28,8 +30,8 @@ import org.eclipse.jetty.http2.generator.ResetGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ResetGenerateParseTest { @@ -70,10 +72,10 @@ public class ResetGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); ResetFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(error, frame.getError()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(error, frame.getError()); } @Test @@ -110,10 +112,10 @@ public class ResetGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); ResetFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(error, frame.getError()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(error, frame.getError()); } } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java index 11723226cc8..0cd08e7a614 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/SettingsGenerateParseTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; @@ -33,8 +36,8 @@ import org.eclipse.jetty.http2.generator.SettingsGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class SettingsGenerateParseTest { @@ -43,11 +46,12 @@ public class SettingsGenerateParseTest @Test public void testGenerateParseNoSettings() { - List frames = testGenerateParse(Collections.emptyMap()); - Assert.assertEquals(1, frames.size()); + + List frames = testGenerateParse(Collections.emptyMap()); + assertEquals(1, frames.size()); SettingsFrame frame = frames.get(0); - Assert.assertEquals(0, frame.getSettings().size()); - Assert.assertTrue(frame.isReply()); + assertEquals(0, frame.getSettings().size()); + assertTrue(frame.isReply()); } @Test @@ -61,12 +65,12 @@ public class SettingsGenerateParseTest Integer value2 = 23; settings1.put(key2, value2); List frames = testGenerateParse(settings1); - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); SettingsFrame frame = frames.get(0); Map settings2 = frame.getSettings(); - Assert.assertEquals(2, settings2.size()); - Assert.assertEquals(value1, settings2.get(key1)); - Assert.assertEquals(value2, settings2.get(key2)); + assertEquals(2, settings2.size()); + assertEquals(value1, settings2.get(key1)); + assertEquals(value2, settings2.get(key2)); } private List testGenerateParse(Map settings) @@ -135,7 +139,7 @@ public class SettingsGenerateParseTest } } - Assert.assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, errorRef.get()); + assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, errorRef.get()); } @Test @@ -174,12 +178,12 @@ public class SettingsGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); SettingsFrame frame = frames.get(0); Map settings2 = frame.getSettings(); - Assert.assertEquals(1, settings2.size()); - Assert.assertEquals(value, settings2.get(key)); - Assert.assertTrue(frame.isReply()); + assertEquals(1, settings2.size()); + assertEquals(value, settings2.get(key)); + assertTrue(frame.isReply()); } } @@ -214,7 +218,7 @@ public class SettingsGenerateParseTest parser.parse(buffer); } - Assert.assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); + assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); } @Test @@ -255,7 +259,7 @@ public class SettingsGenerateParseTest while (buffer.hasRemaining()) parser.parse(buffer); - Assert.assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); + assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); } @Test @@ -289,6 +293,6 @@ public class SettingsGenerateParseTest parser.parse(buffer); } - Assert.assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); + assertEquals(ErrorCode.ENHANCE_YOUR_CALM_ERROR.code, errorRef.get()); } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java index a674468fb12..a9a6ec29897 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/UnknownParseTest.java @@ -28,8 +28,10 @@ import org.eclipse.jetty.http2.ErrorCode; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; public class UnknownParseTest { @@ -68,7 +70,7 @@ public class UnknownParseTest while (buffer.hasRemaining()) parser.parse(buffer); - Assert.assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, failure.get()); + assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, failure.get()); } private void testParse(Function fn) @@ -93,6 +95,6 @@ public class UnknownParseTest parser.parse(fn.apply(buffer)); } - Assert.assertFalse(failure.get()); + assertFalse(failure.get()); } } diff --git a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java index ed707e150d2..51ad3cb2abf 100644 --- a/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java +++ b/jetty-http2/http2-common/src/test/java/org/eclipse/jetty/http2/frames/WindowUpdateGenerateParseTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.http2.frames; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; @@ -28,8 +30,8 @@ import org.eclipse.jetty.http2.generator.WindowUpdateGenerator; import org.eclipse.jetty.http2.parser.Parser; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class WindowUpdateGenerateParseTest { @@ -70,10 +72,10 @@ public class WindowUpdateGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); WindowUpdateFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(windowUpdate, frame.getWindowDelta()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(windowUpdate, frame.getWindowDelta()); } @Test @@ -110,10 +112,10 @@ public class WindowUpdateGenerateParseTest } } - Assert.assertEquals(1, frames.size()); + assertEquals(1, frames.size()); WindowUpdateFrame frame = frames.get(0); - Assert.assertEquals(streamId, frame.getStreamId()); - Assert.assertEquals(windowUpdate, frame.getWindowDelta()); + assertEquals(streamId, frame.getStreamId()); + assertEquals(windowUpdate, frame.getWindowDelta()); } } } diff --git a/jetty-http2/http2-hpack/pom.xml b/jetty-http2/http2-hpack/pom.xml index 3cd0f6a88b6..fe042116485 100644 --- a/jetty-http2/http2-hpack/pom.xml +++ b/jetty-http2/http2-hpack/pom.xml @@ -29,6 +29,13 @@ jetty-io ${project.version} + + org.eclipse.jetty + jetty-http + ${project.version} + tests + test + org.eclipse.jetty.toolchain jetty-test-helper diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java index d91caff99cf..28db8f7a738 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackContextTest.java @@ -20,18 +20,20 @@ package org.eclipse.jetty.http2.hpack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http2.hpack.HpackContext.Entry; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; /* ------------------------------------------------------------ */ @@ -46,8 +48,8 @@ public class HpackContextTest HpackContext ctx = new HpackContext(4096); Entry entry=ctx.get(":method"); assertEquals(":method",entry.getHttpField().getName()); - Assert.assertTrue(entry.isStatic()); - Assert.assertThat(entry.toString(),Matchers.startsWith("{S,2,:method: ")); + assertTrue(entry.isStatic()); + assertThat(entry.toString(),Matchers.startsWith("{S,2,:method: ")); } @Test @@ -55,7 +57,7 @@ public class HpackContextTest { HpackContext ctx = new HpackContext(0); HttpField field = new HttpField("foo","bar"); - Assert.assertNull(ctx.add(field)); + assertNull(ctx.add(field)); } @Test @@ -63,7 +65,7 @@ public class HpackContextTest { HpackContext ctx = new HpackContext(37); HttpField field = new HttpField("foo","bar"); - Assert.assertNull(ctx.add(field)); + assertNull(ctx.add(field)); } @Test @@ -72,8 +74,8 @@ public class HpackContextTest HpackContext ctx = new HpackContext(38); HttpField field = new HttpField("foo","bar"); Entry entry=ctx.add(field); - Assert.assertNotNull(entry); - Assert.assertThat(entry.toString(),Matchers.startsWith("{D,0,foo: bar,")); + assertNotNull(entry); + assertThat(entry.toString(),Matchers.startsWith("{D,0,foo: bar,")); } @Test diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java index f912cf8d9d9..5c0bd8b9e2d 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackDecoderTest.java @@ -19,9 +19,6 @@ package org.eclipse.jetty.http2.hpack; -import java.nio.ByteBuffer; -import java.util.Iterator; - import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpScheme; @@ -30,14 +27,17 @@ import org.eclipse.jetty.http2.hpack.HpackException.CompressionException; import org.eclipse.jetty.http2.hpack.HpackException.StreamException; import org.eclipse.jetty.util.TypeUtil; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.util.Iterator; + +import static org.eclipse.jetty.http.HttpFieldsMatchers.containsHeaderValue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + public class HpackDecoderTest { @@ -178,14 +178,14 @@ public class HpackDecoderTest assertThat(response.getStatus(),is(200)); assertThat(response.getFields().size(),is(6)); - assertTrue(response.getFields().contains(new HttpField(HttpHeader.DATE,"Fri, 15 Jul 2016 02:36:20 GMT"))); - assertTrue(response.getFields().contains(new HttpField(HttpHeader.CONTENT_TYPE,"text/html"))); - assertTrue(response.getFields().contains(new HttpField(HttpHeader.CONTENT_ENCODING,""))); - assertTrue(response.getFields().contains(new HttpField(HttpHeader.CONTENT_LENGTH,"42"))); - assertTrue(response.getFields().contains(new HttpField(HttpHeader.SERVER,"nghttpx nghttp2/1.12.0"))); - assertTrue(response.getFields().contains(new HttpField(HttpHeader.VIA,"1.1 nghttpx"))); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.DATE,"Fri, 15 Jul 2016 02:36:20 GMT")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_TYPE,"text/html")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_ENCODING,"")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.CONTENT_LENGTH,"42")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.SERVER,"nghttpx nghttp2/1.12.0")); + assertThat(response.getFields(), containsHeaderValue(HttpHeader.VIA,"1.1 nghttpx")); } - + @Test public void testResize() throws Exception { @@ -219,14 +219,14 @@ public class HpackDecoderTest try { decoder.decode(buffer); - Assert.fail(); + fail(); } catch(CompressionException e) { - Assert.assertThat(e.getMessage(),Matchers.containsString("Dynamic table resize after fields")); + assertThat(e.getMessage(),Matchers.containsString("Dynamic table resize after fields")); } } - + @Test public void testTooBigToIndex() throws Exception { @@ -235,7 +235,7 @@ public class HpackDecoderTest HpackDecoder decoder = new HpackDecoder(128,8192); MetaData metaData = decoder.decode(buffer); - + assertThat(decoder.getHpackContext().getDynamicTableSize(),is(0)); assertThat(metaData.getFields().get("host"),Matchers.startsWith("This is a very large field")); } @@ -247,10 +247,11 @@ public class HpackDecoderTest ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); HpackDecoder decoder = new HpackDecoder(128,8192); + try { decoder.decode(buffer); - Assert.fail(); + fail(); } catch (HpackException.SessionException e) { @@ -269,11 +270,11 @@ public class HpackDecoderTest try { mdb.build(); - Assert.fail(); + fail(); } catch(StreamException ex) { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Unknown pseudo header")); + assertThat(ex.getMessage(),Matchers.containsString("Unknown pseudo header")); } // 2: Sends a HEADERS frame that contains the pseudo-header field defined for response @@ -285,11 +286,11 @@ public class HpackDecoderTest try { mdb.build(); - Assert.fail(); + fail(); } catch(StreamException ex) { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Request and Response headers")); + assertThat(ex.getMessage(),Matchers.containsString("Request and Response headers")); } // 3: Sends a HEADERS frame that contains a pseudo-header field as trailers @@ -304,11 +305,11 @@ public class HpackDecoderTest try { mdb.build(); - Assert.fail(); + fail(); } catch(StreamException ex) { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Pseudo header :authority after fields")); + assertThat(ex.getMessage(),Matchers.containsString("Pseudo header :authority after fields")); } } @@ -323,11 +324,11 @@ public class HpackDecoderTest try { mdb.build(); - Assert.fail(); + fail(); } catch(StreamException ex) { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Connection specific field 'Connection'")); + assertThat(ex.getMessage(),Matchers.containsString("Connection specific field 'Connection'")); } // 2: Sends a HEADERS frame that contains the TE header field with any value other than "trailers" @@ -336,130 +337,102 @@ public class HpackDecoderTest try { mdb.build(); - Assert.fail(); + fail(); } catch(StreamException ex) { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Unsupported TE value 'not_trailers'")); + assertThat(ex.getMessage(),Matchers.containsString("Unsupported TE value 'not_trailers'")); } mdb = new MetaDataBuilder(4096); mdb.emit(new HttpField(HttpHeader.CONNECTION,"TE")); mdb.emit(new HttpField(HttpHeader.TE,"trailers")); - Assert.assertNotNull(mdb.build()); + assertNotNull(mdb.build()); } @Test() public void test8_1_2_3_RequestPseudoHeaderFields() throws Exception { - MetaDataBuilder mdb; + { + MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); + assertThat( mdb.build(), Matchers.instanceOf( MetaData.Request.class ) ); + } - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/")); - Assert.assertThat(mdb.build(),Matchers.instanceOf(MetaData.Request.class)); + { + // 1: Sends a HEADERS frame with empty ":path" pseudo-header field + final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + mdb.emit( new HttpField( HttpHeader.C_PATH, "" ) ); + StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); + assertThat( ex.getMessage(), Matchers.containsString( "No Path" ) ); - - // 1: Sends a HEADERS frame with empty ":path" pseudo-header field - mdb = new MetaDataBuilder(4096); - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"")); - try - { - mdb.build(); - Assert.fail(); } - catch(StreamException ex) + { - Assert.assertThat(ex.getMessage(),Matchers.containsString("No Path")); - } - - // 2: Sends a HEADERS frame that omits ":method" pseudo-header field - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/")); - try - { - mdb.build(); - Assert.fail(); + // 2: Sends a HEADERS frame that omits ":method" pseudo-header field + final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); + StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); + assertThat( ex.getMessage(), Matchers.containsString( "No Method" ) ); + } - catch(StreamException ex) + { - Assert.assertThat(ex.getMessage(),Matchers.containsString("No Method")); - } - - - // 3: Sends a HEADERS frame that omits ":scheme" pseudo-header field - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/")); - try - { - mdb.build(); - Assert.fail(); + // 3: Sends a HEADERS frame that omits ":scheme" pseudo-header field + final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); + StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); + assertThat( ex.getMessage(), Matchers.containsString( "No Scheme" ) ); + } - catch(StreamException ex) + { - Assert.assertThat(ex.getMessage(),Matchers.containsString("No Scheme")); - } - - // 4: Sends a HEADERS frame that omits ":path" pseudo-header field - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - try - { - mdb.build(); - Assert.fail(); + // 4: Sends a HEADERS frame that omits ":path" pseudo-header field + final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); + assertThat( ex.getMessage(), Matchers.containsString( "No Path" ) ); + } - catch(StreamException ex) + { - Assert.assertThat(ex.getMessage(),Matchers.containsString("No Path")); - } - - // 5: Sends a HEADERS frame with duplicated ":method" pseudo-header field - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/")); - try - { - mdb.build(); - Assert.fail(); + // 5: Sends a HEADERS frame with duplicated ":method" pseudo-header field + final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); + StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); + assertThat( ex.getMessage(), Matchers.containsString( "Duplicate" ) ); } - catch(StreamException ex) + { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Duplicate")); - } - - // 6: Sends a HEADERS frame with duplicated ":scheme" pseudo-header field - mdb = new MetaDataBuilder(4096); - mdb.emit(new HttpField(HttpHeader.C_METHOD,"GET")); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_SCHEME,"http")); - mdb.emit(new HttpField(HttpHeader.C_AUTHORITY,"localhost:8080")); - mdb.emit(new HttpField(HttpHeader.C_PATH,"/")); - try - { - mdb.build(); - Assert.fail(); + // 6: Sends a HEADERS frame with duplicated ":scheme" pseudo-header field + final MetaDataBuilder mdb = new MetaDataBuilder( 4096 ); + mdb.emit( new HttpField( HttpHeader.C_METHOD, "GET" ) ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_SCHEME, "http" ) ); + mdb.emit( new HttpField( HttpHeader.C_AUTHORITY, "localhost:8080" ) ); + mdb.emit( new HttpField( HttpHeader.C_PATH, "/" ) ); + + StreamException ex = assertThrows( StreamException.class, () -> mdb.build() ); + assertThat( ex.getMessage(), Matchers.containsString( "Duplicate" ) ); } - catch(StreamException ex) - { - Assert.assertThat(ex.getMessage(),Matchers.containsString("Duplicate")); - } } @@ -489,16 +462,8 @@ public class HpackDecoderTest String encoded = "82868441" + "84" + "49509FFF"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - - try - { - decoder.decode(buffer); - Assert.fail(); - } - catch (CompressionException ex) - { - Assert.assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); - } + CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); } @@ -511,15 +476,9 @@ public class HpackDecoderTest String encoded = "82868441" + "83" + "495090"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - try - { - decoder.decode(buffer); - Assert.fail(); - } - catch (CompressionException ex) - { - Assert.assertThat(ex.getMessage(), Matchers.containsString("Incorrect padding")); - } + CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + assertThat(ex.getMessage(), Matchers.containsString("Incorrect padding")); + } @@ -532,15 +491,9 @@ public class HpackDecoderTest String encoded = "82868441" + "87" + "497FFFFFFF427F"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - try - { - decoder.decode(buffer); - Assert.fail(); - } - catch (CompressionException ex) - { - Assert.assertThat(ex.getMessage(), Matchers.containsString("EOS in content")); - } + CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + assertThat(ex.getMessage(), Matchers.containsString("EOS in content")); + } @@ -552,15 +505,9 @@ public class HpackDecoderTest String encoded = "82868441" + "81" + "FE"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - try - { - decoder.decode(buffer); - Assert.fail(); - } - catch (CompressionException ex) - { - Assert.assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); - } + CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); + } @@ -572,14 +519,9 @@ public class HpackDecoderTest String encoded = "82868441" + "82" + "FFFE"; ByteBuffer buffer = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); - try - { - decoder.decode(buffer); - Assert.fail(); - } - catch (CompressionException ex) - { - Assert.assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); - } + + CompressionException ex = assertThrows( CompressionException.class, () -> decoder.decode(buffer)); + assertThat(ex.getMessage(), Matchers.containsString("Bad termination")); + } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java index 66381b69c35..43571dcc8b9 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackEncoderTest.java @@ -20,8 +20,9 @@ package org.eclipse.jetty.http2.hpack; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.ByteBuffer; @@ -32,8 +33,7 @@ import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.util.BufferUtil; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /* ------------------------------------------------------------ */ @@ -77,7 +77,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // All are in the dynamic table - Assert.assertEquals(4,encoder.getHpackContext().size()); + assertEquals(4,encoder.getHpackContext().size()); // encode exact same fields again! BufferUtil.clearToFill(buffer); @@ -85,7 +85,7 @@ public class HpackEncoderTest BufferUtil.flipToFlush(buffer,0); // All are in the dynamic table - Assert.assertEquals(4,encoder.getHpackContext().size()); + assertEquals(4,encoder.getHpackContext().size()); // Add 4 more fields for (int i=4;i<=7;i++) @@ -100,7 +100,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // max dynamic table size reached - Assert.assertEquals(5,encoder.getHpackContext().size()); + assertEquals(5,encoder.getHpackContext().size()); // remove some fields @@ -116,7 +116,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // max dynamic table size reached - Assert.assertEquals(5,encoder.getHpackContext().size()); + assertEquals(5,encoder.getHpackContext().size()); // remove another fields @@ -131,7 +131,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // max dynamic table size reached - Assert.assertEquals(5,encoder.getHpackContext().size()); + assertEquals(5,encoder.getHpackContext().size()); // re add the field @@ -147,7 +147,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // max dynamic table size reached - Assert.assertEquals(5,encoder.getHpackContext().size()); + assertEquals(5,encoder.getHpackContext().size()); } @@ -170,7 +170,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // empty dynamic table - Assert.assertEquals(0,encoder.getHpackContext().size()); + assertEquals(0,encoder.getHpackContext().size()); // encode again @@ -182,7 +182,7 @@ public class HpackEncoderTest assertThat(buffer.remaining(),Matchers.greaterThan(0)); // empty dynamic table - Assert.assertEquals(0,encoder.getHpackContext().size()); + assertEquals(0,encoder.getHpackContext().size()); } @@ -268,8 +268,8 @@ public class HpackEncoderTest HpackContext context = encoder.getHpackContext(); - Assert.assertThat(context.getMaxDynamicTableSize(),Matchers.is(50)); - Assert.assertThat(context.size(),Matchers.is(1)); + assertThat(context.getMaxDynamicTableSize(),Matchers.is(50)); + assertThat(context.size(),Matchers.is(1)); } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java index 352dda4b3a4..719a22c06ae 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackPerfTest.java @@ -31,9 +31,9 @@ import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.ajax.JSON; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class HpackPerfTest @@ -42,14 +42,14 @@ public class HpackPerfTest int _unencodedSize; int _encodedSize; - @Before + @BeforeEach public void before() { _unencodedSize=0; _encodedSize=0; } - @After + @AfterEach public void after() { System.err.printf("dynamictable=%d unencoded=%d encoded=%d p=%3.1f%%%n",_maxDynamicTableSize,_unencodedSize,_encodedSize,100.0*_encodedSize/_unencodedSize); diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java index 2f3f461de31..355ffb2953f 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HpackTest.java @@ -20,8 +20,10 @@ package org.eclipse.jetty.http2.hpack; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; @@ -35,8 +37,8 @@ import org.eclipse.jetty.http.MetaData; import org.eclipse.jetty.http.MetaData.Response; import org.eclipse.jetty.http.PreEncodedHttpField; import org.eclipse.jetty.util.BufferUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + public class HpackTest { @@ -94,7 +96,7 @@ public class HpackTest Response decoded1 = (Response)decoder.decode(buffer); assertMetadataSame(original1,decoded1); - Assert.assertEquals("custom-key",decoded1.getFields().getField("Custom-Key").getName()); + assertEquals("custom-key",decoded1.getFields().getField("Custom-Key").getName()); } @Test @@ -128,12 +130,13 @@ public class HpackTest try { decoder.decode(buffer); - Assert.fail(); + fail(); } catch(HpackException.SessionException e) { assertThat(e.getMessage(),containsString("Header too large")); } + } @Test diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java index 3b697ac0fe5..bf7a935458c 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/HuffmanTest.java @@ -18,80 +18,68 @@ package org.eclipse.jetty.http2.hpack; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.nio.ByteBuffer; import java.util.Locale; +import java.util.stream.Stream; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.TypeUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; public class HuffmanTest { - String[][] tests = - { - {"D.4.1","f1e3c2e5f23a6ba0ab90f4ff","www.example.com"}, - {"D.4.2","a8eb10649cbf","no-cache"}, - {"D.6.1k","6402","302"}, - {"D.6.1v","aec3771a4b","private"}, - {"D.6.1d","d07abe941054d444a8200595040b8166e082a62d1bff","Mon, 21 Oct 2013 20:13:21 GMT"}, - {"D.6.1l","9d29ad171863c78f0b97c8e9ae82ae43d3","https://www.example.com"}, - {"D.6.2te","640cff","303"}, - }; - - @Test - public void testDecode() throws Exception + public static Stream data() { - for (String[] test:tests) - { - byte[] encoded=TypeUtil.fromHexString(test[1]); - String decoded=Huffman.decode(ByteBuffer.wrap(encoded)); - Assert.assertEquals(test[0],test[2],decoded); - } + return Stream.of( + new String[][]{ + {"D.4.1", "f1e3c2e5f23a6ba0ab90f4ff", "www.example.com"}, + {"D.4.2", "a8eb10649cbf", "no-cache"}, + {"D.6.1k", "6402", "302"}, + {"D.6.1v", "aec3771a4b", "private"}, + {"D.6.1d", "d07abe941054d444a8200595040b8166e082a62d1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, + {"D.6.1l", "9d29ad171863c78f0b97c8e9ae82ae43d3", "https://www.example.com"}, + {"D.6.2te", "640cff", "303"}, + }).map(Arguments::of); } - @Test - public void testEncode() throws Exception + @ParameterizedTest(name="[{index}] spec={0}") + @MethodSource("data") + public void testDecode(String specSection, String hex, String expected) throws Exception { - for (String[] test:tests) - { - ByteBuffer buf = BufferUtil.allocate(1024); - int pos=BufferUtil.flipToFill(buf); - Huffman.encode(buf,test[2]); - BufferUtil.flipToFlush(buf,pos); - String encoded=TypeUtil.toHexString(BufferUtil.toArray(buf)).toLowerCase(Locale.ENGLISH); - Assert.assertEquals(test[0],test[1],encoded); - Assert.assertEquals(test[1].length()/2,Huffman.octetsNeeded(test[2])); - } + byte[] encoded=TypeUtil.fromHexString(hex); + String decoded=Huffman.decode(ByteBuffer.wrap(encoded)); + assertEquals(expected,decoded,specSection); } - @Test - public void testEncode8859Only() throws Exception + @ParameterizedTest(name="[{index}] spec={0}") + @MethodSource("data") + public void testEncode(String specSection, String hex, String expected) { - char bad[] = {(char)128,(char)0,(char)-1,' '-1}; - for (int i=0;i Huffman.octetsNeeded(s)); + + assertThrows(IllegalArgumentException.class, + () -> Huffman.encode(BufferUtil.allocate(32), s)); + } } diff --git a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java index 6b4e70bb224..b002bf29116 100644 --- a/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java +++ b/jetty-http2/http2-hpack/src/test/java/org/eclipse/jetty/http2/hpack/NBitIntegerTest.java @@ -18,14 +18,14 @@ package org.eclipse.jetty.http2.hpack; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.ByteBuffer; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.TypeUtil; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class NBitIntegerTest { @@ -129,7 +129,7 @@ public class NBitIntegerTest { ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString(encoded)); buf.position(n==8?0:1); - Assert.assertEquals(expected,NBitInteger.decode(buf,n)); + assertEquals(expected,NBitInteger.decode(buf,n)); } @Test @@ -154,7 +154,7 @@ public class NBitIntegerTest ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("77EaFF")); buf.position(2); - Assert.assertEquals(10,NBitInteger.decode(buf,5)); + assertEquals(10,NBitInteger.decode(buf,5)); } @@ -170,7 +170,7 @@ public class NBitIntegerTest String r=TypeUtil.toHexString(BufferUtil.toArray(buf)); - Assert.assertEquals("881f9a0a",r); + assertEquals("881f9a0a",r); } @@ -180,7 +180,7 @@ public class NBitIntegerTest ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("881f9a0aff")); buf.position(2); - Assert.assertEquals(1337,NBitInteger.decode(buf,5)); + assertEquals(1337,NBitInteger.decode(buf,5)); } @@ -196,7 +196,7 @@ public class NBitIntegerTest String r=TypeUtil.toHexString(BufferUtil.toArray(buf)); - Assert.assertEquals("88Ff2a",r); + assertEquals("88Ff2a",r); } @@ -207,7 +207,7 @@ public class NBitIntegerTest ByteBuffer buf = ByteBuffer.wrap(TypeUtil.fromHexString("882aFf")); buf.position(1); - Assert.assertEquals(42,NBitInteger.decode(buf,8)); + assertEquals(42,NBitInteger.decode(buf,8)); } diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/AbstractTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/AbstractTest.java index 8170f205085..3216456974e 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/AbstractTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/AbstractTest.java @@ -28,15 +28,11 @@ import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; public class AbstractTest { - @Rule - public TestTracker tracker = new TestTracker(); protected Server server; protected ServerConnector connector; protected HttpClient client; @@ -75,7 +71,7 @@ public class AbstractTest client.setExecutor(clientExecutor); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java index 7786f250ae9..4b110edd986 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/DirectHTTP2OverTLSTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.http2.client.http; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -41,18 +43,14 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class DirectHTTP2OverTLSTest { - @Rule - public TestTracker tracker = new TestTracker(); private Server server; private ServerConnector connector; private HttpClient client; @@ -89,7 +87,7 @@ public class DirectHTTP2OverTLSTest client.start(); } - @After + @AfterEach public void dispose() throws Exception { if (client != null) @@ -127,6 +125,6 @@ public class DirectHTTP2OverTLSTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } } diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java index a6eb2acb7a8..c159e34c200 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/HttpClientTransportOverHTTP2Test.java @@ -18,6 +18,15 @@ package org.eclipse.jetty.http2.client.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -75,9 +84,8 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class HttpClientTransportOverHTTP2Test extends AbstractTest { @@ -93,16 +101,16 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest httpClient.start(); - Assert.assertTrue(http2Client.isStarted()); - Assert.assertSame(httpClient.getExecutor(), http2Client.getExecutor()); - Assert.assertSame(httpClient.getScheduler(), http2Client.getScheduler()); - Assert.assertSame(httpClient.getByteBufferPool(), http2Client.getByteBufferPool()); - Assert.assertEquals(httpClient.getConnectTimeout(), http2Client.getConnectTimeout()); - Assert.assertEquals(httpClient.getIdleTimeout(), http2Client.getIdleTimeout()); + assertTrue(http2Client.isStarted()); + assertSame(httpClient.getExecutor(), http2Client.getExecutor()); + assertSame(httpClient.getScheduler(), http2Client.getScheduler()); + assertSame(httpClient.getByteBufferPool(), http2Client.getByteBufferPool()); + assertEquals(httpClient.getConnectTimeout(), http2Client.getConnectTimeout()); + assertEquals(httpClient.getIdleTimeout(), http2Client.getIdleTimeout()); httpClient.stop(); - Assert.assertTrue(http2Client.isStopped()); + assertTrue(http2Client.isStopped()); } @Test @@ -125,17 +133,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest } }); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .onRequestCommit(request -> request.abort(new Exception("explicitly_aborted_by_test"))) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); - } + }); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -169,17 +172,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest } }); - try - { + assertThrows(ExecutionException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) .onResponseContent((response, buffer) -> response.abort(new Exception("explicitly_aborted_by_test"))) .send(); - Assert.fail(); - } - catch (ExecutionException x) - { - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); - } + }); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -204,7 +202,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest }) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test @@ -287,7 +285,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest .path("/zero") .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); org.eclipse.jetty.client.api.Request request = client.newRequest("localhost", connector.getLocalPort()) .method(HttpMethod.HEAD) @@ -298,12 +296,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest latch.countDown(); }); - Assert.assertTrue(streamLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(streamLatch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); Stream stream = streamRef.get(); - Assert.assertNotNull(stream); - Assert.assertEquals(lastStream.get(), stream.getId()); + assertNotNull(stream); + assertEquals(lastStream.get(), stream.getId()); } @Test @@ -317,8 +315,8 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); @@ -327,7 +325,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test @@ -341,8 +339,8 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { baseRequest.setHandled(true); - Assert.assertEquals(path, request.getRequestURI()); - Assert.assertEquals(query, request.getQueryString()); + assertEquals(path, request.getRequestURI()); + assertEquals(query, request.getQueryString()); } }); @@ -355,7 +353,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test @@ -383,20 +381,14 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest client.setIdleTimeout(idleTimeout); client.start(); - try - { + assertThrows(TimeoutException.class, ()->{ client.newRequest("localhost", connector.getLocalPort()) // Make sure the connection idle times out, not the stream. .idleTimeout(2 * idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.fail(); - } - catch (TimeoutException e) - { - // Expected. - } + }); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -419,20 +411,14 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest } }); - try - { + assertThrows(TimeoutException.class, ()->{ long idleTimeout = 1000; client.newRequest("localhost", connector.getLocalPort()) .idleTimeout(idleTimeout, TimeUnit.MILLISECONDS) .send(); - Assert.fail(); - } - catch (TimeoutException e) - { - // Expected. - } + }); - Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resetLatch.await(5, TimeUnit.SECONDS)); } @Test @@ -519,8 +505,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest try { int read = input.read(bytes); - if (read < 0) - Assert.fail(); + assertThat(read, greaterThanOrEqualTo(0)); parser.parse(ByteBuffer.wrap(bytes, 0, read)); } catch (SocketTimeoutException x) @@ -529,7 +514,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest } } - Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); + assertTrue(resultLatch.await(5, TimeUnit.SECONDS)); // The client will send a GO_AWAY, but the server will not close. client.stop(); @@ -537,12 +522,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest // Give some time to process the stop/close operations. Thread.sleep(1000); - Assert.assertTrue(h2Client.getBeans(Session.class).isEmpty()); + assertTrue(h2Client.getBeans(Session.class).isEmpty()); for (Session session : sessions) { - Assert.assertTrue(session.isClosed()); - Assert.assertTrue(((HTTP2Session)session).isDisconnected()); + assertTrue(session.isClosed()); + assertTrue(((HTTP2Session)session).isDisconnected()); } } } @@ -571,11 +556,12 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.NO_CONTENT_204, response.getStatus()); + assertEquals(HttpStatus.NO_CONTENT_204, response.getStatus()); // No logic on the client to discard content for no-content status codes. - Assert.assertArrayEquals(bytes, response.getContent()); + assertArrayEquals(bytes, response.getContent()); } + @Test public void testInvalidResponseHPack() throws Exception { @@ -607,10 +593,10 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest latch.countDown(); }); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } - @Ignore + @Disabled @Test public void testExternalServer() throws Exception { @@ -625,7 +611,7 @@ public class HttpClientTransportOverHTTP2Test extends AbstractTest // ContentResponse response = httpClient.GET("https://http2.akamai.com/"); ContentResponse response = httpClient.GET("https://webtide.com/"); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); httpClient.stop(); } diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java index 28260527805..fe030fa838f 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/MaxConcurrentStreamsTest.java @@ -18,22 +18,6 @@ package org.eclipse.jetty.http2.client.http; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.IntStream; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.client.AbstractConnectionPool; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpDestination; @@ -57,8 +41,26 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.util.Promise; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class MaxConcurrentStreamsTest extends AbstractTest { @@ -116,7 +118,7 @@ public class MaxConcurrentStreamsTest extends AbstractTest }); // When the first request returns, the second must be sent. - Assert.assertTrue(latch.await(5 * sleep, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(5 * sleep, TimeUnit.MILLISECONDS)); } @Test @@ -135,7 +137,7 @@ public class MaxConcurrentStreamsTest extends AbstractTest .path("/" + i + "_" + j) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } catch (Throwable x) { @@ -216,12 +218,12 @@ public class MaxConcurrentStreamsTest extends AbstractTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response1.getStatus()); - Assert.assertTrue(failures.toString(), latch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(2, connections.get()); + assertEquals(HttpStatus.OK_200, response1.getStatus()); + assertTrue(latch.await(5, TimeUnit.SECONDS), failures.toString()); + assertEquals(2, connections.get()); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); AbstractConnectionPool connectionPool = (AbstractConnectionPool)destination.getConnectionPool(); - Assert.assertEquals(2, connectionPool.getConnectionCount()); + assertEquals(2, connectionPool.getConnectionCount()); } @Test @@ -262,10 +264,10 @@ public class MaxConcurrentStreamsTest extends AbstractTest // The last exchange should remain in the queue. HttpDestinationOverHTTP2 destination = (HttpDestinationOverHTTP2)client.getDestination("http", "localhost", connector.getLocalPort()); - Assert.assertEquals(1, destination.getHttpExchanges().size()); - Assert.assertEquals(path, destination.getHttpExchanges().peek().getRequest().getPath()); + assertEquals(1, destination.getHttpExchanges().size()); + assertEquals(path, destination.getHttpExchanges().peek().getRequest().getPath()); - Assert.assertTrue(latch.await(5 * sleep, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(5 * sleep, TimeUnit.MILLISECONDS)); } @Test @@ -293,7 +295,7 @@ public class MaxConcurrentStreamsTest extends AbstractTest // Must be able to send another request. ContentResponse response = client.newRequest("localhost", connector.getLocalPort()).path("/check").send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } @Test @@ -321,7 +323,7 @@ public class MaxConcurrentStreamsTest extends AbstractTest } // The requests should be processed in parallel, not sequentially. - Assert.assertTrue(latch.await(maxConcurrent * sleep / 2, TimeUnit.MILLISECONDS)); + assertTrue(latch.await(maxConcurrent * sleep / 2, TimeUnit.MILLISECONDS)); } @Test @@ -348,23 +350,23 @@ public class MaxConcurrentStreamsTest extends AbstractTest Queue failures = new ConcurrentLinkedQueue<>(); ForkJoinPool pool = new ForkJoinPool(parallelism); pool.submit(() -> IntStream.range(0, parallelism).parallel().forEach(i -> - IntStream.range(0, runs).forEach(j -> + IntStream.range(0, runs).forEach(j -> + { + for (int k = 0; k < iterations; ++k) { - for (int k = 0; k < iterations; ++k) - { - client.newRequest("localhost", connector.getLocalPort()) - .path("/" + i + "_" + j + "_" + k) - .send(result -> - { - if (result.isFailed()) - failures.offer(result); - latch.countDown(); - }); - } - }))); + client.newRequest("localhost", connector.getLocalPort()) + .path("/" + i + "_" + j + "_" + k) + .send(result -> + { + if (result.isFailed()) + failures.offer(result); + latch.countDown(); + }); + } + }))); - Assert.assertTrue(latch.await(total * 10, TimeUnit.MILLISECONDS)); - Assert.assertTrue(failures.toString(), failures.isEmpty()); + assertTrue(latch.await(total * 10, TimeUnit.MILLISECONDS)); + assertTrue(failures.isEmpty(), failures.toString()); } @Test @@ -396,8 +398,8 @@ public class MaxConcurrentStreamsTest extends AbstractTest .path("/2") .send(); - Assert.assertEquals(HttpStatus.OK_200, response2.getStatus()); - Assert.assertTrue(latch.await(2 * timeout, TimeUnit.MILLISECONDS)); + assertEquals(HttpStatus.OK_200, response2.getStatus()); + assertTrue(latch.await(2 * timeout, TimeUnit.MILLISECONDS)); } private void primeConnection() throws Exception diff --git a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java index b1769c2b4df..228438357ed 100644 --- a/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java +++ b/jetty-http2/http2-http-client-transport/src/test/java/org/eclipse/jetty/http2/client/http/PushedResourcesTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.http2.client.http; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.util.Random; import java.util.concurrent.CountDownLatch; @@ -46,8 +50,8 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class PushedResourcesTest extends AbstractTest { @@ -90,8 +94,8 @@ public class PushedResourcesTest extends AbstractTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } @Test @@ -143,15 +147,15 @@ public class PushedResourcesTest extends AbstractTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isSucceeded()); + assertTrue(result.isSucceeded()); if (pushedRequest.getPath().equals(path1)) { - Assert.assertArrayEquals(pushBytes1, getContent()); + assertArrayEquals(pushBytes1, getContent()); latch1.countDown(); } else if (pushedRequest.getPath().equals(path2)) { - Assert.assertArrayEquals(pushBytes2, getContent()); + assertArrayEquals(pushBytes2, getContent()); latch2.countDown(); } } @@ -159,10 +163,10 @@ public class PushedResourcesTest extends AbstractTest .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertArrayEquals(bytes, response.getContent()); - Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertArrayEquals(bytes, response.getContent()); + assertTrue(latch1.await(5, TimeUnit.SECONDS)); + assertTrue(latch2.await(5, TimeUnit.SECONDS)); } @Test @@ -197,17 +201,17 @@ public class PushedResourcesTest extends AbstractTest @Override public void onComplete(Result result) { - Assert.assertTrue(result.isSucceeded()); - Assert.assertEquals(oldPath, pushedRequest.getPath()); - Assert.assertEquals(newPath, result.getRequest().getPath()); - Assert.assertArrayEquals(pushBytes, getContent()); + assertTrue(result.isSucceeded()); + assertEquals(oldPath, pushedRequest.getPath()); + assertEquals(newPath, result.getRequest().getPath()); + assertArrayEquals(pushBytes, getContent()); latch.countDown(); } }) .timeout(5, TimeUnit.SECONDS) .send(); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java index 5f9e5f0e89c..26423c54a7f 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/AbstractServerTest.java @@ -42,15 +42,11 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; public class AbstractServerTest { - @Rule - public TestTracker tracker = new TestTracker(); protected ServerConnector connector; protected ByteBufferPool byteBufferPool; protected Generator generator; @@ -91,7 +87,7 @@ public class AbstractServerTest return new MetaData.Request(method, HttpScheme.HTTP, new HostPortHttpField(authority), path, HttpVersion.HTTP_2, fields); } - @After + @AfterEach public void dispose() throws Exception { if (server!=null) diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java index f7e50a3aa98..69caa8949a8 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/CloseTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.http2.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.OutputStream; import java.net.Socket; @@ -45,8 +48,8 @@ import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.io.RuntimeIOException; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class CloseTest extends AbstractServerTest { @@ -116,8 +119,8 @@ public class CloseTest extends AbstractServerTest Thread.sleep(1000); Session session = sessionRef.get(); - Assert.assertTrue(session.isClosed()); - Assert.assertTrue(((HTTP2Session)session).isDisconnected()); + assertTrue(session.isClosed()); + assertTrue(((HTTP2Session)session).isDisconnected()); } } @@ -169,18 +172,18 @@ public class CloseTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); // Wait for the server to close. Thread.sleep(1000); // Client received the TCP FIN from server. - Assert.assertEquals(-1, client.getInputStream().read()); + assertEquals(-1, client.getInputStream().read()); // Server is closed. Session session = sessionRef.get(); - Assert.assertTrue(session.isClosed()); - Assert.assertTrue(((HTTP2Session)session).isDisconnected()); + assertTrue(session.isClosed()); + assertTrue(((HTTP2Session)session).isDisconnected()); } } @@ -238,8 +241,8 @@ public class CloseTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); // Don't close the connection. @@ -247,12 +250,12 @@ public class CloseTest extends AbstractServerTest Thread.sleep(2 * idleTimeout); // Client received the TCP FIN from server. - Assert.assertEquals(-1, client.getInputStream().read()); + assertEquals(-1, client.getInputStream().read()); // Server is closed. Session session = sessionRef.get(); - Assert.assertTrue(session.isClosed()); - Assert.assertTrue(((HTTP2Session)session).isDisconnected()); + assertTrue(session.isClosed()); + assertTrue(((HTTP2Session)session).isDisconnected()); } } } diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java index 3a6e8f3d3ac..649ea7048cb 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2CServerTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.http2.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -55,18 +61,13 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.Utf8StringBuilder; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class HTTP2CServerTest extends AbstractServerTest { - @Before + @BeforeEach public void before() throws Exception { server = new HTTP2CServer(0); @@ -74,7 +75,7 @@ public class HTTP2CServerTest extends AbstractServerTest connector = (ServerConnector)server.getConnectors()[0]; } - @After + @AfterEach public void after() throws Exception { server.stop(); @@ -171,15 +172,15 @@ public class HTTP2CServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latchRef.get().await(5, TimeUnit.SECONDS)); + assertTrue(latchRef.get().await(5, TimeUnit.SECONDS)); HeadersFrame response = headersRef.get(); - Assert.assertNotNull(response); + assertNotNull(response); MetaData.Response responseMetaData = (MetaData.Response)response.getMetaData(); - Assert.assertEquals(200, responseMetaData.getStatus()); + assertEquals(200, responseMetaData.getStatus()); DataFrame responseData = dataRef.get(); - Assert.assertNotNull(responseData); + assertNotNull(responseData); String content = BufferUtil.toString(responseData.getData()); @@ -202,15 +203,15 @@ public class HTTP2CServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latchRef.get().await(5, TimeUnit.SECONDS)); + assertTrue(latchRef.get().await(5, TimeUnit.SECONDS)); response = headersRef.get(); - Assert.assertNotNull(response); + assertNotNull(response); responseMetaData = (MetaData.Response)response.getMetaData(); - Assert.assertEquals(200, responseMetaData.getStatus()); + assertEquals(200, responseMetaData.getStatus()); responseData = dataRef.get(); - Assert.assertNotNull(responseData); + assertNotNull(responseData); content = BufferUtil.toString(responseData.getData()); @@ -269,15 +270,15 @@ public class HTTP2CServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); HeadersFrame response = headersRef.get(); - Assert.assertNotNull(response); + assertNotNull(response); MetaData.Response responseMetaData = (MetaData.Response)response.getMetaData(); - Assert.assertEquals(200, responseMetaData.getStatus()); + assertEquals(200, responseMetaData.getStatus()); DataFrame responseData = dataRef.get(); - Assert.assertNotNull(responseData); + assertNotNull(responseData); String s = BufferUtil.toString(responseData.getData()); @@ -337,7 +338,7 @@ public class HTTP2CServerTest extends AbstractServerTest InputStream input = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String responseLine = reader.readLine(); - Assert.assertThat(responseLine, Matchers.containsString(" 426 ")); + assertThat(responseLine, Matchers.containsString(" 426 ")); while (true) { if (reader.read() < 0) @@ -347,6 +348,6 @@ public class HTTP2CServerTest extends AbstractServerTest // Make sure we did not spin. Thread.sleep(1000); - Assert.assertThat(fills.get(), Matchers.lessThan(5L)); + assertThat(fills.get(), Matchers.lessThan(5L)); } } diff --git a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java index 5029d396059..a8334ca42fe 100644 --- a/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java +++ b/jetty-http2/http2-server/src/test/java/org/eclipse/jetty/http2/server/HTTP2ServerTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.http2.server; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; @@ -67,8 +73,8 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.log.StacklessLogging; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class HTTP2ServerTest extends AbstractServerTest { @@ -103,7 +109,7 @@ public class HTTP2ServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } @@ -154,12 +160,12 @@ public class HTTP2ServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); HeadersFrame response = frameRef.get(); - Assert.assertNotNull(response); + assertNotNull(response); MetaData.Response responseMetaData = (MetaData.Response)response.getMetaData(); - Assert.assertEquals(200, responseMetaData.getStatus()); + assertEquals(200, responseMetaData.getStatus()); } } @@ -220,16 +226,16 @@ public class HTTP2ServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); HeadersFrame response = headersRef.get(); - Assert.assertNotNull(response); + assertNotNull(response); MetaData.Response responseMetaData = (MetaData.Response)response.getMetaData(); - Assert.assertEquals(200, responseMetaData.getStatus()); + assertEquals(200, responseMetaData.getStatus()); DataFrame responseData = dataRef.get(); - Assert.assertNotNull(responseData); - Assert.assertArrayEquals(content, BufferUtil.toArray(responseData.getData())); + assertNotNull(responseData); + assertArrayEquals(content, BufferUtil.toArray(responseData.getData())); } } @@ -259,7 +265,7 @@ public class HTTP2ServerTest extends AbstractServerTest @Override public void onGoAway(GoAwayFrame frame) { - Assert.assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, frame.getError()); + assertEquals(ErrorCode.FRAME_SIZE_ERROR.code, frame.getError()); latch.countDown(); } }, 4096, 8192); @@ -267,7 +273,7 @@ public class HTTP2ServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } @@ -297,7 +303,7 @@ public class HTTP2ServerTest extends AbstractServerTest @Override public void onGoAway(GoAwayFrame frame) { - Assert.assertEquals(ErrorCode.PROTOCOL_ERROR.code, frame.getError()); + assertEquals(ErrorCode.PROTOCOL_ERROR.code, frame.getError()); latch.countDown(); } }, 4096, 8192); @@ -305,7 +311,7 @@ public class HTTP2ServerTest extends AbstractServerTest parseResponse(client, parser); - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS)); } } @@ -370,7 +376,7 @@ public class HTTP2ServerTest extends AbstractServerTest Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter(), 4096, 8192); parser.init(UnaryOperator.identity()); boolean closed = parseResponse(client, parser, 2 * delay); - Assert.assertTrue(closed); + assertTrue(closed); } } @@ -406,7 +412,7 @@ public class HTTP2ServerTest extends AbstractServerTest parser.init(UnaryOperator.identity()); boolean closed = parseResponse(client, parser); - Assert.assertTrue(closed); + assertTrue(closed); } } } @@ -544,11 +550,11 @@ public class HTTP2ServerTest extends AbstractServerTest if (priorityFrame != null) { PriorityFrame priority = frame.getPriority(); - Assert.assertNotNull(priority); - Assert.assertEquals(priorityFrame.getStreamId(), priority.getStreamId()); - Assert.assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); - Assert.assertEquals(priorityFrame.getWeight(), priority.getWeight()); - Assert.assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); + assertNotNull(priority); + assertEquals(priorityFrame.getStreamId(), priority.getStreamId()); + assertEquals(priorityFrame.getParentStreamId(), priority.getParentStreamId()); + assertEquals(priorityFrame.getWeight(), priority.getWeight()); + assertEquals(priorityFrame.isExclusive(), priority.isExclusive()); } serverLatch.countDown(); @@ -570,7 +576,7 @@ public class HTTP2ServerTest extends AbstractServerTest output.write(BufferUtil.toArray(buffer)); output.flush(); - Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); + assertTrue(serverLatch.await(5, TimeUnit.SECONDS)); final CountDownLatch clientLatch = new CountDownLatch(1); Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() @@ -585,8 +591,8 @@ public class HTTP2ServerTest extends AbstractServerTest parser.init(UnaryOperator.identity()); boolean closed = parseResponse(client, parser); - Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); - Assert.assertFalse(closed); + assertTrue(clientLatch.await(5, TimeUnit.SECONDS)); + assertFalse(closed); } } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java index fef7a562023..a8ab2a5df0b 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ArrayByteBufferPoolTest.java @@ -19,15 +19,15 @@ package org.eclipse.jetty.io; import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.util.Arrays; import org.eclipse.jetty.io.ByteBufferPool.Bucket; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("ReferenceEquality") public class ArrayByteBufferPoolTest diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java index e50cf959623..68e681a00f6 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/ByteArrayEndPointTest.java @@ -18,46 +18,42 @@ package org.eclipse.jetty.io; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.util.thread.TimerScheduler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@RunWith(AdvancedRunner.class) public class ByteArrayEndPointTest { private Scheduler _scheduler; - @Before + @BeforeEach public void before() throws Exception { _scheduler = new TimerScheduler(); _scheduler.start(); } - @After + @AfterEach public void after() throws Exception { _scheduler.stop(); @@ -91,7 +87,7 @@ public class ByteArrayEndPointTest try { endp.fill(buffer); - fail(); + fail("Expected IOException"); } catch(IOException e) { @@ -204,10 +200,11 @@ public class ByteArrayEndPointTest fcb = new FutureCallback(); endp.fillInterested(fcb); + try { fcb.get(1000,TimeUnit.MILLISECONDS); - fail(); + fail("Expected ExecutionException"); } catch (ExecutionException e) { @@ -264,7 +261,6 @@ public class ByteArrayEndPointTest } } - @Slow @Test public void testIdle() throws Exception { @@ -299,7 +295,7 @@ public class ByteArrayEndPointTest try { fcb.get(); - fail(); + fail("Expected ExecutionException"); } catch (ExecutionException t) { diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java index 2ab2d9734fb..4d316d05030 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/CyclicTimeoutTest.java @@ -18,29 +18,27 @@ package org.eclipse.jetty.io; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class CyclicTimeoutTest { - @Rule - public TestTracker tracker = new TestTracker(); - private volatile boolean _expired; private ScheduledExecutorScheduler _timer = new ScheduledExecutorScheduler(); private CyclicTimeout _timeout; - @Before + @BeforeEach public void before() throws Exception { _expired=false; @@ -58,7 +56,7 @@ public class CyclicTimeoutTest _timeout.schedule(1000,TimeUnit.MILLISECONDS); } - @After + @AfterEach public void after() throws Exception { _timeout.destroy(); @@ -71,9 +69,9 @@ public class CyclicTimeoutTest for (int i=0;i<20;i++) { Thread.sleep(100); - Assert.assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); } - Assert.assertFalse(_expired); + assertFalse(_expired); } @Test @@ -82,10 +80,10 @@ public class CyclicTimeoutTest for (int i=0;i<5;i++) { Thread.sleep(100); - Assert.assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); } Thread.sleep(1500); - Assert.assertTrue(_expired); + assertTrue(_expired); } @Test @@ -94,11 +92,11 @@ public class CyclicTimeoutTest for (int i=0;i<5;i++) { Thread.sleep(100); - Assert.assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); } _timeout.cancel(); Thread.sleep(1500); - Assert.assertFalse(_expired); + assertFalse(_expired); } @Test @@ -107,11 +105,11 @@ public class CyclicTimeoutTest for (int i=0;i<5;i++) { Thread.sleep(100); - Assert.assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); } - Assert.assertTrue(_timeout.schedule(100,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(100,TimeUnit.MILLISECONDS)); Thread.sleep(400); - Assert.assertTrue(_expired); + assertTrue(_expired); } @Test @@ -120,30 +118,30 @@ public class CyclicTimeoutTest for (int i=0;i<5;i++) { Thread.sleep(100); - Assert.assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(1000,TimeUnit.MILLISECONDS)); } - Assert.assertTrue(_timeout.schedule(10000,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(10000,TimeUnit.MILLISECONDS)); Thread.sleep(1500); - Assert.assertFalse(_expired); + assertFalse(_expired); } @Test public void testMultiple() throws Exception { Thread.sleep(1500); - Assert.assertTrue(_expired); + assertTrue(_expired); _expired=false; - Assert.assertFalse(_timeout.schedule(500,TimeUnit.MILLISECONDS)); + assertFalse(_timeout.schedule(500,TimeUnit.MILLISECONDS)); Thread.sleep(1000); - Assert.assertTrue(_expired); + assertTrue(_expired); _expired=false; _timeout.schedule(500,TimeUnit.MILLISECONDS); Thread.sleep(1000); - Assert.assertTrue(_expired); + assertTrue(_expired); } @Test - @Ignore + @Disabled public void testBusy() throws Exception { QueuedThreadPool pool = new QueuedThreadPool(200); @@ -151,7 +149,7 @@ public class CyclicTimeoutTest long test_until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1500); - Assert.assertTrue(_timeout.schedule(100,TimeUnit.MILLISECONDS)); + assertTrue(_timeout.schedule(100,TimeUnit.MILLISECONDS)); while(System.nanoTime(){ + int i = 0; + for (i = 0; i < 100000; i++) client.getOutputStream().write(1); - Assert.fail(); - } - catch (IOException expected) - { - } + }); } } } @@ -440,7 +437,7 @@ public class IOTest reading.get(5, TimeUnit.SECONDS); read.flip(); - Assert.assertEquals(ByteBuffer.wrap(data), read); + assertEquals(ByteBuffer.wrap(data), read); } @Test diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java index c35ec08d144..a27692ae200 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/IdleTimeoutTest.java @@ -19,14 +19,17 @@ package org.eclipse.jetty.io; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.eclipse.jetty.util.thread.TimerScheduler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class IdleTimeoutTest { @@ -36,7 +39,7 @@ public class IdleTimeoutTest TimerScheduler _timer; IdleTimeout _timeout; - @Before + @BeforeEach public void setUp() throws Exception { _open=true; @@ -60,7 +63,7 @@ public class IdleTimeoutTest _timeout.setIdleTimeout(1000); } - @After + @AfterEach public void tearDown() throws Exception { _open=false; @@ -77,7 +80,7 @@ public class IdleTimeoutTest _timeout.notIdle(); } - Assert.assertNull(_expired); + assertNull(_expired); } @Test @@ -89,7 +92,7 @@ public class IdleTimeoutTest _timeout.notIdle(); } Thread.sleep(1500); - Assert.assertNotNull(_expired); + assertNotNull(_expired); } @Test @@ -102,7 +105,7 @@ public class IdleTimeoutTest } _timeout.onClose(); Thread.sleep(1500); - Assert.assertNull(_expired); + assertNull(_expired); } @Test @@ -115,7 +118,7 @@ public class IdleTimeoutTest } _open=false; Thread.sleep(1500); - Assert.assertNull(_expired); + assertNull(_expired); } @Test @@ -128,14 +131,14 @@ public class IdleTimeoutTest Thread.sleep(100); _timeout.notIdle(); } - Assert.assertNull(_expired); + assertNull(_expired); _timeout.setIdleTimeout(100); long start = System.nanoTime(); while (_expired==null && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime()-start)<5) Thread.sleep(200); - Assert.assertNotNull(_expired); + assertNotNull(_expired); } @Test @@ -148,17 +151,17 @@ public class IdleTimeoutTest } _timeout.setIdleTimeout(10000); Thread.sleep(1500); - Assert.assertNull(_expired); + assertNull(_expired); } @Test public void testMultiple() throws Exception { Thread.sleep(1500); - Assert.assertNotNull(_expired); + assertNotNull(_expired); _expired=null; Thread.sleep(1000); - Assert.assertNotNull(_expired); + assertNotNull(_expired); } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java index e60b98d6122..dc6070c3b0a 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/MappedByteBufferPoolTest.java @@ -24,15 +24,15 @@ import java.util.concurrent.ConcurrentMap; import org.eclipse.jetty.io.ByteBufferPool.Bucket; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.StringUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class MappedByteBufferPoolTest { diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java index 41fa75b364f..8ecef4b3700 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/NIOTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.io; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; @@ -25,12 +29,11 @@ import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +/** + * + */ public class NIOTest { @Test diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java index a99894cc873..034e6eb8097 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SelectorManagerTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.io; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; @@ -29,38 +32,36 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; -import org.eclipse.jetty.io.ManagedSelector.SelectorUpdate; -import org.eclipse.jetty.io.ManagedSelector.Connect; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.TimerScheduler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; public class SelectorManagerTest { private QueuedThreadPool executor = new QueuedThreadPool(); private TimerScheduler scheduler = new TimerScheduler(); - @Before + @BeforeEach public void prepare() throws Exception { executor.start(); scheduler.start(); } - @After + @AfterEach public void dispose() throws Exception { scheduler.stop(); executor.stop(); } - @Slow @Test + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testConnectTimeoutBeforeSuccessfulConnect() throws Exception { ServerSocketChannel server = ServerSocketChannel.open(); @@ -133,8 +134,8 @@ public class SelectorManagerTest latch1.countDown(); } }); - Assert.assertTrue(latch1.await(connectTimeout * 3, TimeUnit.MILLISECONDS)); - Assert.assertFalse(client1.isOpen()); + assertTrue(latch1.await(connectTimeout * 3, TimeUnit.MILLISECONDS)); + assertFalse(client1.isOpen()); // Wait for the first connect to finish, as the selector thread is waiting in finishConnect(). Thread.sleep(timeout); @@ -154,8 +155,8 @@ public class SelectorManagerTest latch2.countDown(); } }); - Assert.assertTrue(latch2.await(connectTimeout * 5, TimeUnit.MILLISECONDS)); - Assert.assertTrue(client2.isOpen()); + assertTrue(latch2.await(connectTimeout * 5, TimeUnit.MILLISECONDS)); + assertTrue(client2.isOpen()); } } finally diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java index f6503d559e4..87f5b03fbf1 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointInterestsTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.io; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -39,9 +42,9 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.util.thread.TimerScheduler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class SocketChannelEndPointInterestsTest { @@ -104,7 +107,7 @@ public class SocketChannelEndPointInterestsTest selectorManager.start(); } - @After + @AfterEach public void destroy() throws Exception { if (scheduler!=null) @@ -188,13 +191,13 @@ public class SocketChannelEndPointInterestsTest OutputStream clientOutput = client.getOutputStream(); clientOutput.write(1); clientOutput.flush(); - Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS)); + assertTrue(latch1.await(5, TimeUnit.SECONDS)); // We do not read to keep the socket write blocked clientOutput.write(2); clientOutput.flush(); - Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS)); + assertTrue(latch2.await(5, TimeUnit.SECONDS)); // Sleep before reading to allow waking up the server only for read Thread.sleep(1000); @@ -204,7 +207,7 @@ public class SocketChannelEndPointInterestsTest while (size.getAndDecrement() > 0) clientInput.read(); - Assert.assertNull(failure.get()); + assertNull(failure.get()); } } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java index 3ba75ca4684..0c5f1f5f21f 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointOpenCloseTest.java @@ -18,18 +18,18 @@ package org.eclipse.jetty.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import org.eclipse.jetty.util.BufferUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class SocketChannelEndPointOpenCloseTest { @@ -41,14 +41,14 @@ public class SocketChannelEndPointOpenCloseTest static ServerSocketChannel connector; - @BeforeClass + @BeforeAll public static void open() throws Exception { connector = ServerSocketChannel.open(); connector.socket().bind(null); } - @AfterClass + @AfterAll public static void close() throws Exception { connector.close(); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java index 703806b8afd..d0e11801a30 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SocketChannelEndPointTest.java @@ -18,6 +18,15 @@ package org.eclipse.jetty.io; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -32,8 +41,6 @@ import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; @@ -41,13 +48,13 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSocket; import org.eclipse.jetty.io.ssl.SslConnection; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; @@ -58,23 +65,15 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.util.thread.TimerScheduler; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; @SuppressWarnings("Duplicates") -@RunWith(Parameterized.class) public class SocketChannelEndPointTest { private static final Logger LOG = Log.getLogger(SocketChannelEndPoint.class); @@ -88,22 +87,15 @@ public class SocketChannelEndPointTest boolean supportsHalfCloses(); } - @Parameterized.Parameters(name = "{0}") - public static List data() throws Exception + public static Stream scenarios() throws Exception { - List ret = new ArrayList<>(); - NormalScenario normalScenario = new NormalScenario(); - ret.add(new Object[]{normalScenario}); - ret.add(new Object[]{new SslScenario(normalScenario)}); + SslScenario sslScenario = new SslScenario(normalScenario); - return ret; + return Stream.of(normalScenario, sslScenario).map(Arguments::of); } - @Rule - public TestTracker tracker = new TestTracker(); - - private final Scenario _scenario; + private Scenario _scenario; private ServerSocketChannel _connector; private QueuedThreadPool _threadPool; @@ -116,7 +108,7 @@ public class SocketChannelEndPointTest private AtomicInteger _blockAt = new AtomicInteger(0); private AtomicInteger _writeCount = new AtomicInteger(1); - public SocketChannelEndPointTest(Scenario scenario) throws Exception + public void init(Scenario scenario) throws Exception { _scenario = scenario; _threadPool = new QueuedThreadPool(); @@ -131,7 +123,7 @@ public class SocketChannelEndPointTest _manager.start(); } - @After + @AfterEach public void stopManager() throws Exception { _scheduler.stop(); @@ -140,9 +132,11 @@ public class SocketChannelEndPointTest _connector.close(); } - @Test - public void testEcho() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + public void testEcho(Scenario scenario) throws Exception { + init(scenario); try (Socket client = _scenario.newClient(_connector)) { client.setSoTimeout(60000); @@ -165,16 +159,9 @@ public class SocketChannelEndPointTest // wait for read timeout client.setSoTimeout(500); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - try - { - client.getInputStream().read(); - Assert.fail(); - } - catch (SocketTimeoutException e) - { - long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start; - Assert.assertThat("timeout duration", duration, greaterThanOrEqualTo(400L)); - } + assertThrows(SocketTimeoutException.class, ()-> client.getInputStream().read()); + long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start; + assertThat("timeout duration", duration, greaterThanOrEqualTo(400L)); // write then shutdown client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8)); @@ -183,8 +170,8 @@ public class SocketChannelEndPointTest for (char c : "Goodbye Cruel TLS".toCharArray()) { int b = client.getInputStream().read(); - Assert.assertThat("expect valid char integer", b, greaterThan(0)); - assertEquals("expect characters to be same", c, (char)b); + assertThat("expect valid char integer", b, greaterThan(0)); + assertEquals(c, (char) b, "expect characters to be same"); } client.close(); @@ -203,7 +190,8 @@ public class SocketChannelEndPointTest @Test public void testShutdown() throws Exception { - assumeTrue("Scenario supports half-close", _scenario.supportsHalfCloses()); + // We don't test SSL as JVM SSL doesn't support half-close + init(new NormalScenario()); try (Socket client = _scenario.newClient(_connector)) { @@ -226,15 +214,8 @@ public class SocketChannelEndPointTest // wait for read timeout long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - try - { - client.getInputStream().read(); - Assert.fail(); - } - catch (SocketTimeoutException e) - { - assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start >= 400); - } + assertThrows(SocketTimeoutException.class, ()-> client.getInputStream().read()); + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start >= 400); // write then shutdown client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8)); @@ -254,9 +235,11 @@ public class SocketChannelEndPointTest } } - @Test - public void testReadBlocked() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + public void testReadBlocked(Scenario scenario) throws Exception { + init(scenario); try (Socket client = _scenario.newClient(_connector); SocketChannel server = _connector.accept()) { @@ -274,21 +257,14 @@ public class SocketChannelEndPointTest clientOutputStream.write("12345678".getBytes(StandardCharsets.UTF_8)); clientOutputStream.flush(); - Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS)); + assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS)); _lastEndPoint.setIdleTimeout(10 * specifiedTimeout); Thread.sleep((11 * specifiedTimeout) / 10); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - try - { - int b = clientInputStream.read(); - Assert.fail("Should have timed out waiting for a response, but read " + b); - } - catch (SocketTimeoutException e) - { - int elapsed = Long.valueOf(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start).intValue(); - Assert.assertThat("Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4)); - } + assertThrows(SocketTimeoutException.class, ()-> clientInputStream.read()); + int elapsed = Long.valueOf(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start).intValue(); + assertThat("Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4)); // write remaining characters clientOutputStream.write("90ABCDEF".getBytes(StandardCharsets.UTF_8)); @@ -304,9 +280,11 @@ public class SocketChannelEndPointTest } } - @Test - public void testStress() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + public void testStress(Scenario scenario) throws Exception { + init(scenario); try (Socket client = _scenario.newClient(_connector)) { client.setSoTimeout(30000); @@ -326,7 +304,7 @@ public class SocketChannelEndPointTest out.write(count); out.flush(); - Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS)); + assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS)); _lastEndPoint.setIdleTimeout(5000); new Thread(() -> @@ -342,7 +320,7 @@ public class SocketChannelEndPointTest for (byte b0 : bytes) { int b = in.read(); - Assert.assertThat(b, greaterThan(0)); + assertThat(b, greaterThan(0)); assertEquals(0xff & b0, b); } @@ -396,7 +374,7 @@ public class SocketChannelEndPointTest { //System.err.println(latch.getCount()); if (latch.getCount() == last) - Assert.fail(); + fail("Latch failure"); last = latch.getCount(); } @@ -405,9 +383,11 @@ public class SocketChannelEndPointTest } } - @Test - public void testWriteBlocked() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + public void testWriteBlocked(Scenario scenario) throws Exception { + init(scenario); try (Socket client = _scenario.newClient(_connector)) { client.setSoTimeout(10000); @@ -437,7 +417,7 @@ public class SocketChannelEndPointTest int b = in.read(); byteNum++; assertTrue(b > 0); - assertEquals("test-" + i + "/" + j, c, (char)b); + assertEquals(c, (char) b, "test-" + i + "/" + j); } if (i == 0) @@ -467,11 +447,13 @@ public class SocketChannelEndPointTest } - // TODO make this test reliable - @Test - @Ignore - public void testRejectedExecution() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + @Tag("Unstable") + @Disabled + public void testRejectedExecution(Scenario scenario) throws Exception { + init(scenario); _manager.stop(); _threadPool.stop(); @@ -557,13 +539,13 @@ public class SocketChannelEndPointTest closed.await(); // assert some clients must have been rejected - Assert.assertThat(rejections.get(), Matchers.greaterThan(0)); + assertThat(rejections.get(), Matchers.greaterThan(0)); // but not all of them - Assert.assertThat(rejections.get(), Matchers.lessThan(20)); + assertThat(rejections.get(), Matchers.lessThan(20)); // none should have timed out - Assert.assertThat(timeout.get(), Matchers.equalTo(0)); + assertThat(timeout.get(), Matchers.equalTo(0)); // and the rest should have worked - Assert.assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get())); + assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get())); // and the selector is still working for new requests try (Socket client = _scenario.newClient(_connector)) diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java index c8176678282..03bf26c0ad8 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.io; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -46,11 +51,11 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.util.thread.TimerScheduler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SslConnectionTest { @@ -130,7 +135,8 @@ public class SslConnectionTest } } - @Before + + @BeforeEach public void initSSL() throws Exception { File keystore = MavenTestingUtils.getTestResourceFile("keystore"); @@ -142,7 +148,7 @@ public class SslConnectionTest startManager(); } - private void startManager() throws Exception + public void startManager() throws Exception { _testFill=true; _writeCallback=null; @@ -159,7 +165,7 @@ public class SslConnectionTest _sslCtxFactory.start(); } - @After + @AfterEach public void stopSSL() throws Exception { stopManager(); @@ -276,8 +282,8 @@ public class SslConnectionTest client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); - Assert.assertEquals(5, len); - Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(5, len); + assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); _dispatches.set(0); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); @@ -303,15 +309,15 @@ public class SslConnectionTest client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); - Assert.assertEquals(5, len); - Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(5, len); + assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); client.startHandshake(); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); len = client.getInputStream().read(buffer); - Assert.assertEquals(5, len); - Assert.assertEquals("World", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(5, len); + assertEquals("World", new String(buffer, 0, len, StandardCharsets.UTF_8)); } } } @@ -334,22 +340,14 @@ public class SslConnectionTest client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); - Assert.assertEquals(5, len); - Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(5, len); + assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); // Try to renegotiate, must fail. client.startHandshake(); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); - try - { - client.getInputStream().read(buffer); - Assert.fail(); - } - catch (SSLException e) - { - // expected - } + assertThrows(SSLException.class, ()-> client.getInputStream().read(buffer)); } } } @@ -373,35 +371,27 @@ public class SslConnectionTest client.getOutputStream().write("Good".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); - Assert.assertEquals(4, len); - Assert.assertEquals("Good", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(4, len); + assertEquals("Good", new String(buffer, 0, len, StandardCharsets.UTF_8)); client.startHandshake(); client.getOutputStream().write("Bye".getBytes(StandardCharsets.UTF_8)); len = client.getInputStream().read(buffer); - Assert.assertEquals(3, len); - Assert.assertEquals("Bye", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(3, len); + assertEquals("Bye", new String(buffer, 0, len, StandardCharsets.UTF_8)); client.startHandshake(); client.getOutputStream().write("Cruel".getBytes(StandardCharsets.UTF_8)); len = client.getInputStream().read(buffer); - Assert.assertEquals(5, len); - Assert.assertEquals("Cruel", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(5, len); + assertEquals("Cruel", new String(buffer, 0, len, StandardCharsets.UTF_8)); client.startHandshake(); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); - try - { - client.getInputStream().read(buffer); - Assert.fail(); - } - catch (SSLException e) - { - // expected - } + assertThrows(SSLException.class, ()-> client.getInputStream().read(buffer)); } } } @@ -426,9 +416,9 @@ public class SslConnectionTest byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); - Assert.assertEquals("Hello Client", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals("Hello Client", new String(buffer, 0, len, StandardCharsets.UTF_8)); - Assert.assertNull(_writeCallback.get(1, TimeUnit.SECONDS)); + assertNull(_writeCallback.get(1, TimeUnit.SECONDS)); } } } @@ -451,15 +441,15 @@ public class SslConnectionTest client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[1024]; int len = client.getInputStream().read(buffer); - Assert.assertEquals(5, len); - Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); + assertEquals(5, len); + assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8)); _dispatches.set(0); client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8)); len = 5; while (len > 0) len -= client.getInputStream().read(buffer); - Assert.assertEquals(0, len); + assertEquals(0, len); } } } @@ -510,7 +500,7 @@ public class SslConnectionTest } } - Assert.assertTrue(count.await(20, TimeUnit.SECONDS)); + assertTrue(count.await(20, TimeUnit.SECONDS)); } } } diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java index 2113f0feabe..ea6af2c6028 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslEngineBehaviorTest.java @@ -19,8 +19,8 @@ package org.eclipse.jetty.io; import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.nio.ByteBuffer; @@ -28,21 +28,21 @@ import java.nio.ByteBuffer; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; -import org.eclipse.jetty.toolchain.test.JDK; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; public class SslEngineBehaviorTest { private static SslContextFactory sslCtxFactory; - @BeforeClass + @BeforeAll public static void startSsl() throws Exception { sslCtxFactory = new SslContextFactory(); @@ -54,17 +54,16 @@ public class SslEngineBehaviorTest sslCtxFactory.start(); } - @AfterClass + @AfterAll public static void stopSsl() throws Exception { sslCtxFactory.stop(); } @Test + @EnabledOnJre(JRE.JAVA_8) public void checkSslEngineBehaviour() throws Exception { - Assume.assumeFalse(JDK.IS_9); - SSLEngine server = sslCtxFactory.newSSLEngine(); SSLEngine client = sslCtxFactory.newSSLEngine(); @@ -79,7 +78,7 @@ public class SslEngineBehaviorTest // start the client client.setUseClientMode(true); client.beginHandshake(); - Assert.assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP,client.getHandshakeStatus()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_WRAP,client.getHandshakeStatus()); // what if we try an unwrap? netS2C.flip(); @@ -104,7 +103,7 @@ public class SslEngineBehaviorTest // start the server server.setUseClientMode(false); server.beginHandshake(); - Assert.assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,server.getHandshakeStatus()); + assertEquals(SSLEngineResult.HandshakeStatus.NEED_UNWRAP,server.getHandshakeStatus()); // what if we try a needless wrap? serverOut.put(BufferUtil.toBuffer("Hello World")); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java index c775dbd7ce3..6b455c40ead 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/WriteFlusherTest.java @@ -18,6 +18,14 @@ package org.eclipse.jetty.io; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InterruptedIOException; import java.nio.ByteBuffer; @@ -36,8 +44,8 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class WriteFlusherTest { @@ -74,10 +82,10 @@ public class WriteFlusherTest FutureCallback callback = new FutureCallback(); flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!")); - Assert.assertTrue(callback.isDone()); - Assert.assertFalse(incompleteFlush.get()); - Assert.assertEquals("How now brown cow!", endPoint.takeOutputString()); - Assert.assertTrue(flusher.isIdle()); + assertTrue(callback.isDone()); + assertFalse(incompleteFlush.get()); + assertEquals("How now brown cow!", endPoint.takeOutputString()); + assertTrue(flusher.isIdle()); } @Test @@ -99,22 +107,17 @@ public class WriteFlusherTest FutureCallback callback = new FutureCallback(); flusher.write(callback, BufferUtil.toBuffer("foo")); - Assert.assertTrue(callback.isDone()); - Assert.assertFalse(incompleteFlush.get()); + assertTrue(callback.isDone()); + assertFalse(incompleteFlush.get()); - try - { + ExecutionException e = assertThrows(ExecutionException.class, ()->{ callback.get(); - Assert.fail(); - } - catch (ExecutionException e) - { - Throwable cause = e.getCause(); - Assert.assertTrue(cause instanceof IOException); - Assert.assertThat(cause.getMessage(), Matchers.containsString("CLOSED")); - } - Assert.assertEquals("", endPoint.takeOutputString()); - Assert.assertTrue(flusher.isFailed()); + }); + assertThat(e.getCause(), instanceOf(IOException.class)); + assertThat(e.getCause().getMessage(), containsString("CLOSED")); + + assertEquals("", endPoint.takeOutputString()); + assertTrue(flusher.isFailed()); } @Test @@ -135,29 +138,25 @@ public class WriteFlusherTest FutureCallback callback = new FutureCallback(); flusher.write(callback, BufferUtil.toBuffer("How now brown cow!")); - Assert.assertFalse(callback.isDone()); - Assert.assertFalse(callback.isCancelled()); + assertFalse(callback.isDone()); + assertFalse(callback.isCancelled()); - Assert.assertTrue(incompleteFlush.get()); + assertTrue(incompleteFlush.get()); - try - { + assertThrows(TimeoutException.class, ()->{ callback.get(100, TimeUnit.MILLISECONDS); - Assert.fail(); - } - catch (TimeoutException x) - { - incompleteFlush.set(false); - } + }); - Assert.assertEquals("How now br", endPoint.takeOutputString()); + incompleteFlush.set(false); + + assertEquals("How now br", endPoint.takeOutputString()); flusher.completeWrite(); - Assert.assertTrue(callback.isDone()); - Assert.assertEquals("own cow!", endPoint.takeOutputString()); - Assert.assertFalse(incompleteFlush.get()); - Assert.assertTrue(flusher.isIdle()); + assertTrue(callback.isDone()); + assertEquals("own cow!", endPoint.takeOutputString()); + assertFalse(incompleteFlush.get()); + assertTrue(flusher.isIdle()); } @Test @@ -178,33 +177,26 @@ public class WriteFlusherTest FutureCallback callback = new FutureCallback(); flusher.write(callback, BufferUtil.toBuffer("How now brown cow!")); - Assert.assertFalse(callback.isDone()); - Assert.assertFalse(callback.isCancelled()); + assertFalse(callback.isDone()); + assertFalse(callback.isCancelled()); - Assert.assertTrue(incompleteFlush.get()); + assertTrue(incompleteFlush.get()); incompleteFlush.set(false); - Assert.assertEquals("How now br", endPoint.takeOutputString()); + assertEquals("How now br", endPoint.takeOutputString()); endPoint.close(); flusher.completeWrite(); - Assert.assertTrue(callback.isDone()); - Assert.assertFalse(incompleteFlush.get()); + assertTrue(callback.isDone()); + assertFalse(incompleteFlush.get()); - try - { - callback.get(); - Assert.fail(); - } - catch (ExecutionException e) - { - Throwable cause = e.getCause(); - Assert.assertTrue(cause instanceof IOException); - Assert.assertThat(cause.getMessage(), Matchers.containsString("CLOSED")); - } - Assert.assertEquals("", endPoint.takeOutputString()); - Assert.assertTrue(flusher.isFailed()); + ExecutionException e = assertThrows(ExecutionException.class, ()-> callback.get()); + assertThat(e.getCause(), instanceOf(IOException.class)); + assertThat(e.getCause().getMessage(), containsString("CLOSED")); + + assertEquals("", endPoint.takeOutputString()); + assertTrue(flusher.isFailed()); } @Test @@ -225,34 +217,27 @@ public class WriteFlusherTest FutureCallback callback = new FutureCallback(); flusher.write(callback, BufferUtil.toBuffer("How now brown cow!")); - Assert.assertFalse(callback.isDone()); - Assert.assertFalse(callback.isCancelled()); + assertFalse(callback.isDone()); + assertFalse(callback.isCancelled()); - Assert.assertTrue(incompleteFlush.get()); + assertTrue(incompleteFlush.get()); incompleteFlush.set(false); - Assert.assertEquals("How now br", endPoint.takeOutputString()); + assertEquals("How now br", endPoint.takeOutputString()); String reason = "Failure"; flusher.onFail(new IOException(reason)); flusher.completeWrite(); - Assert.assertTrue(callback.isDone()); - Assert.assertFalse(incompleteFlush.get()); + assertTrue(callback.isDone()); + assertFalse(incompleteFlush.get()); - try - { - callback.get(); - Assert.fail(); - } - catch (ExecutionException e) - { - Throwable cause = e.getCause(); - Assert.assertTrue(cause instanceof IOException); - Assert.assertEquals(reason, cause.getMessage()); - } - Assert.assertEquals("", endPoint.takeOutputString()); - Assert.assertTrue(flusher.isFailed()); + ExecutionException e = assertThrows(ExecutionException.class, ()-> callback.get()); + assertThat(e.getCause(), instanceOf(IOException.class)); + assertThat(e.getCause().getMessage(), containsString(reason)); + + assertEquals("", endPoint.takeOutputString()); + assertTrue(flusher.isFailed()); } @Test @@ -284,18 +269,18 @@ public class WriteFlusherTest try { futures[i].get(15, TimeUnit.SECONDS); - Assert.assertEquals("How Now Brown Cow. The quick brown fox jumped over the lazy dog!", flushers[i].getContent()); + assertEquals("How Now Brown Cow. The quick brown fox jumped over the lazy dog!", flushers[i].getContent()); completed++; } catch (ExecutionException x) { - Assert.assertEquals(reason, x.getCause().getMessage()); + assertEquals(reason, x.getCause().getMessage()); failed++; } } - Assert.assertThat(completed, Matchers.greaterThan(0)); - Assert.assertThat(failed, Matchers.greaterThan(0)); - Assert.assertEquals(flushers.length, completed + failed); + assertThat(completed, Matchers.greaterThan(0)); + assertThat(failed, Matchers.greaterThan(0)); + assertEquals(flushers.length, completed + failed); } finally { @@ -328,8 +313,8 @@ public class WriteFlusherTest flusher.write(Callback.NOOP, buffer1, buffer2); - Assert.assertTrue(incompleteFlush.get()); - Assert.assertFalse(buffer1.hasRemaining()); + assertTrue(incompleteFlush.get()); + assertFalse(buffer1.hasRemaining()); // Reuse buffer1 buffer1.clear(); @@ -341,10 +326,10 @@ public class WriteFlusherTest flusher.completeWrite(); // Make sure buffer1 is unchanged - Assert.assertEquals(remaining1, buffer1.remaining()); + assertEquals(remaining1, buffer1.remaining()); } - @Test(expected = WritePendingException.class) + @Test public void testConcurrentWrites() throws Exception { ByteArrayEndPoint endPoint = new ByteArrayEndPoint(new byte[0], 16); @@ -375,39 +360,45 @@ public class WriteFlusherTest // Two concurrent writes. new Thread(() -> flusher.write(Callback.NOOP, BufferUtil.toBuffer("foo"))).start(); - Assert.assertTrue(flushLatch.await(1, TimeUnit.SECONDS)); - // The second write throws WritePendingException. - flusher.write(Callback.NOOP, BufferUtil.toBuffer("bar")); + assertTrue(flushLatch.await(1, TimeUnit.SECONDS)); + + assertThrows(WritePendingException.class, ()->{ + // The second write throws WritePendingException. + flusher.write(Callback.NOOP, BufferUtil.toBuffer("bar")); + }); } - @Test(expected = ExecutionException.class) + @Test public void testConcurrentWriteAndOnFail() throws Exception { - ByteArrayEndPoint endPoint = new ByteArrayEndPoint(new byte[0], 16); + assertThrows( ExecutionException.class , () -> { + ByteArrayEndPoint endPoint = new ByteArrayEndPoint( new byte[0], 16 ); - WriteFlusher flusher = new WriteFlusher(endPoint) - { - @Override - protected ByteBuffer[] flush(ByteBuffer[] buffers) throws IOException + WriteFlusher flusher = new WriteFlusher( endPoint ) { - ByteBuffer[] result = super.flush(buffers); - boolean notified = onFail(new Throwable()); - Assert.assertTrue(notified); - return result; - } + @Override + protected ByteBuffer[] flush( ByteBuffer[] buffers ) + throws IOException + { + ByteBuffer[] result = super.flush( buffers ); + boolean notified = onFail( new Throwable() ); + assertTrue( notified ); + return result; + } - @Override - protected void onIncompleteFlush() - { - } - }; + @Override + protected void onIncompleteFlush() + { + } + }; - FutureCallback callback = new FutureCallback(); - flusher.write(callback, BufferUtil.toBuffer("foo")); + FutureCallback callback = new FutureCallback(); + flusher.write( callback, BufferUtil.toBuffer( "foo" ) ); - Assert.assertTrue(flusher.isFailed()); + assertTrue( flusher.isFailed() ); - callback.get(1, TimeUnit.SECONDS); + callback.get( 1, TimeUnit.SECONDS ); + }); } @Test @@ -437,7 +428,7 @@ public class WriteFlusherTest } catch (ExecutionException x) { - Assert.assertEquals(reason, x.getCause().getMessage()); + assertEquals(reason, x.getCause().getMessage()); } } diff --git a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java index 62261b02201..b4318dc03a6 100644 --- a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java +++ b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLdapLoginServiceTest.java @@ -31,6 +31,7 @@ import org.eclipse.jetty.security.DefaultIdentityService; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.UserIdentity; import org.junit.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.runner.RunWith; import javax.security.auth.login.AppConfigurationEntry; diff --git a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java index a9a62c11977..b247eeb1344 100644 --- a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java +++ b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/JAASLoginServiceTest.java @@ -19,8 +19,8 @@ package org.eclipse.jetty.jaas; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.security.Principal; import java.util.Collections; @@ -32,12 +32,10 @@ import javax.security.auth.login.Configuration; import org.eclipse.jetty.security.DefaultIdentityService; import org.eclipse.jetty.server.Request; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * JAASLoginServiceTest - * - * */ public class JAASLoginServiceTest { diff --git a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java index 5c898efa207..593d1530084 100644 --- a/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java +++ b/jetty-jaas/src/test/java/org/eclipse/jetty/jaas/TestLoginModule.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.jaas; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import javax.security.auth.callback.Callback; import javax.security.auth.login.LoginException; diff --git a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java index 3f0d41c33be..e874681a291 100644 --- a/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java +++ b/jetty-jaspi/src/test/java/org/eclipse/jetty/security/jaspi/JaspiTest.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.security.jaspi; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.util.HashMap; @@ -43,9 +43,9 @@ import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Credential; import org.eclipse.jetty.util.security.Password; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class JaspiTest { @@ -89,7 +89,7 @@ public class JaspiTest } } - @Before + @BeforeEach public void before() throws Exception { System.setProperty("org.apache.geronimo.jaspic.configurationFile","src/test/resources/jaspi.xml"); @@ -138,7 +138,7 @@ public class JaspiTest _server.start(); } - @After + @AfterEach public void after() throws Exception { _server.stop(); diff --git a/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java b/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java index 8c985728875..63136a3b57b 100644 --- a/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java +++ b/jetty-jmh/src/main/java/org/eclipse/jetty/http/jmh/MultiPartBenchmark.java @@ -18,22 +18,8 @@ package org.eclipse.jetty.http.jmh; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; - -import javax.servlet.MultipartConfigElement; -import javax.servlet.http.Part; - -import org.eclipse.jetty.http.MultiPartFormInputStream; import org.eclipse.jetty.http.MultiPartCaptureTest.MultipartExpectations; +import org.eclipse.jetty.http.MultiPartFormInputStream; import org.eclipse.jetty.toolchain.test.IO; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; @@ -52,13 +38,25 @@ import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; +import javax.servlet.MultipartConfigElement; +import javax.servlet.http.Part; +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; + @State(Scope.Benchmark) @Threads(4) @Warmup(iterations = 7, time = 500, timeUnit = TimeUnit.MILLISECONDS) @Measurement(iterations = 7, time = 500, timeUnit = TimeUnit.MILLISECONDS) public class MultiPartBenchmark { - public static final int MAX_FILE_SIZE = Integer.MAX_VALUE; public static final int MAX_REQUEST_SIZE = Integer.MAX_VALUE; public static final int FILE_SIZE_THRESHOLD = 50; diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java index b25571da3c9..c007488b3de 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ConnectorServerTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.jmx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.net.ConnectException; import java.net.InetAddress; import java.net.ServerSocket; @@ -32,10 +36,9 @@ import javax.rmi.ssl.SslRMIClientSocketFactory; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Running the tests of this class in the same JVM results often in @@ -49,13 +52,13 @@ import org.junit.Test; * Running each test method in a forked JVM makes these tests all pass, * therefore the issue is likely caused by use of stale stubs cached by the JDK. */ -@Ignore +@Disabled public class ConnectorServerTest { private String objectName = "org.eclipse.jetty:name=rmiconnectorserver"; private ConnectorServer connectorServer; - @After + @AfterEach public void tearDown() throws Exception { if (connectorServer != null) @@ -69,7 +72,7 @@ public class ConnectorServerTest connectorServer.start(); JMXServiceURL address = connectorServer.getAddress(); - Assert.assertTrue(address.toString().matches("service:jmx:rmi://[^:]+:\\d+/jndi/rmi://[^:]+:\\d+/jmxrmi")); + assertTrue(address.toString().matches("service:jmx:rmi://[^:]+:\\d+/jndi/rmi://[^:]+:\\d+/jmxrmi")); } @Test @@ -80,16 +83,10 @@ public class ConnectorServerTest // Verify that I can connect to the RMI registry using a non-loopback address. new Socket(InetAddress.getLocalHost(), 1099).close(); - try - { + assertThrows(ConnectException.class, ()->{ // Verify that I cannot connect to the RMI registry using the loopback address. new Socket(InetAddress.getLoopbackAddress(), 1099).close(); - Assert.fail(); - } - catch (ConnectException ignored) - { - // Ignored. - } + }); } @Test @@ -103,16 +100,10 @@ public class ConnectorServerTest // Verify that I can connect to the RMI registry using a non-loopback address. new Socket(InetAddress.getLocalHost(), registryPort).close(); - try - { + assertThrows(ConnectException.class, ()->{ // Verify that I cannot connect to the RMI registry using the loopback address. new Socket(InetAddress.getLoopbackAddress(), registryPort).close(); - Assert.fail(); - } - catch (ConnectException ignored) - { - // Ignored. - } + }); } @Test @@ -139,16 +130,10 @@ public class ConnectorServerTest InetAddress localHost = InetAddress.getLocalHost(); if (!localHost.isLoopbackAddress()) { - try - { + assertThrows(ConnectException.class, ()->{ // Verify that I cannot connect to the RMIRegistry using a non-loopback address. new Socket(localHost, 1099); - Assert.fail(); - } - catch (ConnectException ignored) - { - // Ignored. - } + }); } InetAddress loopback = InetAddress.getLoopbackAddress(); @@ -163,16 +148,10 @@ public class ConnectorServerTest // Verify that I can connect to the RMI server using a non-loopback address. new Socket(InetAddress.getLocalHost(), connectorServer.getAddress().getPort()).close(); - try - { + assertThrows(ConnectException.class, ()->{ // Verify that I cannot connect to the RMI server using the loopback address. new Socket(InetAddress.getLoopbackAddress(), connectorServer.getAddress().getPort()).close(); - Assert.fail(); - } - catch (ConnectException ignored) - { - // Ignored. - } + }); } @Test @@ -197,16 +176,10 @@ public class ConnectorServerTest InetAddress localHost = InetAddress.getLocalHost(); if (!localHost.isLoopbackAddress()) { - try - { + assertThrows(ConnectException.class, ()->{ // Verify that I cannot connect to the RMIRegistry using a non-loopback address. new Socket(localHost, address.getPort()); - Assert.fail(); - } - catch (ConnectException ignored) - { - // Ignored. - } + }); } InetAddress loopback = InetAddress.getLoopbackAddress(); @@ -224,7 +197,7 @@ public class ConnectorServerTest connectorServer.start(); JMXServiceURL address = connectorServer.getAddress(); - Assert.assertEquals(port, address.getPort()); + assertEquals(port, address.getPort()); InetAddress loopback = InetAddress.getLoopbackAddress(); new Socket(loopback, port).close(); @@ -248,7 +221,7 @@ public class ConnectorServerTest connectorServer.start(); JMXServiceURL address = connectorServer.getAddress(); - Assert.assertEquals(port, address.getPort()); + assertEquals(port, address.getPort()); } @Test diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java index 37d542f82a6..889abadd909 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerLifeCycleTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.jmx; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.lang.management.ManagementFactory; import java.util.Set; @@ -26,17 +28,17 @@ import javax.management.ObjectName; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class MBeanContainerLifeCycleTest { private ContainerLifeCycle container; private MBeanServer mbeanServer; - @Before + @BeforeEach public void prepare() throws Exception { container = new ContainerLifeCycle(); @@ -46,7 +48,7 @@ public class MBeanContainerLifeCycleTest container.start(); } - @After + @AfterEach public void dispose() throws Exception { container.stop(); @@ -61,12 +63,12 @@ public class MBeanContainerLifeCycleTest String pkg = bean.getClass().getPackage().getName(); Set objectNames = mbeanServer.queryNames(ObjectName.getInstance(pkg + ":*"), null); - Assert.assertEquals(1, objectNames.size()); + assertEquals(1, objectNames.size()); // Removing the bean should unregister the MBean. container.removeBean(bean); objectNames = mbeanServer.queryNames(ObjectName.getInstance(pkg + ":*"), null); - Assert.assertEquals(0, objectNames.size()); + assertEquals(0, objectNames.size()); } @Test @@ -77,12 +79,12 @@ public class MBeanContainerLifeCycleTest String pkg = bean.getClass().getPackage().getName(); Set objectNames = mbeanServer.queryNames(ObjectName.getInstance(pkg + ":*"), null); - Assert.assertEquals(1, objectNames.size()); + assertEquals(1, objectNames.size()); container.stop(); objectNames = mbeanServer.queryNames(ObjectName.getInstance(pkg + ":*"), null); - Assert.assertEquals(1, objectNames.size()); + assertEquals(1, objectNames.size()); // Remove the MBeans to start clean on the next test. objectNames.forEach(objectName -> @@ -105,12 +107,12 @@ public class MBeanContainerLifeCycleTest String pkg = bean.getClass().getPackage().getName(); Set objectNames = mbeanServer.queryNames(ObjectName.getInstance(pkg + ":*"), null); - Assert.assertEquals(1, objectNames.size()); + assertEquals(1, objectNames.size()); container.stop(); container.destroy(); objectNames = mbeanServer.queryNames(ObjectName.getInstance(pkg + ":*"), null); - Assert.assertEquals(0, objectNames.size()); + assertEquals(0, objectNames.size()); } } diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java index 1b2ff10b775..ded64808426 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/MBeanContainerTest.java @@ -18,17 +18,23 @@ package org.eclipse.jetty.jmx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.acme.Managed; + import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.ObjectName; -import com.acme.Managed; import org.eclipse.jetty.util.component.Container; import org.eclipse.jetty.util.component.ContainerLifeCycle; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class MBeanContainerTest { @@ -38,7 +44,7 @@ public class MBeanContainerTest private Managed managed; private ObjectName objectName; - @Before + @BeforeEach public void setUp() { mbeanServer = ManagementFactory.getPlatformMBeanServer(); @@ -55,7 +61,7 @@ public class MBeanContainerTest beanName = mbeanContainer.makeName(beanName); // then - Assert.assertEquals("Bean name should be mngd_bean", "mngd_bean", beanName); + assertEquals("mngd_bean", beanName, "Bean name should be mngd_bean"); } @Test @@ -66,11 +72,11 @@ public class MBeanContainerTest // when objectName = mbeanContainer.findMBean(managed); - Assert.assertNotNull(objectName); + assertNotNull(objectName); // then - Assert.assertEquals("Bean must be added", managed, mbeanContainer.findBean(objectName)); - Assert.assertNull("It must return null as there is no bean with the name null", mbeanContainer.findBean(null)); + assertEquals(managed, mbeanContainer.findBean(objectName), "Bean must be added"); + assertNull(mbeanContainer.findBean(null), "It must return null as there is no bean with the name null"); } private Managed getManaged() @@ -86,13 +92,13 @@ public class MBeanContainerTest @Test public void testMBeanContainer() { - Assert.assertNotNull("Container shouldn't be null", mbeanContainer); + assertNotNull(mbeanContainer, "Container shouldn't be null"); } @Test public void testGetMBeanServer() { - Assert.assertEquals("MBean server Instance must be equal", mbeanServer, mbeanContainer.getMBeanServer()); + assertEquals(mbeanServer, mbeanContainer.getMBeanServer(), "MBean server Instance must be equal"); } @Test @@ -105,7 +111,7 @@ public class MBeanContainerTest mbeanContainer.setDomain(domain); // then - Assert.assertEquals("Domain name must be Test", domain, mbeanContainer.getDomain()); + assertEquals(domain, mbeanContainer.getDomain(), "Domain name must be Test"); } @Test @@ -118,7 +124,7 @@ public class MBeanContainerTest objectName = mbeanContainer.findMBean(managed); // then - Assert.assertTrue("Bean must have been registered", mbeanServer.isRegistered(objectName)); + assertTrue(mbeanServer.isRegistered(objectName), "Bean must have been registered"); } @Test @@ -132,7 +138,7 @@ public class MBeanContainerTest mbeanContainer.beanAdded(null, null); // then - Assert.assertEquals("MBean count must not change after beanAdded(null, null) call", mbeanCount, mbeanServer.getMBeanCount()); + assertEquals(mbeanCount, mbeanServer.getMBeanCount(), "MBean count must not change after beanAdded(null, null) call"); } private void setBeanAdded() @@ -153,7 +159,7 @@ public class MBeanContainerTest mbeanContainer.beanRemoved(null, managed); // then - Assert.assertNull("Bean shouldn't be registered with container as we removed the bean", mbeanContainer.findMBean(managed)); + assertNull(mbeanContainer.findMBean(managed), "Bean shouldn't be registered with container as we removed the bean"); } private void setUpBeanRemoved() @@ -174,7 +180,7 @@ public class MBeanContainerTest mbeanContainer.getMBeanServer().unregisterMBean(objectName); // then - Assert.assertFalse("Bean must not have been registered as we unregistered the bean", mbeanServer.isRegistered(objectName)); + assertFalse(mbeanServer.isRegistered(objectName), "Bean must not have been registered as we unregistered the bean"); // this flow covers InstanceNotFoundException. Actual code just eating // the exception. i.e Actual code just printing the stacktrace, whenever // an exception of type InstanceNotFoundException occurs. @@ -184,7 +190,7 @@ public class MBeanContainerTest @Test public void testDump() { - Assert.assertNotNull("Dump operation shouldn't return null if operation is success", mbeanContainer.dump()); + assertNotNull(mbeanContainer.dump(), "Dump operation shouldn't return null if operation is success"); } private void setUpDestroy() @@ -204,7 +210,7 @@ public class MBeanContainerTest mbeanContainer.destroy(); // then - Assert.assertFalse("Unregistered bean - managed", mbeanContainer.getMBeanServer().isRegistered(objectName)); + assertFalse(mbeanContainer.getMBeanServer().isRegistered(objectName), "Unregistered bean - managed"); } @Test @@ -218,7 +224,7 @@ public class MBeanContainerTest mbeanContainer.getMBeanServer().unregisterMBean(objectName); // then - Assert.assertFalse("Unregistered bean - managed", mbeanContainer.getMBeanServer().isRegistered(objectName)); + assertFalse(mbeanContainer.getMBeanServer().isRegistered(objectName), "Unregistered bean - managed"); // this flow covers InstanceNotFoundException. Actual code just eating // the exception. i.e Actual code just printing the stacktrace, whenever // an exception of type InstanceNotFoundException occurs. @@ -252,6 +258,6 @@ public class MBeanContainerTest parent.removeBean(child); - Assert.assertNotNull(mbeanContainer.findMBean(lifeCycle)); + assertNotNull(mbeanContainer.findMBean(lifeCycle)); } } diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java index b4ca2b47fee..0c0b9f95223 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanTest.java @@ -18,6 +18,12 @@ package org.eclipse.jetty.jmx; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.acme.Derived; + import java.lang.management.ManagementFactory; import javax.management.Attribute; @@ -28,13 +34,10 @@ import javax.management.MBeanParameterInfo; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import com.acme.Derived; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class ObjectMBeanTest { @@ -42,13 +45,13 @@ public class ObjectMBeanTest private static MBeanContainer container; - @Before + @BeforeEach public void before() throws Exception { container = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); } - @After + @AfterEach public void after() throws Exception { container.destroy(); @@ -73,12 +76,12 @@ public class ObjectMBeanTest MBeanInfo toss = managed.getMBeanInfo(); - Assert.assertNotNull(mbean.getMBeanInfo()); + assertNotNull(mbean.getMBeanInfo()); MBeanInfo info = mbean.getMBeanInfo(); - Assert.assertEquals("name does not match","com.acme.Derived",info.getClassName()); - Assert.assertEquals("description does not match","Test the mbean stuff",info.getDescription()); + assertEquals("com.acme.Derived", info.getClassName(), "name does not match"); + assertEquals("Test the mbean stuff", info.getDescription(), "description does not match"); // for ( MBeanAttributeInfo i : info.getAttributes()) // { @@ -88,15 +91,15 @@ public class ObjectMBeanTest /* * 2 attributes from lifecycle and 2 from Derived and 1 from MBean */ - Assert.assertEquals("attribute count does not match",6,info.getAttributes().length); + assertEquals(6, info.getAttributes().length, "attribute count does not match"); - Assert.assertEquals("attribute values does not match","Full Name",mbean.getAttribute("fname")); + assertEquals("Full Name", mbean.getAttribute("fname"), "attribute values does not match"); mbean.setAttribute(new Attribute("fname","Fuller Name")); - Assert.assertEquals("set attribute value does not match","Fuller Name",mbean.getAttribute("fname")); + assertEquals("Fuller Name", mbean.getAttribute("fname"), "set attribute value does not match"); - Assert.assertEquals("proxy attribute values do not match","goop",mbean.getAttribute("goop")); + assertEquals("goop", mbean.getAttribute("goop"), "proxy attribute values do not match"); // Thread.sleep(100000); } @@ -113,7 +116,7 @@ public class ObjectMBeanTest MBeanInfo info = mbean.getMBeanInfo(); - Assert.assertEquals("operation count does not match",5,info.getOperations().length); + assertEquals(5, info.getOperations().length, "operation count does not match"); MBeanOperationInfo[] opinfos = info.getOperations(); boolean publish = false; @@ -126,18 +129,18 @@ public class ObjectMBeanTest if ("publish".equals(opinfo.getName())) { publish = true; - Assert.assertEquals("description doesn't match","publish something",opinfo.getDescription()); + assertEquals("publish something", opinfo.getDescription(), "description doesn't match"); } if ("doodle".equals(opinfo.getName())) { doodle = true; - Assert.assertEquals("description doesn't match","Doodle something",opinfo.getDescription()); + assertEquals("Doodle something", opinfo.getDescription(), "description doesn't match"); MBeanParameterInfo[] pinfos = opinfo.getSignature(); - Assert.assertEquals("parameter description doesn't match","A description of the argument",pinfos[0].getDescription()); - Assert.assertEquals("parameter name doesn't match","doodle",pinfos[0].getName()); + assertEquals("A description of the argument", pinfos[0].getDescription(), "parameter description doesn't match"); + assertEquals("doodle", pinfos[0].getName(), "parameter name doesn't match"); } // This is a proxied operation on the JMX wrapper @@ -145,14 +148,14 @@ public class ObjectMBeanTest { good = true; - Assert.assertEquals("description does not match","test of proxy operations",opinfo.getDescription()); - Assert.assertEquals("execution contexts wrong","not bad",mbean.invoke("good",new Object[] {},new String[] {})); + assertEquals("test of proxy operations", opinfo.getDescription(), "description does not match"); + assertEquals("not bad",mbean.invoke("good",new Object[] {}, new String[] {}), "execution contexts wrong"); } } - Assert.assertTrue("publish operation was not not found",publish); - Assert.assertTrue("doodle operation was not not found",doodle); - Assert.assertTrue("good operation was not not found",good); + assertTrue(publish, "publish operation was not not found"); + assertTrue(doodle, "doodle operation was not not found"); + assertTrue(good, "good operation was not not found"); } @@ -166,7 +169,7 @@ public class ObjectMBeanTest mbean.setMBeanContainer(container); managed.setMBeanContainer(container); - Assert.assertNotNull(mbean.getMBeanInfo()); + assertNotNull(mbean.getMBeanInfo()); container.beanAdded(null,derived); container.beanAdded(null,derived.getManagedInstance()); @@ -174,13 +177,13 @@ public class ObjectMBeanTest container.beanAdded(null,managed); // Managed managedInstance = (Managed)mbean.getAttribute("managedInstance"); - // Assert.assertNotNull(managedInstance); - // Assert.assertEquals("managed instance returning nonsense", "foo", managedInstance.getManaged()); + // assertNotNull(managedInstance); + // assertEquals("foo", managedInstance.getManaged(), "managed instance returning nonsense"); } @Test - @Ignore("ignore, used in testing jconsole atm") + @Disabled("ignore, used in testing jconsole atm") public void testThreadPool() throws Exception { @@ -212,14 +215,14 @@ public class ObjectMBeanTest { ObjectMBean mbean = new ObjectMBean(new Derived()); - Assert.assertEquals("fullName",mbean.toVariableName("getFullName")); - Assert.assertEquals("fullName",mbean.toVariableName("getfullName")); - Assert.assertEquals("fullName",mbean.toVariableName("isFullName")); - Assert.assertEquals("fullName",mbean.toVariableName("isfullName")); - Assert.assertEquals("fullName",mbean.toVariableName("setFullName")); - Assert.assertEquals("fullName",mbean.toVariableName("setfullName")); - Assert.assertEquals("fullName",mbean.toVariableName("FullName")); - Assert.assertEquals("fullName",mbean.toVariableName("fullName")); + assertEquals("fullName",mbean.toVariableName("getFullName")); + assertEquals("fullName",mbean.toVariableName("getfullName")); + assertEquals("fullName",mbean.toVariableName("isFullName")); + assertEquals("fullName",mbean.toVariableName("isfullName")); + assertEquals("fullName",mbean.toVariableName("setFullName")); + assertEquals("fullName",mbean.toVariableName("setfullName")); + assertEquals("fullName",mbean.toVariableName("FullName")); + assertEquals("fullName",mbean.toVariableName("fullName")); } } diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java index b11f76120ad..16c3c313a5d 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/ObjectMBeanUtilTest.java @@ -18,10 +18,9 @@ package org.eclipse.jetty.jmx; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import com.acme.Derived; +import com.acme.DerivedExtended; +import com.acme.DerivedManaged; import java.lang.management.ManagementFactory; import java.util.ArrayList; @@ -37,14 +36,12 @@ import javax.management.ReflectionException; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.StdErrLog; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import com.acme.Derived; -import com.acme.DerivedExtended; -import com.acme.DerivedManaged; +import static org.junit.jupiter.api.Assertions.*; public class ObjectMBeanUtilTest { @@ -75,7 +72,7 @@ public class ObjectMBeanUtilTest private static final int EMPTY = 0; - @BeforeClass + @BeforeAll public static void beforeClass() { Logger ombLog = Log.getLogger(ObjectMBean.class); @@ -83,7 +80,7 @@ public class ObjectMBeanUtilTest ((StdErrLog)ombLog).setHideStacks(true); } - @AfterClass + @AfterAll public static void afterClass() { Logger ombLog = Log.getLogger(ObjectMBean.class); @@ -91,7 +88,7 @@ public class ObjectMBeanUtilTest ((StdErrLog)ombLog).setHideStacks(false); } - @Before + @BeforeEach public void setUp() { derivedExtended = new DerivedExtended(); @@ -104,12 +101,12 @@ public class ObjectMBeanUtilTest @Test public void testBasicOperations() { - assertEquals("Managed objects should be equal",derivedExtended,objectMBean.getManagedObject()); - assertNull("This method call always returns null in the actual code",objectMBean.getObjectName()); - assertNull("This method call always returns null in the actual code",objectMBean.getObjectNameBasis()); - assertNull("This method call always returns null in the actual code",objectMBean.getObjectContextBasis()); - assertEquals("Mbean container should be equal",container,objectMBean.getMBeanContainer()); - assertEquals("Mbean description must be equal to : Test the mbean extended stuff","Test the mbean extended stuff",objectMBeanInfo.getDescription()); + assertEquals(derivedExtended, objectMBean.getManagedObject(), "Managed objects should be equal"); + assertNull(objectMBean.getObjectName(), "This method call always returns null in the actual code"); + assertNull(objectMBean.getObjectNameBasis(), "This method call always returns null in the actual code"); + assertNull(objectMBean.getObjectContextBasis(), "This method call always returns null in the actual code"); + assertEquals(container, objectMBean.getMBeanContainer(), "Mbean container should be equal"); + assertEquals("Test the mbean extended stuff", objectMBeanInfo.getDescription(), "Mbean description must be equal to : Test the mbean extended stuff"); } @Test @@ -119,20 +116,22 @@ public class ObjectMBeanUtilTest mBean = ObjectMBean.mbeanFor(null); // then - assertNull("As we are passing null value the output should be null",mBean); + assertNull(mBean, "As we are passing null value the output should be null"); } - @Test(expected = ReflectionException.class) + @Test public void testGetAttributeReflectionException() throws Exception { // given setUpGetAttribute("doodle4","charu"); // when - objectMBean.getAttribute("doodle4"); + ReflectionException e = assertThrows(ReflectionException.class, ()-> { + objectMBean.getAttribute("doodle4"); + }); // then - fail("An InvocationTargetException must have occurred by now as doodle4() internally throwing exception"); + assertNotNull(e, "An InvocationTargetException must have occurred by now as doodle4() internally throwing exception"); } private void setUpGetAttribute(String property, String value) throws Exception @@ -141,14 +140,16 @@ public class ObjectMBeanUtilTest objectMBean.setAttribute(attribute); } - @Test(expected = AttributeNotFoundException.class) + @Test public void testGetAttributeAttributeNotFoundException() throws Exception { // when - objectMBean.getAttribute("ffname"); + AttributeNotFoundException e = assertThrows(AttributeNotFoundException.class, ()->{ + objectMBean.getAttribute("ffname"); + }); // then - fail("An AttributeNotFoundException must have occurred by now as there is no " + "attribute with the name ffname in bean"); + assertNotNull(e, "An AttributeNotFoundException must have occurred by now as there is no " + "attribute with the name ffname in bean"); } @Test @@ -161,33 +162,37 @@ public class ObjectMBeanUtilTest value = (String)objectMBean.getAttribute("fname"); // then - assertEquals("Attribute(fname) value must be equl to charu","charu",value); + assertEquals("charu", value, "Attribute(fname) value must be equl to charu"); } - @Test(expected = AttributeNotFoundException.class) + @Test public void testSetAttributeNullCheck() throws Exception { // given objectMBean.setAttribute(null); // when - objectMBean.getAttribute(null); + AttributeNotFoundException e = assertThrows(AttributeNotFoundException.class, ()->{ + objectMBean.getAttribute(null); + }); // then - fail("An AttributeNotFoundException must have occurred by now as there is no attribute with the name null"); + assertNotNull(e,"An AttributeNotFoundException must have occurred by now as there is no attribute with the name null"); } - @Test(expected = AttributeNotFoundException.class) + @Test public void testSetAttributeAttributeWithWrongAttrName() throws Exception { // given attribute = new Attribute("fnameee","charu"); // when - objectMBean.setAttribute(attribute); + AttributeNotFoundException e = assertThrows(AttributeNotFoundException.class, ()->{ + objectMBean.setAttribute(attribute); + }); // then - fail("An AttributeNotFoundException must have occurred by now as there is no attribute " + "with the name ffname in bean"); + assertNotNull(e, "An AttributeNotFoundException must have occurred by now as there is no attribute " + "with the name ffname in bean"); } @Test @@ -202,7 +207,7 @@ public class ObjectMBeanUtilTest { "fname" }); // then - assertEquals("Fname value must be equal to vijay","vijay",((Attribute)(attributes.get(0))).getValue()); + assertEquals("vijay", ((Attribute)(attributes.get(0))).getValue(), "Fname value must be equal to vijay"); } @Test @@ -216,7 +221,7 @@ public class ObjectMBeanUtilTest mBeanDerivedManaged.getMBeanInfo(); // then - assertNotNull("Address object shouldn't be null",mBeanDerivedManaged.getAttribute("addresses")); + assertNotNull(mBeanDerivedManaged.getAttribute("addresses"), "Address object shouldn't be null"); } @Test @@ -230,8 +235,8 @@ public class ObjectMBeanUtilTest mBeanDerivedManaged.getMBeanInfo(); // then - assertNotNull("Address object shouldn't be null",mBeanDerivedManaged.getAttribute("aliasNames")); - assertNull("Derived object shouldn't be registered with container so its value will be null",mBeanDerivedManaged.getAttribute("derived")); + assertNotNull(mBeanDerivedManaged.getAttribute("aliasNames"), "Address object shouldn't be null"); + assertNull(mBeanDerivedManaged.getAttribute("derived"), "Derived object shouldn't registerd with container so its value will be null"); } private Derived[] getArrayTypeAttribute() @@ -271,7 +276,7 @@ public class ObjectMBeanUtilTest // then // Original code eating the exception and returning zero size list - assertEquals("As there is no attribute with the name fnameee, this should return empty",EMPTY,attributes.size()); + assertEquals(EMPTY,attributes.size(),"As there is no attribute with the name fnameee, this should return empty"); } private AttributeList getAttributes(String name, String value) @@ -282,30 +287,34 @@ public class ObjectMBeanUtilTest return attributes; } - @Test(expected = MBeanException.class) + @Test public void testInvokeMBeanException() throws Exception { // given setMBeanInfoForInvoke(); // when - objectMBean.invoke("doodle2",new Object[] {},new String[] {}); + MBeanException e = assertThrows(MBeanException.class, ()->{ + objectMBean.invoke("doodle2",new Object[] {},new String[] {}); + }); // then - fail("An MBeanException must have occurred by now as doodle2() in Derived bean throwing exception"); + assertNotNull(e, "An MBeanException must have occurred by now as doodle2() in Derived bean throwing exception"); } - @Test(expected = ReflectionException.class) + @Test public void testInvokeReflectionException() throws Exception { // given setMBeanInfoForInvoke(); // when - objectMBean.invoke("doodle1",new Object[] {},new String[] {}); + ReflectionException e = assertThrows(ReflectionException.class, ()->{ + objectMBean.invoke("doodle1",new Object[] {},new String[] {}); + }); // then - fail("An ReflectionException must have occurred by now as doodle1() has private access in Derived bean"); + assertNotNull(e, "ReflectionException is null"); } @Test @@ -318,10 +327,10 @@ public class ObjectMBeanUtilTest value = (String)objectMBean.invoke("good",new Object[] {},new String[] {}); // then - assertEquals("Method(good) invocation on objectMBean must return not bad","not bad",value); + assertEquals("not bad", value, "Method(good) invocation on objectMBean must return not bad"); } - @Test(expected = ReflectionException.class) + @Test public void testInvokeNoSuchMethodException() throws Exception { // given @@ -330,11 +339,14 @@ public class ObjectMBeanUtilTest // when // DerivedMBean contains a managed method with the name good,we must // call this method without any arguments - objectMBean.invoke("good",new Object[] {},new String[] - { "int aone" }); + ReflectionException e = assertThrows(ReflectionException.class, ()->{ + objectMBean.invoke("good",new Object[] {},new String[] + { "int aone" }); + }); // then - fail("An ReflectionException must have occurred by now as we cannot call a methow with wrong signature"); + assertNotNull(e, "An ReflectionException must have occurred by now as we cannot call a methow with wrong signature"); + } private void setMBeanInfoForInvoke() diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/PojoTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/PojoTest.java index ccf8c93cd30..3ea782d22ff 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/PojoTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/jmx/PojoTest.java @@ -21,7 +21,7 @@ package org.eclipse.jetty.jmx; import java.util.Arrays; import java.util.List; import org.eclipse.jetty.util.log.jmx.LogMBean; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.openpojo.reflection.impl.PojoClassFactory; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; diff --git a/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java b/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java index 0fa9adfd3d0..32518893349 100644 --- a/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java +++ b/jetty-jmx/src/test/java/org/eclipse/jetty/util/log/jmx/LogMBeanTest.java @@ -18,12 +18,16 @@ package org.eclipse.jetty.util.log.jmx; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import org.junit.Before; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.acme.Managed; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + public class LogMBeanTest { @@ -33,7 +37,7 @@ public class LogMBeanTest private static final String MANAGED_CLASS = "Managed"; - @Before + @BeforeEach public void setUp() { managed = new Managed(); @@ -44,13 +48,13 @@ public class LogMBeanTest public void testKeySet() { // given - assertFalse("Managed is not registered with loggers",logMBean.getLoggers().contains(MANAGED_CLASS)); + assertThat("Managed is not registered with loggers", MANAGED_CLASS, not(isIn(logMBean.getLoggers()))); // when logMBean.setDebugEnabled(MANAGED_CLASS,true); // then - assertTrue("Managed must be registered with loggers",logMBean.getLoggers().contains(MANAGED_CLASS)); - assertTrue("This must return true as debug is enabled for this class",logMBean.isDebugEnabled(MANAGED_CLASS)); + assertThat("Managed must be registered with loggers", MANAGED_CLASS, isIn(logMBean.getLoggers())); + assertTrue(logMBean.isDebugEnabled(MANAGED_CLASS), "This must return true as debug is enabled for this class"); } } diff --git a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java index 94bfa616a50..96cc462e846 100644 --- a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java +++ b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/factories/TestMailSessionReference.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.jndi.factories; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Properties; @@ -32,7 +32,7 @@ import javax.naming.Name; import javax.naming.NameParser; import org.eclipse.jetty.jndi.NamingUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * diff --git a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java index ba553ae0851..791d1a4630e 100644 --- a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java +++ b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestJNDI.java @@ -18,10 +18,10 @@ package org.eclipse.jetty.jndi.java; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.net.URL; import java.net.URLClassLoader; @@ -49,7 +49,7 @@ import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * */ diff --git a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java index 938c3319a88..238fffac914 100644 --- a/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java +++ b/jetty-jndi/src/test/java/org/eclipse/jetty/jndi/java/TestLocalJNDI.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.jndi.java; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import java.util.Hashtable; @@ -37,8 +37,8 @@ import javax.naming.StringRefAddr; import javax.naming.spi.ObjectFactory; import org.eclipse.jetty.jndi.NamingUtil; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * @@ -108,7 +108,7 @@ public class TestLocalJNDI - @After + @AfterEach public void tearDown() throws Exception { InitialContext ic = new InitialContext(); diff --git a/jetty-jspc-maven-plugin/pom.xml b/jetty-jspc-maven-plugin/pom.xml index 67ec5919e19..ee3fc8c778a 100644 --- a/jetty-jspc-maven-plugin/pom.xml +++ b/jetty-jspc-maven-plugin/pom.xml @@ -67,7 +67,7 @@ ${project.build.directory}/local-repo src/it/settings.xml - ${surefireVersion} + ${surefire.version} ${skipTests} diff --git a/jetty-maven-plugin/pom.xml b/jetty-maven-plugin/pom.xml index 021953379d3..5bf00e0b4f3 100644 --- a/jetty-maven-plugin/pom.xml +++ b/jetty-maven-plugin/pom.xml @@ -79,7 +79,7 @@ ${jetty.stopKey} ${jetty.stopPort} - ${surefireVersion} + ${surefire.version} ${skipTests} diff --git a/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml b/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml index 81770894004..d0ec9a3b7d5 100644 --- a/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-cdi-run-forked/pom.xml @@ -63,7 +63,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml b/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml index 409b362e117..922f4e294b5 100644 --- a/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-deploy-war-mojo-it/pom.xml @@ -46,7 +46,7 @@ org.apache.maven.plugins maven-failsafe-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml index 827f8c9db6f..4bc1474abf3 100644 --- a/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-distro-mojo-it/jetty-simple-webapp/pom.xml @@ -67,7 +67,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml index 9f97a329e02..b9abdc035c9 100644 --- a/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-forked-mojo-it/jetty-simple-webapp/pom.xml @@ -69,7 +69,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml index 6a303b7d4a5..ad1069296e6 100644 --- a/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-mojo-it/jetty-simple-webapp/pom.xml @@ -70,7 +70,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml index c358b071e51..456c2232cde 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-exploded-mojo-it/jetty-simple-webapp/pom.xml @@ -67,7 +67,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ true @@ -75,7 +75,7 @@ org.apache.maven.plugins maven-failsafe-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml index ca935f11364..7bb4e40d157 100644 --- a/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-run-war-mojo-it/jetty-simple-webapp/pom.xml @@ -68,7 +68,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ true @@ -76,7 +76,7 @@ org.apache.maven.plugins maven-failsafe-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml index c269c46875b..4aa97fefa17 100644 --- a/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml +++ b/jetty-maven-plugin/src/it/jetty-start-mojo-it/jetty-simple-webapp/pom.xml @@ -66,7 +66,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/pom.xml b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/pom.xml index b921256af07..be6cd2f74e0 100644 --- a/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/pom.xml +++ b/jetty-maven-plugin/src/it/run-mojo-gwt-it/beer-server/pom.xml @@ -76,7 +76,7 @@ org.apache.maven.plugins maven-surefire-plugin - @surefireVersion@ + @surefire.version@ ${jetty.port.file} diff --git a/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java b/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java index 69e14b3f755..5c74d08c79f 100644 --- a/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java +++ b/jetty-maven-plugin/src/test/java/org/eclipse/jetty/maven/plugin/it/TestGetContent.java @@ -18,10 +18,9 @@ package org.eclipse.jetty.maven.plugin.it; -import org.apache.commons.lang3.StringUtils; -import org.eclipse.jetty.client.HttpClient; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.LineNumberReader; import java.io.Reader; @@ -29,6 +28,10 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jetty.client.HttpClient; +import org.junit.jupiter.api.Test; + /** * */ @@ -39,7 +42,7 @@ public class TestGetContent throws Exception { int port = getPort(); - Assert.assertTrue( port > 0 ); + assertTrue( port > 0 ); HttpClient httpClient = new HttpClient(); try { @@ -48,24 +51,23 @@ public class TestGetContent if (Boolean.getBoolean( "helloServlet" )) { String response = httpClient.GET( "http://localhost:" + port + "/hello?name=beer" ).getContentAsString(); - Assert.assertEquals( "Hello beer", response.trim() ); + assertEquals( "Hello beer", response.trim() ); response = httpClient.GET( "http://localhost:" + port + "/hello?name=foo" ).getContentAsString(); - Assert.assertEquals( "Hello foo", response.trim() ); + assertEquals( "Hello foo", response.trim() ); System.out.println( "helloServlet" ); } if (Boolean.getBoolean( "pingServlet" )) { System.out.println( "pingServlet ok" ); String response = httpClient.GET( "http://localhost:" + port + "/ping?name=beer" ).getContentAsString(); - Assert.assertEquals( "pong beer", response.trim() ); + assertEquals( "pong beer", response.trim() ); System.out.println( "pingServlet" ); } String contentCheck = System.getProperty( "contentCheck" ); if(StringUtils.isNotBlank( contentCheck ) ) { String response = httpClient.GET( "http://localhost:" + port ).getContentAsString(); - Assert.assertTrue( "response not contentCheck: " + contentCheck + ", response:" + response, // - response.contains( contentCheck ) ); + assertTrue(response.contains(contentCheck), "response not contentCheck: " + contentCheck + ", response:" + response); System.out.println( "contentCheck" ); } } @@ -82,7 +84,7 @@ public class TestGetContent int attempts = 70; int port = -1; String s = System.getProperty( "jetty.port.file" ); - Assert.assertNotNull( s ); + assertNotNull( s ); Path p = Paths.get( s ); while ( true ) { @@ -91,7 +93,7 @@ public class TestGetContent try (Reader r = Files.newBufferedReader( p ); LineNumberReader lnr = new LineNumberReader( r );) { s = lnr.readLine(); - Assert.assertNotNull( s ); + assertNotNull( s ); port = Integer.parseInt( s.trim() ); } break; diff --git a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java index 514acd9b27b..6f640e4bf2b 100644 --- a/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java +++ b/jetty-memcached/jetty-memcached-sessions/src/test/java/org/eclipse/jetty/memcached/session/TestMemcachedSessions.java @@ -20,9 +20,9 @@ package org.eclipse.jetty.memcached.session; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.PrintWriter; @@ -46,7 +46,7 @@ import org.eclipse.jetty.server.session.SessionData; import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * TestMemcachedSessions diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java index e3956bec807..cbea7817258 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/SimpleJavaxWebSocket.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.osgi.test; - import static org.junit.Assert.fail; import java.util.concurrent.CountDownLatch; diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2.java index 6694a4cedf6..bb6152af2e5 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootHTTP2.java @@ -20,6 +20,7 @@ package org.eclipse.jetty.osgi.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.systemProperty; @@ -35,11 +36,11 @@ import javax.inject.Inject; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; +import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http2.client.HTTP2Client; import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -121,8 +122,8 @@ public class TestJettyOSGiBootHTTP2 public void checkALPNBootOnBootstrapClasspath() throws Exception { Class alpn = Thread.currentThread().getContextClassLoader().loadClass("org.eclipse.jetty.alpn.ALPN"); - Assert.assertNotNull(alpn); - Assert.assertNull(alpn.getClassLoader()); + assertNotNull(alpn); + assertNull(alpn.getClassLoader()); } @Ignore @@ -170,9 +171,9 @@ public class TestJettyOSGiBootHTTP2 httpClient.start(); ContentResponse response = httpClient.GET("https://localhost:"+port+"/jsp/jstl.jsp"); - assertEquals(200, response.getStatus()); - assertTrue(response.getContentAsString().contains("JSTL Example")); - + assertEquals(response.toString(), response.getStatus(), HttpStatus.OK_200); + String body = response.getContentAsString(); + assertTrue("Body contains \"JSTL Example\": " + body, body.contains("JSTL Example")); } finally { diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootWithJavaxWebSocket.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootWithJavaxWebSocket.java index 7d835eb8f3e..2f26120da88 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootWithJavaxWebSocket.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestJettyOSGiBootWithJavaxWebSocket.java @@ -53,7 +53,6 @@ import aQute.bnd.osgi.Constants; * Test using websocket in osgi */ @RunWith(PaxExam.class) - public class TestJettyOSGiBootWithJavaxWebSocket { private static final String LOG_LEVEL = "WARN"; diff --git a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java index 3cf668e0819..e30a2e81950 100644 --- a/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java +++ b/jetty-osgi/test-jetty-osgi/src/test/java/org/eclipse/jetty/osgi/test/TestOSGiUtil.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.osgi.test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.systemProperty; @@ -37,10 +41,10 @@ import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.osgi.boot.OSGiServerConstants; -import org.eclipse.jetty.toolchain.test.OS; +import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Assert; + import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.osgi.framework.Bundle; @@ -56,7 +60,7 @@ public class TestOSGiUtil public static List + + org.eclipse.jetty + jetty-http + ${project.version} + tests + test + org.eclipse.jetty.toolchain jetty-test-helper diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/AliasedConstraintTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/AliasedConstraintTest.java index da4d6d2e68e..562d5bd85e8 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/AliasedConstraintTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/AliasedConstraintTest.java @@ -18,16 +18,16 @@ package org.eclipse.jetty.security; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; -import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Stream; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Connector; @@ -42,20 +42,17 @@ import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Password; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Some requests for static data that is served by ResourceHandler, but some is secured. *

* This is mainly here to test security bypass techniques using aliased names that should be caught. */ -@RunWith(Parameterized.class) public class AliasedConstraintTest { private static final String TEST_REALM = "TestRealm"; @@ -63,8 +60,7 @@ public class AliasedConstraintTest private static LocalConnector connector; private static ConstraintSecurityHandler security; - - @BeforeClass + @BeforeAll public static void startServer() throws Exception { server = new Server(); @@ -116,14 +112,13 @@ public class AliasedConstraintTest server.start(); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { server.stop(); } - @Parameters(name = "{0}: {1}") - public static Collection data() + public static Stream data() { List data = new ArrayList<>(); @@ -137,20 +132,12 @@ public class AliasedConstraintTest data.add(new Object[] { "/ctx/all/../forbid/index.txt", HttpStatus.FORBIDDEN_403, null }); data.add(new Object[] { "/ctx/FoRbId/index.txt", HttpStatus.NOT_FOUND_404, null }); - return data; + return data.stream().map(Arguments::of); } - @Parameter(value = 0) - public String uri; - - @Parameter(value = 1) - public int expectedStatusCode; - - @Parameter(value = 2) - public String expectedContent; - - @Test - public void testAccess() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testAccess(String uri, int expectedStatusCode, String expectedContent) throws Exception { StringBuilder request = new StringBuilder(); request.append("GET ").append(uri).append(" HTTP/1.1\r\n"); diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java index 027dd5cf174..69ae92eac5d 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/ConstraintTest.java @@ -18,6 +18,17 @@ package org.eclipse.jetty.security; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isIn; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -30,8 +41,10 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import javax.servlet.HttpConstraintElement; import javax.servlet.HttpMethodConstraintElement; @@ -42,6 +55,9 @@ import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.security.authentication.BasicAuthenticator; import org.eclipse.jetty.security.authentication.DigestAuthenticator; import org.eclipse.jetty.security.authentication.FormAuthenticator; @@ -60,11 +76,12 @@ import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Password; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; public class ConstraintTest { @@ -74,7 +91,7 @@ public class ConstraintTest private ConstraintSecurityHandler _security; private HttpConfiguration _config; - @Before + @BeforeEach public void startServer() { _server = new Server(); @@ -108,7 +125,7 @@ public class ConstraintTest _security.setConstraintMappings(getConstraintMappings(), getKnownRoles()); } - @After + @AfterEach public void stopServer() throws Exception { _server.stop(); @@ -197,25 +214,25 @@ public class ConstraintTest { List mappings = new ArrayList<>(_security.getConstraintMappings()); - Assert.assertTrue(mappings.get(0).getConstraint().isForbidden()); - Assert.assertFalse(mappings.get(1).getConstraint().isForbidden()); - Assert.assertFalse(mappings.get(2).getConstraint().isForbidden()); - Assert.assertFalse(mappings.get(3).getConstraint().isForbidden()); + assertTrue(mappings.get(0).getConstraint().isForbidden()); + assertFalse(mappings.get(1).getConstraint().isForbidden()); + assertFalse(mappings.get(2).getConstraint().isForbidden()); + assertFalse(mappings.get(3).getConstraint().isForbidden()); - Assert.assertFalse(mappings.get(0).getConstraint().isAnyRole()); - Assert.assertTrue(mappings.get(1).getConstraint().isAnyRole()); - Assert.assertFalse(mappings.get(2).getConstraint().isAnyRole()); - Assert.assertFalse(mappings.get(3).getConstraint().isAnyRole()); + assertFalse(mappings.get(0).getConstraint().isAnyRole()); + assertTrue(mappings.get(1).getConstraint().isAnyRole()); + assertFalse(mappings.get(2).getConstraint().isAnyRole()); + assertFalse(mappings.get(3).getConstraint().isAnyRole()); - Assert.assertFalse(mappings.get(0).getConstraint().hasRole("administrator")); - Assert.assertTrue(mappings.get(1).getConstraint().hasRole("administrator")); - Assert.assertTrue(mappings.get(2).getConstraint().hasRole("administrator")); - Assert.assertFalse(mappings.get(3).getConstraint().hasRole("administrator")); + assertFalse(mappings.get(0).getConstraint().hasRole("administrator")); + assertTrue(mappings.get(1).getConstraint().hasRole("administrator")); + assertTrue(mappings.get(2).getConstraint().hasRole("administrator")); + assertFalse(mappings.get(3).getConstraint().hasRole("administrator")); - Assert.assertTrue(mappings.get(0).getConstraint().getAuthenticate()); - Assert.assertTrue(mappings.get(1).getConstraint().getAuthenticate()); - Assert.assertTrue(mappings.get(2).getConstraint().getAuthenticate()); - Assert.assertFalse(mappings.get(3).getConstraint().getAuthenticate()); + assertTrue(mappings.get(0).getConstraint().getAuthenticate()); + assertTrue(mappings.get(1).getConstraint().getAuthenticate()); + assertTrue(mappings.get(2).getConstraint().getAuthenticate()); + assertFalse(mappings.get(3).getConstraint().getAuthenticate()); } @@ -229,7 +246,7 @@ public class ConstraintTest { ServletSecurityElement element = new ServletSecurityElement(); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(mappings.isEmpty()); + assertTrue(mappings.isEmpty()); } @@ -245,10 +262,10 @@ public class ConstraintTest HttpConstraintElement httpConstraintElement = new HttpConstraintElement(TransportGuarantee.CONFIDENTIAL); ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(!mappings.isEmpty()); - Assert.assertEquals(1, mappings.size()); + assertTrue(!mappings.isEmpty()); + assertEquals(1, mappings.size()); ConstraintMapping mapping = mappings.get(0); - Assert.assertEquals(2, mapping.getConstraint().getDataConstraint()); + assertEquals(2, mapping.getConstraint().getDataConstraint()); } /** @@ -262,10 +279,10 @@ public class ConstraintTest HttpConstraintElement httpConstraintElement = new HttpConstraintElement(EmptyRoleSemantic.DENY); ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(!mappings.isEmpty()); - Assert.assertEquals(1, mappings.size()); + assertTrue(!mappings.isEmpty()); + assertEquals(1, mappings.size()); ConstraintMapping mapping = mappings.get(0); - Assert.assertTrue(mapping.getConstraint().isForbidden()); + assertTrue(mapping.getConstraint().isForbidden()); } /** @@ -279,14 +296,14 @@ public class ConstraintTest HttpConstraintElement httpConstraintElement = new HttpConstraintElement(TransportGuarantee.NONE, "R1"); ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(!mappings.isEmpty()); - Assert.assertEquals(1, mappings.size()); + assertTrue(!mappings.isEmpty()); + assertEquals(1, mappings.size()); ConstraintMapping mapping = mappings.get(0); - Assert.assertTrue(mapping.getConstraint().getAuthenticate()); - Assert.assertTrue(mapping.getConstraint().getRoles() != null); - Assert.assertEquals(1, mapping.getConstraint().getRoles().length); - Assert.assertEquals("R1", mapping.getConstraint().getRoles()[0]); - Assert.assertEquals(0, mapping.getConstraint().getDataConstraint()); + assertTrue(mapping.getConstraint().getAuthenticate()); + assertTrue(mapping.getConstraint().getRoles() != null); + assertEquals(1, mapping.getConstraint().getRoles().length); + assertEquals("R1", mapping.getConstraint().getRoles()[0]); + assertEquals(0, mapping.getConstraint().getDataConstraint()); } /** @@ -305,16 +322,16 @@ public class ConstraintTest methodElements.add(new HttpMethodConstraintElement("POST", new HttpConstraintElement(TransportGuarantee.CONFIDENTIAL, "R1"))); ServletSecurityElement element = new ServletSecurityElement(methodElements); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(!mappings.isEmpty()); - Assert.assertEquals(2, mappings.size()); - Assert.assertEquals("GET", mappings.get(0).getMethod()); - Assert.assertEquals("R1", mappings.get(0).getConstraint().getRoles()[0]); - Assert.assertTrue(mappings.get(0).getMethodOmissions() == null); - Assert.assertEquals(0, mappings.get(0).getConstraint().getDataConstraint()); - Assert.assertEquals("POST", mappings.get(1).getMethod()); - Assert.assertEquals("R1", mappings.get(1).getConstraint().getRoles()[0]); - Assert.assertEquals(2, mappings.get(1).getConstraint().getDataConstraint()); - Assert.assertTrue(mappings.get(1).getMethodOmissions() == null); + assertTrue(!mappings.isEmpty()); + assertEquals(2, mappings.size()); + assertEquals("GET", mappings.get(0).getMethod()); + assertEquals("R1", mappings.get(0).getConstraint().getRoles()[0]); + assertTrue(mappings.get(0).getMethodOmissions() == null); + assertEquals(0, mappings.get(0).getConstraint().getDataConstraint()); + assertEquals("POST", mappings.get(1).getMethod()); + assertEquals("R1", mappings.get(1).getConstraint().getRoles()[0]); + assertEquals(2, mappings.get(1).getConstraint().getDataConstraint()); + assertTrue(mappings.get(1).getMethodOmissions() == null); } /** @@ -329,16 +346,16 @@ public class ConstraintTest methodElements.add(new HttpMethodConstraintElement("GET")); ServletSecurityElement element = new ServletSecurityElement(new HttpConstraintElement(TransportGuarantee.NONE, "R1"), methodElements); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(!mappings.isEmpty()); - Assert.assertEquals(2, mappings.size()); - Assert.assertTrue(mappings.get(0).getMethodOmissions() != null); - Assert.assertEquals("GET", mappings.get(0).getMethodOmissions()[0]); - Assert.assertTrue(mappings.get(0).getConstraint().getAuthenticate()); - Assert.assertEquals("R1", mappings.get(0).getConstraint().getRoles()[0]); - Assert.assertEquals("GET", mappings.get(1).getMethod()); - Assert.assertTrue(mappings.get(1).getMethodOmissions() == null); - Assert.assertEquals(0, mappings.get(1).getConstraint().getDataConstraint()); - Assert.assertFalse(mappings.get(1).getConstraint().getAuthenticate()); + assertTrue(!mappings.isEmpty()); + assertEquals(2, mappings.size()); + assertTrue(mappings.get(0).getMethodOmissions() != null); + assertEquals("GET", mappings.get(0).getMethodOmissions()[0]); + assertTrue(mappings.get(0).getConstraint().getAuthenticate()); + assertEquals("R1", mappings.get(0).getConstraint().getRoles()[0]); + assertEquals("GET", mappings.get(1).getMethod()); + assertTrue(mappings.get(1).getMethodOmissions() == null); + assertEquals(0, mappings.get(1).getConstraint().getDataConstraint()); + assertFalse(mappings.get(1).getConstraint().getAuthenticate()); } /** @@ -355,16 +372,16 @@ public class ConstraintTest methodElements.add(new HttpMethodConstraintElement("TRACE", new HttpConstraintElement(EmptyRoleSemantic.DENY))); ServletSecurityElement element = new ServletSecurityElement(new HttpConstraintElement(TransportGuarantee.NONE, "R1"), methodElements); List mappings = ConstraintSecurityHandler.createConstraintsWithMappingsForPath("foo", "/foo/*", element); - Assert.assertTrue(!mappings.isEmpty()); - Assert.assertEquals(2, mappings.size()); - Assert.assertTrue(mappings.get(0).getMethodOmissions() != null); - Assert.assertEquals("TRACE", mappings.get(0).getMethodOmissions()[0]); - Assert.assertTrue(mappings.get(0).getConstraint().getAuthenticate()); - Assert.assertEquals("R1", mappings.get(0).getConstraint().getRoles()[0]); - Assert.assertEquals("TRACE", mappings.get(1).getMethod()); - Assert.assertTrue(mappings.get(1).getMethodOmissions() == null); - Assert.assertEquals(0, mappings.get(1).getConstraint().getDataConstraint()); - Assert.assertTrue(mappings.get(1).getConstraint().isForbidden()); + assertTrue(!mappings.isEmpty()); + assertEquals(2, mappings.size()); + assertTrue(mappings.get(0).getMethodOmissions() != null); + assertEquals("TRACE", mappings.get(0).getMethodOmissions()[0]); + assertTrue(mappings.get(0).getConstraint().getAuthenticate()); + assertEquals("R1", mappings.get(0).getConstraint().getRoles()[0]); + assertEquals("TRACE", mappings.get(1).getMethod()); + assertTrue(mappings.get(1).getMethodOmissions() == null); + assertEquals(0, mappings.get(1).getConstraint().getDataConstraint()); + assertTrue(mappings.get(1).getConstraint().isForbidden()); } @Test @@ -384,7 +401,7 @@ public class ConstraintTest _server.start(); Set uncoveredPaths = _security.getPathsWithUncoveredHttpMethods(); - Assert.assertTrue(uncoveredPaths.isEmpty()); //no uncovered methods + assertTrue(uncoveredPaths.isEmpty()); //no uncovered methods //Test only an explicitly named method, no omissions to cover other methods Constraint constraint2 = new Constraint(); @@ -398,9 +415,9 @@ public class ConstraintTest _security.addConstraintMapping(mapping2); uncoveredPaths = _security.getPathsWithUncoveredHttpMethods(); - Assert.assertNotNull(uncoveredPaths); - Assert.assertEquals(1, uncoveredPaths.size()); - Assert.assertTrue(uncoveredPaths.contains("/user/*")); + assertNotNull(uncoveredPaths); + assertEquals(1, uncoveredPaths.size()); + assertThat("/user/*", isIn(uncoveredPaths)); //Test an explicitly named method with a http-method-omission to cover all other methods Constraint constraint2a = new Constraint(); @@ -413,8 +430,8 @@ public class ConstraintTest _security.addConstraintMapping(mapping2a); uncoveredPaths = _security.getPathsWithUncoveredHttpMethods(); - Assert.assertNotNull(uncoveredPaths); - Assert.assertEquals(0, uncoveredPaths.size()); + assertNotNull(uncoveredPaths); + assertEquals(0, uncoveredPaths.size()); //Test a http-method-omission only Constraint constraint3 = new Constraint(); @@ -427,17 +444,189 @@ public class ConstraintTest _security.addConstraintMapping(mapping3); uncoveredPaths = _security.getPathsWithUncoveredHttpMethods(); - Assert.assertNotNull(uncoveredPaths); - Assert.assertTrue(uncoveredPaths.contains("/omit/*")); + assertNotNull(uncoveredPaths); + assertThat("/omit/*", isIn(uncoveredPaths)); _security.setDenyUncoveredHttpMethods(true); uncoveredPaths = _security.getPathsWithUncoveredHttpMethods(); - Assert.assertNotNull(uncoveredPaths); - Assert.assertEquals(0, uncoveredPaths.size()); + assertNotNull(uncoveredPaths); + assertEquals(0, uncoveredPaths.size()); } - @Test - public void testBasic() throws Exception + + + public static Stream basicScenarios() + { + List scenarios = new ArrayList<>(); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/noauth/info HTTP/1.0\r\n\r\n", + HttpStatus.OK_200 + ) + )); + +// rawResponse = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); +// assertThat(rawResponse, startsWith("HTTP/1.1 200 OK")); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/forbid/info HTTP/1.0\r\n\r\n", + HttpStatus.FORBIDDEN_403 + ) + )); + +// rawResponse = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); +// assertThat(rawResponse, startsWith("HTTP/1.1 403 Forbidden")); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/auth/info HTTP/1.0\r\n\r\n", + HttpStatus.UNAUTHORIZED_401, + (response) -> { + String authHeader = response.get(HttpHeader.WWW_AUTHENTICATE); + assertThat(response.toString(), authHeader, containsString("basic realm=\"TestRealm\"")); + } + ) + )); + +// rawResponse = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); +// assertThat(rawResponse, startsWith("HTTP/1.1 401 Unauthorized")); +// assertThat(rawResponse, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/auth/info HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("user:wrong") + "\r\n" + + "\r\n", + HttpStatus.UNAUTHORIZED_401, + (response) -> { + String authHeader = response.get(HttpHeader.WWW_AUTHENTICATE); + assertThat(response.toString(), authHeader, containsString("basic realm=\"TestRealm\"")); + } + ) + )); + +// rawResponse = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + +// "Authorization: Basic " + B64Code.encode("user:wrong") + "\r\n" + +// "\r\n"); +// assertThat(rawResponse, startsWith("HTTP/1.1 401 Unauthorized")); +// assertThat(rawResponse, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/auth/info HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + + "\r\n", + HttpStatus.OK_200 + ) + )); + +// rawResponse = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + +// "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + +// "\r\n"); +// assertThat(rawResponse, startsWith("HTTP/1.1 200 OK")); + + // == test admin + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/admin/info HTTP/1.0\r\n\r\n", + HttpStatus.UNAUTHORIZED_401, + (response) -> { + String authHeader = response.get(HttpHeader.WWW_AUTHENTICATE); + assertThat(response.toString(), authHeader, containsString("basic realm=\"TestRealm\"")); + } + ) + )); + +// rawResponse = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n\r\n"); +// assertThat(rawResponse, startsWith("HTTP/1.1 401 Unauthorized")); +// assertThat(rawResponse, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/admin/info HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("admin:wrong") + "\r\n" + + "\r\n", + HttpStatus.UNAUTHORIZED_401, + (response) -> { + String authHeader = response.get(HttpHeader.WWW_AUTHENTICATE); + assertThat(response.toString(), authHeader, containsString("basic realm=\"TestRealm\"")); + } + ) + )); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/admin/info HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + + "\r\n", + HttpStatus.FORBIDDEN_403, + (response) -> { + assertThat(response.getContent(), containsString("!role")); + } + ) + )); + + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/admin/info HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + + "\r\n", + HttpStatus.OK_200) + )); + + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/admin/relax/info HTTP/1.0\r\n\r\n", + HttpStatus.OK_200 + ) + )); + + // == check GET is in role administrator + scenarios.add(Arguments.of( + new Scenario( + "GET /ctx/omit/x HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + + "\r\n", + HttpStatus.OK_200 + + ) + )); + + // == check POST is in role user + scenarios.add(Arguments.of( + new Scenario( + "POST /ctx/omit/x HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + + "\r\n", HttpStatus.OK_200) + )); + + // == check POST can be in role foo too + scenarios.add(Arguments.of( + new Scenario( + "POST /ctx/omit/x HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("user3:password") + "\r\n" + + "\r\n", + HttpStatus.OK_200) + )); + + // == check HEAD cannot be in role user + scenarios.add(Arguments.of( + new Scenario( + "HEAD /ctx/omit/x HTTP/1.0\r\n" + + "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + + "\r\n", + HttpStatus.FORBIDDEN_403) + )); + + return scenarios.stream(); + } + + @ParameterizedTest + @MethodSource("basicScenarios") + public void testBasic(Scenario scenario) throws Exception { List list = new ArrayList<>(_security.getConstraintMappings()); @@ -476,81 +665,21 @@ public class ConstraintTest knownRoles.add("foo"); _security.setConstraintMappings(list, knownRoles); - - + _security.setAuthenticator(new BasicAuthenticator()); - _server.start(); - - String response; - response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); - response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); - - response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("user:wrong") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); - - response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - // test admin - response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); - - response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("admin:wrong") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); - - response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + - "\r\n"); - - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 ")); - Assert.assertThat(response, Matchers.containsString("!role")); - - response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - response = _connector.getResponse("GET /ctx/admin/relax/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - //check GET is in role administrator - response = _connector.getResponse("GET /ctx/omit/x HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - //check POST is in role user - response = _connector.getResponse("POST /ctx/omit/x HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - //check POST can be in role foo too - response = _connector.getResponse("POST /ctx/omit/x HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("user3:password") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - - //check HEAD cannot be in role user - response = _connector.getResponse("HEAD /ctx/omit/x HTTP/1.0\r\n" + - "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + - "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 ")); + try + { + _server.start(); + String rawResponse = _connector.getResponse(scenario.rawRequest); + HttpTester.Response response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(scenario.expectedStatus)); + if(scenario.extraAsserts != null) + scenario.extraAsserts.accept(response); + } + finally + { + _server.stop(); + } } @@ -607,17 +736,17 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: Digest realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, containsString("WWW-Authenticate: Digest realm=\"TestRealm\"")); Pattern nonceP = Pattern.compile("nonce=\"([^\"]*)\","); Matcher matcher = nonceP.matcher(response); - Assert.assertTrue(matcher.find()); + assertTrue(matcher.find()); String nonce=matcher.group(1); @@ -629,7 +758,7 @@ public class ConstraintTest "nonce=\""+nonce+"\", "+ "response=\""+digest+"\"\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); // right password digest= digest(nonce,"user","password","/ctx/auth/info","2"); @@ -639,7 +768,7 @@ public class ConstraintTest "nonce=\""+nonce+"\", "+ "response=\""+digest+"\"\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); // once only @@ -650,7 +779,7 @@ public class ConstraintTest "nonce=\""+nonce+"\", "+ "response=\""+digest+"\"\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); // increasing digest= digest(nonce,"user","password","/ctx/auth/info","4"); @@ -660,7 +789,7 @@ public class ConstraintTest "nonce=\""+nonce+"\", "+ "response=\""+digest+"\"\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); // out of order digest= digest(nonce,"user","password","/ctx/auth/info","3"); @@ -670,7 +799,7 @@ public class ConstraintTest "nonce=\""+nonce+"\", "+ "response=\""+digest+"\"\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); // stale digest= digest(nonce,"user","password","/ctx/auth/info","5"); @@ -680,8 +809,8 @@ public class ConstraintTest "nonce=\""+nonce+"\", "+ "response=\""+digest+"\"\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("stale=true")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, containsString("stale=true")); } @@ -694,15 +823,15 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("Cache-Control: no-cache")); - Assert.assertThat(response, Matchers.containsString("Expires")); - Assert.assertThat(response, Matchers.containsString("URI=/ctx/testLoginPage")); + assertThat(response, containsString("Cache-Control: no-cache")); + assertThat(response, containsString("Expires")); + assertThat(response, containsString("URI=/ctx/testLoginPage")); String session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); @@ -712,7 +841,7 @@ public class ConstraintTest "Content-Length: 31\r\n" + "\r\n" + "j_username=user&j_password=wrong\r\n"); - Assert.assertThat(response, Matchers.containsString("testErrorPage")); + assertThat(response, containsString("testErrorPage")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -720,23 +849,23 @@ public class ConstraintTest "Content-Length: 35\r\n" + "\r\n" + "j_username=user&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); } @Test @@ -748,25 +877,25 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("JSESSIONID="))); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, not(containsString("JSESSIONID="))); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("JSESSIONID="))); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, not(containsString("JSESSIONID="))); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString(" 302 Found")); - Assert.assertThat(response, Matchers.containsString("/ctx/testLoginPage")); - Assert.assertThat(response, Matchers.containsString("JSESSIONID=")); + assertThat(response, containsString(" 302 Found")); + assertThat(response, containsString("/ctx/testLoginPage")); + assertThat(response, containsString("JSESSIONID=")); String session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/testLoginPage HTTP/1.0\r\n"+ "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.containsString(" 200 OK")); - Assert.assertThat(response, Matchers.containsString("URI=/ctx/testLoginPage")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("JSESSIONID=" + session))); + assertThat(response, containsString(" 200 OK")); + assertThat(response, containsString("URI=/ctx/testLoginPage")); + assertThat(response, not(containsString("JSESSIONID=" + session))); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -774,8 +903,8 @@ public class ConstraintTest "Content-Length: 32\r\n" + "\r\n" + "j_username=user&j_password=wrong"); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("JSESSIONID=" + session))); + assertThat(response, containsString("Location")); + assertThat(response, not(containsString("JSESSIONID=" + session))); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -783,25 +912,25 @@ public class ConstraintTest "Content-Length: 35\r\n" + "\r\n" + "j_username=user&j_password=password"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); - Assert.assertThat(response, Matchers.containsString("JSESSIONID=")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("JSESSIONID=" + session))); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); + assertThat(response, containsString("JSESSIONID=")); + assertThat(response, not(containsString("JSESSIONID=" + session))); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("JSESSIONID=" + session)); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("JSESSIONID=" + session)); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("JSESSIONID=" + session))); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); + assertThat(response, not(containsString("JSESSIONID=" + session))); } @Test @@ -813,25 +942,25 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("POST /ctx/auth/info HTTP/1.0\r\n"+ "Content-Type: application/x-www-form-urlencoded\r\n" + "Content-Length: 27\r\n" + "\r\n" + "test_parameter=test_value\r\n"); - Assert.assertThat(response, Matchers.containsString(" 302 Found")); - Assert.assertThat(response, Matchers.containsString("/ctx/testLoginPage")); + assertThat(response, containsString(" 302 Found")); + assertThat(response, containsString("/ctx/testLoginPage")); String session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/testLoginPage HTTP/1.0\r\n"+ "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.containsString(" 200 OK")); - Assert.assertThat(response, Matchers.containsString("URI=/ctx/testLoginPage")); + assertThat(response, containsString(" 200 OK")); + assertThat(response, containsString("URI=/ctx/testLoginPage")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -840,7 +969,7 @@ public class ConstraintTest "\r\n" + "j_username=user&j_password=wrong\r\n"); - Assert.assertThat(response, Matchers.containsString("Location")); + assertThat(response, containsString("Location")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -848,30 +977,30 @@ public class ConstraintTest "Content-Length: 35\r\n" + "\r\n" + "j_username=user&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); // sneak in other request response = _connector.getResponse("GET /ctx/auth/other HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertTrue(!response.contains("test_value")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, not(containsString("test_value"))); // retry post as GET response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertTrue(response.contains("test_value")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("test_value")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); } @Test @@ -883,47 +1012,47 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString(" 302 Found")); - Assert.assertThat(response, Matchers.containsString("/ctx/testLoginPage")); + assertThat(response, containsString(" 302 Found")); + assertThat(response, containsString("/ctx/testLoginPage")); int jsession=response.indexOf(";jsessionid="); String session = response.substring(jsession + 12, response.indexOf("\r\n",jsession)); response = _connector.getResponse("GET /ctx/testLoginPage;jsessionid="+session+";other HTTP/1.0\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.containsString(" 200 OK")); - Assert.assertThat(response, Matchers.containsString("URI=/ctx/testLoginPage")); + assertThat(response, containsString(" 200 OK")); + assertThat(response, containsString("URI=/ctx/testLoginPage")); response = _connector.getResponse("POST /ctx/j_security_check;jsessionid="+session+";other HTTP/1.0\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n" + "Content-Length: 31\r\n" + "\r\n" + "j_username=user&j_password=wrong\r\n"); - Assert.assertThat(response, Matchers.containsString("Location")); + assertThat(response, containsString("Location")); response = _connector.getResponse("POST /ctx/j_security_check;jsessionid="+session+";other HTTP/1.0\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n" + "Content-Length: 35\r\n" + "\r\n" + "j_username=user&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info;jsessionid="+session+";other HTTP/1.0\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/admin/info;jsessionid="+session+";other HTTP/1.0\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); } @Test @@ -934,58 +1063,58 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user:wrong") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user3:password") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); + assertThat(response, startsWith("HTTP/1.1 403")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); // test admin response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("admin:wrong") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized")); - Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); + assertThat(response, startsWith("HTTP/1.1 401 Unauthorized")); + assertThat(response, containsString("WWW-Authenticate: basic realm=\"TestRealm\"")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 ")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403 ")); + assertThat(response, containsString("!role")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/admin/relax/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); } @Test @@ -998,17 +1127,17 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); // assertThat(response,containsString(" 302 Found")); // assertThat(response,containsString("/ctx/testLoginPage")); - Assert.assertThat(response, Matchers.containsString("Cache-Control: no-cache")); - Assert.assertThat(response, Matchers.containsString("Expires")); - Assert.assertThat(response, Matchers.containsString("URI=/ctx/testLoginPage")); + assertThat(response, containsString("Cache-Control: no-cache")); + assertThat(response, containsString("Expires")); + assertThat(response, containsString("URI=/ctx/testLoginPage")); String session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); @@ -1019,7 +1148,7 @@ public class ConstraintTest "\r\n" + "j_username=user&j_password=wrong\r\n"); // assertThat(response,containsString("Location")); - Assert.assertThat(response, Matchers.containsString("testErrorPage")); + assertThat(response, containsString("testErrorPage")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -1027,22 +1156,22 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=user0&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); @@ -1058,21 +1187,21 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=user2&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); @@ -1088,20 +1217,20 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=admin&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); } @Test @@ -1113,14 +1242,14 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden")); + assertThat(response, startsWith("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\nHost:wibble.com:8888\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString(" 302 Found")); - Assert.assertThat(response, Matchers.containsString("http://wibble.com:8888/ctx/testLoginPage")); + assertThat(response, containsString(" 302 Found")); + assertThat(response, containsString("http://wibble.com:8888/ctx/testLoginPage")); String session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); @@ -1130,7 +1259,7 @@ public class ConstraintTest "Content-Length: 31\r\n" + "\r\n" + "j_username=user&j_password=wrong\r\n"); - Assert.assertThat(response, Matchers.containsString("Location")); + assertThat(response, containsString("Location")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + @@ -1138,29 +1267,29 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=user3&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); // log in again as user2 response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("testLoginPage")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("testLoginPage")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + @@ -1169,29 +1298,29 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=user2&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); //check user2 does not have right role to access /admin/* response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); - Assert.assertThat(response, Matchers.containsString("!role")); + assertThat(response, startsWith("HTTP/1.1 403")); + assertThat(response, containsString("!role")); //log in as user3, who doesn't have a valid role, but we are checking a constraint //of ** which just means they have to be authenticated response = _connector.getResponse("GET /ctx/starstar/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("testLoginPage")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("testLoginPage")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("POST /ctx/j_security_check HTTP/1.0\r\n" + @@ -1200,15 +1329,15 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=user3&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/starstar/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/starstar/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/starstar/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); // log in again as admin @@ -1223,20 +1352,20 @@ public class ConstraintTest "Content-Length: 36\r\n" + "\r\n" + "j_username=admin&j_password=password\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 ")); - Assert.assertThat(response, Matchers.containsString("Location")); - Assert.assertThat(response, Matchers.containsString("/ctx/auth/info")); + assertThat(response, startsWith("HTTP/1.1 302 ")); + assertThat(response, containsString("Location")); + assertThat(response, containsString("/ctx/auth/info")); session = response.substring(response.indexOf("JSESSIONID=") + 11, response.indexOf(";Path=/ctx")); response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Cookie: JSESSIONID=" + session + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); } @@ -1247,38 +1376,42 @@ public class ConstraintTest _security.setAuthenticator(new BasicAuthenticator()); _server.start(); - String response; + String rawResponse; - response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403")); + rawResponse = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n"); + HttpTester.Response response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.FORBIDDEN_403)); _config.setSecurePort(8443); _config.setSecureScheme("https"); - response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found")); - Assert.assertTrue(response.indexOf("Location") > 0); - Assert.assertTrue(response.indexOf(":8443/ctx/data/info") > 0); - Assert.assertThat(response,Matchers.not(Matchers.containsString("https:///"))); + rawResponse = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n"); + response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.FOUND_302)); + String location = response.get(HttpHeader.LOCATION); + assertThat("Location header", location, containsString(":8443/ctx/data/info")); + assertThat("Location header", location, not(containsString("https:///"))); _config.setSecurePort(443); - response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found")); - Assert.assertTrue(response.indexOf("Location") > 0); - Assert.assertTrue(!response.contains(":443/ctx/data/info")); + rawResponse = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n"); + response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.FOUND_302)); + location = response.get(HttpHeader.LOCATION); + assertThat("Location header", location, not(containsString(":443/ctx/data/info"))); _config.setSecurePort(8443); - response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\nHost: wobble.com\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found")); - Assert.assertTrue(response.indexOf("Location") > 0); - Assert.assertTrue(response.indexOf("https://wobble.com:8443/ctx/data/info") > 0); + rawResponse = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\nHost: wobble.com\r\n\r\n"); + response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.FOUND_302)); + location = response.get(HttpHeader.LOCATION); + assertThat("Location header", location, containsString("https://wobble.com:8443/ctx/data/info")); _config.setSecurePort(443); - response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\nHost: wobble.com\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found")); - Assert.assertTrue(response.indexOf("Location") > 0); - Assert.assertTrue(!response.contains(":443")); - Assert.assertTrue(response.indexOf("https://wobble.com/ctx/data/info") > 0); + rawResponse = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\nHost: wobble.com\r\n\r\n"); + response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.FOUND_302)); + location = response.get(HttpHeader.LOCATION); + assertThat("Location header", location, containsString("https://wobble.com/ctx/data/info")); } @Test @@ -1290,14 +1423,16 @@ public class ConstraintTest _server.start(); - String response; - response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n", 100000, TimeUnit.MILLISECONDS); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + String rawResponse; + rawResponse = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n", 100000, TimeUnit.MILLISECONDS); + HttpTester.Response response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.OK_200)); - response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + + rawResponse = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + "\r\n", 100000, TimeUnit.MILLISECONDS); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 500 ")); + response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.INTERNAL_SERVER_ERROR_500)); _server.stop(); @@ -1308,10 +1443,11 @@ public class ConstraintTest _server.start(); - response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + + rawResponse = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + "\r\n", 100000, TimeUnit.MILLISECONDS); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + response = HttpTester.parseResponse(rawResponse); + assertThat(response.toString(), response.getStatus(), is(HttpStatus.OK_200)); } @Test @@ -1324,20 +1460,20 @@ public class ConstraintTest response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n"+ "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("user=null")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("user=null")); response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n"+ "Authorization: Basic " + B64Code.encode("admin:wrong") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("user=null")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("user=null")); response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n"+ "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + "\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("user=admin")); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("user=admin")); } @Test @@ -1348,13 +1484,13 @@ public class ConstraintTest String response; response = _connector.getResponse("GET /ctx/forbid/somethig HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 ")); + assertThat(response, startsWith("HTTP/1.1 403 ")); response = _connector.getResponse("POST /ctx/forbid/post HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 ")); + assertThat(response, startsWith("HTTP/1.1 200 ")); response = _connector.getResponse("GET /ctx/forbid/post HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 ")); // This is so stupid, but it is the S P E C + assertThat(response, startsWith("HTTP/1.1 200 ")); // This is so stupid, but it is the S P E C } private class RequestHandler extends AbstractHandler { @@ -1436,4 +1572,30 @@ public class ConstraintTest response.sendError(500); } } + + public static class Scenario + { + public final String rawRequest; + public final int expectedStatus; + public Consumer extraAsserts; + + public Scenario(String rawRequest, int expectedStatus) + { + this.rawRequest = rawRequest; + this.expectedStatus = expectedStatus; + } + + public Scenario(String rawRequest, int expectedStatus, Consumer extraAsserts) + { + this.rawRequest = rawRequest; + this.expectedStatus = expectedStatus; + this.extraAsserts = extraAsserts; + } + + @Override + public String toString() + { + return rawRequest; + } + } } diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/DataConstraintsTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/DataConstraintsTest.java index f18ac0abaec..fd31fb5396b 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/DataConstraintsTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/DataConstraintsTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.security; +import static org.hamcrest.MatcherAssert.assertThat; + import java.io.IOException; import java.util.Arrays; @@ -41,10 +43,10 @@ import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.util.security.Constraint; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class DataConstraintsTest { @@ -54,7 +56,7 @@ public class DataConstraintsTest private SessionHandler _session; private ConstraintSecurityHandler _security; - @Before + @BeforeEach public void startServer() { _server = new Server(); @@ -101,7 +103,7 @@ public class DataConstraintsTest } - @After + @AfterEach public void stopServer() throws Exception { if (_server.isRunning()) @@ -131,15 +133,15 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/some/thing HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connector.getResponse("GET /ctx/integral/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); - Assert.assertThat(response, Matchers.containsString("Location: BWTP://")); - Assert.assertThat(response, Matchers.containsString(":9999")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("Location: BWTP://")); + assertThat(response, Matchers.containsString(":9999")); response = _connectorS.getResponse("GET /ctx/integral/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } @@ -163,15 +165,15 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/some/thing HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connector.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); - Assert.assertThat(response, Matchers.containsString("Location: BWTP://")); - Assert.assertThat(response, Matchers.containsString(":9999")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("Location: BWTP://")); + assertThat(response, Matchers.containsString(":9999")); response = _connectorS.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } @@ -195,10 +197,10 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); response = _connectorS.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } @@ -223,16 +225,16 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connectorS.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connector.getResponse("POST /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); response = _connectorS.getResponse("POST /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } @Test @@ -257,16 +259,16 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connectorS.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connector.getResponse("POST /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); response = _connectorS.getResponse("POST /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } @@ -296,25 +298,25 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connectorS.getResponse("GET /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connector.getResponse("POST /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); response = _connectorS.getResponse("POST /ctx/confid/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized")); + assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized")); response = _connector.getResponse("GET /ctx/confid/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connector.getResponse("POST /ctx/confid/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 302 Found")); response = _connectorS.getResponse("POST /ctx/confid/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } @@ -338,16 +340,16 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/restricted/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); response = _connectorS.getResponse("GET /ctx/restricted/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/restricted/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); response = _connectorS.getResponse("GET /ctx/restricted/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); } @@ -372,16 +374,16 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/restricted/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); response = _connectorS.getResponse("GET /ctx/restricted/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); response = _connector.getResponse("GET /ctx/restricted/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); response = _connectorS.getResponse("GET /ctx/restricted/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); + assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden")); } @@ -410,16 +412,16 @@ public class DataConstraintsTest String response; response = _connector.getResponse("GET /ctx/restricted/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized")); + assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized")); response = _connectorS.getResponse("GET /ctx/restricted/info HTTP/1.0\r\n\r\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized")); + assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized")); response = _connector.getResponse("GET /ctx/restricted/info HTTP/1.0\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\n\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); response = _connectorS.getResponse("GET /ctx/restricted/info HTTP/1.0\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\n\n"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); + assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found")); } diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java index f05a0b14b56..5fcb9392652 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/PropertyUserStoreTest.java @@ -18,25 +18,24 @@ package org.eclipse.jetty.security; -import org.eclipse.jetty.toolchain.test.FS; -import org.eclipse.jetty.toolchain.test.OS; -import org.eclipse.jetty.toolchain.test.TestingDir; -import org.eclipse.jetty.util.security.Credential; -import org.hamcrest.Matcher; -import org.junit.Rule; -import org.junit.Test; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.condition.OS.MAC; +import static org.junit.jupiter.api.condition.OS.WINDOWS; -import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.FilePermission; -import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.ArrayList; @@ -47,11 +46,16 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeThat; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDir; +import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension; +import org.eclipse.jetty.util.security.Credential; +import org.hamcrest.Matcher; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.extension.ExtendWith; +@ExtendWith(WorkDirExtension.class) public class PropertyUserStoreTest { private final class UserCount implements PropertyUserStore.UserListener @@ -103,14 +107,13 @@ public class PropertyUserStoreTest } } - @Rule - public TestingDir testdir = new TestingDir(); + public WorkDir testdir; - private File initUsersText() throws Exception + private Path initUsersText() throws Exception { - Path dir = testdir.getPath().toRealPath(); - FS.ensureDirExists(dir.toFile()); - File users = dir.resolve("users.txt").toFile(); + Path dir = testdir.getPath(); + Path users = dir.resolve("users.txt"); + Files.deleteIfExists(users); writeUser( users ); return users; @@ -119,8 +122,7 @@ public class PropertyUserStoreTest private String initUsersPackedFileText() throws Exception { - Path dir = testdir.getPath().toRealPath(); - FS.ensureDirExists( dir.toFile() ); + Path dir = testdir.getPath(); File users = dir.resolve( "users.txt" ).toFile(); writeUser( users ); File usersJar = dir.resolve( "users.jar" ).toFile(); @@ -151,10 +153,14 @@ public class PropertyUserStoreTest return "jar:" + usersJar.toURI().toASCIIString() + "!/" + entryPath; } - private void writeUser(File usersFile) - throws Exception + private void writeUser(File usersFile) throws IOException { - try (Writer writer = new BufferedWriter(new FileWriter(usersFile))) + writeUser(usersFile.toPath()); + } + + private void writeUser(Path usersFile) throws IOException + { + try (Writer writer = Files.newBufferedWriter(usersFile, UTF_8)) { writer.append("tom: tom, roleA\n"); writer.append("dick: dick, roleB\n"); @@ -162,10 +168,10 @@ public class PropertyUserStoreTest } } - private void addAdditionalUser(File usersFile, String userRef) throws Exception + private void addAdditionalUser(Path usersFile, String userRef) throws Exception { Thread.sleep(1001); - try (Writer writer = new BufferedWriter(new FileWriter(usersFile,true))) + try (Writer writer = Files.newBufferedWriter(usersFile, UTF_8, StandardOpenOption.APPEND)) { writer.append(userRef); } @@ -174,11 +180,13 @@ public class PropertyUserStoreTest @Test public void testPropertyUserStoreLoad() throws Exception { + testdir.ensureEmpty(); + final UserCount userCount = new UserCount(); - final File usersFile = initUsersText(); + final Path usersFile = initUsersText(); PropertyUserStore store = new PropertyUserStore(); - store.setConfigFile(usersFile); + store.setConfigFile(usersFile.toFile()); store.registerUserListener(userCount); @@ -190,27 +198,22 @@ public class PropertyUserStoreTest userCount.assertThatCount(is(3)); userCount.awaitCount(3); } - + @Test public void testPropertyUserStoreFails() throws Exception { - PropertyUserStore store = new PropertyUserStore(); - store.setConfig("file:/this/file/does/not/exist.txt"); - - try - { + assertThrows(IllegalStateException.class,() -> { + PropertyUserStore store = new PropertyUserStore(); + store.setConfig("file:/this/file/does/not/exist.txt"); store.start(); - fail("file should not exist"); - } - catch (IllegalStateException e) - { - //expected - } + }); } @Test public void testPropertyUserStoreLoadFromJarFile() throws Exception { + testdir.ensureEmpty(); + final UserCount userCount = new UserCount(); final String usersFile = initUsersPackedFileText(); @@ -232,11 +235,13 @@ public class PropertyUserStoreTest } @Test + @DisabledOnOs(MAC) public void testPropertyUserStoreLoadUpdateUser() throws Exception { - assumeThat("Skipping on OSX", OS.IS_OSX, is(false)); + testdir.ensureEmpty(); + final UserCount userCount = new UserCount(); - final File usersFile = initUsersText(); + final Path usersFile = initUsersText(); final AtomicInteger loadCount = new AtomicInteger(0); PropertyUserStore store = new PropertyUserStore() { @@ -248,7 +253,7 @@ public class PropertyUserStoreTest } }; store.setHotReload(true); - store.setConfigFile(usersFile); + store.setConfigFile(usersFile.toFile()); store.registerUserListener(userCount); store.start(); @@ -263,7 +268,7 @@ public class PropertyUserStoreTest userCount.assertThatCount(is(4)); userCount.assertThatUsers(hasItem("skip")); - if (OS.IS_LINUX) + if (OS.LINUX.isCurrentOs()) Files.createFile(testdir.getPath().toRealPath().resolve("unrelated.txt"), PosixFilePermissions.asFileAttribute(EnumSet.noneOf(PosixFilePermission.class))); else @@ -277,19 +282,21 @@ public class PropertyUserStoreTest } @Test + @DisabledOnOs({MAC, WINDOWS}) // File is locked on OS, cannot change. public void testPropertyUserStoreLoadRemoveUser() throws Exception { - assumeThat("Skipping on OSX", OS.IS_OSX, is(false)); + testdir.ensureEmpty(); + final UserCount userCount = new UserCount(); // initial user file (3) users - final File usersFile = initUsersText(); + final Path usersFile = initUsersText(); // adding 4th user addAdditionalUser(usersFile,"skip: skip, roleA\n"); PropertyUserStore store = new PropertyUserStore(); store.setHotReload(true); - store.setConfigFile(usersFile); + store.setConfigFile(usersFile.toFile()); store.registerUserListener(userCount); diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/SpecExampleConstraintTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/SpecExampleConstraintTest.java index ed80f0844f7..22e179c2273 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/SpecExampleConstraintTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/SpecExampleConstraintTest.java @@ -19,9 +19,9 @@ package org.eclipse.jetty.security; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Arrays; @@ -43,10 +43,10 @@ import org.eclipse.jetty.server.session.SessionHandler; import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Password; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @version $Revision: 1441 $ $Date: 2010-04-02 12:28:17 +0200 (Fri, 02 Apr 2010) $ @@ -59,7 +59,7 @@ public class SpecExampleConstraintTest private static SessionHandler _session; private ConstraintSecurityHandler _security; - @BeforeClass + @BeforeAll public static void startServer() { _server = new Server(); @@ -84,7 +84,7 @@ public class SpecExampleConstraintTest _server.addBean(_loginService); } - @Before + @BeforeEach public void setupSecurity() { _security = new ConstraintSecurityHandler(); @@ -224,7 +224,7 @@ public class SpecExampleConstraintTest }), knownRoles); } - @After + @AfterEach public void stopServer() throws Exception { if (_server.isRunning()) diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/UserStoreTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/UserStoreTest.java index 2a51228a53c..be0cb9b6d07 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/UserStoreTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/UserStoreTest.java @@ -18,21 +18,24 @@ package org.eclipse.jetty.security; -import org.eclipse.jetty.server.UserIdentity; -import org.eclipse.jetty.util.security.Credential; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.util.List; import java.util.Set; import java.util.stream.Collectors; +import org.eclipse.jetty.server.UserIdentity; +import org.eclipse.jetty.util.security.Credential; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + public class UserStoreTest { UserStore userStore; - @Before + @BeforeEach public void setup() { userStore = new UserStore(); } @@ -41,30 +44,30 @@ public class UserStoreTest public void addUser() { this.userStore.addUser( "foo", Credential.getCredential( "beer" ), new String[]{"pub"} ); - Assert.assertEquals(1, this.userStore.getKnownUserIdentities().size()); + assertEquals(1, this.userStore.getKnownUserIdentities().size()); UserIdentity userIdentity = this.userStore.getUserIdentity( "foo" ); - Assert.assertNotNull( userIdentity ); - Assert.assertEquals( "foo", userIdentity.getUserPrincipal().getName() ); + assertNotNull( userIdentity ); + assertEquals( "foo", userIdentity.getUserPrincipal().getName() ); Set roles = userIdentity.getSubject().getPrincipals( AbstractLoginService.RolePrincipal.class); List list = roles.stream() .map( rolePrincipal -> rolePrincipal.getName() ) .collect( Collectors.toList() ); - Assert.assertEquals(1, list.size()); - Assert.assertEquals( "pub", list.get( 0 ) ); + assertEquals(1, list.size()); + assertEquals( "pub", list.get( 0 ) ); } @Test public void removeUser() { this.userStore.addUser( "foo", Credential.getCredential( "beer" ), new String[]{"pub"} ); - Assert.assertEquals(1, this.userStore.getKnownUserIdentities().size()); + assertEquals(1, this.userStore.getKnownUserIdentities().size()); UserIdentity userIdentity = this.userStore.getUserIdentity( "foo" ); - Assert.assertNotNull( userIdentity ); - Assert.assertEquals( "foo", userIdentity.getUserPrincipal().getName() ); + assertNotNull( userIdentity ); + assertEquals( "foo", userIdentity.getUserPrincipal().getName() ); userStore.removeUser( "foo" ); userIdentity = this.userStore.getUserIdentity( "foo" ); - Assert.assertNull( userIdentity ); + assertNull( userIdentity ); } } diff --git a/jetty-security/src/test/java/org/eclipse/jetty/security/authentication/SpnegoAuthenticatorTest.java b/jetty-security/src/test/java/org/eclipse/jetty/security/authentication/SpnegoAuthenticatorTest.java index 2fe6cd9cb47..9b03ed72874 100644 --- a/jetty-security/src/test/java/org/eclipse/jetty/security/authentication/SpnegoAuthenticatorTest.java +++ b/jetty-security/src/test/java/org/eclipse/jetty/security/authentication/SpnegoAuthenticatorTest.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.security.authentication; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import javax.servlet.http.HttpServletResponse; @@ -35,8 +35,8 @@ import org.eclipse.jetty.server.HttpOutput; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Response; import org.eclipse.jetty.server.Server; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Test class for {@link SpnegoAuthenticator}. @@ -44,7 +44,7 @@ import org.junit.Test; public class SpnegoAuthenticatorTest { private SpnegoAuthenticator _authenticator; - @Before + @BeforeEach public void setup() throws Exception { _authenticator = new SpnegoAuthenticator(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/AbstractHttpTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/AbstractHttpTest.java index c23e390c7fe..a49653b3cbf 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/AbstractHttpTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/AbstractHttpTest.java @@ -18,8 +18,9 @@ package org.eclipse.jetty.server; +import static org.eclipse.jetty.http.HttpFieldsMatchers.containsHeaderValue; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.io.OutputStreamWriter; @@ -34,34 +35,24 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpTester; +import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.log.StacklessLogging; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; public abstract class AbstractHttpTest { private final static Set __noBodyCodes = new HashSet<>(Arrays.asList(new String[]{"100","101","102","204","304"})); - @Rule - public TestTracker tracker = new TestTracker(); - protected static Server server; protected static ServerConnector connector; - protected String httpVersion; private StacklessLogging stacklessChannelLogging; - - public AbstractHttpTest(String httpVersion) - { - this.httpVersion = httpVersion; - } - - @Before + @BeforeEach public void setUp() throws Exception { server = new Server(); @@ -69,17 +60,17 @@ public abstract class AbstractHttpTest connector.setIdleTimeout(100000); server.addConnector(connector); - stacklessChannelLogging =new StacklessLogging(HttpChannel.class); + stacklessChannelLogging = new StacklessLogging(HttpChannel.class); } - @After + @AfterEach public void tearDown() throws Exception { server.stop(); stacklessChannelLogging.close(); } - protected HttpTester.Response executeRequest() throws URISyntaxException, IOException + protected HttpTester.Response executeRequest(HttpVersion httpVersion) throws URISyntaxException, IOException { try(Socket socket = new Socket("localhost", connector.getLocalPort())) { @@ -87,7 +78,7 @@ public abstract class AbstractHttpTest try(PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()))) { - writer.write("GET / " + httpVersion + "\r\n"); + writer.write("GET / " + httpVersion.asString() + "\r\n"); writer.write("Host: localhost\r\n"); writer.write("\r\n"); writer.flush(); @@ -96,7 +87,7 @@ public abstract class AbstractHttpTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.parseResponse(input, response); - if ("HTTP/1.1".equals(httpVersion) + if (httpVersion.is("HTTP/1.1") && response.isComplete() && response.get("content-length") == null && response.get("transfer-encoding") == null @@ -108,16 +99,6 @@ public abstract class AbstractHttpTest } } - protected void assertResponseBody(HttpTester.Response response, String expectedResponseBody) - { - assertThat("response body is" + expectedResponseBody, response.getContent(), is(expectedResponseBody)); - } - - protected void assertHeader(HttpTester.Response response, String headerName, String expectedValue) - { - assertThat(headerName + "=" + expectedValue, response.get(headerName), is(expectedValue)); - } - protected static class TestCommitException extends IllegalStateException { public TestCommitException() diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncRequestReadTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncRequestReadTest.java index 8b526bf4081..ba5053896d4 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncRequestReadTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncRequestReadTest.java @@ -19,9 +19,9 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.IOException; @@ -41,22 +41,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.IO; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class AsyncRequestReadTest { private static Server server; private static ServerConnector connector; private final static BlockingQueue __total=new BlockingArrayQueue<>(); - @Before + @BeforeEach public void startServer() throws Exception { server = new Server(); @@ -66,7 +63,7 @@ public class AsyncRequestReadTest server.addConnector(connector); } - @After + @AfterEach public void stopServer() throws Exception { server.stop(); @@ -169,10 +166,10 @@ public class AsyncRequestReadTest InputStream in = socket.getInputStream(); String response = IO.toString(in); - assertTrue(tst,response.indexOf("200 OK")>0); + assertThat(response, containsString("200 OK")); long total=__total.poll(30,TimeUnit.SECONDS); - assertEquals(tst,content.length, total); + assertEquals(content.length, total, tst); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java index 51dc865d789..bda5d7b6598 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/AsyncStressTest.java @@ -18,7 +18,7 @@ package org.eclipse.jetty.server; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; @@ -39,19 +39,18 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.HandlerWrapper; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.PropertyFlag; -import org.eclipse.jetty.toolchain.test.annotation.Stress; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) +@Disabled +@Tag("stress") public class AsyncStressTest { private static final Logger LOG = Log.getLogger(AsyncStressTest.class); @@ -73,7 +72,7 @@ public class AsyncStressTest {"/path?suspend=60000&complete=","COMPLETED"}, }; - @Before + @BeforeEach public void init() throws Exception { _server.manage(_threads); @@ -87,7 +86,7 @@ public class AsyncStressTest _addr=InetAddress.getLocalHost(); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); @@ -95,17 +94,9 @@ public class AsyncStressTest } @Test - @Stress("High connection count") public void testAsync() throws Throwable { - if (PropertyFlag.isEnabled("test.stress")) - { - doConnections(1600,240); - } - else - { - doConnections(80,80); - } + doConnections(1600,240); } private void doConnections(int connections,final int loops) throws Throwable diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/CheckReverseProxyHeadersTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/CheckReverseProxyHeadersTest.java index 50da5b93f17..149d458d872 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/CheckReverseProxyHeadersTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/CheckReverseProxyHeadersTest.java @@ -18,26 +18,22 @@ package org.eclipse.jetty.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; -import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; /** * */ -@RunWith(AdvancedRunner.class) public class CheckReverseProxyHeadersTest { @Test diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ClassLoaderDumptTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ClassLoaderDumptTest.java index 22a6dc00b09..b69e4652f41 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ClassLoaderDumptTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ClassLoaderDumptTest.java @@ -20,14 +20,14 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import org.eclipse.jetty.util.component.Dumpable; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ClassLoaderDumptTest { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectionOpenCloseTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectionOpenCloseTest.java index f71c3a24496..b922ceb0906 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectionOpenCloseTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectionOpenCloseTest.java @@ -18,11 +18,12 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; @@ -32,42 +33,33 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpTester; -import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; -@RunWith(AdvancedRunner.class) public class ConnectionOpenCloseTest extends AbstractHttpTest { - public ConnectionOpenCloseTest() - { - super(HttpVersion.HTTP_1_1.asString()); - } - - @Slow @Test + @Tag("Slow") + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testOpenClose() throws Exception { server.setHandler(new AbstractHandler() { @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { throw new IllegalStateException(); } @@ -94,30 +86,31 @@ public class ConnectionOpenCloseTest extends AbstractHttpTest } }); - try (Socket socket = new Socket("localhost", connector.getLocalPort());) + try (Socket socket = new Socket("localhost", connector.getLocalPort())) { socket.setSoTimeout((int)connector.getIdleTimeout()); - Assert.assertTrue(openLatch.await(5, TimeUnit.SECONDS)); + assertTrue(openLatch.await(5, TimeUnit.SECONDS)); socket.shutdownOutput(); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); String response=IO.toString(socket.getInputStream()); - Assert.assertEquals(0,response.length()); + assertEquals(0,response.length()); // Wait some time to see if the callbacks are called too many times TimeUnit.MILLISECONDS.sleep(200); - Assert.assertEquals(2, callbacks.get()); + assertEquals(2, callbacks.get()); } } - - @Slow + @Test + @Tag("Slow") + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testOpenRequestClose() throws Exception { server.setHandler(new AbstractHandler() { @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { baseRequest.setHandled(true); } @@ -159,21 +152,22 @@ public class ConnectionOpenCloseTest extends AbstractHttpTest HttpTester.Response response = HttpTester.parseResponse(inputStream); assertThat("Status Code", response.getStatus(), is(200)); - Assert.assertEquals(-1, inputStream.read()); + assertEquals(-1, inputStream.read()); socket.close(); - Assert.assertTrue(openLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(openLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); // Wait some time to see if the callbacks are called too many times TimeUnit.SECONDS.sleep(1); - Assert.assertEquals(2, callbacks.get()); + assertEquals(2, callbacks.get()); } } - @Slow @Test + @Tag("Slow") + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testSSLOpenRequestClose() throws Exception { SslContextFactory sslContextFactory = new SslContextFactory(); @@ -190,7 +184,7 @@ public class ConnectionOpenCloseTest extends AbstractHttpTest server.setHandler(new AbstractHandler() { @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { baseRequest.setHandled(true); } @@ -232,12 +226,12 @@ public class ConnectionOpenCloseTest extends AbstractHttpTest assertThat(response,Matchers.containsString("200 OK")); socket.close(); - Assert.assertTrue(openLatch.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); + assertTrue(openLatch.await(5, TimeUnit.SECONDS)); + assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); // Wait some time to see if the callbacks are called too many times TimeUnit.SECONDS.sleep(1); - Assert.assertEquals(4, callbacks.get()); + assertEquals(4, callbacks.get()); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java index 3cf455ec8ab..96b5e6ef7ce 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorCloseTestBase.java @@ -18,7 +18,7 @@ package org.eclipse.jetty.server; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.IOException; @@ -30,14 +30,11 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; /** * HttpServer Tester. */ -@RunWith(AdvancedRunner.class) public abstract class ConnectorCloseTestBase extends HttpServerTestFixture { private static String __content = diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorTimeoutTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorTimeoutTest.java index ad5aec5fa65..2c500154ec4 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorTimeoutTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorTimeoutTest.java @@ -18,6 +18,21 @@ package org.eclipse.jetty.server; +import static java.time.Duration.ofSeconds; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -40,28 +55,19 @@ import org.eclipse.jetty.io.AbstractConnection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.ssl.SslConnection; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.StacklessLogging; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public abstract class ConnectorTimeoutTest extends HttpServerTestFixture { protected static final Logger LOG = Log.getLogger(ConnectorTimeoutTest.class); - @Rule - public TestTracker tracker = new TestTracker(); - protected static final int MAX_IDLE_TIME=2000; private int sleepTime = MAX_IDLE_TIME + MAX_IDLE_TIME/5; private int minimumTestRuntime = MAX_IDLE_TIME-MAX_IDLE_TIME/5; @@ -72,7 +78,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture System.setProperty("org.eclipse.jetty.io.nio.IDLE_TICK","500"); } - @Before + @BeforeEach @Override public void before() { @@ -86,7 +92,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture } - @Test(timeout=60000) + @Test public void testMaxIdleWithRequest10() throws Exception { configureServer(new HelloWorldHandler()); @@ -94,62 +100,68 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - os.write(( - "GET / HTTP/1.0\r\n"+ - "host: "+_serverURI.getHost()+":"+_serverURI.getPort()+"\r\n"+ - "connection: keep-alive\r\n"+ - "\r\n").getBytes("utf-8")); - os.flush(); - IO.toString(is); + assertTimeoutPreemptively(ofSeconds(10), ()->{ + os.write(( + "GET / HTTP/1.0\r\n"+ + "host: "+_serverURI.getHost()+":"+_serverURI.getPort()+"\r\n"+ + "connection: keep-alive\r\n"+ + "\r\n").getBytes("utf-8")); + os.flush(); - Thread.sleep(sleepTime); - Assert.assertEquals(-1, is.read()); + IO.toString(is); - Assert.assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start > minimumTestRuntime); - Assert.assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); + Thread.sleep(sleepTime); + assertEquals(-1, is.read()); + }); + + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start > minimumTestRuntime); + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); } - @Test(timeout=60000) + @Test public void testMaxIdleWithRequest11() throws Exception { configureServer(new EchoHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); - String content="Wibble"; - byte[] contentB=content.getBytes("utf-8"); - os.write(( - "POST /echo HTTP/1.1\r\n"+ - "host: "+_serverURI.getHost()+":"+_serverURI.getPort()+"\r\n"+ - "content-type: text/plain; charset=utf-8\r\n"+ - "content-length: "+contentB.length+"\r\n"+ - "\r\n").getBytes("utf-8")); - os.write(contentB); - os.flush(); - IO.toString(is); + assertTimeoutPreemptively(ofSeconds(10), ()-> { + String content = "Wibble"; + byte[] contentB = content.getBytes("utf-8"); + os.write(( + "POST /echo HTTP/1.1\r\n" + + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + + "content-type: text/plain; charset=utf-8\r\n" + + "content-length: " + contentB.length + "\r\n" + + "\r\n").getBytes("utf-8")); + os.write(contentB); + os.flush(); - Thread.sleep(sleepTime); - Assert.assertEquals(-1, is.read()); + IO.toString(is); - Assert.assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start > minimumTestRuntime); - Assert.assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); + Thread.sleep(sleepTime); + assertEquals(-1, is.read()); + }); + + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start > minimumTestRuntime); + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); } - @Test(timeout=60000) + @Test public void testMaxIdleWithRequest10NoClientClose() throws Exception { final Exchanger exchanger = new Exchanger<>(); @@ -174,42 +186,42 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); os.write(( - "GET / HTTP/1.0\r\n"+ - "host: "+_serverURI.getHost()+":"+_serverURI.getPort()+"\r\n"+ - "connection: close\r\n"+ - "\r\n").getBytes("utf-8")); + "GET / HTTP/1.0\r\n" + + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + + "connection: close\r\n" + + "\r\n").getBytes("utf-8")); os.flush(); // Get the server side endpoint - EndPoint endPoint = exchanger.exchange(null,10,TimeUnit.SECONDS); + EndPoint endPoint = exchanger.exchange(null, 10, TimeUnit.SECONDS); if (endPoint instanceof SslConnection.DecryptedEndPoint) endPoint = ((SslConnection.DecryptedEndPoint)endPoint).getSslConnection().getEndPoint(); // read the response String result=IO.toString(is); - Assert.assertThat(result, Matchers.containsString("200 OK")); + assertThat("OK",result, containsString("200 OK")); // check client reads EOF - Assert.assertEquals(-1, is.read()); - Assert.assertTrue(endPoint.isOutputShutdown()); + assertEquals(-1, is.read()); + assertTrue(endPoint.isOutputShutdown()); // wait for idle timeout TimeUnit.MILLISECONDS.sleep(2 * MAX_IDLE_TIME); // check the server side is closed - Assert.assertFalse(endPoint.isOpen()); + assertFalse(endPoint.isOpen()); Object transport = endPoint.getTransport(); if (transport instanceof Channel) - Assert.assertFalse(((Channel)transport).isOpen()); + assertFalse(((Channel)transport).isOpen()); } - @Test(timeout=60000) + @Test public void testMaxIdleWithRequest11NoClientClose() throws Exception { final Exchanger exchanger = new Exchanger<>(); @@ -234,7 +246,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); @@ -260,21 +272,22 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture IO.toString(is); // check client reads EOF - Assert.assertEquals(-1, is.read()); - Assert.assertTrue(endPoint.isOutputShutdown()); + assertEquals(-1, is.read()); + assertTrue(endPoint.isOutputShutdown()); // The server has shutdown the output, the client does not close, // the server should idle timeout and close the connection. TimeUnit.MILLISECONDS.sleep(2 * MAX_IDLE_TIME); - Assert.assertFalse(endPoint.isOpen()); + assertFalse(endPoint.isOpen()); Object transport = endPoint.getTransport(); if (transport instanceof Channel) - Assert.assertFalse(((Channel)transport).isOpen()); + assertFalse(((Channel)transport).isOpen()); } - @Test(timeout=60000) - @Ignore // TODO make more stable + @Test + @Tag("Unstable") + @Disabled // TODO make more stable public void testNoBlockingTimeoutRead() throws Exception { _httpConfiguration.setBlockingTimeout(-1L); @@ -283,7 +296,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); InputStream is=client.getInputStream(); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); @@ -324,17 +337,19 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture e.printStackTrace(); } long duration=TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start; - Assert.assertThat(duration,Matchers.greaterThan(500L)); - - // read the response - String response = IO.toString(is); - Assert.assertThat(response,Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response,Matchers.containsString("LMNOP0123456789ABCDEF")); + assertThat(duration,greaterThan(500L)); + assertTimeoutPreemptively(ofSeconds(10), ()-> { + // read the response + String response = IO.toString(is); + assertThat(response, startsWith("HTTP/1.1 200 OK")); + assertThat(response, containsString("LMNOP0123456789ABCDEF")); + }); } - @Test(timeout=60000) - @Ignore // TODO make more stable + @Test + @Tag("Unstable") + @Disabled // TODO make more stable public void testBlockingTimeoutRead() throws Exception { _httpConfiguration.setBlockingTimeout(750L); @@ -343,7 +358,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); InputStream is=client.getInputStream(); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); @@ -383,14 +398,14 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture { } long duration=TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start; - Assert.assertThat(duration,Matchers.greaterThan(500L)); + assertThat(duration,greaterThan(500L)); try { // read the response String response = IO.toString(is); - Assert.assertThat(response,Matchers.startsWith("HTTP/1.1 500 ")); - Assert.assertThat(response,Matchers.containsString("InterruptedIOException")); + assertThat(response,startsWith("HTTP/1.1 500 ")); + assertThat(response,containsString("InterruptedIOException")); } catch(SSLException e) { @@ -398,15 +413,16 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture } - @Test(timeout=60000) - @Ignore // TODO make more stable + @Test + @Tag("Unstable") + @Disabled // TODO make more stable public void testNoBlockingTimeoutWrite() throws Exception { configureServer(new HugeResponseHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); BufferedReader is=new BufferedReader(new InputStreamReader(client.getInputStream(),StandardCharsets.ISO_8859_1),2048); @@ -421,7 +437,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture // read the header String line=is.readLine(); - Assert.assertThat(line,Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(line,startsWith("HTTP/1.1 200 OK")); while(line.length()!=0) line=is.readLine(); @@ -433,13 +449,14 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture // System.err.println("read "+TimeUnit.NANOSECONDS.toMillis(System.nanoTime())); } line=is.readLine(); - Assert.assertThat(line,Matchers.notNullValue()); - Assert.assertEquals(1022,line.length()); + assertThat(line,notNullValue()); + assertEquals(1022,line.length()); } } - @Test(timeout=60000) - @Ignore // TODO make more stable + @Test + @Tag("Unstable") + @Disabled // TODO make more stable public void testBlockingTimeoutWrite() throws Exception { _httpConfiguration.setBlockingTimeout(750L); @@ -447,7 +464,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); BufferedReader is=new BufferedReader(new InputStreamReader(client.getInputStream(),StandardCharsets.ISO_8859_1),2048); @@ -462,7 +479,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture // read the header String line=is.readLine(); - Assert.assertThat(line,Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(line,startsWith("HTTP/1.1 200 OK")); while(line.length()!=0) line=is.readLine(); @@ -485,17 +502,17 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture {} long end=TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); long duration = end-start; - Assert.assertThat(duration,Matchers.lessThan(20L*128L)); + assertThat(duration,lessThan(20L*128L)); } - @Test(timeout=60000) + @Test public void testMaxIdleNoRequest() throws Exception { configureServer(new EchoHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); InputStream is=client.getInputStream(); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); @@ -503,31 +520,23 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture os.flush(); Thread.sleep(sleepTime); - try - { - String response = IO.toString(is); - Assert.assertThat(response,Matchers.is("")); - Assert.assertEquals(-1, is.read()); - } - catch(SSLException e) - { - if(LOG.isDebugEnabled()) - LOG.debug(e); - else - LOG.info(e.getMessage()); - } - catch(Exception e) - { - if(LOG.isDebugEnabled()) - LOG.debug(e); - else - LOG.info(e.getMessage()); - } - Assert.assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); + assertTimeoutPreemptively(ofSeconds(10), ()-> { + try + { + String response = IO.toString(is); + assertThat(response, is("")); + assertEquals(-1, is.read()); + } + catch (Exception e) + { + LOG.warn(e.getMessage()); + } + }); + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); } - @Test(timeout=60000) + @Test public void testMaxIdleNothingSent() throws Exception { configureServer(new EchoHandler()); @@ -535,41 +544,33 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); InputStream is=client.getInputStream(); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); Thread.sleep(sleepTime); - try - { - String response = IO.toString(is); - Assert.assertThat(response,Matchers.is("")); - Assert.assertEquals(-1, is.read()); - } - catch(SSLException e) - { - if(LOG.isDebugEnabled()) - LOG.debug(e); - else - LOG.info(e.getMessage()); - } - catch(Exception e) - { - if(LOG.isDebugEnabled()) - LOG.debug(e); - else - LOG.info(e.getMessage()); - } - Assert.assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); + assertTimeoutPreemptively(ofSeconds(10), ()-> { + try + { + String response = IO.toString(is); + assertThat(response, is("")); + assertEquals(-1, is.read()); + } + catch (Exception e) + { + LOG.warn(e); + } + }); + assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime); } - @Test(timeout=60000) + @Test public void testMaxIdleDelayedDispatch() throws Exception { configureServer(new EchoHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); InputStream is=client.getInputStream(); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); @@ -584,33 +585,31 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture "\r\n").getBytes("utf-8")); os.flush(); - try - { - String response = IO.toString(is); - Assert.assertThat(response,Matchers.containsString("500")); - Assert.assertEquals(-1, is.read()); - } - catch(SSLException e) - { - e.printStackTrace(); - } - catch(Exception e) - { - e.printStackTrace(); - } + assertTimeoutPreemptively(ofSeconds(10), ()-> { + try + { + String response = IO.toString(is); + assertThat(response, containsString("500")); + assertEquals(-1, is.read()); + } + catch (Exception e) + { + e.printStackTrace(); + } + }); int duration = (int)(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start); - Assert.assertThat(duration,Matchers.greaterThanOrEqualTo(MAX_IDLE_TIME)); - Assert.assertThat(duration,Matchers.lessThan(maximumTestRuntime)); + assertThat(duration,greaterThanOrEqualTo(MAX_IDLE_TIME)); + assertThat(duration,lessThan(maximumTestRuntime)); } - @Test(timeout=60000) + @Test public void testMaxIdleDispatch() throws Exception { configureServer(new EchoHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); InputStream is=client.getInputStream(); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); @@ -625,34 +624,32 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture "1234567890").getBytes("utf-8")); os.flush(); - try - { - String response = IO.toString(is); - Assert.assertThat(response,Matchers.containsString("500")); - Assert.assertEquals(-1, is.read()); - } - catch(SSLException e) - { - e.printStackTrace(); - } - catch(Exception e) - { - e.printStackTrace(); - } + assertTimeoutPreemptively(ofSeconds(10), ()-> { + try + { + String response = IO.toString(is); + assertThat(response, containsString("500")); + assertEquals(-1, is.read()); + } + catch (Exception e) + { + e.printStackTrace(); + } + }); int duration = (int)(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start); - Assert.assertThat(duration+100,Matchers.greaterThanOrEqualTo(MAX_IDLE_TIME)); - Assert.assertThat(duration-100,Matchers.lessThan(maximumTestRuntime)); + assertThat(duration+100,greaterThanOrEqualTo(MAX_IDLE_TIME)); + assertThat(duration-100,lessThan(maximumTestRuntime)); } - @Test(timeout=60000) + @Test public void testMaxIdleWithSlowRequest() throws Exception { configureServer(new EchoHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); @@ -669,30 +666,32 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture "\r\n").getBytes("utf-8")); os.flush(); - for (int i =0;i<20;i++) - { - Thread.sleep(50); - os.write(contentB); - os.flush(); - } + assertTimeoutPreemptively(ofSeconds(10), ()-> { + for (int i = 0; i < 20; i++) + { + Thread.sleep(50); + os.write(contentB); + os.flush(); + } - String in = IO.toString(is); - int offset=0; - for (int i =0;i<20;i++) - { - offset=in.indexOf("Wibble",offset+1); - Assert.assertTrue("" + i, offset > 0); - } + String in = IO.toString(is); + int offset = 0; + for (int i = 0; i < 20; i++) + { + offset = in.indexOf("Wibble", offset + 1); + assertTrue(offset > 0, "" + i); + } + }); } - @Test(timeout=60000) + @Test public void testMaxIdleWithSlowResponse() throws Exception { configureServer(new SlowResponseHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); @@ -705,23 +704,25 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture "\r\n").getBytes("utf-8")); os.flush(); - String in = IO.toString(is); - int offset=0; - for (int i =0;i<20;i++) - { - offset=in.indexOf("Hello World",offset+1); - Assert.assertTrue("" + i, offset > 0); - } + assertTimeoutPreemptively(ofSeconds(10), ()-> { + String in = IO.toString(is); + int offset = 0; + for (int i = 0; i < 20; i++) + { + offset = in.indexOf("Hello World", offset + 1); + assertTrue(offset > 0, "" + i); + } + }); } - @Test(timeout=60000) + @Test public void testMaxIdleWithWait() throws Exception { configureServer(new WaitHandler()); Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); OutputStream os=client.getOutputStream(); InputStream is=client.getInputStream(); @@ -734,9 +735,10 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture "\r\n").getBytes("utf-8")); os.flush(); - String in = IO.toString(is); - int offset=in.indexOf("Hello World"); - Assert.assertTrue(offset > 0); + assertTimeoutPreemptively(ofSeconds(10), ()-> { + String in = IO.toString(is); + assertThat(in, containsString("Hello World")); + }); } protected static class SlowResponseHandler extends AbstractHandler diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutterTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutterTest.java index 581e9fde56a..69962f57967 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutterTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutterTest.java @@ -19,17 +19,14 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import javax.servlet.http.Cookie; import org.eclipse.jetty.http.CookieCompliance; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class CookieCutterTest { private Cookie[] parseCookieHeaders(CookieCompliance compliance,String... headers) @@ -142,7 +139,7 @@ public class CookieCutterTest * Example from RFC2965 */ @Test - @Ignore("comma separation no longer supported by new RFC6265") + @Disabled("comma separation no longer supported by new RFC6265") public void testRFC2965_CookieSpoofingExample() { String rawCookie = "$Version=\"1\"; session_id=\"1234\", " + diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutter_LenientTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutter_LenientTest.java index 24c50417c08..e22f3961a06 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutter_LenientTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/CookieCutter_LenientTest.java @@ -18,152 +18,139 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import java.util.ArrayList; -import java.util.List; +import java.util.stream.Stream; import javax.servlet.http.Cookie; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests of poor various name=value scenarios and expectations of results * due to our efforts at being lenient with what we receive. */ -@RunWith(Parameterized.class) public class CookieCutter_LenientTest { - @Parameterized.Parameters(name = "{0}") - public static List data() + public static Stream data() { - List ret = new ArrayList<>(); - - // Simple test to verify behavior - ret.add(new String[]{"key=value", "key", "value"}); - - // Tests that conform to RFC2109 - // RFC2109 - token values - // token = 1* - // CHAR = - // CTL = - // SP = - // HT = - // tspecials = "(" | ")" | "<" | ">" | "@" - // | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" - // | "{" | "}" | SP | HT - ret.add(new String[]{"abc=xyz", "abc", "xyz"}); - ret.add(new String[]{"abc=!bar", "abc", "!bar"}); - ret.add(new String[]{"abc=#hash", "abc", "#hash"}); - ret.add(new String[]{"abc=#hash", "abc", "#hash"}); - // RFC2109 - quoted-string values - // quoted-string = ( <"> *(qdtext) <"> ) - // qdtext = > + return Stream.of( + // Simple test to verify behavior + Arguments.of("key=value", "key", "value"), - // lenient with spaces and EOF - ret.add(new String[]{"abc=", "abc", ""}); - ret.add(new String[]{"abc = ", "abc", ""}); - ret.add(new String[]{"abc = ;", "abc", ""}); - ret.add(new String[]{"abc = ; ", "abc", ""}); - ret.add(new String[]{"abc = x ", "abc", "x"}); - ret.add(new String[]{"abc=\"\"", "abc", ""}); - ret.add(new String[]{"abc= \"\" ", "abc", ""}); - ret.add(new String[]{"abc= \"x\" ", "abc", "x"}); - ret.add(new String[]{"abc= \"x\" ;", "abc", "x"}); - ret.add(new String[]{"abc= \"x\" ; ", "abc", "x"}); + // Tests that conform to RFC2109 + // RFC2109 - token values + // token = 1* + // CHAR = + // CTL = + // SP = + // HT = + // tspecials = "(" | ")" | "<" | ">" | "@" + // | "," | ";" | ":" | "\" | <"> + // | "/" | "[" | "]" | "?" | "=" + // | "{" | "}" | SP | HT + Arguments.of("abc=xyz", "abc", "xyz"), + Arguments.of("abc=!bar", "abc", "!bar"), + Arguments.of("abc=#hash", "abc", "#hash"), + Arguments.of("abc=#hash", "abc", "#hash"), + // RFC2109 - quoted-string values + // quoted-string = ( <"> *(qdtext) <"> ) + // qdtext = > - // The backslash character ("\") may be used as a single-character quoting - // mechanism only within quoted-string and comment constructs. - // quoted-pair = "\" CHAR - ret.add(new String[]{"abc=\"xyz\"", "abc", "xyz"}); - ret.add(new String[]{"abc=\"!bar\"", "abc", "!bar"}); - ret.add(new String[]{"abc=\"#hash\"", "abc", "#hash"}); - // RFC2109 - other valid name types that conform to 'attr'/'token' syntax - ret.add(new String[]{"!f!o!o!=wat", "!f!o!o!", "wat"}); - ret.add(new String[]{"__MyHost=Foo", "__MyHost", "Foo"}); - ret.add(new String[]{"some-thing-else=to-parse", "some-thing-else", "to-parse"}); - // RFC2109 - names with attr/token syntax starting with '$' (and not a cookie reserved word) - // See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-5.2 - // Cannot pass names through as javax.servlet.http.Cookie class does not allow them - ret.add(new String[]{"$foo=bar", null, null}); + // lenient with spaces and EOF + Arguments.of("abc=", "abc", ""), + Arguments.of("abc = ", "abc", ""), + Arguments.of("abc = ;", "abc", ""), + Arguments.of("abc = ; ", "abc", ""), + Arguments.of("abc = x ", "abc", "x"), + Arguments.of("abc=\"\"", "abc", ""), + Arguments.of("abc= \"\" ", "abc", ""), + Arguments.of("abc= \"x\" ", "abc", "x"), + Arguments.of("abc= \"x\" ;", "abc", "x"), + Arguments.of("abc= \"x\" ; ", "abc", "x"), - // Tests that conform to RFC6265 - ret.add(new String[]{"abc=foobar!", "abc", "foobar!"}); - ret.add(new String[]{"abc=\"foobar!\"", "abc", "foobar!"}); - - // Internal quotes - ret.add(new String[]{"foo=bar\"baz", "foo", "bar\"baz"}); - ret.add(new String[]{"foo=\"bar\"baz\"", "foo", "bar\"baz"}); - ret.add(new String[]{"foo=\"bar\"-\"baz\"", "foo", "bar\"-\"baz"}); - ret.add(new String[]{"foo=\"bar'-\"baz\"", "foo", "bar'-\"baz"}); - ret.add(new String[]{"foo=\"bar''-\"baz\"", "foo", "bar''-\"baz"}); - // These seem dubious until you realize the "lots of equals signs" below works - ret.add(new String[]{"foo=\"bar\"=\"baz\"", "foo", "bar\"=\"baz"}); - ret.add(new String[]{"query=\"?b=c\"&\"d=e\"", "query", "?b=c\"&\"d=e"}); - // Escaped quotes - ret.add(new String[]{"foo=\"bar\\\"=\\\"baz\"", "foo", "bar\"=\"baz"}); - - // Unterminated Quotes - ret.add(new String[]{"x=\"abc", "x", "\"abc"}); - // Unterminated Quotes with valid cookie params after it - ret.add(new String[]{"x=\"abc $Path=/", "x", "\"abc $Path=/"}); - // Unterminated Quotes with trailing escape - ret.add(new String[]{"x=\"abc\\", "x", "\"abc\\"}); - - // UTF-8 values - ret.add(new String[]{"2sides=\u262F", "2sides", "\u262f"}); // 2 byte - ret.add(new String[]{"currency=\"\u20AC\"", "currency", "\u20AC"}); // 3 byte - ret.add(new String[]{"gothic=\"\uD800\uDF48\"", "gothic", "\uD800\uDF48"}); // 4 byte - - // Spaces - ret.add(new String[]{"foo=bar baz", "foo", "bar baz"}); - ret.add(new String[]{"foo=\"bar baz\"", "foo", "bar baz"}); - ret.add(new String[]{"z=a b c d e f g", "z", "a b c d e f g"}); - - // Bad tspecials usage - ret.add(new String[]{"foo=bar;baz", "foo", "bar"}); - ret.add(new String[]{"foo=\"bar;baz\"", "foo", "bar;baz"}); - ret.add(new String[]{"z=a;b,c:d;e/f[g]", "z", "a"}); - ret.add(new String[]{"z=\"a;b,c:d;e/f[g]\"", "z", "a;b,c:d;e/f[g]"}); - - // Quoted with other Cookie keywords - ret.add(new String[]{"x=\"$Version=0\"", "x", "$Version=0"}); - ret.add(new String[]{"x=\"$Path=/\"", "x", "$Path=/"}); - ret.add(new String[]{"x=\"$Path=/ $Domain=.foo.com\"", "x", "$Path=/ $Domain=.foo.com"}); - ret.add(new String[]{"x=\" $Path=/ $Domain=.foo.com \"", "x", " $Path=/ $Domain=.foo.com "}); - ret.add(new String[]{"a=\"b; $Path=/a; c=d; $PATH=/c; e=f\"; $Path=/e/", "a", "b; $Path=/a; c=d; $PATH=/c; e=f"}); - - // Lots of equals signs - ret.add(new String[]{"query=b=c&d=e", "query", "b=c&d=e"}); - - // Escaping - ret.add(new String[]{"query=%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D", "query", "%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D"}); - - // Google cookies (seen in wild, has `tspecials` of ':' in value) - ret.add(new String[]{"GAPS=1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-", "GAPS", "1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-"}); - - // Strong abuse of cookie spec (lots of tspecials) - ret.add(new String[]{"$Version=0; rToken=F_TOKEN''!--\"=&{()}", "rToken", "F_TOKEN''!--\"=&{()}"}); - - return ret; + // The backslash character ("\") may be used as a single-character quoting + // mechanism only within quoted-string and comment constructs. + // quoted-pair = "\" CHAR + Arguments.of("abc=\"xyz\"", "abc", "xyz"), + Arguments.of("abc=\"!bar\"", "abc", "!bar"), + Arguments.of("abc=\"#hash\"", "abc", "#hash"), + // RFC2109 - other valid name types that conform to 'attr'/'token' syntax + Arguments.of("!f!o!o!=wat", "!f!o!o!", "wat"), + Arguments.of("__MyHost=Foo", "__MyHost", "Foo"), + Arguments.of("some-thing-else=to-parse", "some-thing-else", "to-parse"), + // RFC2109 - names with attr/token syntax starting with '$' (and not a cookie reserved word) + // See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-5.2 + // Cannot pass names through as javax.servlet.http.Cookie class does not allow them + Arguments.of("$foo=bar", null, null), + + // Tests that conform to RFC6265 + Arguments.of("abc=foobar!", "abc", "foobar!"), + Arguments.of("abc=\"foobar!\"", "abc", "foobar!"), + + // Internal quotes + Arguments.of("foo=bar\"baz", "foo", "bar\"baz"), + Arguments.of("foo=\"bar\"baz\"", "foo", "bar\"baz"), + Arguments.of("foo=\"bar\"-\"baz\"", "foo", "bar\"-\"baz"), + Arguments.of("foo=\"bar'-\"baz\"", "foo", "bar'-\"baz"), + Arguments.of("foo=\"bar''-\"baz\"", "foo", "bar''-\"baz"), + // These seem dubious until you realize the "lots of equals signs" below works + Arguments.of("foo=\"bar\"=\"baz\"", "foo", "bar\"=\"baz"), + Arguments.of("query=\"?b=c\"&\"d=e\"", "query", "?b=c\"&\"d=e"), + // Escaped quotes + Arguments.of("foo=\"bar\\\"=\\\"baz\"", "foo", "bar\"=\"baz"), + + // Unterminated Quotes + Arguments.of("x=\"abc", "x", "\"abc"), + // Unterminated Quotes with valid cookie params after it + Arguments.of("x=\"abc $Path=/", "x", "\"abc $Path=/"), + // Unterminated Quotes with trailing escape + Arguments.of("x=\"abc\\", "x", "\"abc\\"), + + // UTF-8 values + Arguments.of("2sides=\u262F", "2sides", "\u262f"), // 2 byte + Arguments.of("currency=\"\u20AC\"", "currency", "\u20AC"), // 3 byte + Arguments.of("gothic=\"\uD800\uDF48\"", "gothic", "\uD800\uDF48"), // 4 byte + + // Spaces + Arguments.of("foo=bar baz", "foo", "bar baz"), + Arguments.of("foo=\"bar baz\"", "foo", "bar baz"), + Arguments.of("z=a b c d e f g", "z", "a b c d e f g"), + + // Bad tspecials usage + Arguments.of("foo=bar;baz", "foo", "bar"), + Arguments.of("foo=\"bar;baz\"", "foo", "bar;baz"), + Arguments.of("z=a;b,c:d;e/f[g]", "z", "a"), + Arguments.of("z=\"a;b,c:d;e/f[g]\"", "z", "a;b,c:d;e/f[g]"), + + // Quoted with other Cookie keywords + Arguments.of("x=\"$Version=0\"", "x", "$Version=0"), + Arguments.of("x=\"$Path=/\"", "x", "$Path=/"), + Arguments.of("x=\"$Path=/ $Domain=.foo.com\"", "x", "$Path=/ $Domain=.foo.com"), + Arguments.of("x=\" $Path=/ $Domain=.foo.com \"", "x", " $Path=/ $Domain=.foo.com "), + Arguments.of("a=\"b; $Path=/a; c=d; $PATH=/c; e=f\"; $Path=/e/", "a", "b; $Path=/a; c=d; $PATH=/c; e=f"), + + // Lots of equals signs + Arguments.of("query=b=c&d=e", "query", "b=c&d=e"), + + // Escaping + Arguments.of("query=%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D", "query", "%7B%22sessionCount%22%3A5%2C%22sessionTime%22%3A14151%7D"), + + // Google cookies (seen in wild, has `tspecials` of ':' in value) + Arguments.of("GAPS=1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-", "GAPS", "1:A1aaaAaAA1aaAAAaa1a11a:aAaaAa-aaA1-"), + + // Strong abuse of cookie spec (lots of tspecials) + Arguments.of("$Version=0; rToken=F_TOKEN''!--\"=&{()}", "rToken", "F_TOKEN''!--\"=&{()}") + ); } - @Parameterized.Parameter - public String rawHeader; - - @Parameterized.Parameter(1) - public String expectedName; - - @Parameterized.Parameter(2) - public String expectedValue; - - @Test - public void testLenientBehavior() + @ParameterizedTest + @MethodSource("data") + public void testLenientBehavior(String rawHeader, String expectedName, String expectedValue) { CookieCutter cutter = new CookieCutter(); cutter.addCookieField(rawHeader); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/CustomResourcesMonitorTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/CustomResourcesMonitorTest.java index 486cb80afe5..57b4a5fe9a4 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/CustomResourcesMonitorTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/CustomResourcesMonitorTest.java @@ -19,15 +19,14 @@ package org.eclipse.jetty.server; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.TimerScheduler; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.io.IOException; import java.io.InputStream; @@ -41,7 +40,6 @@ import java.util.stream.Stream; import static org.junit.Assert.*; -@RunWith(AdvancedRunner.class) public class CustomResourcesMonitorTest { Server _server; @@ -50,7 +48,7 @@ public class CustomResourcesMonitorTest Path _monitoredPath; LowResourceMonitor _lowResourceMonitor; - @Before + @BeforeEach public void before() throws Exception { _server = new Server(); @@ -72,7 +70,7 @@ public class CustomResourcesMonitorTest _server.start(); } - @After + @AfterEach public void after() throws Exception { _server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ErrorHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ErrorHandlerTest.java index b773657dff3..f2261e1cc69 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ErrorHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ErrorHandlerTest.java @@ -23,7 +23,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; @@ -42,16 +42,16 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.ErrorHandler; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class ErrorHandlerTest { static Server server; static LocalConnector connector; - @BeforeClass + @BeforeAll public static void before() throws Exception { server = new Server(); @@ -151,7 +151,7 @@ public class ErrorHandlerTest server.start(); } - @AfterClass + @AfterAll public static void after() throws Exception { server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ExtendedServerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ExtendedServerTest.java index 7006ad29cd6..8b0c765638e 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ExtendedServerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ExtendedServerTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; + import java.io.IOException; import java.io.OutputStream; import java.net.Socket; @@ -39,21 +41,18 @@ import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.ManagedSelector; import org.eclipse.jetty.io.SocketChannelEndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.thread.Scheduler; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Extended Server Tester. */ -@RunWith(AdvancedRunner.class) public class ExtendedServerTest extends HttpServerTestBase { - @Before + @BeforeEach public void init() throws Exception { startServer(new ServerConnector(_server,new HttpConnectionFactory() @@ -142,15 +141,15 @@ public class ExtendedServerTest extends HttpServerTestBase // Read the response. String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("DispatchedAt=")); + assertThat(response, Matchers.containsString("HTTP/1.1 200 OK")); + assertThat(response, Matchers.containsString("DispatchedAt=")); String s=response.substring(response.indexOf("DispatchedAt=")+13); s=s.substring(0,s.indexOf('\n')); long dispatched=Long.parseLong(s); - Assert.assertThat(dispatched, Matchers.greaterThanOrEqualTo(start)); - Assert.assertThat(dispatched, Matchers.lessThan(end)); + assertThat(dispatched, Matchers.greaterThanOrEqualTo(start)); + assertThat(dispatched, Matchers.lessThan(end)); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java index 8d5a2618277..873b5e337a1 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ForwardedRequestCustomizerTest.java @@ -18,10 +18,10 @@ package org.eclipse.jetty.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.ArrayDeque; @@ -35,16 +35,12 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.IO; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class ForwardedRequestCustomizerTest { private Server _server; @@ -57,7 +53,7 @@ public class ForwardedRequestCustomizerTest ForwardedRequestCustomizer _customizer; - @Before + @BeforeEach public void init() throws Exception { _server = new Server(); @@ -92,7 +88,7 @@ public class ForwardedRequestCustomizerTest _server.start(); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/GracefulStopTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/GracefulStopTest.java index 40b68925194..2cb23ede8a4 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/GracefulStopTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/GracefulStopTest.java @@ -21,10 +21,14 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.condition.OS.WINDOWS; import java.io.BufferedReader; import java.io.IOException; @@ -51,21 +55,18 @@ import org.eclipse.jetty.server.LocalConnector.LocalEndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.StatisticsHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.OS; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matcher; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -@RunWith(AdvancedRunner.class) -public class GracefulStopTest +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; + +public class GracefulStopTest { /** * Test of standard graceful timeout mechanism when a block request does @@ -106,8 +107,8 @@ public class GracefulStopTest // No Graceful waiters assertThat(TimeUnit.NANOSECONDS.toMillis(stop-start),lessThan(900L)); - assertThat(client.getInputStream().read(),Matchers.is(-1)); - assertThat(handler.handling.get(),Matchers.is(false)); + assertThat(client.getInputStream().read(),is(-1)); + assertThat(handler.handling.get(),is(false)); assertThat(handler.thrown.get(),Matchers.notNullValue()); client.close(); } @@ -147,21 +148,16 @@ public class GracefulStopTest handler.latch.await(); long start = System.nanoTime(); - try - { - server.stop(); - Assert.fail(); - } - catch(TimeoutException e) - { - long stop = System.nanoTime(); - // No Graceful waiters - assertThat(TimeUnit.NANOSECONDS.toMillis(stop-start),greaterThan(900L)); - } - assertThat(client.getInputStream().read(),Matchers.is(-1)); + assertThrows(TimeoutException.class, ()-> server.stop()); - assertThat(handler.handling.get(),Matchers.is(false)); + long stop = System.nanoTime(); + // No Graceful waiters + assertThat(TimeUnit.NANOSECONDS.toMillis(stop-start),greaterThan(900L)); + + assertThat(client.getInputStream().read(),is(-1)); + + assertThat(handler.handling.get(),is(false)); assertThat(handler.thrown.get(),instanceOf(ClosedChannelException.class)); client.close(); @@ -175,9 +171,9 @@ public class GracefulStopTest * @throws Exception on test failure */ @Test + @DisabledOnOs(WINDOWS) // TODO: needs more investigation public void testGracefulComplete() throws Exception { - assumeTrue(!OS.IS_WINDOWS); Server server= new Server(); server.setStopTimeout(10000); @@ -193,7 +189,8 @@ public class GracefulStopTest server.start(); final int port=connector.getLocalPort(); - try(final Socket client1 = new Socket("127.0.0.1", port);final Socket client2 = new Socket("127.0.0.1", port);) + try(final Socket client1 = new Socket("127.0.0.1", port); + final Socket client2 = new Socket("127.0.0.1", port)) { client1.getOutputStream().write(( "POST / HTTP/1.0\r\n"+ @@ -261,12 +258,12 @@ public class GracefulStopTest String response = IO.toString(client1.getInputStream()); - assertThat(handler.handling.get(),Matchers.is(false)); + assertThat(handler.handling.get(),is(false)); assertThat(response, containsString(" 200 OK")); assertThat(response, containsString("read 10/10")); - assertThat(stats.getRequests(),Matchers.is(2)); - assertThat(stats.getResponses5xx(),Matchers.is(1)); + assertThat(stats.getRequests(),is(2)); + assertThat(stats.getResponses5xx(),is(1)); } } @@ -345,8 +342,7 @@ public class GracefulStopTest while(true) { String line = in.readLine(); - if (line==null) - Assert.fail(); + assertThat("Line should not be null", line, is(notNullValue())); if (line.length()==0) break; } @@ -355,11 +351,11 @@ public class GracefulStopTest try { server.stop(); - Assert.assertTrue(stopTimeout==0 || stopTimeout>closeWait); + assertTrue(stopTimeout==0 || stopTimeout>closeWait); } catch(Exception e) { - Assert.assertTrue(stopTimeout>0 && stopTimeout0 && stopTimeout0) - Assert.assertTrue(closed.await(1000,TimeUnit.MILLISECONDS)); + assertTrue(closed.await(1000,TimeUnit.MILLISECONDS)); if (!client.isClosed()) client.close(); @@ -398,7 +394,7 @@ public class GracefulStopTest * @throws Exception on test failure */ @Test - @Ignore // TODO disable while #2046 is fixed + @Disabled // TODO disable while #2046 is fixed public void testSlowCloseTinyGraceful() throws Exception { Log.getLogger(QueuedThreadPool.class).info("Expect some threads can't be stopped"); @@ -410,7 +406,7 @@ public class GracefulStopTest * @throws Exception on test failure */ @Test - @Ignore // TODO disable while #2046 is fixed + @Disabled // TODO disable while #2046 is fixed public void testSlowCloseGraceful() throws Exception { testSlowClose(5000,1000,Matchers.allOf(greaterThan(750L),lessThan(4999L))); @@ -483,7 +479,7 @@ public class GracefulStopTest long end = System.nanoTime()+TimeUnit.SECONDS.toNanos(1); while (endp.isOpen() && System.nanoTime()=2000) - Assert.fail(); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime())-start, lessThanOrEqualTo(2000L)); offset = checkContains(response,offset,"HTTP/1.1 200"); offset = checkContains(response,offset,"pathInfo=/R1"); @@ -1107,7 +1103,7 @@ public class HttpConnectionTest }); server.start(); - Logger logger = Log.getLogger(HttpChannel.class); + Logger logger = Log.getLogger(HttpChannel.class); String response = null; try (StacklessLogging stackless = new StacklessLogging(logger)) { @@ -1205,12 +1201,12 @@ public class HttpConnectionTest private int checkContains(String s,int offset,String c) { - Assert.assertThat(s.substring(offset),Matchers.containsString(c)); + assertThat(s.substring(offset),Matchers.containsString(c)); return s.indexOf(c,offset); } private void checkNotContained(String s,int offset,String c) { - Assert.assertThat(s.substring(offset),Matchers.not(Matchers.containsString(c))); + assertThat(s.substring(offset),Matchers.not(Matchers.containsString(c))); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputAsyncStateTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputAsyncStateTest.java index 6b9f23ad6bf..58dd8d6bb49 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputAsyncStateTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputAsyncStateTest.java @@ -18,6 +18,15 @@ package org.eclipse.jetty.server; +import static org.eclipse.jetty.server.HttpInput.EARLY_EOF_CONTENT; +import static org.eclipse.jetty.server.HttpInput.EOF_CONTENT; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.Queue; @@ -27,23 +36,13 @@ import javax.servlet.ReadListener; import org.eclipse.jetty.server.HttpChannelState.Action; import org.eclipse.jetty.server.HttpInput.Content; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.thread.Scheduler; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; -import static org.eclipse.jetty.server.HttpInput.EARLY_EOF_CONTENT; -import static org.eclipse.jetty.server.HttpInput.EOF_CONTENT; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** @@ -51,7 +50,6 @@ import static org.junit.Assert.assertTrue; */ -@RunWith(AdvancedRunner.class) public class HttpInputAsyncStateTest { @@ -97,7 +95,7 @@ public class HttpInputAsyncStateTest } } - @Before + @BeforeEach public void before() { _noReadInDataAvailable = false; @@ -180,7 +178,7 @@ public class HttpInputAsyncStateTest { case DISPATCH: if (run==null) - Assert.fail(); + fail("Run is null during DISPATCH"); run.run(); break; @@ -197,7 +195,7 @@ public class HttpInputAsyncStateTest break; default: - Assert.fail(); + fail("Bad Action: " + action); } action = _state.unhandle(); } @@ -268,10 +266,10 @@ public class HttpInputAsyncStateTest } - @After + @AfterEach public void after() { - Assert.assertThat(__history.poll(), Matchers.nullValue()); + assertThat(__history.poll(), Matchers.nullValue()); } @Test diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputTest.java index 6beac80e580..39c6c3a87de 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpInputTest.java @@ -18,6 +18,14 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.EOFException; import java.io.IOException; import java.util.Queue; @@ -26,16 +34,11 @@ import java.util.concurrent.TimeoutException; import javax.servlet.ReadListener; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BufferUtil; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class HttpInputTest { private final Queue _history = new LinkedBlockingQueue<>(); @@ -87,7 +90,7 @@ public class HttpInputTest } } - @Before + @BeforeEach public void before() { _in = new HttpInput(new HttpChannelState(new HttpChannel(null, new HttpConfiguration(), null, null) @@ -151,22 +154,22 @@ public class HttpInputTest }; } - @After + @AfterEach public void after() { - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), nullValue()); } @Test public void testEmpty() throws Exception { - Assert.assertThat(_in.available(), Matchers.equalTo(0)); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.available(), equalTo(0)); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_history.poll(), nullValue()); } @Test @@ -176,41 +179,41 @@ public class HttpInputTest _in.addContent(new TContent("CD")); _fillAndParseSimulate.offer("EF"); _fillAndParseSimulate.offer("GH"); - Assert.assertThat(_in.available(), Matchers.equalTo(2)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); + assertThat(_in.available(), equalTo(2)); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.isReady(), equalTo(true)); - Assert.assertThat(_in.getContentConsumed(), Matchers.equalTo(0L)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); - Assert.assertThat(_in.getContentConsumed(), Matchers.equalTo(1L)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'B')); - Assert.assertThat(_in.getContentConsumed(), Matchers.equalTo(2L)); + assertThat(_in.getContentConsumed(), equalTo(0L)); + assertThat(_in.read(), equalTo((int)'A')); + assertThat(_in.getContentConsumed(), equalTo(1L)); + assertThat(_in.read(), equalTo((int)'B')); + assertThat(_in.getContentConsumed(), equalTo(2L)); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'C')); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'D')); + assertThat(_in.read(), equalTo((int)'C')); + assertThat(_in.read(), equalTo((int)'D')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded CD")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded CD")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'E')); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'F')); + assertThat(_in.read(), equalTo((int)'E')); + assertThat(_in.read(), equalTo((int)'F')); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 2")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded EF")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 2")); + assertThat(_history.poll(), equalTo("Content succeeded EF")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'G')); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'H')); + assertThat(_in.read(), equalTo((int)'G')); + assertThat(_in.read(), equalTo((int)'H')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded GH")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded GH")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.getContentConsumed(), Matchers.equalTo(8L)); + assertThat(_in.getContentConsumed(), equalTo(8L)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), nullValue()); } @Test @@ -229,16 +232,16 @@ public class HttpInputTest } }).start(); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); + assertThat(_in.read(), equalTo((int)'A')); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("blockForContent")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("blockForContent")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'B')); + assertThat(_in.read(), equalTo((int)'B')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), nullValue()); } @Test @@ -248,26 +251,26 @@ public class HttpInputTest _in.addContent(new TContent("CD")); _in.eof(); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.available(), Matchers.equalTo(2)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.available(), equalTo(2)); + assertThat(_in.isFinished(), equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'B')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.read(), equalTo((int)'A')); + assertThat(_in.read(), equalTo((int)'B')); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'C')); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'D')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded CD")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); + assertThat(_in.read(), equalTo((int)'C')); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.read(), equalTo((int)'D')); + assertThat(_history.poll(), equalTo("Content succeeded CD")); + assertThat(_history.poll(), nullValue()); + assertThat(_in.isFinished(), equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo(-1)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); + assertThat(_in.read(), equalTo(-1)); + assertThat(_in.isFinished(), equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), nullValue()); } @Test @@ -277,30 +280,23 @@ public class HttpInputTest _in.addContent(new TContent("CD")); _in.earlyEOF(); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.available(), Matchers.equalTo(2)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.available(), equalTo(2)); + assertThat(_in.isFinished(), equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'B')); + assertThat(_in.read(), equalTo((int)'A')); + assertThat(_in.read(), equalTo((int)'B')); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'C')); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'D')); + assertThat(_in.read(), equalTo((int)'C')); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.read(), equalTo((int)'D')); - try - { - _in.read(); - Assert.fail(); - } - catch (EOFException eof) - { - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); - } + assertThrows(EOFException.class, ()-> _in.read()); + assertTrue(_in.isFinished()); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded CD")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), equalTo("Content succeeded CD")); + assertThat(_history.poll(), nullValue()); } @Test @@ -319,174 +315,168 @@ public class HttpInputTest } }).start(); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo(-1)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.read(), equalTo(-1)); + assertThat(_in.isFinished(), equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("blockForContent")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("blockForContent")); + assertThat(_history.poll(), nullValue()); } @Test public void testAsyncEmpty() throws Exception { _in.setReadListener(_listener); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onReadUnready")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("s.onReadUnready")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(false)); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(false)); + assertThat(_history.poll(), nullValue()); } @Test public void testAsyncRead() throws Exception { _in.setReadListener(_listener); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onReadUnready")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("s.onReadUnready")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(false)); + assertThat(_history.poll(), nullValue()); _in.addContent(new TContent("AB")); _fillAndParseSimulate.add("CD"); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("s.onDataAvailable")); + assertThat(_history.poll(), nullValue()); _in.run(); - Assert.assertThat(_history.poll(), Matchers.equalTo("l.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("l.onDataAvailable")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_in.read(), equalTo((int)'A')); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'B')); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_in.read(), equalTo((int)'B')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 1")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_history.poll(), equalTo("produceContent 1")); + assertThat(_history.poll(), equalTo("s.onDataAvailable")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'C')); + assertThat(_in.read(), equalTo((int)'C')); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'D')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded CD")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_in.read(), equalTo((int)'D')); + assertThat(_history.poll(), equalTo("Content succeeded CD")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onReadUnready")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(false)); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("s.onReadUnready")); + assertThat(_history.poll(), nullValue()); } @Test public void testAsyncEOF() throws Exception { _in.setReadListener(_listener); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onReadUnready")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("s.onReadUnready")); + assertThat(_history.poll(), nullValue()); _in.eof(); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_history.poll(), equalTo("s.onDataAvailable")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.read(), Matchers.equalTo(-1)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.read(), equalTo(-1)); + assertThat(_in.isFinished(), equalTo(true)); + assertThat(_history.poll(), nullValue()); } @Test public void testAsyncReadEOF() throws Exception { _in.setReadListener(_listener); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onReadUnready")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("s.onReadUnready")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(false)); + assertThat(_history.poll(), nullValue()); _in.addContent(new TContent("AB")); _fillAndParseSimulate.add("_EOF_"); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("s.onDataAvailable")); + assertThat(_history.poll(), nullValue()); _in.run(); - Assert.assertThat(_history.poll(), Matchers.equalTo("l.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("l.onDataAvailable")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_in.read(), equalTo((int)'A')); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'B')); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_in.read(), equalTo((int)'B')); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 1")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_history.poll(), equalTo("produceContent 1")); + assertThat(_history.poll(), equalTo("s.onDataAvailable")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(false)); - Assert.assertThat(_in.read(), Matchers.equalTo(-1)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isFinished(), equalTo(false)); + assertThat(_in.read(), equalTo(-1)); + assertThat(_in.isFinished(), equalTo(true)); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(true)); + assertThat(_history.poll(), nullValue()); } @Test public void testAsyncError() throws Exception { _in.setReadListener(_listener); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onReadUnready")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), equalTo("s.onReadUnready")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(false)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isReady(), equalTo(false)); + assertThat(_history.poll(), nullValue()); _in.failed(new TimeoutException()); - Assert.assertThat(_history.poll(), Matchers.equalTo("s.onDataAvailable")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("s.onDataAvailable")); + assertThat(_history.poll(), nullValue()); _in.run(); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.equalTo("l.onError:java.util.concurrent.TimeoutException")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_in.isFinished(), equalTo(true)); + assertThat(_history.poll(), equalTo("l.onError:java.util.concurrent.TimeoutException")); + assertThat(_history.poll(), nullValue()); - Assert.assertThat(_in.isReady(), Matchers.equalTo(true)); - try - { - _in.read(); - Assert.fail(); - } - catch (IOException e) - { - Assert.assertThat(e.getCause(), Matchers.instanceOf(TimeoutException.class)); - Assert.assertThat(_in.isFinished(), Matchers.equalTo(true)); - } + assertThat(_in.isReady(), equalTo(true)); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + IOException e = assertThrows(IOException.class, ()->_in.read()); + assertThat(e.getCause(), instanceOf(TimeoutException.class)); + assertThat(_in.isFinished(), equalTo(true)); + + assertThat(_history.poll(), nullValue()); } @Test @@ -506,18 +496,18 @@ public class HttpInputTest _in.addContent(new TContent("CD")); _fillAndParseSimulate.offer("EF"); _fillAndParseSimulate.offer("GH"); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); + assertThat(_in.read(), equalTo((int)'A')); - Assert.assertFalse(_in.consumeAll()); - Assert.assertThat(_in.getContentConsumed(), Matchers.equalTo(8L)); + assertFalse(_in.consumeAll()); + assertThat(_in.getContentConsumed(), equalTo(8L)); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded CD")); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 2")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded EF")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded GH")); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 0")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), equalTo("Content succeeded CD")); + assertThat(_history.poll(), equalTo("produceContent 2")); + assertThat(_history.poll(), equalTo("Content succeeded EF")); + assertThat(_history.poll(), equalTo("Content succeeded GH")); + assertThat(_history.poll(), equalTo("produceContent 0")); + assertThat(_history.poll(), nullValue()); } @Test @@ -528,16 +518,16 @@ public class HttpInputTest _fillAndParseSimulate.offer("EF"); _fillAndParseSimulate.offer("GH"); _fillAndParseSimulate.offer("_EOF_"); - Assert.assertThat(_in.read(), Matchers.equalTo((int)'A')); + assertThat(_in.read(), equalTo((int)'A')); - Assert.assertTrue(_in.consumeAll()); - Assert.assertThat(_in.getContentConsumed(), Matchers.equalTo(8L)); + assertTrue(_in.consumeAll()); + assertThat(_in.getContentConsumed(), equalTo(8L)); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded AB")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded CD")); - Assert.assertThat(_history.poll(), Matchers.equalTo("produceContent 3")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded EF")); - Assert.assertThat(_history.poll(), Matchers.equalTo("Content succeeded GH")); - Assert.assertThat(_history.poll(), Matchers.nullValue()); + assertThat(_history.poll(), equalTo("Content succeeded AB")); + assertThat(_history.poll(), equalTo("Content succeeded CD")); + assertThat(_history.poll(), equalTo("produceContent 3")); + assertThat(_history.poll(), equalTo("Content succeeded EF")); + assertThat(_history.poll(), equalTo("Content succeeded GH")); + assertThat(_history.poll(), nullValue()); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitBadBehaviourTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitBadBehaviourTest.java index 9c2ff16a6d0..dc0ac7ce03d 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitBadBehaviourTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitBadBehaviourTest.java @@ -18,16 +18,17 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.stream.Stream; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; @@ -37,50 +38,51 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.http.HttpVersion; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; //TODO: reset buffer tests //TODO: add protocol specific tests for connection: close and/or chunking -@RunWith(value = Parameterized.class) public class HttpManyWaysToAsyncCommitBadBehaviourTest extends AbstractHttpTest { private final String CONTEXT_ATTRIBUTE = getClass().getName() + ".asyncContext"; - private boolean dispatch; // if true we dispatch, otherwise we complete - @Parameterized.Parameters - public static Collection data() + public static Stream httpVersions() { - Object[][] data = new Object[][]{{HttpVersion.HTTP_1_0.asString(), true}, {HttpVersion.HTTP_1_0.asString(), - false}, {HttpVersion.HTTP_1_1.asString(), true}, {HttpVersion.HTTP_1_1.asString(), false}}; - return Arrays.asList(data); + // boolean dispatch - if true we dispatch, otherwise we complete + final boolean DISPATCH = true; + final boolean COMPLETE = false; + + List ret = new ArrayList<>(); + ret.add(Arguments.of(HttpVersion.HTTP_1_0, DISPATCH)); + ret.add(Arguments.of(HttpVersion.HTTP_1_0, COMPLETE)); + ret.add(Arguments.of(HttpVersion.HTTP_1_1, DISPATCH)); + ret.add(Arguments.of(HttpVersion.HTTP_1_1, COMPLETE)); + return ret.stream(); } - public HttpManyWaysToAsyncCommitBadBehaviourTest(String httpVersion, boolean dispatch) + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerSetsHandledAndWritesSomeContent(HttpVersion httpVersion, boolean dispatch) throws Exception { - super(httpVersion); - this.httpVersion = httpVersion; - this.dispatch = dispatch; - } - - @Test - public void testHandlerSetsHandledAndWritesSomeContent() throws Exception - { - server.setHandler(new SetHandledWriteSomeDataHandler(false)); + server.setHandler(new SetHandledWriteSomeDataHandler(false, dispatch)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code is 500", response.getStatus(), is(500)); } private class SetHandledWriteSomeDataHandler extends ThrowExceptionOnDemandHandler { - private SetHandledWriteSomeDataHandler(boolean throwException) + private final boolean dispatch; + + private SetHandledWriteSomeDataHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitTest.java index 86b224d5239..c668a017ddc 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToAsyncCommitTest.java @@ -18,13 +18,15 @@ package org.eclipse.jetty.server; +import static org.eclipse.jetty.http.HttpFieldsMatchers.containsHeaderValue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import javax.servlet.AsyncContext; import javax.servlet.ServletException; @@ -32,61 +34,57 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.http.HttpVersion; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; //TODO: reset buffer tests //TODO: add protocol specific tests for connection: close and/or chunking -@RunWith(value = Parameterized.class) public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest { private final String CONTEXT_ATTRIBUTE = getClass().getName() + ".asyncContext"; - private boolean dispatch; // if true we dispatch, otherwise we complete - @Parameterized.Parameters(name = "{0} dispatch={1}") - public static Collection data() + public static Stream httpVersion() { - Object[][] data = new Object[][] - { - {HttpVersion.HTTP_1_0.asString(), true}, - {HttpVersion.HTTP_1_1.asString(), true}, - {HttpVersion.HTTP_1_0.asString(), false}, - {HttpVersion.HTTP_1_1.asString(), false} - }; - return Arrays.asList(data); + // boolean dispatch - if true we dispatch, otherwise we complete + final boolean DISPATCH = true; + final boolean COMPLETE = false; + + List ret = new ArrayList<>(); + ret.add(Arguments.of(HttpVersion.HTTP_1_0, DISPATCH)); + ret.add(Arguments.of(HttpVersion.HTTP_1_1, DISPATCH)); + ret.add(Arguments.of(HttpVersion.HTTP_1_0, COMPLETE)); + ret.add(Arguments.of(HttpVersion.HTTP_1_1, COMPLETE)); + return ret.stream(); } - public HttpManyWaysToAsyncCommitTest(String httpVersion, boolean dispatch) + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerDoesNotSetHandled(HttpVersion httpVersion, boolean dispatch) throws Exception { - super(httpVersion); - this.httpVersion = httpVersion; - this.dispatch = dispatch; - } - - @Test - public void testHandlerDoesNotSetHandled() throws Exception - { - DoesNotSetHandledHandler handler = new DoesNotSetHandledHandler(false); + DoesNotSetHandledHandler handler = new DoesNotSetHandledHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(404)); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testHandlerDoesNotSetHandledAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerDoesNotSetHandledAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - DoesNotSetHandledHandler handler = new DoesNotSetHandledHandler(true); + DoesNotSetHandledHandler handler = new DoesNotSetHandledHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(500)); assertThat("no exceptions", handler.failure(), is(nullValue())); @@ -94,9 +92,12 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest private class DoesNotSetHandledHandler extends ThrowExceptionOnDemandHandler { - private DoesNotSetHandledHandler(boolean throwException) + private final boolean dispatch; + + private DoesNotSetHandledHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -122,29 +123,31 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testHandlerSetsHandledTrueOnly() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerSetsHandledTrueOnly(HttpVersion httpVersion, boolean dispatch) throws Exception { - OnlySetHandledHandler handler = new OnlySetHandledHandler(false); + OnlySetHandledHandler handler = new OnlySetHandledHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - if (HttpVersion.HTTP_1_1.asString().equals(httpVersion)) - assertHeader(response, "content-length", "0"); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.CONTENT_LENGTH, "0")); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testHandlerSetsHandledTrueOnlyAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerSetsHandledTrueOnlyAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - OnlySetHandledHandler handler = new OnlySetHandledHandler(true); + OnlySetHandledHandler handler = new OnlySetHandledHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(500)); assertThat("no exceptions", handler.failure(), is(nullValue())); @@ -152,9 +155,12 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest private class OnlySetHandledHandler extends ThrowExceptionOnDemandHandler { - private OnlySetHandledHandler(boolean throwException) + private final boolean dispatch; + + private OnlySetHandledHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -181,28 +187,30 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testHandlerSetsHandledAndWritesSomeContent() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerSetsHandledAndWritesSomeContent(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetHandledWriteSomeDataHandler handler = new SetHandledWriteSomeDataHandler(false); + SetHandledWriteSomeDataHandler handler = new SetHandledWriteSomeDataHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertHeader(response, "content-length", "6"); + assertThat(response, containsHeaderValue(HttpHeader.CONTENT_LENGTH, "6")); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testHandlerSetsHandledAndWritesSomeContentAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerSetsHandledAndWritesSomeContentAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetHandledWriteSomeDataHandler handler = new SetHandledWriteSomeDataHandler(true); + SetHandledWriteSomeDataHandler handler = new SetHandledWriteSomeDataHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(500)); assertThat("no exceptions", handler.failure(), is(nullValue())); @@ -210,9 +218,12 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest private class SetHandledWriteSomeDataHandler extends ThrowExceptionOnDemandHandler { - private SetHandledWriteSomeDataHandler(boolean throwException) + private final boolean dispatch; + + private SetHandledWriteSomeDataHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -247,42 +258,47 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testHandlerExplicitFlush() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerExplicitFlush(HttpVersion httpVersion, boolean dispatch) throws Exception { - ExplicitFlushHandler handler = new ExplicitFlushHandler(false); + ExplicitFlushHandler handler = new ExplicitFlushHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); } - @Test - public void testHandlerExplicitFlushAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandlerExplicitFlushAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - ExplicitFlushHandler handler = new ExplicitFlushHandler(true); + ExplicitFlushHandler handler = new ExplicitFlushHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); } private class ExplicitFlushHandler extends ThrowExceptionOnDemandHandler { - private ExplicitFlushHandler(boolean throwException) + private final boolean dispatch; + + private ExplicitFlushHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -319,41 +335,46 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testHandledAndFlushWithoutContent() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandledAndFlushWithoutContent(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetHandledAndFlushWithoutContentHandler handler = new SetHandledAndFlushWithoutContentHandler(false); + SetHandledAndFlushWithoutContentHandler handler = new SetHandledAndFlushWithoutContentHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); } - @Test - public void testHandledAndFlushWithoutContentAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testHandledAndFlushWithoutContentAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetHandledAndFlushWithoutContentHandler handler = new SetHandledAndFlushWithoutContentHandler(true); + SetHandledAndFlushWithoutContentHandler handler = new SetHandledAndFlushWithoutContentHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); } private class SetHandledAndFlushWithoutContentHandler extends ThrowExceptionOnDemandHandler { - private SetHandledAndFlushWithoutContentHandler(boolean throwException) + private final boolean dispatch; + + private SetHandledAndFlushWithoutContentHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -388,41 +409,48 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testWriteFlushWriteMore() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testWriteFlushWriteMore(HttpVersion httpVersion, boolean dispatch) throws Exception { - WriteFlushWriteMoreHandler handler = new WriteFlushWriteMoreHandler(false); + WriteFlushWriteMoreHandler handler = new WriteFlushWriteMoreHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); // HTTP/1.0 does not do chunked. it will just send content and close + + // HTTP/1.0 does not do chunked. it will just send content and close + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); } - @Test - public void testWriteFlushWriteMoreAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testWriteFlushWriteMoreAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - WriteFlushWriteMoreHandler handler = new WriteFlushWriteMoreHandler(true); + WriteFlushWriteMoreHandler handler = new WriteFlushWriteMoreHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); } private class WriteFlushWriteMoreHandler extends ThrowExceptionOnDemandHandler { - private WriteFlushWriteMoreHandler(boolean throwException) + private final boolean dispatch; + + private WriteFlushWriteMoreHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -460,44 +488,49 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testBufferOverflow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testBufferOverflow(HttpVersion httpVersion, boolean dispatch) throws Exception { - OverflowHandler handler = new OverflowHandler(false); + OverflowHandler handler = new OverflowHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobar")); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testBufferOverflowAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testBufferOverflowAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - OverflowHandler handler = new OverflowHandler(true); + OverflowHandler handler = new OverflowHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Buffer size is too small, so the content is written directly producing a 200 response assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobar")); + if (httpVersion.is("HTTP/1.1")) + assertThat(response, containsHeaderValue(HttpHeader.TRANSFER_ENCODING, "chunked")); assertThat("no exceptions", handler.failure(), is(nullValue())); } private class OverflowHandler extends ThrowExceptionOnDemandHandler { - private OverflowHandler(boolean throwException) + private final boolean dispatch; + + private OverflowHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -534,42 +567,47 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testSetContentLengthAndWriteExactlyThatAmountOfBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testSetContentLengthAndWriteExactlyThatAmountOfBytes(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetContentLengthAndWriteThatAmountOfBytesHandler handler = new SetContentLengthAndWriteThatAmountOfBytesHandler(false); + SetContentLengthAndWriteThatAmountOfBytesHandler handler = new SetContentLengthAndWriteThatAmountOfBytesHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue(HttpHeader.CONTENT_LENGTH, "3")); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testSetContentLengthAndWriteExactlyThatAmountOfBytesAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testSetContentLengthAndWriteExactlyThatAmountOfBytesAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetContentLengthAndWriteThatAmountOfBytesHandler handler = new SetContentLengthAndWriteThatAmountOfBytesHandler(true); + SetContentLengthAndWriteThatAmountOfBytesHandler handler = new SetContentLengthAndWriteThatAmountOfBytesHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); //TODO: should we expect 500 here? assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue(HttpHeader.CONTENT_LENGTH, "3")); assertThat("no exceptions", handler.failure(), is(nullValue())); } private class SetContentLengthAndWriteThatAmountOfBytesHandler extends ThrowExceptionOnDemandHandler { - private SetContentLengthAndWriteThatAmountOfBytesHandler(boolean throwException) + private final boolean dispatch; + + private SetContentLengthAndWriteThatAmountOfBytesHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -606,43 +644,48 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testSetContentLengthAndWriteMoreBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testSetContentLengthAndWriteMoreBytes(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetContentLengthAndWriteMoreBytesHandler handler = new SetContentLengthAndWriteMoreBytesHandler(false); + SetContentLengthAndWriteMoreBytesHandler handler = new SetContentLengthAndWriteMoreBytesHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); // jetty truncates the body when content-length is reached.! This is correct and desired behaviour? assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue(HttpHeader.CONTENT_LENGTH, "3")); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testSetContentLengthAndWriteMoreAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testSetContentLengthAndWriteMoreAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - SetContentLengthAndWriteMoreBytesHandler handler = new SetContentLengthAndWriteMoreBytesHandler(true); + SetContentLengthAndWriteMoreBytesHandler handler = new SetContentLengthAndWriteMoreBytesHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // TODO: we throw before response is committed. should we expect 500? assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue(HttpHeader.CONTENT_LENGTH, "3")); assertThat("no exceptions", handler.failure(), is(nullValue())); } private class SetContentLengthAndWriteMoreBytesHandler extends ThrowExceptionOnDemandHandler { - private SetContentLengthAndWriteMoreBytesHandler(boolean throwException) + private final boolean dispatch; + + private SetContentLengthAndWriteMoreBytesHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -679,28 +722,30 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testWriteAndSetContentLength() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testWriteAndSetContentLength(HttpVersion httpVersion, boolean dispatch) throws Exception { - WriteAndSetContentLengthHandler handler = new WriteAndSetContentLengthHandler(false); + WriteAndSetContentLengthHandler handler = new WriteAndSetContentLengthHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); //TODO: jetty ignores setContentLength and sends transfer-encoding header. Correct? } - @Test - public void testWriteAndSetContentLengthAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testWriteAndSetContentLengthAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - WriteAndSetContentLengthHandler handler = new WriteAndSetContentLengthHandler(true); + WriteAndSetContentLengthHandler handler = new WriteAndSetContentLengthHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("no exceptions", handler.failure(), is(nullValue())); @@ -708,9 +753,12 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest private class WriteAndSetContentLengthHandler extends ThrowExceptionOnDemandHandler { - private WriteAndSetContentLengthHandler(boolean throwException) + private final boolean dispatch; + + private WriteAndSetContentLengthHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override @@ -747,28 +795,30 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest } } - @Test - public void testWriteAndSetContentLengthTooSmall() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testWriteAndSetContentLengthTooSmall(HttpVersion httpVersion, boolean dispatch) throws Exception { - WriteAndSetContentLengthTooSmallHandler handler = new WriteAndSetContentLengthTooSmallHandler(false); + WriteAndSetContentLengthTooSmallHandler handler = new WriteAndSetContentLengthTooSmallHandler(false, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Setting a content-length too small throws an IllegalStateException assertThat("response code", response.getStatus(), is(500)); assertThat("no exceptions", handler.failure(), is(nullValue())); } - @Test - public void testWriteAndSetContentLengthTooSmallAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersion") + public void testWriteAndSetContentLengthTooSmallAndThrow(HttpVersion httpVersion, boolean dispatch) throws Exception { - WriteAndSetContentLengthTooSmallHandler handler = new WriteAndSetContentLengthTooSmallHandler(true); + WriteAndSetContentLengthTooSmallHandler handler = new WriteAndSetContentLengthTooSmallHandler(true, dispatch); server.setHandler(handler); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Setting a content-length too small throws an IllegalStateException assertThat("response code", response.getStatus(), is(500)); @@ -777,9 +827,12 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest private class WriteAndSetContentLengthTooSmallHandler extends ThrowExceptionOnDemandHandler { - private WriteAndSetContentLengthTooSmallHandler(boolean throwException) + private final boolean dispatch; + + private WriteAndSetContentLengthTooSmallHandler(boolean throwException, boolean dispatch) { super(throwException); + this.dispatch = dispatch; } @Override diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToCommitTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToCommitTest.java index cd8c407c220..7c68256f3fb 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToCommitTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpManyWaysToCommitTest.java @@ -18,15 +18,16 @@ package org.eclipse.jetty.server; +import static org.eclipse.jetty.http.HttpFieldsMatchers.containsHeaderValue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumingThat; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; +import java.util.stream.Stream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -35,45 +36,42 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; //TODO: reset buffer tests //TODO: add protocol specific tests for connection: close and/or chunking -@RunWith(Parameterized.class) public class HttpManyWaysToCommitTest extends AbstractHttpTest { - @Parameterized.Parameters(name = "{0}") - public static Collection data() + public static Stream httpVersions() { - Object[][] data = new Object[][]{{HttpVersion.HTTP_1_0.asString()}, {HttpVersion.HTTP_1_1.asString()}}; - return Arrays.asList(data); + return Stream.of( + HttpVersion.HTTP_1_0, + HttpVersion.HTTP_1_1 + ).map(Arguments::of); } - public HttpManyWaysToCommitTest(String httpVersion) - { - super(httpVersion); - } - - @Test - public void testHandlerDoesNotSetHandled() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerDoesNotSetHandled(HttpVersion httpVersion) throws Exception { server.setHandler(new DoesNotSetHandledHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(404)); } - @Test - public void testHandlerDoesNotSetHandledAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerDoesNotSetHandledAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new DoesNotSetHandledHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(500)); } @@ -93,26 +91,28 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testHandlerSetsHandledTrueOnly() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerSetsHandledTrueOnly(HttpVersion httpVersion) throws Exception { server.setHandler(new OnlySetHandledHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); if (HttpVersion.HTTP_1_1.asString().equals(httpVersion)) - assertHeader(response, "content-length", "0"); + assertThat(response, containsHeaderValue("content-length", "0")); } - @Test - public void testHandlerSetsHandledTrueOnlyAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerSetsHandledTrueOnlyAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new OnlySetHandledHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(500)); } @@ -132,26 +132,28 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testHandlerSetsHandledAndWritesSomeContent() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerSetsHandledAndWritesSomeContent(HttpVersion httpVersion) throws Exception { server.setHandler(new SetHandledWriteSomeDataHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - assertHeader(response, "content-length", "6"); + assertThat(response.getContent(), is("foobar")); + assertThat(response, containsHeaderValue("content-length", "6")); } - @Test - public void testHandlerSetsHandledAndWritesSomeContentAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerSetsHandledAndWritesSomeContentAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new SetHandledWriteSomeDataHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(500)); assertThat("response body", response.getContent(), not(is("foobar"))); @@ -173,33 +175,35 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testHandlerExplicitFlush() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerExplicitFlush(HttpVersion httpVersion) throws Exception { server.setHandler(new ExplicitFlushHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobar")); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } - @Test - public void testHandlerExplicitFlushAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandlerExplicitFlushAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new ExplicitFlushHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Since the 200 was committed, the 500 did not get the chance to be written assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foobar")); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } private class ExplicitFlushHandler extends ThrowExceptionOnDemandHandler @@ -219,30 +223,32 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testHandledAndFlushWithoutContent() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledAndFlushWithoutContent(HttpVersion httpVersion) throws Exception { server.setHandler(new SetHandledAndFlushWithoutContentHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } - @Test - public void testHandledAndFlushWithoutContentAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledAndFlushWithoutContentAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new SetHandledAndFlushWithoutContentHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } private class SetHandledAndFlushWithoutContentHandler extends ThrowExceptionOnDemandHandler @@ -261,32 +267,34 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testHandledWriteFlushWriteMore() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledWriteFlushWriteMore(HttpVersion httpVersion) throws Exception { server.setHandler(new WriteFlushWriteMoreHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobar")); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } - @Test - public void testHandledWriteFlushWriteMoreAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledWriteFlushWriteMoreAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new WriteFlushWriteMoreHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Since the 200 was committed, the 500 did not get the chance to be written assertThat("response code", response.getStatus(), is(200)); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } private class WriteFlushWriteMoreHandler extends ThrowExceptionOnDemandHandler @@ -307,61 +315,65 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testHandledOverflow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledOverflow(HttpVersion httpVersion) throws Exception { server.setHandler(new OverflowHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobar")); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } - @Test - public void testHandledOverflow2() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledOverflow2(HttpVersion httpVersion) throws Exception { server.setHandler(new Overflow2Handler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobarfoobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobarfoobar")); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } - @Test - public void testHandledOverflow3() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledOverflow3(HttpVersion httpVersion) throws Exception { server.setHandler(new Overflow3Handler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobarfoobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobarfoobar")); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } - @Test - public void testHandledBufferOverflowAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testHandledBufferOverflowAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new OverflowHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Response was committed when we throw, so 200 expected assertThat("response code", response.getStatus(), is(200)); - assertResponseBody(response, "foobar"); - if (!"HTTP/1.0".equals(httpVersion)) - assertHeader(response, "transfer-encoding", "chunked"); + assertThat(response.getContent(), is("foobar")); + assumingThat(httpVersion == HttpVersion.HTTP_1_1, + () -> assertThat(response, containsHeaderValue("transfer-encoding", "chunked"))); } private class OverflowHandler extends ThrowExceptionOnDemandHandler @@ -421,63 +433,68 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testSetContentLengthFlushAndWriteInsufficientBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthFlushAndWriteInsufficientBytes(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteInsufficientBytesHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); - assertHeader(response, "content-length", "6"); + assertThat(response, containsHeaderValue("content-length", "6")); byte content[] = response.getContentBytes(); assertThat("content bytes", content.length, is(0)); - assertTrue("response eof", response.isEarlyEOF()); + assertTrue(response.isEarlyEOF(), "response eof"); } - @Test - public void testSetContentLengthAndWriteInsufficientBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthAndWriteInsufficientBytes(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteInsufficientBytesHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response is error", response.getStatus(), is(500)); - assertFalse("response not eof", response.isEarlyEOF()); + assertFalse(response.isEarlyEOF(), "response not eof"); } - @Test - public void testSetContentLengthAndFlushWriteInsufficientBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthAndFlushWriteInsufficientBytes(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteInsufficientBytesHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response has no status", response.getStatus(), is(200)); - assertTrue("response eof", response.isEarlyEOF()); + assertTrue(response.isEarlyEOF(), "response eof"); } - @Test - public void testSetContentLengthAndWriteExactlyThatAmountOfBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthAndWriteExactlyThatAmountOfBytes(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteThatAmountOfBytesHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue("content-length", "3")); } - @Test - public void testSetContentLengthAndWriteExactlyThatAmountOfBytesAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthAndWriteExactlyThatAmountOfBytesAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteThatAmountOfBytesHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Setting the content-length and then writing the bytes commits the response assertThat("response code", response.getStatus(), is(200)); @@ -520,26 +537,28 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testSetContentLengthAndWriteMoreBytes() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthAndWriteMoreBytes(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteMoreBytesHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue("content-length", "3")); } - @Test - public void testSetContentLengthAndWriteMoreAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testSetContentLengthAndWriteMoreAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new SetContentLengthAndWriteMoreBytesHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Setting the content-length and then writing the bytes commits the response assertThat("response code", response.getStatus(), is(200)); @@ -564,26 +583,28 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testWriteAndSetContentLength() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testWriteAndSetContentLength(HttpVersion httpVersion) throws Exception { server.setHandler(new WriteAndSetContentLengthHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); assertThat("response code", response.getStatus(), is(200)); assertThat("response body", response.getContent(), is("foo")); - assertHeader(response, "content-length", "3"); + assertThat(response, containsHeaderValue("content-length", "3")); } - @Test - public void testWriteAndSetContentLengthAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testWriteAndSetContentLengthAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new WriteAndSetContentLengthHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Writing the bytes and then setting the content-length commits the response assertThat("response code", response.getStatus(), is(200)); @@ -607,26 +628,28 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest } } - @Test - public void testWriteAndSetContentLengthTooSmall() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testWriteAndSetContentLengthTooSmall(HttpVersion httpVersion) throws Exception { server.setHandler(new WriteAndSetContentLengthTooSmallHandler(false)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Setting a content-length too small throws an IllegalStateException assertThat("response code", response.getStatus(), is(500)); assertThat("response body", response.getContent(), not(is("foo"))); } - @Test - public void testWriteAndSetContentLengthTooSmallAndThrow() throws Exception + @ParameterizedTest + @MethodSource("httpVersions") + public void testWriteAndSetContentLengthTooSmallAndThrow(HttpVersion httpVersion) throws Exception { server.setHandler(new WriteAndSetContentLengthTooSmallHandler(true)); server.start(); - HttpTester.Response response = executeRequest(); + HttpTester.Response response = executeRequest(httpVersion); // Setting a content-length too small throws an IllegalStateException assertThat("response code", response.getStatus(), is(500)); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpOutputTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpOutputTest.java index bb5613e11a4..9f6a6253585 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpOutputTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpOutputTest.java @@ -20,8 +20,9 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.FilterInputStream; import java.io.IOException; @@ -41,21 +42,18 @@ import org.eclipse.jetty.server.HttpOutput.Interceptor; import org.eclipse.jetty.server.LocalConnector.LocalEndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.HotSwapHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.resource.Resource; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * */ -@RunWith(AdvancedRunner.class) public class HttpOutputTest { private Server _server; @@ -63,7 +61,7 @@ public class HttpOutputTest private ContentHandler _handler; private HotSwapHandler _swap; - @Before + @BeforeEach public void init() throws Exception { _server = new Server(); @@ -82,7 +80,7 @@ public class HttpOutputTest _server.start(); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); @@ -121,9 +119,9 @@ public class HttpOutputTest assertThat(response,containsString("\r\nXXXXXXXXXXXXXXXXXXXXXXXXXXX")); for (int i=0;i<4*1024;i++) - assertEquals("i="+i,(byte)0x99,buffer[i]); + assertEquals((byte)0x99, buffer[i], "i="+i); for (int i=12*1024;i<16*1024;i++) - assertEquals("i="+i,(byte)0x66,buffer[i]); + assertEquals((byte)0x66, buffer[i], "i="+i); } @Test @@ -754,7 +752,7 @@ public class HttpOutputTest while (out.isReady()) { - Assert.assertTrue(out.isReady()); + assertTrue(out.isReady()); int len=_content.remaining(); if (len>_arrayBuffer.length) len=_arrayBuffer.length; @@ -770,7 +768,7 @@ public class HttpOutputTest else out.write(_arrayBuffer,0,len); } - // Assert.assertFalse(out.isReady()); + // assertFalse(out.isReady()); } @Override @@ -815,8 +813,8 @@ public class HttpOutputTest while (out.isReady()) { - Assert.assertTrue(isFirstWrite || !_byteBuffer.hasRemaining()); - Assert.assertTrue(out.isReady()); + assertTrue(isFirstWrite || !_byteBuffer.hasRemaining()); + assertTrue(out.isReady()); if(BufferUtil.isEmpty(_content)) { async.complete(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java index abd1f9fffa0..49021ba059f 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestBase.java @@ -18,6 +18,16 @@ package org.eclipse.jetty.server; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.EOFException; @@ -43,28 +53,15 @@ import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.AbstractLogger; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; -@RunWith(AdvancedRunner.class) public abstract class HttpServerTestBase extends HttpServerTestFixture { private static final String REQUEST1_HEADER = "POST / HTTP/1.0\n" + "Host: localhost\n" + "Content-Type: text/xml; charset=utf-8\n" + "Connection: close\n" + "Content-Length: "; @@ -130,8 +127,8 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture // Read the response. String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("Hello world")); + assertThat(response, Matchers.containsString("HTTP/1.1 200 OK")); + assertThat(response, Matchers.containsString("Hello world")); } } @@ -153,8 +150,8 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture // Read the response. String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("Allow: GET")); + assertThat(response, Matchers.containsString("HTTP/1.1 200 OK")); + assertThat(response, Matchers.containsString("Allow: GET")); } try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort())) @@ -170,8 +167,8 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture // Read the response. String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 400 ")); - Assert.assertThat(response, Matchers.not(Matchers.containsString("Allow: "))); + assertThat(response, Matchers.containsString("HTTP/1.1 400 ")); + assertThat(response, Matchers.not(Matchers.containsString("Allow: "))); } } @@ -199,7 +196,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture // Read the response. String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 431 ")); + assertThat(response, Matchers.containsString("HTTP/1.1 431 ")); } } @@ -235,7 +232,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture // Read the response. String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 414 ")); + assertThat(response, Matchers.containsString("HTTP/1.1 414 ")); } } @@ -395,7 +392,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture try { String response = readResponse(client); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 431 ")); + assertThat(response, Matchers.containsString("HTTP/1.1 431 ")); } catch(Exception e) { @@ -424,7 +421,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String response = readResponse(client); // Check the response - assertEquals("response", RESPONSE1, response); + assertEquals(RESPONSE1, response, "response"); } } @@ -512,7 +509,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String response = readResponse(client); // Check the response - assertEquals("response", RESPONSE1, response); + assertEquals(RESPONSE1, response, "response"); } } @@ -535,7 +532,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String response = readResponse(client); // Check the response - assertEquals("response " + i, RESPONSE2, response); + assertEquals(RESPONSE2, response, "response " + i); } catch (IOException e) { @@ -548,7 +545,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture @Test - @Slow + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testRequest2Sliced2() throws Exception { configureServer(new EchoHandler()); @@ -572,7 +569,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String response = readResponse(client); // Check the response - assertEquals("response for " + i + " " + message.toString(), RESPONSE2, response); + assertEquals(RESPONSE2, response, "response for " + i + " " + message.toString()); Thread.sleep(10); } @@ -580,7 +577,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture } @Test - @Slow + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testRequest2Sliced3() throws Exception { configureServer(new EchoHandler()); @@ -604,7 +601,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String response = readResponse(client); // Check the response - assertEquals("response for " + i + " " + message.toString(), RESPONSE2, response); + assertEquals(RESPONSE2, response, "response for " + i + " " + message.toString()); Thread.sleep(10); } @@ -614,7 +611,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture - @Test + @Test // TODO: Parameterize public void testFlush() throws Exception { configureServer(new DataHandler()); @@ -636,7 +633,7 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture InputStream in = (InputStream)url.getContent(); String response = IO.toString(in, e == 0 ? null : encoding[e]); - assertEquals(test, b * w, response.length()); + assertEquals(b * w, response.length(), test); } catch (Exception x) { @@ -888,8 +885,8 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture chunked |= "Transfer-Encoding: chunked".equals(line); closed |= "Connection: close".equals(line); } - Assert.assertTrue(chunked); - Assert.assertFalse(closed); + assertTrue(chunked); + assertFalse(closed); // Read the chunks int max = Integer.MIN_VALUE; @@ -900,25 +897,25 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture if (line.length() == 0) break; int len = line.length(); - Assert.assertEquals(Integer.valueOf(chunk, 16).intValue(), len); + assertEquals(Integer.valueOf(chunk, 16).intValue(), len); if (max < len) max = len; } // Check that biggest chunk was <= buffer size - Assert.assertEquals(_connector.getBean(HttpConnectionFactory.class).getHttpConfiguration().getOutputBufferSize() , max); + assertEquals(_connector.getBean(HttpConnectionFactory.class).getHttpConfiguration().getOutputBufferSize() , max); // read and check the times are < 999ms String[] times = in.readLine().split(","); for (String t : times) - Assert.assertTrue(Integer.parseInt(t) < 999); + assertTrue(Integer.parseInt(t) < 999); // read the EOF chunk String end = in.readLine(); - Assert.assertEquals("0", end); + assertEquals("0", end); end = in.readLine(); - Assert.assertEquals(0, end.length()); + assertEquals(0, end.length()); // read the non-chunked response header chunked = false; @@ -932,19 +929,19 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture chunked |= "Transfer-Encoding: chunked".equals(line); closed |= "Connection: close".equals(line); } - Assert.assertFalse(chunked); - Assert.assertTrue(closed); + assertFalse(chunked); + assertTrue(closed); String bigline = in.readLine(); - Assert.assertEquals(10 * 128 * 1024, bigline.length()); + assertEquals(10 * 128 * 1024, bigline.length()); // read and check the times are < 999ms times = in.readLine().split(","); for (String t : times) - Assert.assertTrue(t, Integer.parseInt(t) < 999); + assertTrue(Integer.parseInt(t) < 999,t); // check close - Assert.assertTrue(in.readLine() == null); + assertTrue(in.readLine() == null); } } @@ -1153,9 +1150,9 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String in = IO.toString(is); - Assert.assertThat(in,containsString("123456789")); - Assert.assertThat(in,not(containsString("ABCDEFGHI"))); - Assert.assertThat(in,containsString("abcdefghi")); + assertThat(in,containsString("123456789")); + assertThat(in,not(containsString("ABCDEFGHI"))); + assertThat(in,containsString("abcdefghi")); } } @@ -1453,8 +1450,8 @@ public abstract class HttpServerTestBase extends HttpServerTestFixture String response2 = readResponse(client2); // Check the response - assertEquals("client1", RESPONSE1, response1); - assertEquals("client2", RESPONSE1, response2); + assertEquals(RESPONSE1, response1, "client1"); + assertEquals(RESPONSE1, response2, "client2"); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestFixture.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestFixture.java index b2b6cf1a3f0..b93d761f8e6 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestFixture.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpServerTestFixture.java @@ -33,17 +33,16 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.HotSwapHandler; -import org.eclipse.jetty.toolchain.test.PropertyFlag; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; public class HttpServerTestFixture { // Useful constants protected static final long PAUSE=10L; - protected static final int LOOPS= PropertyFlag.isEnabled("test.stress")?250:50; + protected static final int LOOPS = 50; protected QueuedThreadPool _threadPool; protected Server _server; @@ -60,7 +59,7 @@ public class HttpServerTestFixture return socket; } - @Before + @BeforeEach public void before() { _threadPool = new QueuedThreadPool(); @@ -84,7 +83,7 @@ public class HttpServerTestFixture _serverURI = _server.getURI(); } - @After + @AfterEach public void stopServer() throws Exception { _server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpVersionCustomizerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpVersionCustomizerTest.java index a23a7cf6262..6d95c1fcdba 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpVersionCustomizerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpVersionCustomizerTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SocketChannel; @@ -30,22 +34,12 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.TestTracker; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -@RunWith(AdvancedRunner.class) +import org.junit.jupiter.api.Test; + public class HttpVersionCustomizerTest { - @Rule - public TestTracker tracker = new TestTracker(); - @Test public void testCustomizeHttpVersion() throws Exception { @@ -61,7 +55,7 @@ public class HttpVersionCustomizerTest { baseRequest.setHandled(true); response.setStatus(500); - Assert.assertEquals(HttpVersion.HTTP_1_1.asString(), request.getProtocol()); + assertEquals(HttpVersion.HTTP_1_1.asString(), request.getProtocol()); response.setStatus(200); response.getWriter().println("OK"); } @@ -77,8 +71,8 @@ public class HttpVersionCustomizerTest socket.write(request.generate()); HttpTester.Response response = HttpTester.parseResponse(HttpTester.from(socket)); - Assert.assertNotNull(response); - Assert.assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); + assertNotNull(response); + assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); } } finally diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpWriterTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpWriterTest.java index 03ed90a29cd..7543f94ced0 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/HttpWriterTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/HttpWriterTest.java @@ -18,7 +18,7 @@ package org.eclipse.jetty.server; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.ByteBuffer; @@ -26,22 +26,19 @@ import java.nio.charset.StandardCharsets; import org.eclipse.jetty.io.ArrayByteBufferPool; import org.eclipse.jetty.io.ByteBufferPool; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.Utf8StringBuilder; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class HttpWriterTest { private HttpOutput _httpOut; private ByteBuffer _bytes; - @Before + @BeforeEach public void init() throws Exception { _bytes = BufferUtil.allocate(2048); @@ -138,7 +135,7 @@ public class HttpWriterTest { HttpWriter _writer = new Iso88591HttpWriter(_httpOut); _writer.write("How now \uFF22rown cow"); - assertEquals("How now ?rown cow",new String(BufferUtil.toArray(_bytes),StandardCharsets.ISO_8859_1)); + assertEquals(new String(BufferUtil.toArray(_bytes), StandardCharsets.ISO_8859_1), "How now ?rown cow"); } @Test @@ -252,8 +249,8 @@ public class HttpWriterTest private void assertArrayEquals(byte[] b1, byte[] b2) { String test=new String(b1)+"=="+new String(b2); - assertEquals(test,b1.length,b2.length); + assertEquals(b1.length,b2.length,test); for (int i=0;i ranges = InclusiveByteRange.satisfiableRanges( strings.elements(), 200); - assertNull("Invalid Range [" + rangeString + "] should result in no satisfiable ranges",ranges); + assertNull(ranges,"Invalid Range [" + rangeString + "] should result in no satisfiable ranges"); } private void assertRange(String msg, int expectedFirst, int expectedLast, int size, InclusiveByteRange actualRange) { - assertEquals(msg + " - first",expectedFirst,actualRange.getFirst()); - assertEquals(msg + " - last",expectedLast,actualRange.getLast()); + assertEquals(expectedFirst,actualRange.getFirst(),msg + " - first"); + assertEquals(expectedLast,actualRange.getLast(),msg + " - last"); String expectedHeader = String.format("bytes %d-%d/%d",expectedFirst,expectedLast,size); - assertEquals(msg + " - header range string",expectedHeader,actualRange.toHeaderRangeString(size)); + assertThat(msg + " - header range string",actualRange.toHeaderRangeString(size),is(expectedHeader)); } private void assertSimpleRange(int expectedFirst, int expectedLast, String rangeId, int size) { InclusiveByteRange range = parseRange(rangeId,size); - assertEquals("Range [" + rangeId + "] - first",expectedFirst,range.getFirst()); - assertEquals("Range [" + rangeId + "] - last",expectedLast,range.getLast()); + assertEquals(expectedFirst,range.getFirst(),"Range [" + rangeId + "] - first"); + assertEquals(expectedLast,range.getLast(),"Range [" + rangeId + "] - last"); String expectedHeader = String.format("bytes %d-%d/%d",expectedFirst,expectedLast,size); - assertEquals("Range [" + rangeId + "] - header range string",expectedHeader,range.toHeaderRangeString(size)); + assertEquals(expectedHeader, range.toHeaderRangeString(size), "Range [" + rangeId + "] - header range string"); } private InclusiveByteRange parseRange(String rangeString, int size) @@ -67,9 +68,9 @@ public class InclusiveByteRangeTest strings.add(rangeString); List ranges = InclusiveByteRange.satisfiableRanges(strings.elements(),size); - assertNotNull("Satisfiable Ranges should not be null",ranges); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",1,ranges.size()); - return (InclusiveByteRange)ranges.iterator().next(); + assertNotNull(ranges,"Satisfiable Ranges should not be null"); + assertEquals(1,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); + return ranges.iterator().next(); } private List parseRanges(int size, String... rangeString) @@ -77,17 +78,17 @@ public class InclusiveByteRangeTest Vector strings = new Vector<>(); for (String range : rangeString) strings.add(range); - + List ranges = InclusiveByteRange.satisfiableRanges(strings.elements(),size); - assertNotNull("Satisfiable Ranges should not be null",ranges); + assertNotNull(ranges,"Satisfiable Ranges should not be null"); return ranges; } @Test public void testHeader416RangeString() { - assertEquals("416 Header on size 100","bytes */100",InclusiveByteRange.to416HeaderRangeString(100)); - assertEquals("416 Header on size 123456789","bytes */123456789",InclusiveByteRange.to416HeaderRangeString(123456789)); + assertEquals("bytes */100", InclusiveByteRange.to416HeaderRangeString(100), "416 Header on size 100"); + assertEquals("bytes */123456789", InclusiveByteRange.to416HeaderRangeString(123456789), "416 Header on size 123456789"); } @Test @@ -112,7 +113,7 @@ public class InclusiveByteRangeTest rangeString = "bytes=5-20,35-65"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",5,20,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",35,49,size,inclusiveByteRangeIterator.next()); @@ -145,7 +146,7 @@ public class InclusiveByteRangeTest rangeString = "bytes=5-20,35-65,-5"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",5,20,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",35,49,size,inclusiveByteRangeIterator.next()); @@ -160,7 +161,7 @@ public class InclusiveByteRangeTest rangeString = "bytes=5-20,15-25"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",1,ranges.size()); + assertEquals(1,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",5,25,size,inclusiveByteRangeIterator.next()); } @@ -173,7 +174,7 @@ public class InclusiveByteRangeTest rangeString = "bytes=5-10,15-20"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",5,10,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",15,20,size,inclusiveByteRangeIterator.next()); @@ -187,12 +188,12 @@ public class InclusiveByteRangeTest rangeString = "bytes=5-10,15-20,5-10,15-20,5-10,5-10,5-10,5-10,5-10,5-10"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",5,10,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",15,20,size,inclusiveByteRangeIterator.next()); } - + @Test public void testMultipleOverlappingRanges() { @@ -201,11 +202,11 @@ public class InclusiveByteRangeTest rangeString = "bytes=5-15,20-30,10-25"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",1,ranges.size()); + assertEquals(1,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",5,30,size,inclusiveByteRangeIterator.next()); } - + @Test public void testMultipleOverlappingRangesOrdered() { @@ -214,12 +215,12 @@ public class InclusiveByteRangeTest rangeString = "bytes=20-30,5-15,0-5,25-35"; List ranges = parseRanges(size,rangeString); - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",20,35,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",0,15,size,inclusiveByteRangeIterator.next()); } - + @Test public void testMultipleOverlappingRangesOrderedSplit() { @@ -227,13 +228,13 @@ public class InclusiveByteRangeTest String rangeString; rangeString = "bytes=20-30,5-15,0-5,25-35"; List ranges = parseRanges(size,"bytes=20-30","bytes=5-15","bytes=0-5,25-35"); - - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",20,35,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",0,15,size,inclusiveByteRangeIterator.next()); } - + @Test public void testNasty() { @@ -242,19 +243,19 @@ public class InclusiveByteRangeTest rangeString = "bytes=90-100, 10-20, 30-40, -161"; List ranges = parseRanges(size,rangeString); - - assertEquals("Satisfiable Ranges of [" + rangeString + "] count",2,ranges.size()); + + assertEquals(2,ranges.size(),"Satisfiable Ranges of [" + rangeString + "] count"); Iterator inclusiveByteRangeIterator = ranges.iterator(); assertRange("Range [" + rangeString + "]",30,199,size,inclusiveByteRangeIterator.next()); assertRange("Range [" + rangeString + "]",10,20,size,inclusiveByteRangeIterator.next()); } - + @Test public void testRange_OpenEnded() { assertSimpleRange(50, 499, "bytes=50-", 500); } - + @Test public void testSimpleRange() { @@ -262,7 +263,7 @@ public class InclusiveByteRangeTest assertSimpleRange(195,199,"bytes=-5",200); assertSimpleRange(50,119,"bytes=50-150",120); assertSimpleRange(50,119,"bytes=50-",120); - + assertSimpleRange(1,50,"bytes= 1 - 50",120); } @@ -271,81 +272,81 @@ public class InclusiveByteRangeTest { Vector strings = new Vector<>(); strings.add(badRange); - + List ranges = InclusiveByteRange.satisfiableRanges(strings.elements(),size); // if one part is bad, the entire set of ranges should be treated as bad, per RFC7233 assertThat("Should have no ranges", ranges, is(nullValue())); } - + @Test - @Ignore + @Disabled public void testBadRange_SetPartiallyBad() { assertBadRangeList(500, "bytes=1-50,1-b,a-50"); } - + @Test public void testBadRange_NoNumbers() { assertBadRangeList(500, "bytes=a-b"); } - + @Test public void testBadRange_Empty() { assertBadRangeList(500, "bytes="); } - + @Test - @Ignore + @Disabled public void testBadRange_ZeroPrefixed() { assertBadRangeList(500, "bytes=01-050"); } - + @Test public void testBadRange_Hex() { assertBadRangeList(500, "bytes=0F-FF"); } - + @Test - @Ignore + @Disabled public void testBadRange_TabWhitespace() { assertBadRangeList(500, "bytes=\t1\t-\t50"); } - + @Test public void testBadRange_TabDelim() { assertBadRangeList(500, "bytes=1-50\t90-101\t200-250"); } - + @Test public void testBadRange_SemiColonDelim() { assertBadRangeList(500, "bytes=1-50;90-101;200-250"); } - + @Test public void testBadRange_NegativeSize() { assertBadRangeList(500, "bytes=50-1"); } - + @Test public void testBadRange_DoubleDash() { assertBadRangeList(500, "bytes=1--20"); } - + @Test public void testBadRange_TrippleDash() { assertBadRangeList(500, "bytes=1---"); } - + @Test public void testBadRange_ZeroedNegativeSize() { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/InsufficientThreadsDetectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/InsufficientThreadsDetectionTest.java index c6dcb840be8..fb13cd58978 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/InsufficientThreadsDetectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/InsufficientThreadsDetectionTest.java @@ -18,33 +18,28 @@ package org.eclipse.jetty.server; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.util.log.Log; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; -import org.eclipse.jetty.util.thread.ThreadPoolBudget; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) -public class InsufficientThreadsDetectionTest +public class InsufficientThreadsDetectionTest { private Server _server; - @After + @AfterEach public void dispose() throws Exception { _server.stop(); } - @Test() + @Test public void testConnectorUsesServerExecutorWithNotEnoughThreads() throws Exception { - try - { + assertThrows(IllegalStateException.class, ()->{ // server has 3 threads in the executor _server = new Server(new QueuedThreadPool(3)); @@ -57,12 +52,7 @@ public class InsufficientThreadsDetectionTest // should throw IllegalStateException because there are no required threads in server pool _server.start(); - Assert.fail(); - } - catch(IllegalStateException e) - { - Log.getLogger(ThreadPoolBudget.class).warn(e.toString()); - } + }); } @Test @@ -85,8 +75,7 @@ public class InsufficientThreadsDetectionTest @Test public void testCaseForMultipleConnectors() throws Exception { - try - { + assertThrows(IllegalStateException.class, ()->{ // server has 4 threads in the executor _server = new Server(new QueuedThreadPool(4)); @@ -102,12 +91,6 @@ public class InsufficientThreadsDetectionTest // should throw exception because limit was overflown _server.start(); - - Assert.fail(); - } - catch(IllegalStateException e) - { - Log.getLogger(ThreadPoolBudget.class).warn(e.toString()); - } + }); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/LocalAsyncContextTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/LocalAsyncContextTest.java index c079003e710..f92f1354f86 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/LocalAsyncContextTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/LocalAsyncContextTest.java @@ -18,11 +18,12 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import javax.servlet.AsyncContext; @@ -35,22 +36,19 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.HandlerWrapper; import org.eclipse.jetty.server.session.SessionHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class LocalAsyncContextTest { protected Server _server; protected SuspendHandler _handler; protected Connector _connector; - @Before + @BeforeEach public void init() throws Exception { _server = new Server(); @@ -76,7 +74,7 @@ public class LocalAsyncContextTest return new LocalConnector(_server); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); @@ -225,11 +223,11 @@ public class LocalAsyncContextTest protected void check(String response, String... content) { - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); int i = 0; for (String m : content) { - Assert.assertThat(response, Matchers.containsString(m)); + assertThat(response, Matchers.containsString(m)); i = response.indexOf(m, i); i += m.length(); } @@ -520,6 +518,6 @@ public class LocalAsyncContextTest now = System.nanoTime(); } - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/LocalConnectorTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/LocalConnectorTest.java index 959fb093c49..2aaf7e87a72 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/LocalConnectorTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/LocalConnectorTest.java @@ -21,8 +21,8 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; @@ -30,20 +30,17 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.server.LocalConnector.LocalEndPoint; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BufferUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class LocalConnectorTest { private Server _server; private LocalConnector _connector; - @Before + @BeforeEach public void prepare() throws Exception { _server = new Server(); @@ -54,7 +51,7 @@ public class LocalConnectorTest _server.start(); } - @After + @AfterEach public void dispose() throws Exception { _server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/LowResourcesMonitorTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/LowResourcesMonitorTest.java index 7b70fbf1dab..9d7bf40fcba 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/LowResourcesMonitorTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/LowResourcesMonitorTest.java @@ -19,15 +19,13 @@ package org.eclipse.jetty.server; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.TimerScheduler; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.InputStream; import java.net.Socket; @@ -37,11 +35,12 @@ import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CountDownLatch; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.*; +import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; -@RunWith(AdvancedRunner.class) public class LowResourcesMonitorTest { QueuedThreadPool _threadPool; @@ -49,7 +48,7 @@ public class LowResourcesMonitorTest ServerConnector _connector; LowResourceMonitor _lowResourcesMonitor; - @Before + @BeforeEach public void before() throws Exception { _threadPool = new QueuedThreadPool(); @@ -77,7 +76,7 @@ public class LowResourcesMonitorTest _server.start(); } - @After + @AfterEach public void after() throws Exception { _server.stop(); @@ -91,8 +90,8 @@ public class LowResourcesMonitorTest Thread.sleep(1200); _threadPool.setMaxThreads(_threadPool.getThreads()-_threadPool.getIdleThreads()+10); Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(), _lowResourcesMonitor.isLowOnResources()); - + assertFalse(_lowResourcesMonitor.isLowOnResources(), _lowResourcesMonitor.getReasons()); + final CountDownLatch latch = new CountDownLatch(1); for (int i=0;i<100;i++) @@ -115,7 +114,8 @@ public class LowResourcesMonitorTest latch.countDown(); Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); + + assertFalse(_lowResourcesMonitor.isLowOnResources(), _lowResourcesMonitor.getReasons()); } @@ -129,8 +129,8 @@ public class LowResourcesMonitorTest System.out.println("maxThreads:"+maxThreads); _threadPool.setMaxThreads(maxThreads); Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); - + assertFalse(_lowResourcesMonitor.isLowOnResources(), _lowResourcesMonitor.getReasons()); + for (AbstractConnector c : _server.getBeans(AbstractConnector.class)) assertThat(c.isAccepting(),Matchers.is(true)); @@ -157,19 +157,19 @@ public class LowResourcesMonitorTest latch.countDown(); Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); + assertFalse(_lowResourcesMonitor.isLowOnResources(), _lowResourcesMonitor.getReasons()); for (AbstractConnector c : _server.getBeans(AbstractConnector.class)) assertThat(c.isAccepting(),Matchers.is(true)); } - @Ignore ("not reliable") + @Disabled("not reliable") @Test public void testLowOnMemory() throws Exception { _lowResourcesMonitor.setMaxMemory(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+(100*1024*1024)); Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); + assertFalse(_lowResourcesMonitor.isLowOnResources(), _lowResourcesMonitor.getReasons()); byte[] data = new byte[100*1024*1024]; Arrays.fill(data,(byte)1); @@ -183,7 +183,7 @@ public class LowResourcesMonitorTest System.gc(); Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); + assertFalse(_lowResourcesMonitor.isLowOnResources(),_lowResourcesMonitor.getReasons()); } @@ -191,7 +191,7 @@ public class LowResourcesMonitorTest public void testMaxConnectionsAndMaxIdleTime() throws Exception { _lowResourcesMonitor.setMaxMemory(0); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); + assertFalse(_lowResourcesMonitor.isLowOnResources(), _lowResourcesMonitor.getReasons()); assertEquals( 20, _lowResourcesMonitor.getMaxConnections() ); Socket[] socket = new Socket[_lowResourcesMonitor.getMaxConnections()+1]; @@ -205,7 +205,7 @@ public class LowResourcesMonitorTest { // wait for low idle time to close sockets, but not new Socket Thread.sleep(1200); - assertFalse(_lowResourcesMonitor.getReasons(),_lowResourcesMonitor.isLowOnResources()); + assertFalse(_lowResourcesMonitor.isLowOnResources(),_lowResourcesMonitor.getReasons()); for (int i=0;i qualities=fields.getValues("Q",", \t"); List list=HttpFields.qualityList(qualities); - assertEquals("Quality parameters","aaa",HttpFields.valueParameters(list.get(0),null)); - assertEquals("Quality parameters","aa2",HttpFields.valueParameters(list.get(1),null)); - assertEquals("Quality parameters","abb",HttpFields.valueParameters(list.get(2),null)); - assertEquals("Quality parameters","bbb",HttpFields.valueParameters(list.get(3),null)); - assertEquals("Quality parameters","ccc",HttpFields.valueParameters(list.get(4),null)); - assertEquals("Quality parameters","ddd",HttpFields.valueParameters(list.get(5),null)); + assertEquals("aaa",HttpFields.valueParameters(list.get(0), null), "Quality parameters"); + assertEquals("aa2",HttpFields.valueParameters(list.get(1), null), "Quality parameters"); + assertEquals("abb",HttpFields.valueParameters(list.get(2), null), "Quality parameters"); + assertEquals("bbb",HttpFields.valueParameters(list.get(3), null), "Quality parameters"); + assertEquals("ccc",HttpFields.valueParameters(list.get(4), null), "Quality parameters"); + assertEquals("ddd",HttpFields.valueParameters(list.get(5), null), "Quality parameters"); } @@ -370,7 +366,7 @@ public class PartialRFC2616Test public void test4_4_4() throws Exception { // No _content length - assertTrue("Skip 411 checks as IE breaks this rule",true); + assertTrue(true, "Skip 411 checks as IE breaks this rule"); // offset=0; connector.reopen(); // response=connector.getResponse("GET /R2 HTTP/1.1\n"+ // "Host: localhost\n"+ @@ -578,7 +574,7 @@ public class PartialRFC2616Test String head=connector.getResponse("HEAD /R1 HTTP/1.0\n"+"Host: localhost\n"+"\n"); checkContains(head,0,"HTTP/1.1 200","HEAD"); checkContains(head,0,"Content-Type: text/html","HEAD _content"); - assertEquals("HEAD no body",-1,head.indexOf("")); + assertEquals(-1, head.indexOf(""), "HEAD no body"); } catch (Exception e) { @@ -684,13 +680,13 @@ public class PartialRFC2616Test private int checkContains(String s, int offset, String c, String test) { - Assert.assertThat(test,s.substring(offset),containsString(c)); + assertThat(test,s.substring(offset),containsString(c)); return s.indexOf(c,offset); } private void checkNotContained(String s, int offset, String c, String test) { - Assert.assertThat(test,s.substring(offset),not(containsString(c))); + assertThat(test,s.substring(offset),not(containsString(c))); } private void checkNotContained(String s, String c, String test) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java index 7a713bbef93..913d2fffaa7 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyConnectionTest.java @@ -18,26 +18,26 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; + import org.eclipse.jetty.server.handler.ErrorHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * */ -@RunWith(AdvancedRunner.class) public class ProxyConnectionTest { private Server _server; private LocalConnector _connector; - @Before + @BeforeEach public void init() throws Exception { _server = new Server(); @@ -59,7 +59,7 @@ public class ProxyConnectionTest _server.start(); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); @@ -75,10 +75,10 @@ public class ProxyConnectionTest "Connection: close\n"+ "\n"); - Assert.assertThat(response,Matchers.containsString("HTTP/1.1 200")); - Assert.assertThat(response,Matchers.containsString("pathInfo=/path")); - Assert.assertThat(response,Matchers.containsString("local=5.6.7.8:222")); - Assert.assertThat(response,Matchers.containsString("remote=1.2.3.4:111")); + assertThat(response,Matchers.containsString("HTTP/1.1 200")); + assertThat(response,Matchers.containsString("pathInfo=/path")); + assertThat(response,Matchers.containsString("local=5.6.7.8:222")); + assertThat(response,Matchers.containsString("remote=1.2.3.4:111")); } @Test @@ -90,10 +90,10 @@ public class ProxyConnectionTest "Connection: close\n"+ "\n"); - Assert.assertThat(response,Matchers.containsString("HTTP/1.1 200")); - Assert.assertThat(response,Matchers.containsString("pathInfo=/path")); - Assert.assertThat(response,Matchers.containsString("remote=eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee:65535")); - Assert.assertThat(response,Matchers.containsString("local=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:65535")); + assertThat(response,Matchers.containsString("HTTP/1.1 200")); + assertThat(response,Matchers.containsString("pathInfo=/path")); + assertThat(response,Matchers.containsString("remote=eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee:65535")); + assertThat(response,Matchers.containsString("local=ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:65535")); } @Test @@ -105,7 +105,7 @@ public class ProxyConnectionTest "Connection: close\n"+ "\n"); - Assert.assertNull(response); + assertNull(response); } @Test @@ -113,7 +113,7 @@ public class ProxyConnectionTest { _connector.setIdleTimeout(100); String response=_connector.getResponse("PROXY TIMEOUT"); - Assert.assertNull(response); + assertNull(response); } @Test @@ -124,7 +124,7 @@ public class ProxyConnectionTest "Host: server:80\n"+ "Connection: close\n"+ "\n"); - Assert.assertNull(response); + assertNull(response); } @Test @@ -135,7 +135,7 @@ public class ProxyConnectionTest "Host: server:80\n"+ "Connection: close\n"+ "\n"); - Assert.assertNull(response); + assertNull(response); } @Test @@ -148,7 +148,7 @@ public class ProxyConnectionTest "Host: server:80\n"+ "Connection: close\n"+ "\n"); - Assert.assertNull(response); + assertNull(response); } } @@ -160,7 +160,7 @@ public class ProxyConnectionTest "Host: server:80\n"+ "Connection: close\n"+ "\n"); - Assert.assertNull(response); + assertNull(response); } @Test @@ -171,7 +171,7 @@ public class ProxyConnectionTest "Host: server:80\n"+ "Connection: close\n"+ "\n"); - Assert.assertNull(response); + assertNull(response); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyProtocolTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyProtocolTest.java index 204d0568349..3d3249a7d9e 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyProtocolTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ProxyProtocolTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.server; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -31,13 +33,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class ProxyProtocolTest { private Server server; @@ -52,7 +51,7 @@ public class ProxyProtocolTest server.start(); } - @After + @AfterEach public void destroy() throws Exception { if (server != null) @@ -89,7 +88,7 @@ public class ProxyProtocolTest InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); String response1 = reader.readLine(); - Assert.assertTrue(response1.startsWith("HTTP/1.1 200 ")); + assertTrue(response1.startsWith("HTTP/1.1 200 ")); while (true) { if (reader.readLine().isEmpty()) @@ -106,7 +105,7 @@ public class ProxyProtocolTest output.flush(); String response2 = reader.readLine(); - Assert.assertTrue(response2.startsWith("HTTP/1.1 200 ")); + assertTrue(response2.startsWith("HTTP/1.1 200 ")); while (true) { if (reader.readLine() == null) diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java index cb2d4c327bf..b7add70fecf 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/RequestTest.java @@ -22,17 +22,19 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; @@ -48,6 +50,7 @@ import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import javax.servlet.DispatcherType; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; @@ -65,20 +68,19 @@ import org.eclipse.jetty.server.LocalConnector.LocalEndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ErrorHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; +import org.eclipse.jetty.toolchain.test.FS; +import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class RequestTest { private static final Logger LOG = Log.getLogger(RequestTest.class); @@ -86,7 +88,7 @@ public class RequestTest private LocalConnector _connector; private RequestHandler _handler; - @Before + @BeforeEach public void init() throws Exception { _server = new Server(); @@ -109,7 +111,7 @@ public class RequestTest _server.start(); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); @@ -1062,6 +1064,77 @@ public class RequestTest assertThat(response, containsString(" 200 OK")); } + @Test + @Disabled("See issue #1175") + public void testMultiPartFormDataReadInputThenParams() throws Exception + { + final File tmpdir = MavenTestingUtils.getTargetTestingDir("multipart"); + FS.ensureEmpty(tmpdir); + + Handler handler = new AbstractHandler() + { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, + ServletException + { + if (baseRequest.getDispatcherType() != DispatcherType.REQUEST) + return; + + // Fake a @MultiPartConfig'd servlet endpoint + MultipartConfigElement multipartConfig = new MultipartConfigElement(tmpdir.getAbsolutePath()); + request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfig); + + // Normal processing + baseRequest.setHandled(true); + + // Fake the commons-fileupload behavior + int length = request.getContentLength(); + InputStream in = request.getInputStream(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + IO.copy(in, out, length); // KEY STEP (Don't Change!) commons-fileupload does not read to EOF + + // Record what happened as servlet response headers + response.setIntHeader("x-request-content-length", request.getContentLength()); + response.setIntHeader("x-request-content-read", out.size()); + String foo = request.getParameter("foo"); // uri query parameter + String bar = request.getParameter("bar"); // form-data content parameter + response.setHeader("x-foo", foo == null ? "null" : foo); + response.setHeader("x-bar", bar == null ? "null" : bar); + } + }; + + _server.stop(); + _server.setHandler(handler); + _server.start(); + + String multipart = "--AaBbCc\r\n"+ + "content-disposition: form-data; name=\"bar\"\r\n"+ + "\r\n"+ + "BarContent\r\n"+ + "--AaBbCc\r\n"+ + "content-disposition: form-data; name=\"stuff\"\r\n"+ + "Content-Type: text/plain;charset=ISO-8859-1\r\n"+ + "\r\n"+ + "000000000000000000000000000000000000000000000000000\r\n"+ + "--AaBbCc--\r\n"; + + String request="POST /?foo=FooUri HTTP/1.1\r\n"+ + "Host: whatever\r\n"+ + "Content-Type: multipart/form-data; boundary=\"AaBbCc\"\r\n"+ + "Content-Length: "+multipart.getBytes().length+"\r\n"+ + "Connection: close\r\n"+ + "\r\n"+ + multipart; + + + HttpTester.Response response = HttpTester.parseResponse(_connector.getResponse(request)); + + // It should always be possible to read query string + assertThat("response.x-foo", response.get("x-foo"), is("FooUri")); + // Not possible to read request content parameters? + assertThat("response.x-bar", response.get("x-bar"), is("null")); // TODO: should this work? + } + @Test public void testPartialRead() throws Exception { @@ -1505,7 +1578,7 @@ public class RequestTest } - @Ignore("No longer relevant") + @Disabled("No longer relevant") @Test public void testCookieLeak() throws Exception { @@ -1684,11 +1757,11 @@ public class RequestTest } } - @Test(expected = UnsupportedEncodingException.class) + @Test public void testNotSupportedCharacterEncoding() throws UnsupportedEncodingException { Request request = new Request(null, null); - request.setCharacterEncoding("doesNotExist"); + assertThrows(UnsupportedEncodingException.class, ()-> request.setCharacterEncoding("doesNotExist")); } @Test diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java index 9b7911bf6e3..446cc3f4682 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ResourceCacheTest.java @@ -18,8 +18,8 @@ package org.eclipse.jetty.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -31,15 +31,11 @@ import org.eclipse.jetty.http.CompressedContentFormat; import org.eclipse.jetty.http.HttpContent; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.http.ResourceHttpContent; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.OS; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.resource.ResourceCollection; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class ResourceCacheTest { @Test @@ -58,17 +54,17 @@ public class ResourceCacheTest CachedContentFactory rc2 = new CachedContentFactory(rc3,r[1],mime,false,false,CompressedContentFormat.NONE); CachedContentFactory rc1 = new CachedContentFactory(rc2,r[0],mime,false,false,CompressedContentFormat.NONE); - assertEquals("1 - one", getContent(rc1, "1.txt")); - assertEquals("2 - two", getContent(rc1, "2.txt")); - assertEquals("3 - three", getContent(rc1, "3.txt")); + assertEquals(getContent(rc1, "1.txt"), "1 - one"); + assertEquals(getContent(rc1, "2.txt"), "2 - two"); + assertEquals(getContent(rc1, "3.txt"), "3 - three"); - assertEquals("1 - two", getContent(rc2, "1.txt")); - assertEquals("2 - two", getContent(rc2, "2.txt")); - assertEquals("3 - three", getContent(rc2, "3.txt")); + assertEquals(getContent(rc2, "1.txt"), "1 - two"); + assertEquals(getContent(rc2, "2.txt"), "2 - two"); + assertEquals(getContent(rc2, "3.txt"), "3 - three"); assertEquals(null, getContent(rc3, "1.txt")); - assertEquals("2 - three", getContent(rc3, "2.txt")); - assertEquals("3 - three", getContent(rc3, "3.txt")); + assertEquals(getContent(rc3, "2.txt"), "2 - three"); + assertEquals(getContent(rc3, "3.txt"), "3 - three"); } @@ -96,17 +92,17 @@ public class ResourceCacheTest CachedContentFactory rc1 = new CachedContentFactory(rc2,r[0],mime,false,false,CompressedContentFormat.NONE); - assertEquals("1 - one", getContent(rc1, "1.txt")); - assertEquals("2 - two", getContent(rc1, "2.txt")); - assertEquals("3 - three", getContent(rc1, "3.txt")); + assertEquals(getContent(rc1, "1.txt"), "1 - one"); + assertEquals(getContent(rc1, "2.txt"), "2 - two"); + assertEquals(getContent(rc1, "3.txt"), "3 - three"); - assertEquals("1 - two", getContent(rc2, "1.txt")); - assertEquals("2 - two", getContent(rc2, "2.txt")); - assertEquals("3 - three", getContent(rc2, "3.txt")); + assertEquals(getContent(rc2, "1.txt"), "1 - two"); + assertEquals(getContent(rc2, "2.txt"), "2 - two"); + assertEquals(getContent(rc2, "3.txt"), "3 - three"); assertEquals(null, getContent(rc3, "1.txt")); - assertEquals("2 - three", getContent(rc3, "2.txt")); - assertEquals("3 - three", getContent(rc3, "3.txt")); + assertEquals(getContent(rc3, "2.txt"), "2 - three"); + assertEquals(getContent(rc3, "3.txt"), "3 - three"); } @@ -151,7 +147,7 @@ public class ResourceCacheTest assertEquals(80,content.getContentLengthValue()); assertEquals(0,cache.getCachedSize()); - if (OS.IS_LINUX) + if (org.junit.jupiter.api.condition.OS.LINUX.isCurrentOs()) { // Initially not using memory mapped files content.getDirectBuffer(); @@ -174,6 +170,7 @@ public class ResourceCacheTest // with both types of buffer loaded, this is not too large for cache because // mapped buffers don't count, so we can continue } + content.getIndirectBuffer(); assertEquals(80,cache.getCachedSize()); assertEquals(1,cache.getCachedFiles()); @@ -289,8 +286,8 @@ public class ResourceCacheTest CachedContentFactory cache = new CachedContentFactory(null,resources[0],mime,false,false,CompressedContentFormat.NONE); - assertEquals("4 - four", getContent(cache, "four.txt")); - assertEquals("4 - four (no extension)", getContent(cache, "four")); + assertEquals(getContent(cache, "four.txt"), "4 - four"); + assertEquals(getContent(cache, "four"), "4 - four (no extension)"); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java index 9d0021130a7..fd2396c5aef 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ResponseTest.java @@ -18,6 +18,21 @@ package org.eclipse.jetty.server; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; @@ -62,33 +77,15 @@ import org.eclipse.jetty.server.session.NullSessionDataStore; import org.eclipse.jetty.server.session.Session; import org.eclipse.jetty.server.session.SessionData; import org.eclipse.jetty.server.session.SessionHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.util.thread.TimerScheduler; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@RunWith(AdvancedRunner.class) public class ResponseTest { @@ -115,7 +112,7 @@ public class ResponseTest private HttpChannel _channel; private ByteBuffer _content = BufferUtil.allocate(16*1024); - @Before + @BeforeEach public void init() throws Exception { BufferUtil.clear(_content); @@ -186,7 +183,7 @@ public class ResponseTest }); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); @@ -404,20 +401,20 @@ public class ResponseTest out.close(); /* Test A */ - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestA1 1.234.567,89")); - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestA2 1.234.567,89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestA1 1.234.567,89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestA2 1.234.567,89")); /* Test B */ - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestB1 1.234.567,89")); - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestB2 1.234.567,89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestB1 1.234.567,89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestB2 1.234.567,89")); /* Test C */ - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestC1 1,234,567.89")); - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestC2 1,234,567.89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestC1 1,234,567.89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestC2 1,234,567.89")); /* Test D */ - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestD1 1.234.567,89")); - Assert.assertThat(BufferUtil.toString(_content),Matchers.containsString("TestD2 1.234.567,89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestD1 1.234.567,89")); + assertThat(BufferUtil.toString(_content),Matchers.containsString("TestD2 1.234.567,89")); } @@ -701,22 +698,15 @@ public class ResponseTest PrintWriter writer = response.getWriter(); writer.println("test"); writer.flush(); - Assert.assertFalse(writer.checkError()); + assertFalse(writer.checkError()); Throwable cause = new IOException("problem at mill"); _channel.abort(cause); writer.println("test"); - Assert.assertTrue(writer.checkError()); - try - { - writer.println("test"); - Assert.fail(); - } - catch(RuntimeIOException e) - { - Assert.assertEquals(cause,e.getCause()); - } + assertTrue(writer.checkError()); + RuntimeIOException e = assertThrows(RuntimeIOException.class, ()-> writer.println("test")); + assertEquals(cause,e.getCause()); } @Test @@ -837,18 +827,18 @@ public class ResponseTest String expected = tests[i][1] .replace("@HOST@",host==null ? request.getLocalAddr() : (host.contains(":")?("["+host+"]"):host )) .replace("@PORT@",host==null ? ":8888" : (port==80?"":(":"+port))); - assertEquals("test-"+i+" "+host+":"+port,expected,location); + assertEquals(expected, location, "test-"+i+" "+host+":"+port); } } } } - @Test(expected = IllegalStateException.class) + @Test public void testInvalidSendRedirect() throws Exception { // Request is /path/info, so we need 3 ".." for an invalid redirect. Response response = getResponse(); - response.sendRedirect("../../../invalid"); + assertThrows(IllegalStateException.class, ()-> response.sendRedirect("../../../invalid")); } @Test @@ -857,15 +847,8 @@ public class ResponseTest Response response = getResponse(); response.setBufferSize(20 * 1024); response.getWriter().print("hello"); - try - { - response.setBufferSize(21 * 1024); - fail("Expected IllegalStateException on Request.setBufferSize"); - } - catch (Exception e) - { - assertTrue(e instanceof IllegalStateException); - } + + assertThrows(IllegalStateException.class, ()-> response.setBufferSize(21 * 1024)); } @Test @@ -914,14 +897,14 @@ public class ResponseTest LineNumberReader reader = new LineNumberReader(new InputStreamReader(socket.getInputStream())); String line = reader.readLine(); - Assert.assertThat(line, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(line, startsWith("HTTP/1.1 200 OK")); // look for blank line while (line != null && line.length() > 0) line = reader.readLine(); // Read the first line of the GET line = reader.readLine(); - Assert.assertThat(line, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(line, startsWith("HTTP/1.1 200 OK")); String last = null; while (line != null) @@ -1032,9 +1015,10 @@ public class ResponseTest assertNotNull(set); ArrayList list = Collections.list(set); - assertEquals(2, list.size()); - assertTrue(list.contains("name=value;Path=/path;Domain=domain;Secure;HttpOnly")); - assertTrue(list.contains("name2=value2;Path=/path;Domain=domain")); + assertThat(list, containsInAnyOrder( + "name=value;Path=/path;Domain=domain;Secure;HttpOnly", + "name2=value2;Path=/path;Domain=domain" + )); //get rid of the cookies response.reset(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorAsyncContextTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorAsyncContextTest.java index f75d9f47d0b..164e3d6f3c6 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorAsyncContextTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorAsyncContextTest.java @@ -21,11 +21,8 @@ package org.eclipse.jetty.server; import java.net.Socket; import java.nio.charset.StandardCharsets; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.IO; -import org.junit.runner.RunWith; -@RunWith(AdvancedRunner.class) public class ServerConnectorAsyncContextTest extends LocalAsyncContextTest { @Override diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorCloseTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorCloseTest.java index dbad405bd61..848dafa97eb 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorCloseTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorCloseTest.java @@ -18,25 +18,19 @@ package org.eclipse.jetty.server; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.After; -import org.junit.Before; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; -/* ------------------------------------------------------------ */ -@RunWith(AdvancedRunner.class) public class ServerConnectorCloseTest extends ConnectorCloseTestBase { - - /* ------------------------------------------------------------ */ - @Before + @BeforeEach public void init() throws Exception { startServer(new ServerConnector(_server)); } - @After + @AfterEach public void after() throws Exception { _server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorHttpServerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorHttpServerTest.java index 08656d03bbe..5724e364e08 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorHttpServerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorHttpServerTest.java @@ -18,17 +18,14 @@ package org.eclipse.jetty.server; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.Before; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; /** * HttpServer Tester. */ -@RunWith(AdvancedRunner.class) public class ServerConnectorHttpServerTest extends HttpServerTestBase { - @Before + @BeforeEach public void init() throws Exception { // Run this test with 0 acceptors. Other tests already check the acceptors >0 diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTest.java index fef0e36ef58..3ae014fb538 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTest.java @@ -20,12 +20,14 @@ package org.eclipse.jetty.server; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -50,19 +52,11 @@ import org.eclipse.jetty.io.SocketChannelEndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.OS; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.StacklessLogging; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertTrue; - -@RunWith(AdvancedRunner.class) public class ServerConnectorTest { public static class ReuseInfoHandler extends AbstractHandler @@ -146,7 +140,7 @@ public class ServerConnectorTest assertThat("Response",response,containsString("connector._reuseAddress() = true")); // Java on Windows is incapable of propagating reuse-address this to the opened socket. - if (!OS.IS_WINDOWS) + if (!org.junit.jupiter.api.condition.OS.WINDOWS.isCurrentOs()) { assertThat("Response",response,containsString("socket.getReuseAddress() = true")); } @@ -182,7 +176,7 @@ public class ServerConnectorTest assertThat("Response",response,containsString("connector._reuseAddress() = true")); // Java on Windows is incapable of propagating reuse-address this to the opened socket. - if (!OS.IS_WINDOWS) + if (!org.junit.jupiter.api.condition.OS.WINDOWS.isCurrentOs()) { assertThat("Response",response,containsString("socket.getReuseAddress() = true")); } @@ -218,7 +212,7 @@ public class ServerConnectorTest assertThat("Response",response,containsString("connector._reuseAddress() = false")); // Java on Windows is incapable of propagating reuse-address this to the opened socket. - if (!OS.IS_WINDOWS) + if (!org.junit.jupiter.api.condition.OS.WINDOWS.isCurrentOs()) { assertThat("Response",response,containsString("socket.getReuseAddress() = false")); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java index 8e101f64beb..36f233a0003 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java @@ -18,6 +18,14 @@ package org.eclipse.jetty.server; +import static java.time.Duration.ofSeconds; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -34,20 +42,15 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.session.SessionHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.StacklessLogging; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest { - @Before + @BeforeEach public void init() throws Exception { ServerConnector connector = new ServerConnector(_server,1,1); @@ -55,14 +58,16 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest startServer(connector); } - @Test(timeout=60000) + @Test public void testStartStopStart() throws Exception { - _server.stop(); - _server.start(); + assertTimeoutPreemptively(ofSeconds(10),()->{ + _server.stop(); + _server.start(); + }); } - @Test(timeout=60000) + @Test public void testIdleTimeoutAfterSuspend() throws Exception { _server.stop(); @@ -74,10 +79,13 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest _handler.setSuspendFor(100); _handler.setResumeAfter(25); - Assert.assertTrue(process(null).toUpperCase(Locale.ENGLISH).contains("RESUMED")); + assertTimeoutPreemptively(ofSeconds(10),()-> { + String process = process(null).toUpperCase(Locale.ENGLISH); + assertThat(process, containsString("RESUMED")); + }); } - @Test(timeout=60000) + @Test public void testIdleTimeoutAfterTimeout() throws Exception { SuspendHandler _handler = new SuspendHandler(); @@ -88,10 +96,13 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest _server.start(); _handler.setSuspendFor(50); - Assert.assertTrue(process(null).toUpperCase(Locale.ENGLISH).contains("TIMEOUT")); + assertTimeoutPreemptively(ofSeconds(10),()-> { + String process = process(null).toUpperCase(Locale.ENGLISH); + assertThat(process, containsString("TIMEOUT")); + }); } - @Test(timeout=60000) + @Test public void testIdleTimeoutAfterComplete() throws Exception { SuspendHandler _handler = new SuspendHandler(); @@ -103,7 +114,10 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest _handler.setSuspendFor(100); _handler.setCompleteAfter(25); - Assert.assertTrue(process(null).toUpperCase(Locale.ENGLISH).contains("COMPLETED")); + assertTimeoutPreemptively(ofSeconds(10),()-> { + String process = process(null).toUpperCase(Locale.ENGLISH); + assertThat(process, containsString("COMPLETED")); + }); } private synchronized String process(String content) throws IOException, InterruptedException @@ -127,7 +141,7 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); String response = IO.toString(inputStream); long timeElapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start; - Assert.assertThat(timeElapsed,Matchers.greaterThanOrEqualTo(MAX_IDLE_TIME-100L)); + assertThat(timeElapsed,greaterThanOrEqualTo(MAX_IDLE_TIME-100L)); return response; } } @@ -148,7 +162,7 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()); client.setSoTimeout(10000); - Assert.assertFalse(client.isClosed()); + assertFalse(client.isClosed()); final OutputStream os = client.getOutputStream(); final InputStream is = client.getInputStream(); @@ -196,13 +210,13 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest } }); - try (StacklessLogging scope = new StacklessLogging(HttpChannel.class)) + try (StacklessLogging ignore = new StacklessLogging(HttpChannel.class)) { requestFuture.get(2, TimeUnit.SECONDS); responseFuture.get(3, TimeUnit.SECONDS); - - Assert.assertThat(response.toString(), Matchers.containsString(" 500 ")); - Assert.assertThat(response.toString(), Matchers.not(Matchers.containsString("========="))); + + assertThat(response.toString(), containsString(" 500 ")); + assertThat(response.toString(), not(containsString("========="))); } } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ShutdownMonitorTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ShutdownMonitorTest.java index 566131a0ca5..76fd9486a59 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ShutdownMonitorTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ShutdownMonitorTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedReader; import java.io.Closeable; import java.io.InputStreamReader; @@ -26,21 +30,15 @@ import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.util.thread.ShutdownThread; -import org.junit.After; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class ShutdownMonitorTest { - @After + @AfterEach public void dispose() { ShutdownMonitor.reset(); @@ -71,19 +69,19 @@ public class ShutdownMonitorTest String reply = input.readLine(); assertEquals("OK", reply); // Socket must be closed afterwards. - Assert.assertNull(input.readLine()); + assertNull(input.readLine()); } } } - @Ignore("Issue #2626") + @Disabled("Issue #2626") @Test public void testStartStopDifferentPortDifferentKey() throws Exception { testStartStop(false); } - @Ignore("Issue #2626") + @Disabled("Issue #2626") @Test public void testStartStopSamePortDifferentKey() throws Exception { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/SlowClientWithPipelinedRequestTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/SlowClientWithPipelinedRequestTest.java index a6431d29fae..3cd93a4b4c3 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/SlowClientWithPipelinedRequestTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/SlowClientWithPipelinedRequestTest.java @@ -18,7 +18,10 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.lessThan; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.InputStream; @@ -36,13 +39,10 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; -@RunWith(AdvancedRunner.class) public class SlowClientWithPipelinedRequestTest { private final AtomicInteger handles = new AtomicInteger(); @@ -75,7 +75,7 @@ public class SlowClientWithPipelinedRequestTest server.start(); } - @After + @AfterEach public void stopServer() throws Exception { if (server != null) @@ -124,7 +124,7 @@ public class SlowClientWithPipelinedRequestTest InputStream input = client.getInputStream(); int read = input.read(); - Assert.assertTrue(read >= 0); + assertTrue(read >= 0); // As soon as we can read the response, send a pipelined request // so it is a different read for the server and it will trigger NIO output.write(("" + @@ -136,7 +136,7 @@ public class SlowClientWithPipelinedRequestTest // Simulate a slow reader Thread.sleep(1000); - Assert.assertThat(handles.get(), lessThan(10)); + assertThat(handles.get(), lessThan(10)); // We are sure we are not spinning, read the content StringBuilder lines = new StringBuilder().append((char)read); @@ -152,7 +152,7 @@ public class SlowClientWithPipelinedRequestTest if (crlfs == 4) break; } - Assert.assertTrue(lines.toString().contains(" 200 ")); + assertThat(lines.toString(), containsString(" 200 ")); // Read the body for (int i = 0; i < contentLength; ++i) input.read(); @@ -171,7 +171,7 @@ public class SlowClientWithPipelinedRequestTest if (crlfs == 4) break; } - Assert.assertTrue(lines.toString().contains(" 200 ")); + assertThat(lines.toString(), containsString(" 200 ")); client.close(); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java index 13c5c84f30c..41d673c031e 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/StressTest.java @@ -18,6 +18,13 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.condition.OS.MAC; + import java.io.IOException; import java.net.Socket; import java.util.Queue; @@ -31,24 +38,21 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.handler.HandlerWrapper; -import org.eclipse.jetty.toolchain.test.AdvancedRunner; -import org.eclipse.jetty.toolchain.test.OS; -import org.eclipse.jetty.toolchain.test.annotation.Stress; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; - -@RunWith(AdvancedRunner.class) +@Disabled +@Tag("stress") +@DisabledOnOs(MAC) // TODO: needs investigation public class StressTest { private static final Logger LOG = Log.getLogger(StressTest.class); @@ -88,7 +92,7 @@ public class StressTest "/path/f", }; - @BeforeClass + @BeforeAll public static void init() throws Exception { _threads = new QueuedThreadPool(); @@ -107,14 +111,14 @@ public class StressTest _server.start(); } - @AfterClass + @AfterAll public static void destroy() throws Exception { _server.stop(); _server.join(); } - @Before + @BeforeEach public void reset() { _handled.set(0); @@ -125,17 +129,12 @@ public class StressTest @Test public void testMinNonPersistent() throws Throwable { - assumeTrue(!OS.IS_OSX); doThreads(10,10,false); } @Test - @Stress("Hey, its called StressTest for a reason") public void testNonPersistent() throws Throwable { - // TODO needs to be further investigated - assumeTrue(!OS.IS_OSX); - doThreads(20,20,false); Thread.sleep(1000); doThreads(200,10,false); @@ -146,17 +145,12 @@ public class StressTest @Test public void testMinPersistent() throws Throwable { - // TODO needs to be further investigated - assumeTrue(!OS.IS_OSX); doThreads(10,10,true); } @Test - @Stress("Hey, its called StressTest for a reason") public void testPersistent() throws Throwable { - // TODO needs to be further investigated - assumeTrue(!OS.IS_OSX); doThreads(40,40,true); Thread.sleep(1000); doThreads(200,10,true); @@ -377,7 +371,7 @@ public class StressTest int bodies = count(response,"HTTP/1.1 200 OK"); if (__tests.length!=bodies) System.err.println("responses=\n"+response+"\n---"); - assertEquals(name,__tests.length,bodies); + assertEquals(__tests.length,bodies,name); long bind=connected-start; long flush=(written-connected)/__tests.length; @@ -429,10 +423,10 @@ public class StressTest long end=TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); String endOfResponse = "\r\n\r\n"; - assertTrue("response = '" + response + "'", response.contains(endOfResponse)); + assertThat(response, containsString(endOfResponse)); response=response.substring(response.indexOf(endOfResponse) + endOfResponse.length()); - assertTrue(uri,response.startsWith("DATA "+__tests[i])); + assertThat(uri, response, startsWith("DATA "+__tests[i])); long latency=end-start; _latencies[5].add(new Long(latency)); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ThreadStarvationTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ThreadStarvationTest.java index 8cd7fa3671e..08116346aa8 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ThreadStarvationTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ThreadStarvationTest.java @@ -18,10 +18,10 @@ package org.eclipse.jetty.server; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; @@ -38,6 +38,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; @@ -52,27 +53,22 @@ import org.eclipse.jetty.io.LeakTrackingByteBufferPool; import org.eclipse.jetty.io.MappedByteBufferPool; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.TestTracker; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.Scheduler; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class ThreadStarvationTest { final static int BUFFER_SIZE=1024*1024; final static int BUFFERS=64; final static int THREADS=5; final static int CLIENTS=THREADS+2; - @Rule - public TestTracker tracker = new TestTracker(); - + interface ConnectorProvider { ServerConnector newConnector(Server server, int acceptors, int selectors); } @@ -81,15 +77,14 @@ public class ThreadStarvationTest Socket newSocket(String host, int port) throws IOException; } - @Parameterized.Parameters(name = "{0}") - public static List params() + public static Stream scenarios() { - List params = new ArrayList<>(); + List params = new ArrayList<>(); // HTTP ConnectorProvider http = (server, acceptors, selectors) -> new ServerConnector(server, acceptors, selectors); ClientSocketProvider httpClient = (host, port) -> new Socket(host, port); - params.add(new Object[]{ "http", http, httpClient }); + params.add(new Scenario("http", http, httpClient)); // HTTPS/SSL/TLS ConnectorProvider https = (server, acceptors, selectors) -> { @@ -135,24 +130,16 @@ public class ThreadStarvationTest return sslContext.getSocketFactory().createSocket(host,port); } }; - params.add(new Object[]{ "https/ssl/tls", https, httpsClient }); + params.add(new Scenario("https/ssl/tls", https, httpsClient )); - return params; + return params.stream().map(Arguments::of); } - private final ConnectorProvider connectorProvider; - private final ClientSocketProvider clientSocketProvider; private QueuedThreadPool _threadPool; private Server _server; private ServerConnector _connector; - - public ThreadStarvationTest(String testType, ConnectorProvider connectorProvider, ClientSocketProvider clientSocketProvider) - { - this.connectorProvider = connectorProvider; - this.clientSocketProvider = clientSocketProvider; - } - - private Server prepareServer(Handler handler) + + private Server prepareServer(Scenario scenario, Handler handler) { _threadPool = new QueuedThreadPool(); _threadPool.setMinThreads(THREADS); @@ -161,24 +148,25 @@ public class ThreadStarvationTest _server = new Server(_threadPool); int acceptors = 1; int selectors = 1; - _connector = connectorProvider.newConnector(_server, acceptors, selectors); + _connector = scenario.connectorProvider.newConnector(_server, acceptors, selectors); _server.addConnector(_connector); _server.setHandler(handler); return _server; } - @After + @AfterEach public void dispose() throws Exception { _server.stop(); } - @Test - public void testReadInput() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + public void testReadInput(Scenario scenario) throws Exception { - prepareServer(new ReadHandler()).start(); + prepareServer(scenario, new ReadHandler()).start(); - try(Socket client = clientSocketProvider.newSocket("localhost", _connector.getLocalPort())) + try(Socket client = scenario.clientSocketProvider.newSocket("localhost", _connector.getLocalPort())) { client.setSoTimeout(10000); OutputStream os = client.getOutputStream(); @@ -200,10 +188,11 @@ public class ThreadStarvationTest } } - @Test - public void testReadStarvation() throws Exception + @ParameterizedTest + @MethodSource("scenarios") + public void testReadStarvation(Scenario scenario) throws Exception { - prepareServer(new ReadHandler()); + prepareServer(scenario, new ReadHandler()); _server.start(); ExecutorService clientExecutors = Executors.newFixedThreadPool(CLIENTS); @@ -213,7 +202,7 @@ public class ThreadStarvationTest for(int i=0; i { - try (Socket client = clientSocketProvider.newSocket("localhost", _connector.getLocalPort()); + try (Socket client = scenario.clientSocketProvider.newSocket("localhost", _connector.getLocalPort()); OutputStream out = client.getOutputStream(); InputStream in = client.getInputStream()) { @@ -286,12 +275,13 @@ public class ThreadStarvationTest } } } - - @Test - public void testWriteStarvation() throws Exception + + @ParameterizedTest + @MethodSource("scenarios") + public void testWriteStarvation(Scenario scenario) throws Exception { - prepareServer(new WriteHandler()); + prepareServer(scenario, new WriteHandler()); _server.start(); ExecutorService clientExecutors = Executors.newFixedThreadPool(CLIENTS); @@ -302,7 +292,7 @@ public class ThreadStarvationTest { clientTasks.add(() -> { - try (Socket client = clientSocketProvider.newSocket("localhost", _connector.getLocalPort()); + try (Socket client = scenario.clientSocketProvider.newSocket("localhost", _connector.getLocalPort()); OutputStream out = client.getOutputStream(); InputStream in = client.getInputStream()) { @@ -385,4 +375,24 @@ public class ThreadStarvationTest } } } + + public static class Scenario + { + public final String testType; + public final ConnectorProvider connectorProvider; + public final ClientSocketProvider clientSocketProvider; + + public Scenario(String testType, ConnectorProvider connectorProvider, ClientSocketProvider clientSocketProvider) + { + this.testType = testType; + this.connectorProvider = connectorProvider; + this.clientSocketProvider = clientSocketProvider; + } + + @Override + public String toString() + { + return this.testType; + } + } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/AllowSymLinkAliasCheckerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/AllowSymLinkAliasCheckerTest.java index 38b6c9b2aa7..94ff99eb590 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/AllowSymLinkAliasCheckerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/AllowSymLinkAliasCheckerTest.java @@ -18,10 +18,11 @@ package org.eclipse.jetty.server.handler; +import static java.time.Duration.ofSeconds; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assume.assumeNoException; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import java.io.File; import java.io.IOException; @@ -32,6 +33,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.server.LocalConnector; @@ -40,46 +42,45 @@ import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.resource.PathResource; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.opentest4j.TestAbortedException; -@RunWith(Parameterized.class) public class AllowSymLinkAliasCheckerTest { - @Parameterized.Parameters(name = "{0}") - public static List params() + public static Stream params() { - List data = new ArrayList<>(); + List data = new ArrayList<>(); - String dirs[] = {"/testdir/", "/testdirlnk/", "/testdirprefixlnk/", "/testdirsuffixlnk/", + String dirs[] = {"/workDir/", "/testdirlnk/", "/testdirprefixlnk/", "/testdirsuffixlnk/", "/testdirwraplnk/"}; for (String dirname : dirs) { - data.add(new Object[]{dirname, 200, "text/html", "Directory: " + dirname}); - data.add(new Object[]{dirname + "testfile.txt", 200, "text/plain", "Hello TestFile"}); - data.add(new Object[]{dirname + "testfilelnk.txt", 200, "text/plain", "Hello TestFile"}); - data.add(new Object[]{dirname + "testfileprefixlnk.txt", 200, "text/plain", "Hello TestFile"}); + data.add(Arguments.of(dirname, 200, "text/html", "Directory: " + dirname)); + data.add(Arguments.of(dirname + "testfile.txt", 200, "text/plain", "Hello TestFile")); + data.add(Arguments.of(dirname + "testfilelnk.txt", 200, "text/plain", "Hello TestFile")); + data.add(Arguments.of(dirname + "testfileprefixlnk.txt", 200, "text/plain", "Hello TestFile")); } - return data; + return data.stream(); } private Server server; private LocalConnector localConnector; private Path rootPath; - @Before + @BeforeEach public void setup() throws Exception { setupRoot(); setupServer(); } - @After + @AfterEach public void teardown() throws Exception { if( server != null ) @@ -93,28 +94,28 @@ public class AllowSymLinkAliasCheckerTest rootPath = MavenTestingUtils.getTargetTestingPath(AllowSymLinkAliasCheckerTest.class.getSimpleName()); FS.ensureEmpty(rootPath); - Path testdir = rootPath.resolve("testdir"); + Path testdir = rootPath.resolve("workDir"); FS.ensureDirExists(testdir); try { - // If we used testdir (Path) from above, these symlinks + // If we used workDir (Path) from above, these symlinks // would point to an absolute path. - // Create a relative symlink testdirlnk -> testdir - Files.createSymbolicLink(rootPath.resolve("testdirlnk"), new File("testdir").toPath()); - // Create a relative symlink testdirprefixlnk -> ./testdir - Files.createSymbolicLink(rootPath.resolve("testdirprefixlnk"), new File("./testdir").toPath()); - // Create a relative symlink testdirsuffixlnk -> testdir/ - Files.createSymbolicLink(rootPath.resolve("testdirsuffixlnk"), new File("testdir/").toPath()); - // Create a relative symlink testdirwraplnk -> ./testdir/ - Files.createSymbolicLink(rootPath.resolve("testdirwraplnk"), new File("./testdir/").toPath()); + // Create a relative symlink testdirlnk -> workDir + Files.createSymbolicLink(rootPath.resolve("testdirlnk"), new File("workDir").toPath()); + // Create a relative symlink testdirprefixlnk -> ./workDir + Files.createSymbolicLink(rootPath.resolve("testdirprefixlnk"), new File("./workDir").toPath()); + // Create a relative symlink testdirsuffixlnk -> workDir/ + Files.createSymbolicLink(rootPath.resolve("testdirsuffixlnk"), new File("workDir/").toPath()); + // Create a relative symlink testdirwraplnk -> ./workDir/ + Files.createSymbolicLink(rootPath.resolve("testdirwraplnk"), new File("./workDir/").toPath()); } catch (UnsupportedOperationException | FileSystemException e) { // If unable to create symlink, no point testing the rest. // This is the path that Microsoft Windows takes. - assumeNoException(e); + abortNotSupported(e); } Path testfileTxt = testdir.resolve("testfile.txt"); @@ -136,7 +137,7 @@ public class AllowSymLinkAliasCheckerTest { // If unable to create symlink, no point testing the rest. // This is the path that Microsoft Windows takes. - assumeNoException(e); + abortNotSupported(e); } try @@ -151,10 +152,17 @@ public class AllowSymLinkAliasCheckerTest { // If unable to create symlink, no point testing the rest. // This is the path that Microsoft Windows takes. - assumeNoException(e); + abortNotSupported(e); } } + private void abortNotSupported(Throwable t) + { + if (t == null) + return; + throw new TestAbortedException("Unsupported Behavior", t); + } + private void setupServer() throws Exception { // Setup server @@ -180,21 +188,9 @@ public class AllowSymLinkAliasCheckerTest server.start(); } - @Parameterized.Parameter(0) - public String requestURI; - @Parameterized.Parameter(1) - public int expectedResponseStatus; - @Parameterized.Parameter(2) - public String expectedResponseContentType; - @Parameterized.Parameter(3) - public String expectedResponseContentContains; - - public AllowSymLinkAliasCheckerTest() - { - } - - @Test(timeout = 5000) - public void testAccess() throws Exception + @ParameterizedTest + @MethodSource("params") + public void testAccess(String requestURI, int expectedResponseStatus, String expectedResponseContentType, String expectedResponseContentContains) throws Exception { HttpTester.Request request = HttpTester.newRequest(); @@ -202,9 +198,11 @@ public class AllowSymLinkAliasCheckerTest request.setHeader("Host", "tester"); request.setURI(requestURI); - String responseString = localConnector.getResponse(BufferUtil.toString(request.generate())); - assertThat("Response status code", responseString, startsWith("HTTP/1.1 " + expectedResponseStatus + " ")); - assertThat("Response Content-Type", responseString, containsString("\nContent-Type: " + expectedResponseContentType)); - assertThat("Response", responseString, containsString(expectedResponseContentContains)); + assertTimeoutPreemptively(ofSeconds(5), ()-> { + String responseString = localConnector.getResponse(BufferUtil.toString(request.generate())); + assertThat("Response status code", responseString, startsWith("HTTP/1.1 " + expectedResponseStatus + " ")); + assertThat("Response Content-Type", responseString, containsString("\nContent-Type: " + expectedResponseContentType)); + assertThat("Response", responseString, containsString(expectedResponseContentContains)); + }); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BadRequestLogHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BadRequestLogHandlerTest.java index 3ecdf109ae1..1c54de4ca0a 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BadRequestLogHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BadRequestLogHandlerTest.java @@ -18,8 +18,9 @@ package org.eclipse.jetty.server.handler; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import java.io.IOException; import java.io.InputStream; @@ -33,8 +34,10 @@ import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -50,19 +53,18 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Testing oddball request scenarios (like error 400) where the error should * be logged */ -@RunWith(Parameterized.class) -@Ignore +@Tag("Unstable") +@Disabled public class BadRequestLogHandlerTest { private static final Logger LOG = Log.getLogger(BadRequestLogHandlerTest.class); @@ -90,8 +92,7 @@ public class BadRequestLogHandlerTest } } - @Parameters - public static List data() + public static Stream data() { List data = new ArrayList<>(); @@ -104,17 +105,12 @@ public class BadRequestLogHandlerTest + "Connection: close\r\n\r\n" , "GET HTTP/1.1 400" }); - return data; + return data.stream().map(Arguments::of); } - @Parameter(0) - public String requestHeader; - - @Parameter(1) - public String expectedLog; - - @Test(timeout=4000) - public void testLogHandler() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandler(String requestHeader, String expectedLog) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -148,22 +144,26 @@ public class BadRequestLogHandlerTest socket.setSoTimeout(1000); socket.connect(endpoint); - try(OutputStream out = socket.getOutputStream(); - OutputStreamWriter writer = new OutputStreamWriter(out,StandardCharsets.UTF_8); - InputStream in = socket.getInputStream(); - InputStreamReader reader = new InputStreamReader(in,StandardCharsets.UTF_8)) - { - StringReader request = new StringReader(requestHeader); - IO.copy(request,writer); - writer.flush(); - StringWriter response = new StringWriter(); - IO.copy(reader,response); - LOG.info("Response: {}",response); - } finally { - socket.close(); - } + assertTimeoutPreemptively(Duration.ofSeconds(4), ()-> { + try (OutputStream out = socket.getOutputStream(); + OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); + InputStream in = socket.getInputStream(); + InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) + { + StringReader request = new StringReader(requestHeader); + IO.copy(request, writer); + writer.flush(); + StringWriter response = new StringWriter(); + IO.copy(reader, response); + LOG.info("Response: {}", response); + } + finally + { + socket.close(); + } + }); - assertRequestLog(captureLog); + assertRequestLog(expectedLog, captureLog); } finally { @@ -171,7 +171,7 @@ public class BadRequestLogHandlerTest } } - private void assertRequestLog(CaptureLog captureLog) + private void assertRequestLog(final String expectedLog, CaptureLog captureLog) { int captureCount = captureLog.captured.size(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BufferedResponseHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BufferedResponseHandlerTest.java index 3c8d6d7a3cd..683b357f781 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BufferedResponseHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/BufferedResponseHandlerTest.java @@ -20,7 +20,7 @@ package org.eclipse.jetty.server.handler; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.util.Arrays; @@ -34,10 +34,10 @@ import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Resource Handler test @@ -51,7 +51,7 @@ public class BufferedResponseHandlerTest private static BufferedResponseHandler _bufferedHandler; private static TestHandler _test; - @BeforeClass + @BeforeAll public static void setUp() throws Exception { _server = new Server(); @@ -76,13 +76,13 @@ public class BufferedResponseHandlerTest // BufferedResponseHandler.LOG.setDebugEnabled(true); } - @AfterClass + @AfterAll public static void tearDown() throws Exception { _server.stop(); } - @Before + @BeforeEach public void before() { _test._bufferSize=-1; diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerCollectionTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerCollectionTest.java index 7fcc449d071..fb478fb7e7b 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerCollectionTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerCollectionTest.java @@ -22,10 +22,11 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; @@ -40,8 +41,8 @@ import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ContextHandlerCollectionTest { @@ -144,16 +145,14 @@ public class ContextHandlerCollectionTest if (handler==null) { - Assert.assertThat(t,response,Matchers.containsString(" 302 ")); + assertThat(t,response,Matchers.containsString(" 302 ")); } else { assertThat(t,response,endsWith(handler.toString())); if (!handler.isHandled()) { - System.err.printf("FAILED %s",t); - System.err.println(response); - Assert.fail(); + fail("FAILED " + t + "\n" + response); } } } @@ -225,9 +224,9 @@ public class ContextHandlerCollectionTest String response=connector.getResponse("GET / HTTP/1.0\n" + "Host: "+host+"\nConnection:close\n\n"); // System.err.println(response); if(succeed) - assertTrue("'"+host+"' should have been handled.",handler.isHandled()); + assertTrue(handler.isHandled(),"'"+host+"' should have been handled."); else - assertFalse("'"+host + "' should not have been handled.", handler.isHandled()); + assertFalse(handler.isHandled(),"'"+host + "' should not have been handled."); handler.reset(); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerGetResourceTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerGetResourceTest.java index 910af9237f3..0dd1f95efe5 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerGetResourceTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerGetResourceTest.java @@ -18,14 +18,17 @@ package org.eclipse.jetty.server.handler; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.condition.OS.LINUX; +import static org.junit.jupiter.api.condition.OS.MAC; import java.io.File; import java.net.MalformedURLException; @@ -36,12 +39,12 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.OS; import org.eclipse.jetty.util.resource.Resource; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; public class ContextHandlerGetResourceTest { @@ -53,7 +56,7 @@ public class ContextHandlerGetResourceTest private final static AtomicBoolean allowAliases= new AtomicBoolean(false); private final static AtomicBoolean allowSymlinks= new AtomicBoolean(false); - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { File testRoot = MavenTestingUtils.getTargetTestingDir(ContextHandlerGetResourceTest.class.getSimpleName()); @@ -77,9 +80,9 @@ public class ContextHandlerGetResourceTest File transit = new File(docroot.getParentFile(),"transit"); transit.delete(); - if (OS.IS_UNIX) + if (!OS.WINDOWS.isCurrentOs()) { - // Create alias as 8.3 name so same test will produce an alias on both windows an normal systems + // Create alias as 8.3 name so same test will produce an alias on both windows an unix/normal systems File eightDotThree=new File(sub,"TEXTFI~1.TXT"); Files.createSymbolicLink(eightDotThree.toPath(),verylong.toPath()); @@ -124,7 +127,7 @@ public class ContextHandlerGetResourceTest server.start(); } - @AfterClass + @AfterAll public static void afterClass() throws Exception { server.stop(); @@ -316,7 +319,7 @@ public class ContextHandlerGetResourceTest @Test public void testSlashSlash() throws Exception { - File expected = new File(docroot, OS.separators("subdir/data.txt")); + File expected = new File(docroot, FS.separators("subdir/data.txt")); URL expectedUrl = expected.toURI().toURL(); String path="//subdir/data.txt"; @@ -335,7 +338,7 @@ public class ContextHandlerGetResourceTest @Test public void testAliasedFile() throws Exception { - Assume.assumeTrue("OS Supports 8.3 Aliased / Alternate References",OS_ALIAS_SUPPORTED); + assumeTrue(OS_ALIAS_SUPPORTED, "OS Supports 8.3 Aliased / Alternate References"); final String path="/subdir/TEXTFI~1.TXT"; Resource resource=context.getResource(path); @@ -348,7 +351,7 @@ public class ContextHandlerGetResourceTest @Test public void testAliasedFileAllowed() throws Exception { - Assume.assumeTrue("OS Supports 8.3 Aliased / Alternate References",OS_ALIAS_SUPPORTED); + assumeTrue(OS_ALIAS_SUPPORTED, "OS Supports 8.3 Aliased / Alternate References"); try { allowAliases.set(true); @@ -370,10 +373,9 @@ public class ContextHandlerGetResourceTest } @Test + @EnabledOnOs({LINUX, MAC}) public void testSymlinkKnown() throws Exception { - Assume.assumeTrue(OS.IS_UNIX); - try { allowSymlinks.set(true); @@ -397,10 +399,9 @@ public class ContextHandlerGetResourceTest } @Test + @EnabledOnOs({LINUX, MAC}) public void testSymlinkNested() throws Exception { - Assume.assumeTrue(OS.IS_UNIX); - try { allowSymlinks.set(true); @@ -420,10 +421,9 @@ public class ContextHandlerGetResourceTest } @Test + @EnabledOnOs({LINUX, MAC}) public void testSymlinkUnknown() throws Exception { - if (!OS.IS_UNIX) - return; try { allowSymlinks.set(true); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerTest.java index 15d1adaeb99..4a0f739040e 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ContextHandlerTest.java @@ -19,13 +19,13 @@ package org.eclipse.jetty.server.handler; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -39,8 +39,8 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.resource.Resource; import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ContextHandlerTest { @@ -93,9 +93,9 @@ public class ContextHandlerTest server.start(); connector.getResponse("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n"); - Assert.assertTrue(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); + assertTrue(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); handlerA.reset(); handlerB.reset(); @@ -103,9 +103,9 @@ public class ContextHandlerTest connector.getResponse("GET / HTTP/1.0\n" + "Host: www.example2.com\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertTrue(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); + assertFalse(handlerA.isHandled()); + assertTrue(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); } finally @@ -147,31 +147,31 @@ public class ContextHandlerTest IsHandledHandler handlerD = new IsHandledHandler(); contextD.setHandler(handlerD); contextD.setVirtualHosts(new String[]{ "www.example.com@name" }); - + ContextHandler contextE = new ContextHandler("/"); contextE.setDisplayName("E"); IsHandledHandler handlerE = new IsHandledHandler(); contextE.setHandler(handlerE); contextE.setVirtualHosts(new String[]{ "*.example.com" }); - + ContextHandler contextF = new ContextHandler("/"); contextF.setDisplayName("F"); IsHandledHandler handlerF = new IsHandledHandler(); contextF.setHandler(handlerF); contextF.setVirtualHosts(new String[]{ "*.example.com@name" }); - + ContextHandler contextG = new ContextHandler("/"); contextG.setDisplayName("G"); IsHandledHandler handlerG = new IsHandledHandler(); contextG.setHandler(handlerG); contextG.setVirtualHosts(new String[]{ "*.com@name" }); - + ContextHandler contextH = new ContextHandler("/"); contextH.setDisplayName("H"); IsHandledHandler handlerH = new IsHandledHandler(); contextH.setHandler(handlerH); contextH.setVirtualHosts(new String[]{ "*.com" }); - + HandlerCollection c = new HandlerCollection(); c.addHandler(contextA); c.addHandler(contextB); @@ -181,21 +181,21 @@ public class ContextHandlerTest c.addHandler(contextF); c.addHandler(contextG); c.addHandler(contextH); - + server.setHandler(c); server.start(); try { connector.getResponse("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n"); - Assert.assertTrue(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertTrue(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -206,14 +206,14 @@ public class ContextHandlerTest handlerH.reset(); connector.getResponse("GET / HTTP/1.0\n" + "Host: localhost\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertTrue(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertFalse(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertTrue(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -224,14 +224,14 @@ public class ContextHandlerTest handlerH.reset(); connectorN.getResponse("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n"); - Assert.assertTrue(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertTrue(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -242,14 +242,14 @@ public class ContextHandlerTest handlerH.reset(); connectorN.getResponse("GET / HTTP/1.0\n" + "Host: localhost\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertTrue(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertFalse(handlerA.isHandled()); + assertTrue(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -264,7 +264,7 @@ public class ContextHandlerTest { server.stop(); } - + // Reversed order to check priority when multiple matches HandlerCollection d = new HandlerCollection(); d.addHandler(contextH); @@ -275,22 +275,22 @@ public class ContextHandlerTest d.addHandler(contextC); d.addHandler(contextB); d.addHandler(contextA); - - + + server.setHandler(d); server.start(); try { connector.getResponse("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertTrue(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertFalse(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertTrue(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -301,14 +301,14 @@ public class ContextHandlerTest handlerH.reset(); connector.getResponse("GET / HTTP/1.0\n" + "Host: localhost\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertTrue(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertFalse(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertTrue(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -319,14 +319,14 @@ public class ContextHandlerTest handlerH.reset(); connectorN.getResponse("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertFalse(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertTrue(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertFalse(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertFalse(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertTrue(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -337,14 +337,14 @@ public class ContextHandlerTest handlerH.reset(); connectorN.getResponse("GET / HTTP/1.0\n" + "Host: localhost\n\n"); - Assert.assertFalse(handlerA.isHandled()); - Assert.assertFalse(handlerB.isHandled()); - Assert.assertTrue(handlerC.isHandled()); - Assert.assertFalse(handlerD.isHandled()); - Assert.assertFalse(handlerE.isHandled()); - Assert.assertFalse(handlerF.isHandled()); - Assert.assertFalse(handlerG.isHandled()); - Assert.assertFalse(handlerH.isHandled()); + assertFalse(handlerA.isHandled()); + assertFalse(handlerB.isHandled()); + assertTrue(handlerC.isHandled()); + assertFalse(handlerD.isHandled()); + assertFalse(handlerE.isHandled()); + assertFalse(handlerF.isHandled()); + assertFalse(handlerG.isHandled()); + assertFalse(handlerH.isHandled()); handlerA.reset(); handlerB.reset(); handlerC.reset(); @@ -359,7 +359,7 @@ public class ContextHandlerTest { server.stop(); } - + } @@ -380,19 +380,19 @@ public class ContextHandlerTest // System.err.println(server.dump()); - Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/")); - Assert.assertEquals(fooA._scontext, rootA._scontext.getContext("/foo")); - Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar")); - Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar/bob.jsp")); - Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/other")); - Assert.assertEquals(fooA._scontext, rootA._scontext.getContext("/foo/other")); + assertEquals(rootA._scontext, rootA._scontext.getContext("/")); + assertEquals(fooA._scontext, rootA._scontext.getContext("/foo")); + assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar")); + assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar/bob.jsp")); + assertEquals(rootA._scontext, rootA._scontext.getContext("/other")); + assertEquals(fooA._scontext, rootA._scontext.getContext("/foo/other")); - Assert.assertEquals(rootA._scontext, foobarA._scontext.getContext("/")); - Assert.assertEquals(fooA._scontext, foobarA._scontext.getContext("/foo")); - Assert.assertEquals(foobarA._scontext, foobarA._scontext.getContext("/foo/bar")); - Assert.assertEquals(foobarA._scontext, foobarA._scontext.getContext("/foo/bar/bob.jsp")); - Assert.assertEquals(rootA._scontext, foobarA._scontext.getContext("/other")); - Assert.assertEquals(fooA._scontext, foobarA._scontext.getContext("/foo/other")); + assertEquals(rootA._scontext, foobarA._scontext.getContext("/")); + assertEquals(fooA._scontext, foobarA._scontext.getContext("/foo")); + assertEquals(foobarA._scontext, foobarA._scontext.getContext("/foo/bar")); + assertEquals(foobarA._scontext, foobarA._scontext.getContext("/foo/bar/bob.jsp")); + assertEquals(rootA._scontext, foobarA._scontext.getContext("/other")); + assertEquals(fooA._scontext, foobarA._scontext.getContext("/foo/other")); } @Test @@ -413,39 +413,39 @@ public class ContextHandlerTest // check that all contexts start normally server.start(); - Assert.assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); - Assert.assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo/bar'")); + assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); + assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo/bar'")); // If we stop foobar, then requests will be handled by foo foobar.stop(); - Assert.assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); - Assert.assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); + assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); + assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); // If we shutdown foo then requests will be 503'd foo.shutdown().get(); - Assert.assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("503")); - Assert.assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("503")); + assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("503")); + assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("503")); // If we stop foo then requests will be handled by root foo.stop(); - Assert.assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); // If we start foo then foobar requests will be handled by foo foo.start(); - Assert.assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); - Assert.assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); + assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); + assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); // If we start foobar then foobar requests will be handled by foobar foobar.start(); - Assert.assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); - Assert.assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); - Assert.assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo/bar'")); + assertThat(connector.getResponse("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''")); + assertThat(connector.getResponse("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'")); + assertThat(connector.getResponse("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo/bar'")); } @@ -482,17 +482,17 @@ public class ContextHandlerTest // System.err.println(server.dump()); - Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/")); - Assert.assertEquals(fooA._scontext, rootA._scontext.getContext("/foo")); - Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar")); - Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar/bob")); + assertEquals(rootA._scontext, rootA._scontext.getContext("/")); + assertEquals(fooA._scontext, rootA._scontext.getContext("/foo")); + assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar")); + assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar/bob")); - Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/other")); - Assert.assertEquals(rootB._scontext, rootB._scontext.getContext("/other")); - Assert.assertEquals(rootC._scontext, rootC._scontext.getContext("/other")); + assertEquals(rootA._scontext, rootA._scontext.getContext("/other")); + assertEquals(rootB._scontext, rootB._scontext.getContext("/other")); + assertEquals(rootC._scontext, rootC._scontext.getContext("/other")); - Assert.assertEquals(fooB._scontext, rootB._scontext.getContext("/foo/other")); - Assert.assertEquals(rootC._scontext, rootC._scontext.getContext("/foo/other")); + assertEquals(fooB._scontext, rootB._scontext.getContext("/foo/other")); + assertEquals(rootC._scontext, rootC._scontext.getContext("/foo/other")); } @@ -542,27 +542,27 @@ public class ContextHandlerTest // test singular context.setVirtualHosts(new String[] { "www.example.com"} ); - Assert.assertEquals(1, context.getVirtualHosts().length); + assertEquals(1, context.getVirtualHosts().length); // test adding two more context.addVirtualHosts(new String[] { "foo.com@connector1", "*.example2.com"}); - Assert.assertEquals(3, context.getVirtualHosts().length); + assertEquals(3, context.getVirtualHosts().length); // test adding existing context context.addVirtualHosts(new String[] { "www.example.com" }); - Assert.assertEquals(3, context.getVirtualHosts().length); + assertEquals(3, context.getVirtualHosts().length); // test removing existing context.removeVirtualHosts(new String[] { "*.example2.com" }); - Assert.assertEquals(2, context.getVirtualHosts().length); + assertEquals(2, context.getVirtualHosts().length); // test removing non-existent context.removeVirtualHosts(new String[] { "www.example3.com" }); - Assert.assertEquals(2, context.getVirtualHosts().length); + assertEquals(2, context.getVirtualHosts().length); // test removing all remaining and resets to null context.removeVirtualHosts(new String[] { "www.example.com", "foo.com@connector1" }); - Assert.assertArrayEquals(null, context.getVirtualHosts()); + assertArrayEquals(null, context.getVirtualHosts()); } @@ -572,31 +572,31 @@ public class ContextHandlerTest ContextHandler handler = new ContextHandler(); handler.setServer(new Server()); handler.setAttribute("aaa","111"); - Assert.assertEquals("111", handler.getServletContext().getAttribute("aaa")); - Assert.assertEquals(null, handler.getAttribute("bbb")); + assertEquals("111", handler.getServletContext().getAttribute("aaa")); + assertEquals(null, handler.getAttribute("bbb")); handler.start(); handler.getServletContext().setAttribute("aaa","000"); handler.setAttribute("ccc","333"); handler.getServletContext().setAttribute("ddd","444"); - Assert.assertEquals("111", handler.getServletContext().getAttribute("aaa")); - Assert.assertEquals(null, handler.getServletContext().getAttribute("bbb")); + assertEquals("111", handler.getServletContext().getAttribute("aaa")); + assertEquals(null, handler.getServletContext().getAttribute("bbb")); handler.getServletContext().setAttribute("bbb","222"); - Assert.assertEquals("333", handler.getServletContext().getAttribute("ccc")); - Assert.assertEquals("444", handler.getServletContext().getAttribute("ddd")); + assertEquals("333", handler.getServletContext().getAttribute("ccc")); + assertEquals("444", handler.getServletContext().getAttribute("ddd")); - Assert.assertEquals("111", handler.getAttribute("aaa")); - Assert.assertEquals(null, handler.getAttribute("bbb")); - Assert.assertEquals("333", handler.getAttribute("ccc")); - Assert.assertEquals(null, handler.getAttribute("ddd")); + assertEquals("111", handler.getAttribute("aaa")); + assertEquals(null, handler.getAttribute("bbb")); + assertEquals("333", handler.getAttribute("ccc")); + assertEquals(null, handler.getAttribute("ddd")); handler.stop(); - Assert.assertEquals("111", handler.getServletContext().getAttribute("aaa")); - Assert.assertEquals(null, handler.getServletContext().getAttribute("bbb")); - Assert.assertEquals("333", handler.getServletContext().getAttribute("ccc")); - Assert.assertEquals(null, handler.getServletContext().getAttribute("ddd")); + assertEquals("111", handler.getServletContext().getAttribute("aaa")); + assertEquals(null, handler.getServletContext().getAttribute("bbb")); + assertEquals("333", handler.getServletContext().getAttribute("ccc")); + assertEquals(null, handler.getServletContext().getAttribute("ddd")); } @Test @@ -606,10 +606,10 @@ public class ContextHandlerTest String[] protectedTargets = {"/foo-inf", "/bar-inf"}; handler.setProtectedTargets(protectedTargets); - Assert.assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z")); - Assert.assertFalse(handler.isProtectedTarget("/foo/x/y/z")); - Assert.assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1")); - Assert.assertFalse(handler.isProtectedTarget("/foo-inf-bar")); + assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z")); + assertFalse(handler.isProtectedTarget("/foo/x/y/z")); + assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1")); + assertFalse(handler.isProtectedTarget("/foo-inf-bar")); protectedTargets = new String[4]; System.arraycopy(handler.getProtectedTargets(), 0, protectedTargets, 0, 2); @@ -617,20 +617,20 @@ public class ContextHandlerTest protectedTargets[3] = "/def"; handler.setProtectedTargets(protectedTargets); - Assert.assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z")); - Assert.assertFalse(handler.isProtectedTarget("/foo/x/y/z")); - Assert.assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1")); - Assert.assertTrue(handler.isProtectedTarget("/abc/124")); - Assert.assertTrue(handler.isProtectedTarget("//def")); + assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z")); + assertFalse(handler.isProtectedTarget("/foo/x/y/z")); + assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1")); + assertTrue(handler.isProtectedTarget("/abc/124")); + assertTrue(handler.isProtectedTarget("//def")); - Assert.assertTrue(handler.isProtectedTarget("/ABC/7777")); + assertTrue(handler.isProtectedTarget("/ABC/7777")); } @Test public void testIsShutdown() { ContextHandler handler = new ContextHandler(); - Assert.assertEquals(false, handler.isShutdown()); + assertEquals(false, handler.isShutdown()); } @Test @@ -723,15 +723,15 @@ public class ContextHandlerTest ContextHandler handler = new ContextHandler(); - Assert.assertTrue("Not a directory " + testDirectory, testDirectory.isDirectory()); + assertTrue(testDirectory.isDirectory(),"Not a directory " + testDirectory); handler.setBaseResource(Resource.newResource(Resource.toURL(testDirectory))); List paths = new ArrayList<>(handler.getResourcePaths(root)); - Assert.assertEquals(2, paths.size()); + assertEquals(2, paths.size()); Collections.sort(paths); - Assert.assertEquals("/WEB-INF/jsp/", paths.get(0)); - Assert.assertEquals("/WEB-INF/web.xml", paths.get(1)); + assertEquals("/WEB-INF/jsp/", paths.get(0)); + assertEquals("/WEB-INF/web.xml", paths.get(1)); } private File setupTestDirectory() throws IOException @@ -739,19 +739,19 @@ public class ContextHandlerTest File tmpDir = new File( System.getProperty( "basedir",".") + "/target/tmp/ContextHandlerTest" ); tmpDir=tmpDir.getCanonicalFile(); if (!tmpDir.exists()) - Assert.assertTrue(tmpDir.mkdirs()); + assertTrue(tmpDir.mkdirs()); File tmp = File.createTempFile("cht",null, tmpDir ); - Assert.assertTrue(tmp.delete()); - Assert.assertTrue(tmp.mkdir()); + assertTrue(tmp.delete()); + assertTrue(tmp.mkdir()); tmp.deleteOnExit(); File root = new File(tmp,getClass().getName()); - Assert.assertTrue(root.mkdir()); + assertTrue(root.mkdir()); File webInf = new File(root,"WEB-INF"); - Assert.assertTrue(webInf.mkdir()); + assertTrue(webInf.mkdir()); - Assert.assertTrue(new File(webInf, "jsp").mkdir()); - Assert.assertTrue(new File(webInf, "web.xml").createNewFile()); + assertTrue(new File(webInf, "jsp").mkdir()); + assertTrue(new File(webInf, "web.xml").createNewFile()); return root; } @@ -767,9 +767,9 @@ public class ContextHandlerTest { connector.getResponse("GET / HTTP/1.1\n" + "Host: "+host+"\nConnection:close\n\n"); if(succeed) - Assert.assertTrue("'" + host + "' should have been handled.", handler.isHandled()); + assertTrue(handler.isHandled(),"'" + host + "' should have been handled."); else - Assert.assertFalse("'" + host + "' should not have been handled.", handler.isHandled()); + assertFalse(handler.isHandled(),"'" + host + "' should not have been handled."); handler.reset(); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DebugHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DebugHandlerTest.java index 2cf85e1db72..936a909a41f 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DebugHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DebugHandlerTest.java @@ -18,8 +18,10 @@ package org.eclipse.jetty.server.handler; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; import java.io.ByteArrayOutputStream; import java.io.File; @@ -52,9 +54,9 @@ import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.Scheduler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class DebugHandlerTest { @@ -77,7 +79,7 @@ public class DebugHandlerTest private ByteArrayOutputStream capturedLog; @SuppressWarnings("deprecation") - @Before + @BeforeEach public void startServer() throws Exception { server = new Server(); @@ -146,7 +148,7 @@ public class DebugHandlerTest } } - @After + @AfterEach public void stopServer() throws Exception { server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DefaultHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DefaultHandlerTest.java index b30f2e14260..2c1fd4edebd 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DefaultHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/DefaultHandlerTest.java @@ -18,8 +18,10 @@ package org.eclipse.jetty.server.handler; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.OutputStream; import java.net.Socket; @@ -31,10 +33,9 @@ import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class DefaultHandlerTest { @@ -42,7 +43,7 @@ public class DefaultHandlerTest private ServerConnector connector; private DefaultHandler handler; - @Before + @BeforeEach public void before() throws Exception { server = new Server(); @@ -65,7 +66,7 @@ public class DefaultHandlerTest server.start(); } - @After + @AfterEach public void after() throws Exception { server.stop(); @@ -87,13 +88,13 @@ public class DefaultHandlerTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.Response response = HttpTester.parseResponse(input); - Assert.assertEquals(HttpStatus.NOT_FOUND_404, response.getStatus()); - Assert.assertEquals("text/html;charset=ISO-8859-1", response.get(HttpHeader.CONTENT_TYPE)); + assertEquals(HttpStatus.NOT_FOUND_404, response.getStatus()); + assertEquals("text/html;charset=ISO-8859-1", response.get(HttpHeader.CONTENT_TYPE)); String content = new String(response.getContentBytes(),StandardCharsets.ISO_8859_1); - Assert.assertThat(content,containsString("Contexts known to this server are:")); - Assert.assertThat(content,containsString("/foo")); - Assert.assertThat(content,containsString("/bar")); + assertThat(content,containsString("Contexts known to this server are:")); + assertThat(content,containsString("/foo")); + assertThat(content,containsString("/bar")); } } @@ -113,13 +114,13 @@ public class DefaultHandlerTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.Response response = HttpTester.parseResponse(input); - Assert.assertEquals(HttpStatus.NOT_FOUND_404, response.getStatus()); - Assert.assertEquals("text/html;charset=ISO-8859-1", response.get(HttpHeader.CONTENT_TYPE)); + assertEquals(HttpStatus.NOT_FOUND_404, response.getStatus()); + assertEquals("text/html;charset=ISO-8859-1", response.get(HttpHeader.CONTENT_TYPE)); String content = new String(response.getContentBytes(),StandardCharsets.ISO_8859_1); - Assert.assertThat(content,not(containsString("Contexts known to this server are:"))); - Assert.assertThat(content,not(containsString("/foo"))); - Assert.assertThat(content,not(containsString("/bar"))); + assertThat(content,not(containsString("Contexts known to this server are:"))); + assertThat(content,not(containsString("/foo"))); + assertThat(content,not(containsString("/bar"))); } } @@ -139,8 +140,8 @@ public class DefaultHandlerTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.Response response = HttpTester.parseResponse(input); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertEquals("image/x-icon", response.get(HttpHeader.CONTENT_TYPE)); + assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals("image/x-icon", response.get(HttpHeader.CONTENT_TYPE)); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/HandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/HandlerTest.java index bc2ddb3bc58..37d648f7adb 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/HandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/HandlerTest.java @@ -18,10 +18,11 @@ package org.eclipse.jetty.server.handler; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; @@ -29,12 +30,10 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.HandlerWrapper; -import org.hamcrest.Matchers; -import org.junit.Test; +import org.eclipse.jetty.server.Server; +import org.junit.jupiter.api.Test; public class HandlerTest { @@ -73,16 +72,9 @@ public class HandlerTest public void testWrapperThisLoop() { HandlerWrapper a = new HandlerWrapper(); - - try - { - a.setHandler(a); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> a.setHandler(a)); + assertThat(e.getMessage(),containsString("loop")); } @Test @@ -92,16 +84,9 @@ public class HandlerTest HandlerWrapper b = new HandlerWrapper(); a.setHandler(b); - - try - { - b.setHandler(a); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> b.setHandler(a)); + assertThat(e.getMessage(),containsString("loop")); } @Test @@ -113,16 +98,9 @@ public class HandlerTest a.setHandler(b); b.setHandler(c); - - try - { - c.setHandler(a); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> c.setHandler(a)); + assertThat(e.getMessage(),containsString("loop")); } @Test @@ -134,16 +112,9 @@ public class HandlerTest a.setHandler(b); c.setHandler(a); - - try - { - b.setHandler(c); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> b.setHandler(c)); + assertThat(e.getMessage(),containsString("loop")); } @@ -203,16 +174,9 @@ public class HandlerTest public void testCollectionThisLoop() { HandlerCollection a = new HandlerCollection(); - - try - { - a.addHandler(a); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> a.addHandler(a)); + assertThat(e.getMessage(),containsString("loop")); } @Test @@ -231,15 +195,8 @@ public class HandlerTest b.setHandlers(new Handler[]{b1,b2}); c.setHandlers(new Handler[]{c1,c2}); - try - { - b2.addHandler(a); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> b2.addHandler(a)); + assertThat(e.getMessage(),containsString("loop")); } @Test @@ -258,15 +215,8 @@ public class HandlerTest c.setHandlers(new Handler[]{c1,c2}); b2.addHandler(a); - try - { - a.addHandler(b); - fail(); - } - catch(IllegalStateException e) - { - assertThat(e.getMessage(),containsString("loop")); - } + IllegalStateException e = assertThrows(IllegalStateException.class, ()-> a.addHandler(b)); + assertThat(e.getMessage(),containsString("loop")); } @Test @@ -328,15 +278,8 @@ public class HandlerTest { } }); - - try - { - a.insertHandler(b); - fail(); - } - catch(IllegalArgumentException e) - { - assertThat(e.getMessage(),containsString("bad tail")); - } + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, ()-> a.insertHandler(b)); + assertThat(e.getMessage(),containsString("bad tail")); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/IPAccessHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/IPAccessHandlerTest.java index 89679bb87cc..be13ae5bfb9 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/IPAccessHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/IPAccessHandlerTest.java @@ -18,8 +18,8 @@ package org.eclipse.jetty.server.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.EOFException; @@ -29,12 +29,12 @@ import java.io.OutputStream; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.Arrays; -import java.util.Collection; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -46,28 +46,19 @@ import org.eclipse.jetty.server.NetworkConnector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class IPAccessHandlerTest { private static Server _server; private static NetworkConnector _connector; private static IPAccessHandler _handler; - private String _white; - private String _black; - private String _host; - private String _uri; - private String _code; - private boolean _byPath; - - @BeforeClass + @BeforeAll public static void setUp() throws Exception { @@ -90,7 +81,7 @@ public class IPAccessHandlerTest } /* ------------------------------------------------------------ */ - @AfterClass + @AfterAll public static void tearDown() throws Exception { @@ -98,26 +89,16 @@ public class IPAccessHandlerTest } /* ------------------------------------------------------------ */ - public IPAccessHandlerTest(String white, String black, String host, String uri, String code, boolean byPath) - { - _white = white; - _black = black; - _host = host; - _uri = uri; - _code = code; - _byPath = byPath; - } - - /* ------------------------------------------------------------ */ - @Test - public void testHandler() + @ParameterizedTest + @MethodSource("data") + public void testHandler(String white, String black, String host, String uri, String code, boolean byPath) throws Exception { - _handler.setWhite(_white.split(";",-1)); - _handler.setBlack(_black.split(";",-1)); - _handler.setWhiteListByPath(_byPath); + _handler.setWhite(white.split(";",-1)); + _handler.setBlack(black.split(";",-1)); + _handler.setWhiteListByPath(byPath); - String request = "GET " + _uri + " HTTP/1.1\n" + "Host: "+ _host + "\n\n"; + String request = "GET " + uri + " HTTP/1.1\n" + "Host: "+ host + "\n\n"; Socket socket = new Socket("127.0.0.1", _connector.getLocalPort()); socket.setSoTimeout(5000); try @@ -130,9 +111,9 @@ public class IPAccessHandlerTest Response response = readResponse(input); Object[] params = new Object[]{ - "Request WBHUC", _white, _black, _host, _uri, _code, + "Request WBHUC", white, black, host, uri, code, "Response", response.getCode()}; - assertEquals(Arrays.deepToString(params), _code, response.getCode()); + assertEquals(code, response.getCode(), Arrays.deepToString(params)); } finally { @@ -152,7 +133,7 @@ public class IPAccessHandlerTest assertTrue(responseLine.lookingAt()); String code = responseLine.group(1); - Map headers = new LinkedHashMap(); + Map headers = new LinkedHashMap<>(); while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) @@ -248,8 +229,7 @@ public class IPAccessHandlerTest } /* ------------------------------------------------------------ */ - @Parameters - public static Collection data() { + public static Stream data() { Object[][] data = new Object[][] { // Empty lists {"", "", "127.0.0.1", "/", "200", false}, @@ -560,6 +540,6 @@ public class IPAccessHandlerTest {"172.0.0.0-255|/dump/*;127.0.0.0-255|/dump/*", "", "127.0.0.1", "/dispatch", "200", true}, // _whiteListByPath {"172.0.0.0-255|/dump/*;127.0.0.0-255|/dump/*", "", "127.0.0.1", "/dump/info", "200", true}, }; - return Arrays.asList(data); - }; + return Arrays.asList(data).stream().map(Arguments::of); + } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogHandlerTest.java index 8d4db5cb22b..a57c4186c85 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogHandlerTest.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.server.handler; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; import java.io.IOException; import java.io.InputStream; @@ -31,6 +31,7 @@ import java.net.HttpURLConnection; import java.net.URI; import java.util.ArrayList; import java.util.List; +import java.util.stream.Stream; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; @@ -54,20 +55,19 @@ import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.StacklessLogging; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests for RequestLogHandler behavior. *

* Tests different request handler behavior against different server+error configurations */ -@RunWith(Parameterized.class) -@Ignore +@Tag("Unstable") +@Disabled public class RequestLogHandlerTest { private static final Logger LOG = Log.getLogger(RequestLogHandlerTest.class); @@ -347,8 +347,7 @@ public class RequestLogHandlerTest } } - @Parameters(name = "{0}") - public static List data() + public static Stream data() { List data = new ArrayList<>(); @@ -363,24 +362,16 @@ public class RequestLogHandlerTest data.add(new Object[] { new IOExceptionHandler(), "/test/", "GET /test/ HTTP/1.1 500" }); data.add(new Object[] { new RuntimeExceptionHandler(), "/test/", "GET /test/ HTTP/1.1 500" }); - return data; + return data.stream().map(Arguments::of); } - @Parameter(0) - public Handler testHandler; - - @Parameter(1) - public String requestPath; - - @Parameter(2) - public String expectedLogEntry; - /** * Test a RequestLogHandler at the end of a HandlerCollection. all other configuration on server at defaults. * @throws Exception if test failure */ - @Test(timeout = 4000) - public void testLogHandlerCollection() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandlerCollection(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -431,7 +422,7 @@ public class RequestLogHandlerTest connection.disconnect(); } - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -439,8 +430,9 @@ public class RequestLogHandlerTest } } - @Test(timeout = 4000) - public void testMultipleLogHandlers() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testMultipleLogHandlers(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -499,7 +491,7 @@ public class RequestLogHandlerTest } for (CaptureLog captureLog:captureLogs) - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -511,8 +503,9 @@ public class RequestLogHandlerTest * Test a RequestLogHandler at the end of a HandlerCollection and also with the default ErrorHandler as server bean in place. * @throws Exception if test failure */ - @Test(timeout = 4000) - public void testLogHandlerCollection_ErrorHandler_ServerBean() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandlerCollection_ErrorHandler_ServerBean(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -566,7 +559,7 @@ public class RequestLogHandlerTest connection.disconnect(); } - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -578,8 +571,9 @@ public class RequestLogHandlerTest * Test a RequestLogHandler at the end of a HandlerCollection and also with the ErrorHandler in place. * @throws Exception if test failure */ - @Test(timeout=4000) - public void testLogHandlerCollection_AltErrorHandler() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandlerCollection_AltErrorHandler(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -640,7 +634,7 @@ public class RequestLogHandlerTest connection.disconnect(); } - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -652,8 +646,9 @@ public class RequestLogHandlerTest * Test a RequestLogHandler at the end of a HandlerCollection and also with the ErrorHandler in place. * @throws Exception if test failure */ - @Test(timeout=4000) - public void testLogHandlerCollection_OKErrorHandler() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandlerCollection_OKErrorHandler(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -714,7 +709,7 @@ public class RequestLogHandlerTest connection.disconnect(); } - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -726,8 +721,9 @@ public class RequestLogHandlerTest * Test a RequestLogHandler at the end of a HandlerCollection and also with the ErrorHandler in place. * @throws Exception if test failure */ - @Test(timeout=4000) - public void testLogHandlerCollection_DispatchErrorHandler() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandlerCollection_DispatchErrorHandler(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -788,7 +784,7 @@ public class RequestLogHandlerTest connection.disconnect(); } - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -796,8 +792,9 @@ public class RequestLogHandlerTest } } - @Test(timeout = 4000) - public void testLogHandlerWrapped() throws Exception + @ParameterizedTest + @MethodSource("data") + public void testLogHandlerWrapped(Handler testHandler, String requestPath, String expectedLogEntry) throws Exception { Server server = new Server(); ServerConnector connector = new ServerConnector(server); @@ -813,7 +810,7 @@ public class RequestLogHandlerTest server.setHandler(requestLog); - try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class,HttpChannelState.class)) + try (StacklessLogging ignore = new StacklessLogging(HttpChannel.class,HttpChannelState.class)) { server.start(); @@ -848,7 +845,7 @@ public class RequestLogHandlerTest connection.disconnect(); } - assertRequestLog(captureLog); + assertRequestLog(expectedLogEntry, captureLog); } finally { @@ -856,7 +853,7 @@ public class RequestLogHandlerTest } } - private void assertRequestLog(CaptureLog captureLog) + private void assertRequestLog(final String expectedLogEntry, CaptureLog captureLog) { int captureCount = captureLog.captured.size(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogTest.java index 7e0f8e7ddde..040e919d4b0 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/RequestLogTest.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.server.handler; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.io.InputStream; @@ -36,9 +36,9 @@ import org.eclipse.jetty.server.AbstractNCSARequestLog; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class RequestLogTest { @@ -47,7 +47,7 @@ public class RequestLogTest LocalConnector _connector; - @Before + @BeforeEach public void before() throws Exception { _log = new Exchanger(); @@ -59,7 +59,7 @@ public class RequestLogTest _server.start(); } - @After + @AfterEach public void after() throws Exception { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerRangeTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerRangeTest.java index c2074af755b..49898253edb 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerRangeTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerRangeTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.server.handler; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + import java.io.File; import java.io.FileWriter; import java.io.InputStream; @@ -30,21 +33,18 @@ import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.resource.Resource; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.is; - -@Ignore("Unfixed range bug - Issue #107") +@Disabled("Unfixed range bug - Issue #107") public class ResourceHandlerRangeTest { private static Server server; private static URI serverUri; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { server = new Server(); @@ -83,7 +83,7 @@ public class ResourceHandlerRangeTest serverUri = new URI(String.format("http://%s:%d/",host,port)); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { server.stop(); @@ -106,7 +106,7 @@ public class ResourceHandlerRangeTest response = IO.toString(is); } - Assert.assertThat("Content Length",contentLength,is(5)); - Assert.assertThat("Response Content",response,is("56789")); + assertThat("Content Length",contentLength,is(5)); + assertThat("Response Content",response,is("56789")); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java index cac9454a6a3..9bb4d3dd179 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ResourceHandlerTest.java @@ -27,7 +27,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.BufferedReader; import java.io.File; @@ -49,15 +50,15 @@ import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.IO; import org.hamcrest.Matchers; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; /** * Resource Handler test @@ -74,7 +75,7 @@ public class ResourceHandlerTest private static ContextHandler _contextHandler; private static ResourceHandler _resourceHandler; - @BeforeClass + @BeforeAll public static void setUp() throws Exception { File dir = MavenTestingUtils.getTargetFile("test-classes/simple"); @@ -139,13 +140,13 @@ public class ResourceHandlerTest _server.start(); } - @AfterClass + @AfterAll public static void tearDown() throws Exception { _server.stop(); } - @Before + @BeforeEach public void before() { _config.setOutputBufferSize(4096); @@ -249,9 +250,9 @@ public class ResourceHandlerTest socket.getOutputStream().write("GET /resource/bigger.txt HTTP/1.0\n\n".getBytes()); Thread.sleep(1000); String response = IO.toString(socket.getInputStream()); - Assert.assertThat(response,Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response,Matchers.containsString(" 400\tThis is a big file" + LN + " 1\tThis is a big file")); - Assert.assertThat(response,Matchers.endsWith(" 400\tThis is a big file" + LN)); + assertThat(response,Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response,Matchers.containsString(" 400\tThis is a big file" + LN + " 1\tThis is a big file")); + assertThat(response,Matchers.endsWith(" 400\tThis is a big file" + LN)); } } @@ -282,7 +283,7 @@ public class ResourceHandlerTest } @Test - @Slow + @DisabledIfSystemProperty(named = "env", matches = "ci") // TODO: SLOW, needs review public void testSlowBiggest() throws Exception { _connector.setIdleTimeout(9000); @@ -318,9 +319,9 @@ public class ResourceHandlerTest // System.err.println(++i+": "+BufferUtil.toDetailString(buffer)); } - Assert.assertEquals('E',buffer.get(buffer.limit()-4)); - Assert.assertEquals('N',buffer.get(buffer.limit()-3)); - Assert.assertEquals('D',buffer.get(buffer.limit()-2)); + assertEquals('E',buffer.get(buffer.limit()-4)); + assertEquals('N',buffer.get(buffer.limit()-3)); + assertEquals('D',buffer.get(buffer.limit()-2)); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java index a5b5220a6d5..447d7e0257c 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ScopedHandlerTest.java @@ -18,7 +18,7 @@ package org.eclipse.jetty.server.handler; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -29,14 +29,14 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Response; import org.eclipse.jetty.server.Server; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ScopedHandlerTest { private StringBuilder _history=new StringBuilder(); - @Before + @BeforeEach public void resetHistory() { _history.setLength(0); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/SecuredRedirectHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/SecuredRedirectHandlerTest.java index 1d2d75c73e0..506cbc9a542 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/SecuredRedirectHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/SecuredRedirectHandlerTest.java @@ -20,7 +20,7 @@ package org.eclipse.jetty.server.handler; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; @@ -51,9 +51,9 @@ import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.toolchain.test.IO; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class SecuredRedirectHandlerTest { @@ -63,7 +63,7 @@ public class SecuredRedirectHandlerTest private static URI serverHttpUri; private static URI serverHttpsUri; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { // Setup SSL @@ -154,7 +154,7 @@ public class SecuredRedirectHandlerTest HttpsURLConnection.setDefaultSSLSocketFactory(sslContextFactory.getSslContext().getSocketFactory()); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { HttpsURLConnection.setDefaultSSLSocketFactory(origSsf); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ShutdownHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ShutdownHandlerTest.java index 1251c8f8809..6e59da1d6c5 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ShutdownHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ShutdownHandlerTest.java @@ -18,6 +18,9 @@ package org.eclipse.jetty.server.handler; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; @@ -38,8 +41,8 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.component.LifeCycle; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Test; public class ShutdownHandlerTest { @@ -79,10 +82,10 @@ public class ShutdownHandlerTest }); HttpTester.Response response = shutdown(shutdownToken); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); - Assert.assertTrue(stopLatch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(AbstractLifeCycle.STOPPED, server.getState()); + assertTrue(stopLatch.await(5, TimeUnit.SECONDS)); + assertEquals(AbstractLifeCycle.STOPPED, server.getState()); } @Test @@ -91,10 +94,10 @@ public class ShutdownHandlerTest start(null); HttpTester.Response response = shutdown("wrongToken"); - Assert.assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus()); + assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus()); Thread.sleep(1000); - Assert.assertEquals(AbstractLifeCycle.STARTED, server.getState()); + assertEquals(AbstractLifeCycle.STARTED, server.getState()); } @Test @@ -111,10 +114,10 @@ public class ShutdownHandlerTest }); HttpTester.Response response = shutdown(shutdownToken); - Assert.assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus()); + assertEquals(HttpStatus.UNAUTHORIZED_401, response.getStatus()); Thread.sleep(1000); - Assert.assertEquals(AbstractLifeCycle.STARTED, server.getState()); + assertEquals(AbstractLifeCycle.STARTED, server.getState()); } private HttpTester.Response shutdown(String shutdownToken) throws IOException diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java index fd593d62316..d8bcbb19656 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/StatisticsHandlerTest.java @@ -37,16 +37,14 @@ import org.eclipse.jetty.io.ConnectionStatistics; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + public class StatisticsHandlerTest { @@ -56,7 +54,7 @@ public class StatisticsHandlerTest private LatchHandler _latchHandler; private StatisticsHandler _statsHandler; - @Before + @BeforeEach public void init() throws Exception { _server = new Server(); @@ -73,7 +71,7 @@ public class StatisticsHandlerTest _latchHandler.setHandler(_statsHandler); } - @After + @AfterEach public void destroy() throws Exception { _server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ThreadLimitHandlerTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ThreadLimitHandlerTest.java index ed3bd5596c6..8bb3bca2a2f 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ThreadLimitHandlerTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/handler/ThreadLimitHandlerTest.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.server.handler; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.net.Socket; @@ -40,10 +40,10 @@ import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ThreadLimitHandlerTest { @@ -52,7 +52,7 @@ public class ThreadLimitHandlerTest private LocalConnector _local; - @Before + @BeforeEach public void before() throws Exception { @@ -63,7 +63,7 @@ public class ThreadLimitHandlerTest } - @After + @AfterEach public void after() throws Exception { @@ -98,15 +98,15 @@ public class ThreadLimitHandlerTest last.set(null); _local.getResponse("GET / HTTP/1.0\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nX-Forwarded-For: 1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nForwarded: for=1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); } @Test @@ -127,19 +127,19 @@ public class ThreadLimitHandlerTest last.set(null); _local.getResponse("GET / HTTP/1.0\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nX-Forwarded-For: 1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("1.2.3.4")); + assertThat(last.get(),Matchers.is("1.2.3.4")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nForwarded: for=1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nX-Forwarded-For: 1.1.1.1\r\nX-Forwarded-For: 6.6.6.6,1.2.3.4\r\nForwarded: for=1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("1.2.3.4")); + assertThat(last.get(),Matchers.is("1.2.3.4")); } @@ -161,19 +161,19 @@ public class ThreadLimitHandlerTest last.set(null); _local.getResponse("GET / HTTP/1.0\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nX-Forwarded-For: 1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("0.0.0.0")); + assertThat(last.get(),Matchers.is("0.0.0.0")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nForwarded: for=1.2.3.4\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("1.2.3.4")); + assertThat(last.get(),Matchers.is("1.2.3.4")); last.set(null); _local.getResponse("GET / HTTP/1.0\r\nX-Forwarded-For: 1.1.1.1\r\nForwarded: for=6.6.6.6; for=1.2.3.4\r\nX-Forwarded-For: 6.6.6.6\r\nForwarded: proto=https\r\n\r\n"); - Assert.assertThat(last.get(),Matchers.is("1.2.3.4")); + assertThat(last.get(),Matchers.is("1.2.3.4")); } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/session/SessionCookieTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/session/SessionCookieTest.java index 0758e7a1000..f79d597e071 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/session/SessionCookieTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/session/SessionCookieTest.java @@ -23,10 +23,10 @@ import javax.servlet.http.HttpServletRequest; import org.eclipse.jetty.http.HttpCookie; import org.eclipse.jetty.server.Server; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.TimeUnit; diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLCloseTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLCloseTest.java index 0f6eb0fe945..344a620fc58 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLCloseTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLCloseTest.java @@ -40,7 +40,7 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SSLCloseTest { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLEngineTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLEngineTest.java index 7c45e44526b..af5f7b4b10f 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLEngineTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLEngineTest.java @@ -24,9 +24,10 @@ package org.eclipse.jetty.server.ssl; import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.BufferedReader; import java.io.IOException; @@ -58,9 +59,9 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @@ -104,7 +105,7 @@ public class SSLEngineTest private ServerConnector connector; - @Before + @BeforeEach public void startServer() throws Exception { String keystore = MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath(); @@ -124,7 +125,7 @@ public class SSLEngineTest server.addConnector(connector); } - @After + @AfterEach public void stopServer() throws Exception { server.stop(); @@ -236,7 +237,7 @@ public class SSLEngineTest // Read the response. String responses=readResponse(client[i]); // Check the responses - assertEquals(String.format("responses loop=%d connection=%d",l,i),RESPONSE0+RESPONSE0+RESPONSE1,responses); + assertThat(String.format("responses loop=%d connection=%d",l,i),RESPONSE0+RESPONSE0+RESPONSE1,is(responses)); } } finally @@ -247,7 +248,7 @@ public class SSLEngineTest { try { - assertEquals(-1,client[i].getInputStream().read()); + assertThat("Client should read EOF", client[i].getInputStream().read(), is(-1)); } catch(SocketException e) { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java index d2157cf8e4b..a91feeb69d9 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SSLSelectChannelConnectorLoadTest.java @@ -19,7 +19,7 @@ package org.eclipse.jetty.server.ssl; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.BufferedReader; import java.io.FileInputStream; @@ -49,9 +49,9 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class SSLSelectChannelConnectorLoadTest { @@ -59,7 +59,7 @@ public class SSLSelectChannelConnectorLoadTest private static ServerConnector connector; private static SSLContext sslContext; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { String keystorePath = System.getProperty("basedir", ".") + "/src/test/resources/keystore"; @@ -89,7 +89,7 @@ public class SSLSelectChannelConnectorLoadTest sslContext.init(null, trustManagerFactory.getTrustManagers(), null); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { server.stop(); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java index d71bec70861..9dfc1ffb8b9 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SelectChannelServerSslTest.java @@ -18,6 +18,14 @@ package org.eclipse.jetty.server.ssl; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.condition.OS.WINDOWS; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -51,21 +59,13 @@ import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; -import org.eclipse.jetty.toolchain.test.OS; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isEmptyOrNullString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.condition.DisabledOnOs; /** * HttpServer Tester. @@ -79,7 +79,7 @@ public class SelectChannelServerSslTest extends HttpServerTestBase _scheme="https"; } - @Before + @BeforeEach public void init() throws Exception { String keystorePath = MavenTestingUtils.getTestResourcePath("keystore").toString(); @@ -133,11 +133,9 @@ public class SelectChannelServerSslTest extends HttpServerTestBase } @Override + @DisabledOnOs(WINDOWS) // Don't run on Windows (buggy JVM) public void testFullMethod() throws Exception { - // Don't run on Windows (buggy JVM) - Assume.assumeTrue(!OS.IS_WINDOWS); - try { super.testFullMethod(); @@ -158,10 +156,9 @@ public class SelectChannelServerSslTest extends HttpServerTestBase } @Override + @DisabledOnOs(WINDOWS) // Don't run on Windows (buggy JVM) public void testFullURI() throws Exception { - // Don't run on Windows (buggy JVM) - Assume.assumeTrue(!OS.IS_WINDOWS); try { super.testFullURI(); @@ -240,12 +237,12 @@ public class SelectChannelServerSslTest extends HttpServerTestBase @Override @Test - @Ignore("Override and ignore this test as SSLSocket.shutdownOutput() is not supported, " + + @Disabled("Override and ignore this test as SSLSocket.shutdownOutput() is not supported, " + "but shutdownOutput() is needed by the test.") public void testInterruptedRequest(){} @Override - @Ignore + @Disabled public void testAvailable() throws Exception { } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SlowClientsTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SlowClientsTest.java index d9e7e208f82..540eff7351e 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SlowClientsTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SlowClientsTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.server.ssl; +import static java.time.Duration.ofSeconds; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -44,15 +46,18 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Ignore +@Tag("Unstable") +@Disabled public class SlowClientsTest { private Logger logger = Log.getLogger(getClass()); - @Test(timeout = 10000) + @Test public void testSlowClientsWithSmallThreadPool() throws Exception { File keystore = MavenTestingUtils.getTestResourceFile("keystore"); @@ -66,6 +71,7 @@ public class SlowClientsTest QueuedThreadPool serverThreads = new QueuedThreadPool(maxThreads); serverThreads.setDetailedDump(true); Server server = new Server(serverThreads); + try { ServerConnector connector = new ServerConnector(server, 1, 1, sslContextFactory); @@ -87,48 +93,50 @@ public class SlowClientsTest SSLContext sslContext = sslContextFactory.getSslContext(); - CompletableFuture[] futures = new CompletableFuture[2 * maxThreads]; - ExecutorService executor = Executors.newFixedThreadPool(futures.length); - for (int i = 0; i < futures.length; i++) - { - int k = i; - futures[i] = CompletableFuture.runAsync(() -> + Assertions.assertTimeoutPreemptively(ofSeconds(10),()-> { + CompletableFuture[] futures = new CompletableFuture[2 * maxThreads]; + ExecutorService executor = Executors.newFixedThreadPool(futures.length); + for (int i = 0; i < futures.length; i++) { - try (SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket("localhost", connector.getLocalPort())) + int k = i; + futures[i] = CompletableFuture.runAsync(() -> { - socket.setSoTimeout(contentLength / 1024); - OutputStream output = socket.getOutputStream(); - String target = "/" + k; - String request = "GET " + target + " HTTP/1.1\r\n" + - "Host: localhost\r\n" + - "Connection: close\r\n" + - "\r\n"; - output.write(request.getBytes(StandardCharsets.UTF_8)); - output.flush(); - - while (serverThreads.getIdleThreads() > 0) - Thread.sleep(50); - - InputStream input = socket.getInputStream(); - while (true) + try (SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket("localhost", connector.getLocalPort())) { - int read = input.read(); - if (read < 0) - break; + socket.setSoTimeout(contentLength / 1024); + OutputStream output = socket.getOutputStream(); + String target = "/" + k; + String request = "GET " + target + " HTTP/1.1\r\n" + + "Host: localhost\r\n" + + "Connection: close\r\n" + + "\r\n"; + output.write(request.getBytes(StandardCharsets.UTF_8)); + output.flush(); + + while (serverThreads.getIdleThreads() > 0) + Thread.sleep(50); + + InputStream input = socket.getInputStream(); + while (true) + { + int read = input.read(); + if (read < 0) + break; + } + logger.info("FINISHED {}", target); } - logger.info("FINISHED {}", target); - } - catch (IOException x) - { - throw new UncheckedIOException(x); - } - catch (InterruptedException x) - { - throw new UncheckedIOException(new InterruptedIOException()); - } - }, executor); - } - CompletableFuture.allOf(futures).join(); + catch (IOException x) + { + throw new UncheckedIOException(x); + } + catch (InterruptedException x) + { + throw new UncheckedIOException(new InterruptedIOException()); + } + }, executor); + } + CompletableFuture.allOf(futures).join(); + }); } finally { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SniSslConnectionFactoryTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SniSslConnectionFactoryTest.java index 7492da30bfd..1957f23cf6b 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SniSslConnectionFactoryTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SniSslConnectionFactoryTest.java @@ -18,9 +18,11 @@ package org.eclipse.jetty.server.ssl; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileNotFoundException; @@ -41,7 +43,6 @@ import javax.net.ssl.SNIServerName; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -60,10 +61,9 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.Utf8StringBuilder; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SniSslConnectionFactoryTest { @@ -72,7 +72,7 @@ public class SniSslConnectionFactoryTest private HttpConfiguration _https_config; private int _port; - @Before + @BeforeEach public void before() throws Exception { String keystorePath = "src/test/resources/snikeystore"; @@ -115,7 +115,7 @@ public class SniSslConnectionFactoryTest _port = https.getLocalPort(); } - @After + @AfterEach public void after() throws Exception { if (_server != null) @@ -126,7 +126,7 @@ public class SniSslConnectionFactoryTest public void testConnect() throws Exception { String response = getResponse("127.0.0.1", null); - Assert.assertThat(response, Matchers.containsString("X-HOST: 127.0.0.1")); + assertThat(response, Matchers.containsString("X-HOST: 127.0.0.1")); } @Test @@ -151,47 +151,47 @@ public class SniSslConnectionFactoryTest // The first entry in the keystore is www.example.com, and it will // be returned by default, so make sure that here we don't ask for it. String response = getResponse("jetty.eclipse.org", "jetty.eclipse.org"); - Assert.assertThat(response, Matchers.containsString("X-HOST: jetty.eclipse.org")); + assertThat(response, Matchers.containsString("X-HOST: jetty.eclipse.org")); } @Test public void testSNIConnect() throws Exception { String response = getResponse("jetty.eclipse.org", "jetty.eclipse.org"); - Assert.assertThat(response, Matchers.containsString("X-HOST: jetty.eclipse.org")); + assertThat(response, Matchers.containsString("X-HOST: jetty.eclipse.org")); response = getResponse("www.example.com", "www.example.com"); - Assert.assertThat(response, Matchers.containsString("X-HOST: www.example.com")); + assertThat(response, Matchers.containsString("X-HOST: www.example.com")); response = getResponse("foo.domain.com", "*.domain.com"); - Assert.assertThat(response, Matchers.containsString("X-HOST: foo.domain.com")); + assertThat(response, Matchers.containsString("X-HOST: foo.domain.com")); response = getResponse("m.san.com", "san example"); - Assert.assertThat(response, Matchers.containsString("X-HOST: m.san.com")); + assertThat(response, Matchers.containsString("X-HOST: m.san.com")); response = getResponse("www.san.com", "san example"); - Assert.assertThat(response, Matchers.containsString("X-HOST: www.san.com")); + assertThat(response, Matchers.containsString("X-HOST: www.san.com")); } @Test public void testWildSNIConnect() throws Exception { String response = getResponse("domain.com", "www.domain.com", "*.domain.com"); - Assert.assertThat(response, Matchers.containsString("X-HOST: www.domain.com")); + assertThat(response, Matchers.containsString("X-HOST: www.domain.com")); response = getResponse("domain.com", "domain.com", "*.domain.com"); - Assert.assertThat(response, Matchers.containsString("X-HOST: domain.com")); + assertThat(response, Matchers.containsString("X-HOST: domain.com")); response = getResponse("www.domain.com", "www.domain.com", "*.domain.com"); - Assert.assertThat(response, Matchers.containsString("X-HOST: www.domain.com")); + assertThat(response, Matchers.containsString("X-HOST: www.domain.com")); } @Test public void testBadSNIConnect() throws Exception { String response = getResponse("www.example.com", "some.other.com", "www.example.com"); - Assert.assertThat(response, Matchers.containsString("HTTP/1.1 400 ")); - Assert.assertThat(response, Matchers.containsString("Host does not match SNI")); + assertThat(response, Matchers.containsString("HTTP/1.1 400 ")); + assertThat(response, Matchers.containsString("Host does not match SNI")); } @Test @@ -219,7 +219,7 @@ public class SniSslConnectionFactoryTest InputStream input = sslSocket.getInputStream(); String response = response(input); - Assert.assertTrue(response.startsWith("HTTP/1.1 200 ")); + assertTrue(response.startsWith("HTTP/1.1 200 ")); // Same socket, send a request for a different domain but same alias. request = "" + @@ -230,7 +230,7 @@ public class SniSslConnectionFactoryTest output.flush(); response = response(input); - Assert.assertTrue(response.startsWith("HTTP/1.1 200 ")); + assertTrue(response.startsWith("HTTP/1.1 200 ")); // Same socket, send a request for a different domain but different alias. request = "" + @@ -274,7 +274,7 @@ public class SniSslConnectionFactoryTest InputStream input = sslSocket.getInputStream(); String response = response(input); - Assert.assertTrue(response.startsWith("HTTP/1.1 200 ")); + assertTrue(response.startsWith("HTTP/1.1 200 ")); // Now, on the same socket, send a request for a different valid domain. request = "" + @@ -285,7 +285,7 @@ public class SniSslConnectionFactoryTest output.flush(); response = response(input); - Assert.assertTrue(response.startsWith("HTTP/1.1 200 ")); + assertTrue(response.startsWith("HTTP/1.1 200 ")); // Now make a request for an invalid domain for this connection. request = "" + @@ -296,8 +296,8 @@ public class SniSslConnectionFactoryTest output.flush(); response = response(input); - Assert.assertTrue(response.startsWith("HTTP/1.1 400 ")); - Assert.assertThat(response, Matchers.containsString("Host does not match SNI")); + assertTrue(response.startsWith("HTTP/1.1 400 ")); + assertThat(response, Matchers.containsString("Host does not match SNI")); } finally { @@ -312,7 +312,7 @@ public class SniSslConnectionFactoryTest while (true) { int read = input.read(); - Assert.assertTrue(read >= 0); + assertTrue(read >= 0); buffer.append((byte)read); crlfs = (read == '\r' || read == '\n') ? crlfs + 1 : 0; if (crlfs == 4) @@ -324,8 +324,8 @@ public class SniSslConnectionFactoryTest private String getResponse(String host, String cn) throws Exception { String response = getResponse(host, host, cn); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 ")); - Assert.assertThat(response, Matchers.containsString("X-URL: /ctx/path")); + assertThat(response, Matchers.startsWith("HTTP/1.1 200 ")); + assertThat(response, Matchers.containsString("X-URL: /ctx/path")); return response; } @@ -351,7 +351,7 @@ public class SniSslConnectionFactoryTest if (cn != null) { X509Certificate cert = ((X509Certificate)sslSocket.getSession().getPeerCertificates()[0]); - Assert.assertThat(cert.getSubjectX500Principal().getName("CANONICAL"), Matchers.startsWith("cn=" + cn)); + assertThat(cert.getSubjectX500Principal().getName("CANONICAL"), Matchers.startsWith("cn=" + cn)); } String response = "GET /ctx/path HTTP/1.0\r\nHost: " + reqHost + ":" + _port + "\r\n\r\n"; @@ -397,12 +397,12 @@ public class SniSslConnectionFactoryTest }); String response = getResponse("127.0.0.1", null); - Assert.assertThat(response, Matchers.containsString("X-HOST: 127.0.0.1")); + assertThat(response, Matchers.containsString("X-HOST: 127.0.0.1")); - Assert.assertEquals("customize connector class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); - Assert.assertEquals("customize ssl class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); - Assert.assertEquals("customize connector class org.eclipse.jetty.server.HttpConnection,true", history.poll()); - Assert.assertEquals("customize http class org.eclipse.jetty.server.HttpConnection,true", history.poll()); - Assert.assertEquals(0, history.size()); + assertEquals("customize connector class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); + assertEquals("customize ssl class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); + assertEquals("customize connector class org.eclipse.jetty.server.HttpConnection,true", history.poll()); + assertEquals("customize http class org.eclipse.jetty.server.HttpConnection,true", history.poll()); + assertEquals(0, history.size()); } } diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslConnectionFactoryTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslConnectionFactoryTest.java index 0493af67479..71335ce544d 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslConnectionFactoryTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslConnectionFactoryTest.java @@ -18,6 +18,11 @@ package org.eclipse.jetty.server.ssl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -53,10 +58,10 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SslConnectionFactoryTest { @@ -64,7 +69,7 @@ public class SslConnectionFactoryTest private ServerConnector _connector; private int _port; - @Before + @BeforeEach public void before() throws Exception { String keystorePath = "src/test/resources/keystore"; @@ -110,7 +115,7 @@ public class SslConnectionFactoryTest _port = https.getLocalPort(); } - @After + @AfterEach public void after() throws Exception { _server.stop(); @@ -121,14 +126,14 @@ public class SslConnectionFactoryTest public void testConnect() throws Exception { String response = getResponse("127.0.0.1", null); - Assert.assertThat(response, Matchers.containsString("host=127.0.0.1")); + assertThat(response, Matchers.containsString("host=127.0.0.1")); } @Test public void testSNIConnect() throws Exception { String response = getResponse("localhost", "localhost", "jetty.eclipse.org"); - Assert.assertThat(response, Matchers.containsString("host=localhost")); + assertThat(response, Matchers.containsString("host=localhost")); } @Test @@ -141,7 +146,7 @@ public class SslConnectionFactoryTest socket.setSoTimeout(1000); // Expect TLS message type == 21: Alert - Assert.assertThat(socket.getInputStream().read(), Matchers.equalTo(21)); + assertThat(socket.getInputStream().read(), Matchers.equalTo(21)); } } @@ -178,28 +183,28 @@ public class SslConnectionFactoryTest }); String response = getResponse("127.0.0.1", null); - Assert.assertThat(response, Matchers.containsString("host=127.0.0.1")); + assertThat(response, Matchers.containsString("host=127.0.0.1")); - Assert.assertEquals("customize connector class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); - Assert.assertEquals("customize ssl class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); - Assert.assertEquals("customize connector class org.eclipse.jetty.server.HttpConnection,true", history.poll()); - Assert.assertEquals("customize http class org.eclipse.jetty.server.HttpConnection,true", history.poll()); - Assert.assertEquals(0, history.size()); + assertEquals("customize connector class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); + assertEquals("customize ssl class org.eclipse.jetty.io.ssl.SslConnection,false", history.poll()); + assertEquals("customize connector class org.eclipse.jetty.server.HttpConnection,true", history.poll()); + assertEquals("customize http class org.eclipse.jetty.server.HttpConnection,true", history.poll()); + assertEquals(0, history.size()); } - @Test(expected = IllegalStateException.class) + @Test public void testServerWithoutHttpConnectionFactory() throws Exception { _server.stop(); - Assert.assertNotNull(_connector.removeConnectionFactory(HttpVersion.HTTP_1_1.asString())); - _server.start(); + assertNotNull(_connector.removeConnectionFactory(HttpVersion.HTTP_1_1.asString())); + assertThrows(IllegalStateException.class, ()-> _server.start()); } private String getResponse(String host, String cn) throws Exception { String response = getResponse(host, host, cn); - Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); - Assert.assertThat(response, Matchers.containsString("url=/ctx/path")); + assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK")); + assertThat(response, Matchers.containsString("url=/ctx/path")); return response; } @@ -226,7 +231,7 @@ public class SslConnectionFactoryTest if (cn != null) { X509Certificate cert = ((X509Certificate)sslSocket.getSession().getPeerCertificates()[0]); - Assert.assertThat(cert.getSubjectX500Principal().getName("CANONICAL"), Matchers.startsWith("cn=" + cn)); + assertThat(cert.getSubjectX500Principal().getName("CANONICAL"), Matchers.startsWith("cn=" + cn)); } sslSocket.getOutputStream().write(("GET /ctx/path HTTP/1.0\r\nHost: " + reqHost + ":" + _port + "\r\n\r\n").getBytes(StandardCharsets.ISO_8859_1)); diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslContextFactoryReloadTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslContextFactoryReloadTest.java index d85b043314c..674f13495b7 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslContextFactoryReloadTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslContextFactoryReloadTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.server.ssl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -51,9 +55,9 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.eclipse.jetty.util.thread.Scheduler; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; + +import org.junit.jupiter.api.Test; public class SslContextFactoryReloadTest { @@ -86,7 +90,7 @@ public class SslContextFactoryReloadTest server.start(); } - @After + @AfterEach public void dispose() throws Exception { if (server != null) @@ -104,7 +108,7 @@ public class SslContextFactoryReloadTest try (SSLSocket client1 = (SSLSocket)socketFactory.createSocket("localhost", connector.getLocalPort())) { String serverDN1 = client1.getSession().getPeerPrincipal().getName(); - Assert.assertThat(serverDN1, Matchers.startsWith("CN=localhost1")); + assertThat(serverDN1, Matchers.startsWith("CN=localhost1")); String request = "" + "GET / HTTP/1.1\r\n" + @@ -116,8 +120,8 @@ public class SslContextFactoryReloadTest output1.flush(); HttpTester.Response response1 = HttpTester.parseResponse(HttpTester.from(client1.getInputStream())); - Assert.assertNotNull(response1); - Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); + assertNotNull(response1); + assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); // Reconfigure SslContextFactory. sslContextFactory.reload(sslContextFactory -> @@ -130,15 +134,15 @@ public class SslContextFactoryReloadTest try (SSLSocket client2 = (SSLSocket)socketFactory.createSocket("localhost", connector.getLocalPort())) { String serverDN2 = client2.getSession().getPeerPrincipal().getName(); - Assert.assertThat(serverDN2, Matchers.startsWith("CN=localhost2")); + assertThat(serverDN2, Matchers.startsWith("CN=localhost2")); OutputStream output2 = client1.getOutputStream(); output2.write(request.getBytes(StandardCharsets.UTF_8)); output2.flush(); HttpTester.Response response2 = HttpTester.parseResponse(HttpTester.from(client1.getInputStream())); - Assert.assertNotNull(response2); - Assert.assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); + assertNotNull(response2); + assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); } // Must still be possible to make requests with the first connection. @@ -146,8 +150,8 @@ public class SslContextFactoryReloadTest output1.flush(); response1 = HttpTester.parseResponse(HttpTester.from(client1.getInputStream())); - Assert.assertNotNull(response1); - Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); + assertNotNull(response1); + assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); } } @@ -225,8 +229,8 @@ public class SslContextFactoryReloadTest InputStream inputStream = client.getInputStream(); HttpTester.Response response1 = HttpTester.parseResponse(HttpTester.from(inputStream)); - Assert.assertNotNull(response1); - Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); + assertNotNull(response1); + assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); String request2 = "" + "GET / HTTP/1.1\r\n" + @@ -237,12 +241,12 @@ public class SslContextFactoryReloadTest outputStream.flush(); HttpTester.Response response2 = HttpTester.parseResponse(HttpTester.from(inputStream)); - Assert.assertNotNull(response2); - Assert.assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); + assertNotNull(response2); + assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200)); } } - Assert.assertEquals(0, reloads.get()); + assertEquals(0, reloads.get()); } finally { diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java index 7ac9806dd11..9f7e7b10541 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslSelectChannelTimeoutTest.java @@ -29,7 +29,7 @@ import javax.net.ssl.TrustManagerFactory; import org.eclipse.jetty.server.ConnectorTimeoutTest; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; public class SslSelectChannelTimeoutTest extends ConnectorTimeoutTest { @@ -41,7 +41,7 @@ public class SslSelectChannelTimeoutTest extends ConnectorTimeoutTest return __sslContext.getSocketFactory().createSocket(host,port); } - @Before + @BeforeEach public void init() throws Exception { String keystorePath = System.getProperty("basedir",".") + "/src/test/resources/keystore"; diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java index df344785ac2..d3015f55164 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ssl/SslUploadTest.java @@ -18,8 +18,8 @@ package org.eclipse.jetty.server.ssl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileInputStream; @@ -44,10 +44,10 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** */ @@ -57,7 +57,7 @@ public class SslUploadTest private static ServerConnector connector; private static int total; - @BeforeClass + @BeforeAll public static void startServer() throws Exception { File keystore = MavenTestingUtils.getTestResourceFile("keystore"); @@ -78,7 +78,7 @@ public class SslUploadTest server.start(); } - @AfterClass + @AfterAll public static void stopServer() throws Exception { server.stop(); @@ -86,7 +86,7 @@ public class SslUploadTest } @Test - @Ignore + @Disabled public void test() throws Exception { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextDispatchWithQueryStrings.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextDispatchWithQueryStrings.java index 1894ea01d00..20b0d3be7e3 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextDispatchWithQueryStrings.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextDispatchWithQueryStrings.java @@ -18,9 +18,9 @@ package org.eclipse.jetty.servlet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -36,9 +36,9 @@ import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * This tests verifies that merging of queryStrings works when dispatching @@ -50,7 +50,7 @@ public class AsyncContextDispatchWithQueryStrings private ServletContextHandler _contextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); private LocalConnector _connector = new LocalConnector(_server); - @Before + @BeforeEach public void setUp() throws Exception { _connector.setIdleTimeout(30000); @@ -80,7 +80,7 @@ public class AsyncContextDispatchWithQueryStrings assertThat(responseString,startsWith("HTTP/1.1 200")); } - @After + @AfterEach public void tearDown() throws Exception { _server.stop(); diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextListenersTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextListenersTest.java index f21d39e6ef3..e2b3056991d 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextListenersTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextListenersTest.java @@ -18,6 +18,8 @@ package org.eclipse.jetty.servlet; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.io.OutputStream; import java.net.Socket; @@ -37,9 +39,8 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class AsyncContextListenersTest { @@ -58,7 +59,7 @@ public class AsyncContextListenersTest _server.start(); } - @After + @AfterEach public void dispose() throws Exception { _server.stop(); @@ -116,7 +117,7 @@ public class AsyncContextListenersTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.Response response = HttpTester.parseResponse(input); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); completes.get().await(10,TimeUnit.SECONDS); // Send a second request @@ -125,7 +126,7 @@ public class AsyncContextListenersTest output.flush(); response = HttpTester.parseResponse(input); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); completes.get().await(10,TimeUnit.SECONDS); } } @@ -187,7 +188,7 @@ public class AsyncContextListenersTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.Response response = HttpTester.parseResponse(input); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); completes.get().await(10,TimeUnit.SECONDS); // Send a second request @@ -196,7 +197,7 @@ public class AsyncContextListenersTest output.flush(); response = HttpTester.parseResponse(input); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); completes.get().await(10,TimeUnit.SECONDS); } } @@ -264,7 +265,7 @@ public class AsyncContextListenersTest HttpTester.Input input = HttpTester.from(socket.getInputStream()); HttpTester.Response response = HttpTester.parseResponse(input); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); completes.get().await(10,TimeUnit.SECONDS); // Send a second request @@ -273,7 +274,7 @@ public class AsyncContextListenersTest output.flush(); response = HttpTester.parseResponse(input); - Assert.assertEquals(200, response.getStatus()); + assertEquals(200, response.getStatus()); completes.get().await(10,TimeUnit.SECONDS); } } diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextTest.java index 0bb47f7571e..8d440e80d2a 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncContextTest.java @@ -19,9 +19,9 @@ package org.eclipse.jetty.servlet; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -49,10 +49,9 @@ import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.log.StacklessLogging; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * This tests the correct functioning of the AsyncContext @@ -65,7 +64,7 @@ public class AsyncContextTest private ServletContextHandler _contextHandler; private LocalConnector _connector; - @Before + @BeforeEach public void setUp() throws Exception { _server = new Server(); @@ -107,7 +106,7 @@ public class AsyncContextTest _server.start(); } - @After + @AfterEach public void after() throws Exception { _server.stop(); @@ -503,7 +502,7 @@ public class AsyncContextTest } } - @After + @AfterEach public void tearDown() throws Exception { _server.stop(); diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncListenerTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncListenerTest.java index 31c71760070..fd40ad7dbf7 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncListenerTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncListenerTest.java @@ -18,6 +18,10 @@ package org.eclipse.jetty.servlet; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import java.io.Writer; import java.util.concurrent.TimeUnit; @@ -38,12 +42,8 @@ import org.eclipse.jetty.server.QuietServletException; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ErrorHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class AsyncListenerTest { @@ -61,7 +61,7 @@ public class AsyncListenerTest server.start(); } - @After + @AfterEach public void dispose() throws Exception { if (server != null) @@ -444,7 +444,7 @@ public class AsyncListenerTest "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n")); - Assert.assertEquals(HttpStatus.OK_200, response.getStatus()); + assertEquals(HttpStatus.OK_200, response.getStatus()); } // Unique named RuntimeException to help during debugging / assertions. diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncServletIOTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncServletIOTest.java index 301d3b9d7b2..d0d080f7a57 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncServletIOTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/AsyncServletIOTest.java @@ -19,14 +19,15 @@ package org.eclipse.jetty.servlet; import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.IOException; @@ -42,7 +43,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; import java.util.function.UnaryOperator; import javax.servlet.AsyncContext; @@ -68,10 +68,9 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; // TODO need these on HTTP2 as well! public class AsyncServletIOTest @@ -88,7 +87,7 @@ public class AsyncServletIOTest protected ServletHandler _servletHandler; protected ServerConnector _connector; - @Before + @BeforeEach public void setUp() throws Exception { _wQTP = new WrappingQTP(); @@ -134,7 +133,7 @@ public class AsyncServletIOTest _read.set(0); } - @After + @AfterEach public void tearDown() throws Exception { _server.stop(); @@ -174,7 +173,7 @@ public class AsyncServletIOTest public void testBigWrites() throws Exception { process(102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400,102400); - Assert.assertThat("On Write Possible",_owp.get(),greaterThanOrEqualTo(1)); + assertThat("On Write Possible",_owp.get(),greaterThanOrEqualTo(1)); } @Test @@ -217,7 +216,7 @@ public class AsyncServletIOTest // response line String line = in.readLine(); LOG.debug("response-line: "+line); - Assert.assertThat(line,startsWith("HTTP/1.1 200 OK")); + assertThat(line,startsWith("HTTP/1.1 200 OK")); // Skip headers while (line!=null) @@ -239,8 +238,8 @@ public class AsyncServletIOTest } } - Assert.assertEquals(list.get(0),"data"); - Assert.assertTrue(_servlet2.completed.await(5, TimeUnit.SECONDS)); + assertEquals(list.get(0),"data"); + assertTrue(_servlet2.completed.await(5, TimeUnit.SECONDS)); } @Test @@ -266,7 +265,7 @@ public class AsyncServletIOTest // response line String line = in.readLine(); LOG.debug("response-line: "+line); - Assert.assertThat(line,startsWith("HTTP/1.1 200 OK")); + assertThat(line,startsWith("HTTP/1.1 200 OK")); // Skip headers while (line!=null) @@ -280,11 +279,11 @@ public class AsyncServletIOTest // Get body line = in.readLine(); LOG.debug("body: "+line); - Assert.assertEquals("DONE",line); + assertEquals("DONE",line); // The connection should be aborted line = in.readLine(); - Assert.assertNull(line); + assertNull(line); } } @@ -345,7 +344,7 @@ public class AsyncServletIOTest // response line String line = in.readLine(); LOG.debug("response-line: "+line); - Assert.assertThat(line,startsWith("HTTP/1.1 200 OK")); + assertThat(line,startsWith("HTTP/1.1 200 OK")); // Skip headers while (line!=null) @@ -375,8 +374,8 @@ public class AsyncServletIOTest LOG.debug("line: "+brief(line)); if ("-".equals(line)) continue; - assertEquals("Line Length",writes[w],line.length()); - assertEquals("Line Contents",line.charAt(0),'0'+(w%10)); + assertEquals(writes[w], line.length(), "Line Length"); + assertEquals(line.charAt(0), '0'+(w%10), "Line Contents"); w++; if (w", response); + assertThat(body, containsString("/one/;JSESSIONID=1234567890")); + assertThat(body, containsString("/two/;JSESSIONID=1234567890")); + assertThat(body, containsString("/three/;JSESSIONID=1234567890")); + + assertThat(body, not(containsString(" HTTP/1.0\n"); - req1.append("\n"); + String req1 = "GET /context/; HTTP/1.0\r\n" + + "\r\n"; + String rawResponse = connector.getResponse(req1); + HttpTester.Response response = HttpTester.parseResponse(rawResponse); - String response = connector.getResponse(req1.toString()); + String body = response.getContent(); + assertThat(body, not(containsString("