From 40f41ad8487a2e54b50744a3135b7594c32de29f Mon Sep 17 00:00:00 2001 From: xuwei-k <6b656e6a69@gmail.com> Date: Sat, 8 Apr 2023 10:09:16 +0900 Subject: [PATCH] migrate to scalatest --- .github/workflows/build-test.yml | 2 +- .../ws/ahc/AhcCurlRequestLoggerSpec.scala | 78 +++--- .../ws/ahc/StandaloneWSClientSupport.scala | 5 +- .../test/scala/play/NettyServerProvider.scala | 22 +- .../ws/ahc/AhcCurlRequestLoggerSpec.scala | 76 ++--- .../api/libs/ws/ahc/AhcWSClientSpec.scala | 70 +++-- .../libs/ws/ahc/AhcWSRequestFilterSpec.scala | 43 ++- .../api/libs/ws/ahc/JsonRequestSpec.scala | 19 +- .../ws/ahc/StandaloneWSClientSupport.scala | 5 +- .../play/api/libs/ws/ahc/XMLRequestSpec.scala | 24 +- .../api/libs/ws/ahc/cache/CachingSpec.scala | 16 +- .../play/libs/ws/ahc/AhcWSClientSpec.scala | 25 +- .../libs/ws/ahc/AhcWSRequestFilterSpec.scala | 60 ++-- .../scala/play/api/libs/oauth/OAuthSpec.scala | 6 +- .../libs/ws/ahc/AhcConfigBuilderSpec.scala | 64 ++--- .../ws/ahc/AhcWSClientConfigParserSpec.scala | 42 +-- .../api/libs/ws/ahc/AhcWSRequestSpec.scala | 262 ++++++++++-------- .../api/libs/ws/ahc/AhcWSResponseSpec.scala | 157 +++++------ .../libs/ws/ahc/cache/AhcWSCacheSpec.scala | 22 +- .../cache/BackgroundAsyncHandlerSpec.scala | 4 +- .../ws/ahc/cache/CacheAsyncHandlerSpec.scala | 4 +- .../ws/ahc/cache/CacheableResponseSpec.scala | 18 +- .../play/libs/ws/ahc/AhcWSRequestSpec.scala | 226 +++++++-------- .../play/libs/ws/ahc/AhcWSResponseSpec.scala | 18 +- .../api/libs/ws/JsonBodyReadablesSpec.scala | 19 +- .../play/api/libs/ws/WSConfigParserSpec.scala | 16 +- project/Dependencies.scala | 7 +- 27 files changed, 657 insertions(+), 653 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index e213624c..1963acc4 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -39,7 +39,7 @@ jobs: with: java: 17, 11 scala: 2.13.x, 3.x - cmd: sbt ++$MATRIX_SCALA 'testOnly -- xonly timefactor 5' + cmd: sbt ++$MATRIX_SCALA test finish: name: Finish diff --git a/integration-tests/src/test/java/play/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala b/integration-tests/src/test/java/play/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala index 413be5f5..dbb8efcb 100644 --- a/integration-tests/src/test/java/play/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala +++ b/integration-tests/src/test/java/play/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala @@ -4,9 +4,8 @@ package play.libs.ws.ahc -import org.specs2.concurrent.ExecutionEnv -import org.specs2.concurrent.FutureAwait -import org.specs2.mutable.Specification +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.mvc.Results @@ -22,11 +21,11 @@ import scala.jdk.CollectionConverters._ import scala.jdk.FutureConverters._ import play.api.routing.sird._ -class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) - extends Specification +class AhcCurlRequestLoggerSpec + extends AnyWordSpec with NettyServerProvider with StandaloneWSClientSupport - with FutureAwait + with ScalaFutures with DefaultBodyWritables { override def routes(components: BuiltInComponents) = { @@ -56,9 +55,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch("--verbose") + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).exists(_.contains("--verbose"))) } "add all headers" in withClient() { client => @@ -71,11 +70,11 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) + .futureValue val messages = testLogger.getLoggingEvents.asScala.map(_.getMessage) - messages must containMatch("--header 'My-Header: My-Header-Value'") + assert(messages.exists(_.contains("--header 'My-Header: My-Header-Value'"))) } "add all cookies" in withClient() { client => @@ -88,11 +87,11 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) + .futureValue val messages = testLogger.getLoggingEvents.asScala.map(_.getMessage) - messages must containMatch("""--cookie 'cookie1=value1'""") + assert(messages.exists(_.contains("""--cookie 'cookie1=value1'"""))) } "add method" in withClient() { client => @@ -104,9 +103,11 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch("--request GET") + assert( + testLogger.getLoggingEvents.asScala.map(_.getMessage).exists(_.contains("--request GET")) + ) } "add authorization header" in withClient() { client => @@ -119,14 +120,20 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) - - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch( - """--header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='""" + .futureValue + + assert( + testLogger.getLoggingEvents.asScala + .map(_.getMessage) + .exists( + _.contains( + """--header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='""" + ) + ) ) } - "handle body" in { + "handle body" should { "add when in memory" in withClient() { client => val testLogger = createTestLogger @@ -138,9 +145,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch("the-body") + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).exists(_.contains("the-body"))) } "do nothing for empty bodies" in withClient() { client => @@ -153,9 +160,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must not containMatch "--data" + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).forall(!_.contains("--data"))) } } @@ -171,18 +178,19 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(curlRequestLogger) .get() .asScala - .awaitFor(defaultTimeout) - - testLogger.getLoggingEvents.get(0).getMessage must beEqualTo( - s""" - |curl \\ - | --verbose \\ - | --request GET \\ - | --header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \\ - | --header 'content-type: text/plain' \\ - | --header 'My-Header: My-Header-Value' \\ - | --data 'the-body' \\ - | 'http://localhost:$testServerPort/' + .futureValue + + assert( + testLogger.getLoggingEvents.get(0).getMessage == + s""" + |curl \\ + | --verbose \\ + | --request GET \\ + | --header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \\ + | --header 'content-type: text/plain' \\ + | --header 'My-Header: My-Header-Value' \\ + | --data 'the-body' \\ + | 'http://localhost:$testServerPort/' """.stripMargin.trim ) } diff --git a/integration-tests/src/test/java/play/libs/ws/ahc/StandaloneWSClientSupport.scala b/integration-tests/src/test/java/play/libs/ws/ahc/StandaloneWSClientSupport.scala index 933625f2..e68ab919 100644 --- a/integration-tests/src/test/java/play/libs/ws/ahc/StandaloneWSClientSupport.scala +++ b/integration-tests/src/test/java/play/libs/ws/ahc/StandaloneWSClientSupport.scala @@ -5,7 +5,6 @@ package play.libs.ws.ahc import akka.stream.Materializer -import org.specs2.execute.Result import play.api.libs.ws.ahc.AhcConfigBuilder import play.api.libs.ws.ahc.AhcWSClientConfig import play.api.libs.ws.ahc.{ AhcWSClientConfigFactory => ScalaAhcWSClientConfigFactory } @@ -15,9 +14,9 @@ trait StandaloneWSClientSupport { def materializer: Materializer - def withClient( + def withClient[A]( config: AhcWSClientConfig = ScalaAhcWSClientConfigFactory.forConfig() - )(block: StandaloneAhcWSClient => Result): Result = { + )(block: StandaloneAhcWSClient => A): A = { val asyncHttpClient = new DefaultAsyncHttpClient(new AhcConfigBuilder(config).build()) val client = new StandaloneAhcWSClient(asyncHttpClient, materializer) try { diff --git a/integration-tests/src/test/scala/play/NettyServerProvider.scala b/integration-tests/src/test/scala/play/NettyServerProvider.scala index f2116efd..45cd9ece 100644 --- a/integration-tests/src/test/scala/play/NettyServerProvider.scala +++ b/integration-tests/src/test/scala/play/NettyServerProvider.scala @@ -5,13 +5,17 @@ package play import akka.actor.ActorSystem -import org.specs2.concurrent.ExecutionEnv -import org.specs2.specification.BeforeAfterAll import scala.concurrent.duration._ import scala.concurrent.Await +import scala.concurrent.ExecutionContext import akka.stream.Materializer +import org.scalatest.BeforeAndAfterAll +import org.scalatest.Suite +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.time.Millis +import org.scalatest.time.Span import play.api.mvc.Handler import play.api.mvc.RequestHeader import play.core.server.NettyServer @@ -19,17 +23,17 @@ import play.core.server.ServerConfig import play.api.BuiltInComponents import play.api.Mode -trait NettyServerProvider extends BeforeAfterAll { +trait NettyServerProvider extends BeforeAndAfterAll with ScalaFutures { self: Suite => + + final implicit override def patienceConfig: PatienceConfig = + PatienceConfig(Span(3000, Millis)) /** * @return Routes to be used by the test. */ def routes(components: BuiltInComponents): PartialFunction[RequestHeader, Handler] - /** - * The execution context environment. - */ - def executionEnv: ExecutionEnv + protected implicit def executionContext: ExecutionContext = ExecutionContext.global lazy val testServerPort: Int = server.httpPort.getOrElse(sys.error("undefined port number")) val defaultTimeout: FiniteDuration = 5.seconds @@ -47,7 +51,9 @@ trait NettyServerProvider extends BeforeAfterAll { ) )(components => routes(components)) - override def beforeAll(): Unit = {} + override def beforeAll(): Unit = { + super.beforeAll() + } override def afterAll(): Unit = { server.stop() diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala index 33130432..3b185be6 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcCurlRequestLoggerSpec.scala @@ -4,9 +4,8 @@ package play.api.libs.ws.ahc -import org.specs2.concurrent.ExecutionEnv -import org.specs2.concurrent.FutureAwait -import org.specs2.mutable.Specification +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.libs.ws.DefaultBodyWritables @@ -23,11 +22,11 @@ import play.api.routing.sird._ import scala.jdk.CollectionConverters._ -class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) - extends Specification +class AhcCurlRequestLoggerSpec + extends AnyWordSpec with NettyServerProvider with StandaloneWSClientSupport - with FutureAwait + with ScalaFutures with DefaultBodyWritables { override def routes(components: BuiltInComponents): PartialFunction[RequestHeader, Handler] = { @@ -57,9 +56,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .url(s"http://localhost:$testServerPort/") .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch("--verbose") + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).exists(_.contains("--verbose"))) } "add all headers" in withClient() { client => @@ -71,11 +70,11 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .addHttpHeaders("My-Header" -> "My-Header-Value") .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) + .futureValue val messages = testLogger.getLoggingEvents.asScala.map(_.getMessage) - messages must containMatch("--header 'My-Header: My-Header-Value'") + assert(messages.exists(_.contains("--header 'My-Header: My-Header-Value'"))) } "add all cookies" in withClient() { client => @@ -87,11 +86,11 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .addCookies(DefaultWSCookie("cookie1", "value1")) .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) + .futureValue val messages = testLogger.getLoggingEvents.asScala.map(_.getMessage) - messages must containMatch("--cookie 'cookie1=value1'") + assert(messages.exists(_.contains("--cookie 'cookie1=value1'"))) } "add method" in withClient() { client => @@ -102,9 +101,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .url(s"http://localhost:$testServerPort/") .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch("--request GET") + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).exists(_.contains("--request GET"))) } "add authorization header" in withClient() { client => @@ -116,14 +115,20 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .withAuth("username", "password", WSAuthScheme.BASIC) .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) - - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch( - """--header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='""" + .futureValue + + assert( + testLogger.getLoggingEvents.asScala + .map(_.getMessage) + .exists( + _.contains( + """--header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='""" + ) + ) ) } - "handle body" in { + "handle body" should { "add when in memory" in withClient() { client => val testLogger = createTestLogger @@ -134,9 +139,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .withBody("the-body") .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must containMatch("the-body") + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).exists(_.contains("the-body"))) } "do nothing for empty bodies" in withClient() { client => @@ -148,9 +153,9 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .withBody(EmptyBody) .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) + .futureValue - testLogger.getLoggingEvents.asScala.map(_.getMessage) must not containMatch "--data" + assert(testLogger.getLoggingEvents.asScala.map(_.getMessage).forall(!_.contains("--data"))) } } @@ -165,18 +170,19 @@ class AhcCurlRequestLoggerSpec(implicit val executionEnv: ExecutionEnv) .withAuth("username", "password", WSAuthScheme.BASIC) .withRequestFilter(curlRequestLogger) .get() - .awaitFor(defaultTimeout) - - testLogger.getLoggingEvents.get(0).getMessage must beEqualTo( - s""" - |curl \\ - | --verbose \\ - | --request GET \\ - | --header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \\ - | --header 'My-Header: My-Header-Value' \\ - | --header 'Content-Type: text/plain' \\ - | --data 'the-body' \\ - | 'http://localhost:$testServerPort/' + .futureValue + + assert( + testLogger.getLoggingEvents.get(0).getMessage == + s""" + |curl \\ + | --verbose \\ + | --request GET \\ + | --header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \\ + | --header 'My-Header: My-Header-Value' \\ + | --header 'Content-Type: text/plain' \\ + | --data 'the-body' \\ + | 'http://localhost:$testServerPort/' """.stripMargin.trim ) } diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSClientSpec.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSClientSpec.scala index 8b40f04f..2e93f3fe 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSClientSpec.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSClientSpec.scala @@ -6,11 +6,8 @@ package play.api.libs.ws.ahc import akka.stream.scaladsl.Sink import akka.util.ByteString -import org.specs2.concurrent.ExecutionEnv -import org.specs2.concurrent.FutureAwait -import org.specs2.execute.Result -import org.specs2.matcher.FutureMatchers -import org.specs2.mutable.Specification +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.http.Status.MOVED_PERMANENTLY @@ -24,18 +21,17 @@ import play.shaded.ahc.org.asynchttpclient.handler.MaxRedirectException import scala.concurrent._ -class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) - extends Specification +class AhcWSClientSpec + extends AnyWordSpec with NettyServerProvider with StandaloneWSClientSupport - with FutureMatchers - with FutureAwait + with ScalaFutures with DefaultBodyReadables with DefaultBodyWritables { - def withClientFollowingRedirect( + def withClientFollowingRedirect[A]( config: AhcWSClientConfig = AhcWSClientConfigFactory.forConfig() - )(block: StandaloneAhcWSClient => Result): Result = { + )(block: StandaloneAhcWSClient => A): A = { withClient( config.copy( wsClientConfig = config.wsClientConfig.copy(followRedirects = true) @@ -106,13 +102,15 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) "url" should { "throw an exception on invalid url" in { withClient() { client => - { client.url("localhost") } must throwAn[IllegalArgumentException] + assertThrows[IllegalArgumentException] { + client.url("localhost") + } } } "not throw exception on valid url" in { withClient() { client => - { client.url(s"http://localhost:$testServerPort") } must not(throwAn[IllegalArgumentException]) + client.url(s"http://localhost:$testServerPort") } } } @@ -125,7 +123,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/index").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -143,7 +141,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/index").get().map(res => res.body[Foo]), defaultTimeout ) - result must beEqualTo(Foo("Say hello to play")) + assert(result == Foo("Say hello to play")) } } @@ -154,22 +152,22 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) defaultTimeout ) val bytes: ByteString = Await.result(resultSource.runWith(Sink.head), defaultTimeout) - bytes.utf8String must beEqualTo("Say hello to play") + assert(bytes.utf8String == "Say hello to play") } } - "when following redirect" in { + "when following redirect" should { "honor the number of redirects allowed" in { // 1. Default number of max redirects is 5 withClientFollowingRedirect() { client => - { + assertThrows[MaxRedirectException] { val request = client // 2. Ask to redirect 10 times .url(s"http://localhost:$testServerPort/redirects/302/10") .get() Await.result(request, defaultTimeout) - } must throwA[MaxRedirectException] + } } } @@ -179,7 +177,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/redirect/302").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -188,7 +186,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) val ahcWsConfig = AhcWSClientConfigFactory.forConfig().copy(wsClientConfig = wsConfig) withClient(config = ahcWsConfig) { client => val result = Await.result(client.url(s"http://localhost:$testServerPort/redirect/302").get(), defaultTimeout) - result.status must beEqualTo(302) + assert(result.status == 302) } } @@ -201,7 +199,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) .withFollowRedirects(false) .get() val result = Await.result(request, defaultTimeout) - result.status must beEqualTo(302) + assert(result.status == 302) } } @@ -211,7 +209,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/redirect/301").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -221,7 +219,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/redirect/302").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -231,7 +229,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/redirect/303").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -241,7 +239,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/redirect/307").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -251,7 +249,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/redirect/308").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -262,7 +260,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) .withVirtualHost("localhost1") .get() val result = Await.result(request, defaultTimeout) - result.header("Req-Host") must beSome("localhost1") + assert(result.header("Req-Host") == Some("localhost1")) } } @@ -273,7 +271,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) .addHttpHeaders("X-Test" -> "Test") .get() val result = Await.result(request, defaultTimeout) - result.header("Req-X-Test") must beSome("Test") + assert(result.header("Req-X-Test") == Some("Test")) } } @@ -284,7 +282,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) .withAuth("test", "test", WSAuthScheme.BASIC) .get() val result = Await.result(request, defaultTimeout) - result.header("Req-Authorization") must beSome + assert(result.header("Req-Authorization").isDefined) } } @@ -294,7 +292,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/cookie").get().map(res => res.body[String]), defaultTimeout ) - result must beEqualTo(s"Cookie value => redirect-cookie") + assert(result == s"Cookie value => redirect-cookie") } } @@ -311,11 +309,11 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) client.url(s"http://localhost:$testServerPort/cookie-destination").get().map(res => res.body[String]), defaultTimeout ) - res2 must beEqualTo(s"Request is missing required cookie 'flash'") + assert(res2 == s"Request is missing required cookie 'flash'") } } - "switch to get " in { + "switch to get " should { "for HTTP 301 Moved Permanently" in { withClientFollowingRedirect() { client => val request = client @@ -328,7 +326,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) // 2. So when following the redirect, the GET path should be found // and we get its body - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -338,7 +336,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) .url(s"http://localhost:$testServerPort/redirect/303") .post("request body") val result = Await.result(request.map(res => res.body[String]), defaultTimeout) - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } @@ -354,7 +352,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) // 2. So when following the redirect, the GET path should be found // and we get its body - result must beEqualTo("Say hello to play") + assert(result == "Say hello to play") } } } diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestFilterSpec.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestFilterSpec.scala index d1fd61ca..2db9ef64 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestFilterSpec.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestFilterSpec.scala @@ -4,9 +4,8 @@ package play.api.libs.ws.ahc -import org.specs2.concurrent.ExecutionEnv -import org.specs2.matcher.FutureMatchers -import org.specs2.mutable.Specification +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.libs.ws._ @@ -14,11 +13,11 @@ import play.api.mvc.Results import scala.collection.mutable -class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) - extends Specification +class AhcWSRequestFilterSpec + extends AnyWordSpec with NettyServerProvider with StandaloneWSClientSupport - with FutureMatchers + with ScalaFutures with DefaultBodyReadables { override def routes(components: BuiltInComponents) = { case _ => @@ -67,9 +66,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) }) .get() .map { response => - response.body[String] must contain("some string") + assert(response.body[String].contains("some string")) } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "stream with adhoc request filter" in withClient() { client => @@ -81,9 +80,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withMethod("GET") .stream() .map { response => - response.body[String] must contain("some string") + assert(response.body[String].contains("some string")) } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "work with one request filter" in withClient() { client => @@ -93,9 +92,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withRequestFilter(new CallbackRequestFilter(callList, 1)) .get() .map { _ => - callList must contain(1) + assert(callList.contains(1)) } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "stream with one request filter" in withClient() { client => @@ -106,9 +105,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withMethod("GET") .stream() .map { _ => - callList must contain(1) + assert(callList.contains(1)) } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "work with three request filter" in withClient() { client => @@ -120,9 +119,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withRequestFilter(new CallbackRequestFilter(callList, 3)) .get() .map { _ => - callList must containTheSameElementsAs(Seq(1, 2, 3)) + assert(callList.toSet == Set(1, 2, 3)) } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "stream with three request filters" in withClient() { client => @@ -135,9 +134,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withMethod("GET") .stream() .map { _ => - callList must containTheSameElementsAs(Seq(1, 2, 3)) + assert(callList.toSet == Set(1, 2, 3)) } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "should allow filters to modify the request" in withClient() { client => @@ -148,9 +147,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withRequestFilter(new HeaderAppendingFilter(appendedHeader, appendedHeaderValue)) .get() .map { response => - response.headers("X-Request-Id").head must be_==("someid") + assert(response.headers("X-Request-Id").head == "someid") } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } "allow filters to modify the streaming request" in withClient() { client => @@ -162,9 +161,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .withMethod("GET") .stream() .map { response => - response.headers("X-Request-Id").head must be_==("someid") + assert(response.headers("X-Request-Id").head == "someid") } - .await(retries = 0, timeout = defaultTimeout) + .futureValue } } } diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/JsonRequestSpec.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/JsonRequestSpec.scala index 9b246aa1..27d822eb 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/JsonRequestSpec.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/JsonRequestSpec.scala @@ -14,8 +14,8 @@ import org.mockito.Mockito.verify import org.mockito.Mockito.when import org.mockito.Mockito -import org.specs2.mutable.Specification -import org.specs2.specification.AfterAll +import org.scalatest.BeforeAndAfterAll +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.json.JsString import play.api.libs.json.JsValue import play.api.libs.json.Json @@ -29,8 +29,7 @@ import scala.reflect.ClassTag /** */ -class JsonRequestSpec extends Specification with AfterAll with JsonBodyWritables { - sequential +class JsonRequestSpec extends AnyWordSpec with BeforeAndAfterAll with JsonBodyWritables { private def mock[A](implicit a: ClassTag[A]): A = Mockito.mock(a.runtimeClass).asInstanceOf[A] @@ -50,8 +49,8 @@ class JsonRequestSpec extends Specification with AfterAll with JsonBodyWritables .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get("Content-Type") must be_==("application/json") - ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""") + assert(req.getHeaders.get("Content-Type") == "application/json") + assert(ByteString.fromArray(req.getByteData).utf8String == """{"k1":"v1"}""") } "set a json node using the default object mapper" in { @@ -65,8 +64,8 @@ class JsonRequestSpec extends Specification with AfterAll with JsonBodyWritables .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get("Content-Type") must be_==("application/json") - ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""") + assert(req.getHeaders.get("Content-Type") == "application/json") + assert(ByteString.fromArray(req.getByteData).utf8String == """{"k1":"v1"}""") } "read an encoding of UTF-8" in { @@ -81,7 +80,7 @@ class JsonRequestSpec extends Specification with AfterAll with JsonBodyWritables val value: JsValue = JsonBodyReadables.readableAsJson.transform(response) verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.UTF_8) verify(ahcResponse, times(1)).getContentType - value.toString must beEqualTo(json) + assert(value.toString == json) } "read an encoding of ISO-8859-1" in { @@ -96,6 +95,6 @@ class JsonRequestSpec extends Specification with AfterAll with JsonBodyWritables val value: JsValue = JsonBodyReadables.readableAsJson.transform(response) verify(ahcResponse, times(1)).getResponseBody(StandardCharsets.ISO_8859_1) verify(ahcResponse, times(1)).getContentType - value.toString must beEqualTo(json) + assert(value.toString == json) } } diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/StandaloneWSClientSupport.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/StandaloneWSClientSupport.scala index 41cc268b..5fffcbae 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/StandaloneWSClientSupport.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/StandaloneWSClientSupport.scala @@ -5,15 +5,14 @@ package play.api.libs.ws.ahc import akka.stream.Materializer -import org.specs2.execute.Result trait StandaloneWSClientSupport { def materializer: Materializer - def withClient( + def withClient[A]( config: AhcWSClientConfig = AhcWSClientConfigFactory.forConfig() - )(block: StandaloneAhcWSClient => Result): Result = { + )(block: StandaloneAhcWSClient => A): A = { val client = StandaloneAhcWSClient(config)(materializer) try { block(client) diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/XMLRequestSpec.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/XMLRequestSpec.scala index aec0b266..dd0241f2 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/XMLRequestSpec.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/XMLRequestSpec.scala @@ -9,17 +9,15 @@ import java.nio.charset.StandardCharsets import akka.actor.ActorSystem import akka.stream.Materializer import akka.util.ByteString -import org.specs2.matcher.MustMatchers -import org.specs2.mutable.Specification -import org.specs2.specification.AfterAll +import org.scalatest.BeforeAndAfterAll +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.ws._ import scala.xml.Elem /** */ -class XMLRequestSpec extends Specification with AfterAll with MustMatchers { - sequential +class XMLRequestSpec extends AnyWordSpec with BeforeAndAfterAll { implicit val system: ActorSystem = ActorSystem() implicit val materializer: Materializer = Materializer.matFromSystem @@ -59,8 +57,8 @@ class XMLRequestSpec extends Specification with AfterAll with MustMatchers { .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get("Content-Type") must be_==("text/xml; charset=UTF-8") - ByteString.fromArray(req.getByteData).utf8String must be_==("") + assert(req.getHeaders.get("Content-Type") == "text/xml; charset=UTF-8") + assert(ByteString.fromArray(req.getByteData).utf8String == "") } "read an XML node in Utf-8" in { @@ -76,9 +74,9 @@ class XMLRequestSpec extends Specification with AfterAll with MustMatchers { val readables = new XMLBodyReadables() {} /* UTF-8 */ val value: Elem = readables.readableAsXml.transform(new StubResponse(test.getBytes(StandardCharsets.UTF_8))) - (value \\ "note" \ "to").text must be_==("Tove") - (value \\ "note" \ "from").text must be_==("Jani") - (value \\ "note" \ "heading").text must be_==("Reminder") + assert((value \\ "note" \ "to").text == "Tove") + assert((value \\ "note" \ "from").text == "Jani") + assert((value \\ "note" \ "heading").text == "Reminder") } "read an XML node in Utf-16" in { @@ -94,8 +92,8 @@ class XMLRequestSpec extends Specification with AfterAll with MustMatchers { val readables = new XMLBodyReadables() {} /* UTF-16 */ val value: Elem = readables.readableAsXml.transform(new StubResponse(test.getBytes(StandardCharsets.UTF_16))) - (value \\ "note" \ "to").text must be_==("Tove") - (value \\ "note" \ "from").text must be_==("Jani") - (value \\ "note" \ "heading").text must be_==("Reminder") + assert((value \\ "note" \ "to").text == "Tove") + assert((value \\ "note" \ "from").text == "Jani") + assert((value \\ "note" \ "heading").text == "Reminder") } } diff --git a/integration-tests/src/test/scala/play/api/libs/ws/ahc/cache/CachingSpec.scala b/integration-tests/src/test/scala/play/api/libs/ws/ahc/cache/CachingSpec.scala index 361cea81..be384129 100644 --- a/integration-tests/src/test/scala/play/api/libs/ws/ahc/cache/CachingSpec.scala +++ b/integration-tests/src/test/scala/play/api/libs/ws/ahc/cache/CachingSpec.scala @@ -7,10 +7,7 @@ package play.api.libs.ws.ahc.cache import org.mockito.ArgumentMatchers.any import org.mockito.Mockito import org.mockito.Mockito.when -import org.specs2.concurrent.ExecutionEnv -import org.specs2.matcher.FutureMatchers -import org.specs2.mutable.Specification -import org.specs2.specification.AfterAll +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.libs.ws.ahc._ @@ -24,11 +21,7 @@ import play.shaded.ahc.org.asynchttpclient._ import scala.concurrent.Future import scala.reflect.ClassTag -class CachingSpec(implicit val executionEnv: ExecutionEnv) - extends Specification - with NettyServerProvider - with AfterAll - with FutureMatchers { +class CachingSpec extends AnyWordSpec with NettyServerProvider { private def mock[A](implicit a: ClassTag[A]): A = Mockito.mock(a.runtimeClass).asInstanceOf[A] @@ -64,12 +57,11 @@ class CachingSpec(implicit val executionEnv: ExecutionEnv) ws.url(s"http://localhost:$testServerPort/hello") .get() .map { response => - response.body[String] must be_==("

Say hello to play

") + assert(response.body[String] == "

Say hello to play

") } - .await + .futureValue Mockito.verify(cache).get(EffectiveURIKey("GET", new java.net.URI(s"http://localhost:$testServerPort/hello"))) - success } } } diff --git a/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSClientSpec.scala b/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSClientSpec.scala index bcb908ac..1b34919a 100644 --- a/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSClientSpec.scala +++ b/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSClientSpec.scala @@ -6,9 +6,8 @@ package play.libs.ws.ahc import akka.stream.javadsl.Sink import akka.util.ByteString -import org.specs2.concurrent.ExecutionEnv -import org.specs2.matcher.FutureMatchers -import org.specs2.mutable.Specification +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.mvc.AnyContentAsText @@ -19,13 +18,12 @@ import play.libs.ws._ import scala.jdk.FutureConverters._ import scala.concurrent.Future -import scala.concurrent.duration._ -class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) - extends Specification +class AhcWSClientSpec + extends AnyWordSpec with NettyServerProvider with StandaloneWSClientSupport - with FutureMatchers + with ScalaFutures with XMLBodyWritables with XMLBodyReadables { @@ -59,8 +57,8 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) .url(s"http://localhost:$testServerPort") .post(someOtherMethod("hello world")) .asScala - .map(response => response.getBody() must be_==("hello world")) - .await(retries = 0, timeout = 5.seconds) + .map(response => assert(response.getBody() == "hello world")) + .futureValue } "source successfully" in withClient() { client => @@ -69,7 +67,7 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) response.getBodyAsSource.runWith(Sink.head[ByteString](), materializer).asScala } val expected: ByteString = ByteString.fromString("

Say hello to play

") - result must be_==(expected).await(retries = 0, timeout = 5.seconds) + assert(result.futureValue == expected) } "round trip XML successfully" in withClient() { client => @@ -96,11 +94,10 @@ class AhcWSClientSpec(implicit val executionEnv: ExecutionEnv) val responseXml = response.getBody(xml()) responseXml.normalizeDocument() - (responseXml.isEqualNode(document) must beTrue).and { - response.getUri must beEqualTo(new java.net.URI(s"http://localhost:$testServerPort")) - } + assert(responseXml.isEqualNode(document)) + assert(response.getUri == new java.net.URI(s"http://localhost:$testServerPort")) } - .await(retries = 0, timeout = 5.seconds) + .futureValue } } } diff --git a/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSRequestFilterSpec.scala b/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSRequestFilterSpec.scala index 33212913..67facfe8 100644 --- a/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSRequestFilterSpec.scala +++ b/integration-tests/src/test/scala/play/libs/ws/ahc/AhcWSRequestFilterSpec.scala @@ -4,21 +4,19 @@ package play.libs.ws.ahc -import org.specs2.concurrent.ExecutionEnv -import org.specs2.matcher.FutureMatchers -import org.specs2.mutable.Specification +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.wordspec.AnyWordSpec import play.NettyServerProvider import play.api.BuiltInComponents import play.api.mvc.Results -import scala.concurrent.duration._ import scala.jdk.FutureConverters._ -class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) - extends Specification +class AhcWSRequestFilterSpec + extends AnyWordSpec with NettyServerProvider with StandaloneWSClientSupport - with FutureMatchers { + with ScalaFutures { override def routes(components: BuiltInComponents) = { case _ => components.defaultActionBuilder { req => @@ -43,11 +41,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(new CallbackRequestFilter(callList, 1)) .get() .asScala - responseFuture - .map { _ => - callList.asScala must contain(1) - } - .await(retries = 0, timeout = 5.seconds) + responseFuture.map { _ => + assert(callList.asScala.map(_.intValue()).contains(1)) + }.futureValue } "stream with one request filter" in withClient() { client => @@ -59,11 +55,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(new CallbackRequestFilter(callList, 1)) .stream() .asScala - responseFuture - .map { _ => - callList.asScala must contain(1) - } - .await(retries = 0, timeout = 5.seconds) + responseFuture.map { _ => + assert(callList.asScala.map(_.intValue()).contains(1)) + }.futureValue } "work with three request filter" in withClient() { client => @@ -77,11 +71,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(new CallbackRequestFilter(callList, 3)) .get() .asScala - responseFuture - .map { _ => - callList.asScala must containTheSameElementsAs(Seq(1, 2, 3)) - } - .await(retries = 0, timeout = 5.seconds) + responseFuture.map { _ => + assert(callList.asScala.toSet == Set(1, 2, 3)) + }.futureValue } "stream with three request filters" in withClient() { client => @@ -95,11 +87,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .setRequestFilter(new CallbackRequestFilter(callList, 3)) .stream() .asScala - responseFuture - .map { _ => - callList.asScala must containTheSameElementsAs(Seq(1, 2, 3)) - } - .await(retries = 0, timeout = 5.seconds) + responseFuture.map { _ => + assert(callList.asScala.toSet == Set(1, 2, 3)) + }.futureValue } "should allow filters to modify the request" in withClient() { client => @@ -112,11 +102,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .get() .asScala - responseFuture - .map { response => - response.getHeaders.get("X-Request-Id").get(0) must be_==("someid") - } - .await(retries = 0, timeout = 5.seconds) + responseFuture.map { response => + assert(response.getHeaders.get("X-Request-Id").get(0) == "someid") + }.futureValue } "allow filters to modify the streaming request" in withClient() { client => @@ -129,11 +117,9 @@ class AhcWSRequestFilterSpec(implicit val executionEnv: ExecutionEnv) .stream() .asScala - responseFuture - .map { response => - response.getHeaders.get("X-Request-Id").get(0) must be_==("someid") - } - .await(retries = 0, timeout = 5.seconds) + responseFuture.map { response => + assert(response.getHeaders.get("X-Request-Id").get(0) == "someid") + }.futureValue } } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/oauth/OAuthSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/oauth/OAuthSpec.scala index cbe5f748..615f7c50 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/oauth/OAuthSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/oauth/OAuthSpec.scala @@ -4,12 +4,12 @@ package play.api.libs.oauth -import org.specs2.mutable.Specification +import org.scalatest.wordspec.AnyWordSpec -class OAuthSpec extends Specification { +class OAuthSpec extends AnyWordSpec { "OAuth" should { "be able to use signpost OAuth" in { - Class.forName("play.shaded.oauth.oauth.signpost.OAuth") must not(throwA[ClassNotFoundException]) + Class.forName("play.shaded.oauth.oauth.signpost.OAuth") } } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcConfigBuilderSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcConfigBuilderSpec.scala index c597fcdb..ae6e9d3d 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcConfigBuilderSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcConfigBuilderSpec.scala @@ -9,7 +9,7 @@ import com.typesafe.config.ConfigFactory import com.typesafe.sslconfig.ssl.Protocols import com.typesafe.sslconfig.ssl.SSLConfigFactory import com.typesafe.sslconfig.ssl.SSLConfigSettings -import org.specs2.mutable.Specification +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.ws.WSClientConfig import play.shaded.ahc.org.asynchttpclient.proxy.ProxyServerSelector import play.shaded.ahc.org.asynchttpclient.util.ProxyUtils @@ -18,7 +18,7 @@ import scala.concurrent.duration._ /** */ -class AhcConfigBuilderSpec extends Specification { +class AhcConfigBuilderSpec extends AnyWordSpec { val defaultWsConfig = WSClientConfig() val defaultConfig = AhcWSClientConfig(defaultWsConfig) @@ -35,11 +35,11 @@ class AhcConfigBuilderSpec extends Specification { builder.setFollowRedirect(false) } .build() - ahcConfig.isCompressionEnforced must beFalse - ahcConfig.isFollowRedirect must beFalse - ahcConfig.getConnectTimeout must_== 120000 - ahcConfig.getRequestTimeout must_== 120000 - ahcConfig.getReadTimeout must_== 120000 + assert(ahcConfig.isCompressionEnforced == false) + assert(ahcConfig.isFollowRedirect == false) + assert(ahcConfig.getConnectTimeout == 120000) + assert(ahcConfig.getRequestTimeout == 120000) + assert(ahcConfig.getReadTimeout == 120000) } "with basic options" should { @@ -49,13 +49,13 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getReadTimeout must_== defaultWsConfig.idleTimeout.toMillis - actual.getRequestTimeout must_== defaultWsConfig.requestTimeout.toMillis - actual.getConnectTimeout must_== defaultWsConfig.connectionTimeout.toMillis - actual.isFollowRedirect must_== defaultWsConfig.followRedirects - actual.getCookieStore must_== null + assert(actual.getReadTimeout == defaultWsConfig.idleTimeout.toMillis) + assert(actual.getRequestTimeout == defaultWsConfig.requestTimeout.toMillis) + assert(actual.getConnectTimeout == defaultWsConfig.connectionTimeout.toMillis) + assert(actual.isFollowRedirect == defaultWsConfig.followRedirects) + assert(actual.getCookieStore == null) - actual.getEnabledProtocols.toSeq must not contain Protocols.deprecatedProtocols + assert(actual.getEnabledProtocols.toSeq.forall(x => !Protocols.deprecatedProtocols.contains(x))) } "use an explicit idle timeout" in { @@ -64,7 +64,7 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getReadTimeout must_== 42L + assert(actual.getReadTimeout == 42L) } "use an explicit request timeout" in { @@ -73,7 +73,7 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getRequestTimeout must_== 47L + assert(actual.getRequestTimeout == 47L) } "use an explicit connection timeout" in { @@ -82,7 +82,7 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getConnectTimeout must_== 99L + assert(actual.getConnectTimeout == 99L) } "use an explicit followRedirects option" in { @@ -91,7 +91,7 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.isFollowRedirect must_== true + assert(actual.isFollowRedirect == true) } "use an explicit proxy if useProxyProperties is true and there are system defined proxy settings" in { @@ -106,9 +106,9 @@ class AhcConfigBuilderSpec extends Specification { val proxyServerSelector = actual.getProxyServerSelector - proxyServerSelector must not(beNull) + assert(proxyServerSelector != null) - (proxyServerSelector must not).be_==(ProxyServerSelector.NO_PROXY_SELECTOR) + assert(proxyServerSelector != ProxyServerSelector.NO_PROXY_SELECTOR) } finally { // Unset http.proxyHost System.clearProperty(ProxyUtils.PROXY_HOST) @@ -122,42 +122,42 @@ class AhcConfigBuilderSpec extends Specification { val config = defaultConfig.copy(keepAlive = false) val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.isKeepAlive must_== false + assert(actual.isKeepAlive == false) } "allow setting ahc maximumConnectionsPerHost" in { val config = defaultConfig.copy(maxConnectionsPerHost = 3) val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getMaxConnectionsPerHost must_== 3 + assert(actual.getMaxConnectionsPerHost == 3) } "allow setting ahc maximumConnectionsTotal" in { val config = defaultConfig.copy(maxConnectionsTotal = 6) val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getMaxConnections must_== 6 + assert(actual.getMaxConnections == 6) } "allow setting ahc maxNumberOfRedirects" in { val config = defaultConfig.copy(maxNumberOfRedirects = 0) val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getMaxRedirects must_== 0 + assert(actual.getMaxRedirects == 0) } "allow setting ahc maxRequestRetry" in { val config = defaultConfig.copy(maxRequestRetry = 99) val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.getMaxRequestRetry must_== 99 + assert(actual.getMaxRequestRetry == 99) } "allow setting ahc disableUrlEncoding" in { val config = defaultConfig.copy(disableUrlEncoding = true) val builder = new AhcConfigBuilder(config) val actual = builder.build() - actual.isDisableUrlEncodingForBoundRequests must_== true + assert(actual.isDisableUrlEncodingForBoundRequests == true) } } @@ -177,12 +177,12 @@ class AhcConfigBuilderSpec extends Specification { val config = defaultConfig.copy(wsClientConfig = wsConfig) val builder = new AhcConfigBuilder(config) - sslConfig.protocol must_== "TLSv1.2" + assert(sslConfig.protocol == "TLSv1.2") val asyncClientConfig = builder.build() // ...and return a result so specs2 is happy. - asyncClientConfig.getSslEngineFactory must not(beNull) + assert(asyncClientConfig.getSslEngineFactory != null) } "should validate certificates" in { @@ -192,7 +192,7 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val asyncConfig = builder.build() - asyncConfig.isUseInsecureTrustManager must beFalse + assert(asyncConfig.isUseInsecureTrustManager == false) } "should disable the hostname verifier if loose.acceptAnyCertificate is enabled" in { @@ -203,7 +203,7 @@ class AhcConfigBuilderSpec extends Specification { val builder = new AhcConfigBuilder(config) val asyncConfig = builder.build() - asyncConfig.isUseInsecureTrustManager must beTrue + assert(asyncConfig.isUseInsecureTrustManager) } } @@ -218,7 +218,7 @@ class AhcConfigBuilderSpec extends Specification { val actual = builder.configureProtocols(existingProtocols, sslConfig) - actual.toSeq must containTheSameElementsAs(Protocols.recommendedProtocols.toIndexedSeq) + assert(actual.toSet == Protocols.recommendedProtocols.toSet) } "provide explicit protocols if specified" in { @@ -231,7 +231,7 @@ class AhcConfigBuilderSpec extends Specification { val actual = builder.configureProtocols(existingProtocols, sslConfig) - actual.toSeq must containTheSameElementsAs(Seq("derp", "baz", "quux")) + assert(actual.toSet == Set("derp", "baz", "quux")) } } @@ -247,7 +247,7 @@ class AhcConfigBuilderSpec extends Specification { val actual = builder.configureCipherSuites(existingCiphers, sslConfig) - actual.toSeq must containTheSameElementsAs(Seq("goodone", "goodtwo")) + assert(actual.toSet == Set("goodone", "goodtwo")) } } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSClientConfigParserSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSClientConfigParserSpec.scala index e5f27948..d104962c 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSClientConfigParserSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSClientConfigParserSpec.scala @@ -5,12 +5,12 @@ package play.api.libs.ws.ahc import com.typesafe.config.ConfigFactory -import org.specs2.mutable._ +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.ws.WSClientConfig import scala.concurrent.duration._ -class AhcWSClientConfigParserSpec extends Specification { +class AhcWSClientConfigParserSpec extends AnyWordSpec { val defaultWsConfig = WSClientConfig() val defaultConfig = AhcWSClientConfig(defaultWsConfig) @@ -30,15 +30,15 @@ class AhcWSClientConfigParserSpec extends Specification { // since we use typesafe ssl-config we can't match the objects directly since they aren't case classes, // and also AhcWSClientConfig has a duration which will be parsed into nanocseconds while the case class uses minutes - s1.wsClientConfig.toString must_== s2.wsClientConfig.toString - s1.maxConnectionsPerHost must_== s2.maxConnectionsPerHost - s1.maxConnectionsTotal must_== s2.maxConnectionsTotal - s1.maxConnectionLifetime must_== s2.maxConnectionLifetime - s1.idleConnectionInPoolTimeout must_== s2.idleConnectionInPoolTimeout - s1.maxNumberOfRedirects must_== s2.maxNumberOfRedirects - s1.maxRequestRetry must_== s2.maxRequestRetry - s1.disableUrlEncoding must_== s2.disableUrlEncoding - s1.keepAlive must_== s2.keepAlive + assert(s1.wsClientConfig.toString == s2.wsClientConfig.toString) + assert(s1.maxConnectionsPerHost == s2.maxConnectionsPerHost) + assert(s1.maxConnectionsTotal == s2.maxConnectionsTotal) + assert(s1.maxConnectionLifetime == s2.maxConnectionLifetime) + assert(s1.idleConnectionInPoolTimeout == s2.idleConnectionInPoolTimeout) + assert(s1.maxNumberOfRedirects == s2.maxNumberOfRedirects) + assert(s1.maxRequestRetry == s2.maxRequestRetry) + assert(s1.disableUrlEncoding == s2.disableUrlEncoding) + assert(s1.keepAlive == s2.keepAlive) } "parse ws ahc section" in { @@ -54,22 +54,22 @@ class AhcWSClientConfigParserSpec extends Specification { |play.ws.ahc.keepAlive = false """.stripMargin) - actual.maxConnectionsPerHost must_== 3 - actual.maxConnectionsTotal must_== 6 - actual.maxConnectionLifetime must_== 1.minute - actual.idleConnectionInPoolTimeout must_== 30.seconds - actual.connectionPoolCleanerPeriod must_== 10.seconds - actual.maxNumberOfRedirects must_== 0 - actual.maxRequestRetry must_== 99 - actual.disableUrlEncoding must beTrue - actual.keepAlive must beFalse + assert(actual.maxConnectionsPerHost == 3) + assert(actual.maxConnectionsTotal == 6) + assert(actual.maxConnectionLifetime == 1.minute) + assert(actual.idleConnectionInPoolTimeout == 30.seconds) + assert(actual.connectionPoolCleanerPeriod == 10.seconds) + assert(actual.maxNumberOfRedirects == 0) + assert(actual.maxRequestRetry == 99) + assert(actual.disableUrlEncoding) + assert(actual.keepAlive == false) } "with keepAlive" should { "parse keepAlive default as true" in { val actual = parseThis("""""".stripMargin) - actual.keepAlive must beTrue + assert(actual.keepAlive) } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestSpec.scala index 45e4ebc4..23bd3b4b 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSRequestSpec.scala @@ -12,9 +12,9 @@ import akka.stream.Materializer import akka.util.ByteString import org.mockito.Mockito -import org.specs2.execute.Result -import org.specs2.mutable.Specification -import org.specs2.specification.AfterAll +import org.scalatest.BeforeAndAfterAll +import org.scalatest.OptionValues +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.oauth.ConsumerKey import play.api.libs.oauth.RequestToken @@ -28,9 +28,12 @@ import play.shaded.ahc.org.asynchttpclient.{ Request => AHCRequest } import scala.reflect.ClassTag -class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReadables with DefaultBodyWritables { - - sequential +class AhcWSRequestSpec + extends AnyWordSpec + with BeforeAndAfterAll + with DefaultBodyReadables + with DefaultBodyWritables + with OptionValues { private def mock[A](implicit a: ClassTag[A]): A = Mockito.mock(a.runtimeClass).asInstanceOf[A] @@ -44,11 +47,11 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada system.terminate() } - def withClient(block: StandaloneWSClient => Result): Result = { + def withClient[A](block: StandaloneWSClient => A): A = { block(wsClient) } - "Given the full URL" in { + "Given the full URL" should { implicit val materializer: Materializer = mock[akka.stream.Materializer] val client = mock[StandaloneAhcWSClient] @@ -56,46 +59,56 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada "request withQueryStringParameters" in { val request = StandaloneAhcWSRequest(client, "http://example.com") - request.uri.toString must equalTo("http://example.com") - request.withQueryStringParameters("bar" -> "baz").uri.toString must equalTo("http://example.com?bar=baz") - request.withQueryStringParameters("bar" -> "baz", "bar" -> "bah").uri.toString must equalTo( - "http://example.com?bar=bah&bar=baz" + assert(request.uri.toString == "http://example.com") + assert(request.withQueryStringParameters("bar" -> "baz").uri.toString == "http://example.com?bar=baz") + assert( + request + .withQueryStringParameters("bar" -> "baz", "bar" -> "bah") + .uri + .toString == "http://example.com?bar=bah&bar=baz" ) } "correctly URL-encode the query string part" in { val request = StandaloneAhcWSRequest(client, "http://example.com") - request.withQueryStringParameters("&" -> "=").uri.toString must equalTo("http://example.com?%26=%3D") + assert(request.withQueryStringParameters("&" -> "=").uri.toString == "http://example.com?%26=%3D") } "set all query string parameters" in { val request = StandaloneAhcWSRequest(client, "http://example.com") - request.withQueryStringParameters("bar" -> "baz").uri.toString must equalTo("http://example.com?bar=baz") - request.withQueryStringParameters("bar" -> "baz", "bar" -> "bah").uri.toString must equalTo( - "http://example.com?bar=bah&bar=baz" + assert(request.withQueryStringParameters("bar" -> "baz").uri.toString == "http://example.com?bar=baz") + assert( + request + .withQueryStringParameters("bar" -> "baz", "bar" -> "bah") + .uri + .toString == "http://example.com?bar=bah&bar=baz" ) } "discard old query parameters when setting new ones" in { val request = StandaloneAhcWSRequest(client, "http://example.com") - request - .withQueryStringParameters("bar" -> "baz") - .withQueryStringParameters("bar" -> "bah") - .uri - .toString must equalTo("http://example.com?bar=bah") + assert( + request + .withQueryStringParameters("bar" -> "baz") + .withQueryStringParameters("bar" -> "bah") + .uri + .toString == "http://example.com?bar=bah" + ) } "add query string param" in { val request = StandaloneAhcWSRequest(client, "http://example.com") - request - .withQueryStringParameters("bar" -> "baz") - .addQueryStringParameters("bar" -> "bah") - .uri - .toString must equalTo("http://example.com?bar=bah&bar=baz") + assert( + request + .withQueryStringParameters("bar" -> "baz") + .addQueryStringParameters("bar" -> "bah") + .uri + .toString == "http://example.com?bar=bah&bar=baz" + ) } "support adding several query string values for a parameter" in { @@ -104,9 +117,10 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withQueryStringParameters("play" -> "foo1") .addQueryStringParameters("play" -> "foo2") - newRequest.queryString.get("play") must beSome[Seq[String]].which(_.contains("foo1")) - newRequest.queryString.get("play") must beSome[Seq[String]].which(_.contains("foo2")) - newRequest.queryString.get("play") must beSome[Seq[String]].which(_.size == 2) + val actual = newRequest.queryString.get("play").value + assert(actual.contains("foo1")) + assert(actual.contains("foo2")) + assert(actual.size == 2) } "support several query string values for a parameter" in { @@ -118,16 +132,16 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .buildRequest() val paramsList: Seq[Param] = req.getQueryParams.asScala.toSeq - paramsList.exists(p => (p.getName == "foo") && (p.getValue == "foo1")) must beTrue - paramsList.exists(p => (p.getName == "foo") && (p.getValue == "foo2")) must beTrue - paramsList.count(p => p.getName == "foo") must beEqualTo(2) + assert(paramsList.exists(p => (p.getName == "foo") && (p.getValue == "foo1"))) + assert(paramsList.exists(p => (p.getName == "foo") && (p.getValue == "foo2"))) + assert(paramsList.count(p => p.getName == "foo") == 2) } } } - "For Cookies" in { + "For Cookies" should { def cookie(name: String, value: String): WSCookie = DefaultWSCookie(name, value) @@ -139,9 +153,9 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getCookies.asScala must size(1) - req.getCookies.asScala.head.name must beEqualTo("cookie1") - req.getCookies.asScala.head.value must beEqualTo("value1") + assert(req.getCookies.asScala.size == 1) + assert(req.getCookies.asScala.head.name == "cookie1") + assert(req.getCookies.asScala.head.value == "value1") } } @@ -153,12 +167,12 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getCookies.asScala must size(2) - req.getCookies.asScala.head.name must beEqualTo("cookie1") - req.getCookies.asScala.head.value must beEqualTo("value1") + assert(req.getCookies.asScala.size == 2) + assert(req.getCookies.asScala.head.name == "cookie1") + assert(req.getCookies.asScala.head.value == "value1") - req.getCookies.asScala(1).name must beEqualTo("cookie2") - req.getCookies.asScala(1).value must beEqualTo("value2") + assert(req.getCookies.asScala(1).name == "cookie2") + assert(req.getCookies.asScala(1).value == "value2") } } @@ -171,12 +185,12 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getCookies.asScala must size(2) - req.getCookies.asScala.head.name must beEqualTo("cookie1") - req.getCookies.asScala.head.value must beEqualTo("value1") + assert(req.getCookies.asScala.size == 2) + assert(req.getCookies.asScala.head.name == "cookie1") + assert(req.getCookies.asScala.head.value == "value1") - req.getCookies.asScala(1).name must beEqualTo("cookie2") - req.getCookies.asScala(1).value must beEqualTo("value2") + assert(req.getCookies.asScala(1).name == "cookie2") + assert(req.getCookies.asScala(1).value == "value2") } } @@ -189,12 +203,12 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getCookies.asScala must size(2) - req.getCookies.asScala.head.name must beEqualTo("cookie3") - req.getCookies.asScala.head.value must beEqualTo("value3") + assert(req.getCookies.asScala.size == 2) + assert(req.getCookies.asScala.head.name == "cookie3") + assert(req.getCookies.asScala.head.value == "value3") - req.getCookies.asScala(1).name must beEqualTo("cookie4") - req.getCookies.asScala(1).value must beEqualTo("value4") + assert(req.getCookies.asScala(1).name == "cookie4") + assert(req.getCookies.asScala(1).value == "value4") } } @@ -207,13 +221,13 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.entries.asScala must size(1) - req.getHeaders.get("Cookie") must beEqualTo("cookie1=value1, cookie2=value2") + assert(req.getHeaders.entries.asScala.size == 1) + assert(req.getHeaders.get("Cookie") == "cookie1=value1, cookie2=value2") } } } - "For HTTP Headers" in { + "For HTTP Headers" should { "support setting headers" in { withClient { client => @@ -222,7 +236,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withHttpHeaders("key" -> "value1", "key" -> "value2") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.getAll("key").asScala must containTheSameElementsAs(Seq("value1", "value2")) + assert(req.getHeaders.getAll("key").asScala.toSet == Set("value1", "value2")) } } @@ -234,8 +248,8 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withHttpHeaders("key2" -> "value2") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get("key1") must beNull - req.getHeaders.get("key2") must beEqualTo("value2") + assert(req.getHeaders.get("key1") == null) + assert(req.getHeaders.get("key2") == "value2") } } @@ -247,7 +261,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .addHttpHeaders("key" -> "value2") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.getAll("key").asScala must containTheSameElementsAs(Seq("value1", "value2")) + assert(req.getHeaders.getAll("key").asScala.toSet == Set("value1", "value2")) } } @@ -259,8 +273,8 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .addHttpHeaders("key2" -> "value2") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get("key1") must beEqualTo("value1") - req.getHeaders.get("key2") must beEqualTo("value2") + assert(req.getHeaders.get("key1") == "value1") + assert(req.getHeaders.get("key2") == "value2") } } @@ -274,8 +288,10 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withBody("I am a text/plain body") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.getAll(HttpHeaderNames.CONTENT_TYPE.toString()).asScala must_== Seq( - "fake/contenttype; charset=utf-8" + assert( + req.getHeaders.getAll(HttpHeaderNames.CONTENT_TYPE.toString()).asScala == Seq( + "fake/contenttype; charset=utf-8" + ) ) } } @@ -287,7 +303,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withHttpHeaders("key" -> "value1", "KEY" -> "value2") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.getAll("key").asScala must containTheSameElementsAs(Seq("value1", "value2")) + assert(req.getHeaders.getAll("key").asScala.toSet == Set("value1", "value2")) } } @@ -297,7 +313,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .url("http://playframework.com/") .withHttpHeaders("Key1" -> "value1", "Key2" -> "value2") - req.header("Key1") must beSome("value1") + assert(req.header("Key1") == Some("value1")) } } @@ -307,7 +323,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .url("http://playframework.com/") .withHttpHeaders("Key1" -> "value1", "Key1" -> "value2", "Key2" -> "some") - req.headerValues("Key1") must containTheSameElementsAs(Seq("value1", "value2")) + assert(req.headerValues("Key1").toSet == Set("value1", "value2")) } } @@ -317,7 +333,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .url("http://playframework.com/") .withHttpHeaders("Key1" -> "value1", "Key1" -> "value2", "Key2" -> "some") - req.header("Non") must beNone + assert(req.header("Non").isEmpty) } } @@ -327,7 +343,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .url("http://playframework.com/") .withHttpHeaders("Key1" -> "value1", "Key1" -> "value2", "Key2" -> "some") - req.headerValues("Non") must beEmpty + assert(req.headerValues("Non").isEmpty) } } @@ -337,13 +353,13 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .url("http://playframework.com/") .withHttpHeaders("Key1" -> "value1", "Key1" -> "value2", "Key2" -> "value") - req.headers("Key1") must containTheSameElementsAs(Seq("value1", "value2")) - req.headers("Key2") must containTheSameElementsAs(Seq("value")) + assert(req.headers("Key1").toSet == Set("value1", "value2")) + assert(req.headers("Key2").toSet == Set("value")) } } } - "For requests with body" in { + "For requests with body" should { "Have form params for content type application/x-www-form-urlencoded" in { withClient { client => @@ -352,7 +368,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withBody(Map("param1" -> Seq("value1"))) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (new String(req.getByteData, "UTF-8")) must_== "param1=value1" + assert((new String(req.getByteData, "UTF-8")) == "param1=value1") } } @@ -369,13 +385,15 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() // Note we use getFormParams instead of getByteData here. - req.getFormParams.asScala must containTheSameElementsAs( - List(new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1")) + assert( + req.getFormParams.asScala.toSet == List( + new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1") + ).toSet ) - req.getByteData must beNull // should NOT result in byte data. + assert(req.getByteData == null) // should NOT result in byte data. val headers = req.getHeaders - headers.get("Content-Length") must beNull + assert(headers.get("Content-Length") == null) } } @@ -391,7 +409,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - reqEmptyParams.getFormParams.asScala must beEmpty + assert(reqEmptyParams.getFormParams.asScala.isEmpty) } } @@ -404,9 +422,9 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (new String(req.getByteData, "UTF-8")) must be_==("HELLO WORLD") + assert((new String(req.getByteData, "UTF-8")) == "HELLO WORLD") val headers = req.getHeaders - headers.get("Content-Length") must beNull + assert(headers.get("Content-Length") == null) } } @@ -421,7 +439,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withBody("HELLO WORLD") // and body is set to string (see #5221) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (new String(req.getByteData, "UTF-8")) must be_==("HELLO WORLD") // should result in byte data. + assert((new String(req.getByteData, "UTF-8")) == "HELLO WORLD") // should result in byte data. } } @@ -434,7 +452,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - ByteString(req.getByteData) must_== binData + assert(ByteString(req.getByteData) == binData) } "Preserve existing headers when setting the body" in { @@ -445,12 +463,12 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withBody("HELLO WORLD") // will set content-type header .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get("Some-Header") must beEqualTo("Some-Value") + assert(req.getHeaders.get("Some-Header") == "Some-Value") } } } - "When using a Proxy Server" in { + "When using a Proxy Server" should { "support a proxy server with basic" in withClient { client => val proxy = DefaultWSProxyServer( @@ -467,11 +485,11 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .buildRequest() val actual = req.getProxyServer - (actual.getHost must be).equalTo("localhost") - (actual.getPort must be).equalTo(8080) - (actual.getRealm.getPrincipal must be).equalTo("principal") - (actual.getRealm.getPassword must be).equalTo("password") - (actual.getRealm.getScheme must be).equalTo(AuthScheme.BASIC) + assert(actual.getHost == "localhost") + assert(actual.getPort == 8080) + assert(actual.getRealm.getPrincipal == "principal") + assert(actual.getRealm.getPassword == "password") + assert(actual.getRealm.getScheme == AuthScheme.BASIC) } "support a proxy server with NTLM" in withClient { client => @@ -490,12 +508,12 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .buildRequest() val actual = req.getProxyServer - (actual.getHost must be).equalTo("localhost") - (actual.getPort must be).equalTo(8080) - (actual.getRealm.getPrincipal must be).equalTo("principal") - (actual.getRealm.getPassword must be).equalTo("password") - (actual.getRealm.getNtlmDomain must be).equalTo("somentlmdomain") - (actual.getRealm.getScheme must be).equalTo(AuthScheme.NTLM) + assert(actual.getHost == "localhost") + assert(actual.getPort == 8080) + assert(actual.getRealm.getPrincipal == "principal") + assert(actual.getRealm.getPassword == "password") + assert(actual.getRealm.getNtlmDomain == "somentlmdomain") + assert(actual.getRealm.getScheme == AuthScheme.NTLM) } "support a proxy server" in withClient { client => @@ -507,19 +525,19 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .buildRequest() val actual = req.getProxyServer - (actual.getHost must be).equalTo("localhost") - (actual.getPort must be).equalTo(8080) - actual.getRealm must beNull + assert(actual.getHost == "localhost") + assert(actual.getPort == 8080) + assert(actual.getRealm == null) } } - "StandaloneAhcWSRequest supports" in { + "StandaloneAhcWSRequest supports" should { "replace url" in withClient { client => val req = client .url("http://playframework.com/") .withUrl("http://www.example.com/") - req.url must_=== "http://www.example.com/" + assert(req.url == "http://www.example.com/") } "a custom signature calculator" in { @@ -538,7 +556,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .sign(calc) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - called must beTrue + assert(called) } } @@ -548,7 +566,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withVirtualHost("192.168.1.1") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (req.getVirtualHost must be).equalTo("192.168.1.1") + assert(req.getVirtualHost == "192.168.1.1") } "follow redirects" in withClient { client => @@ -557,7 +575,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withFollowRedirects(follow = true) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getFollowRedirect must beEqualTo(true) + assert(req.getFollowRedirect == true) } "enable url encoding by default" in withClient { client => @@ -566,7 +584,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .addQueryStringParameters("abc+def" -> "uvw+xyz") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getUrl must beEqualTo("http://playframework.com/?abc%2Bdef=uvw%2Bxyz") + assert(req.getUrl == "http://playframework.com/?abc%2Bdef=uvw%2Bxyz") } "disable url encoding globally via client config" in { @@ -576,7 +594,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .addQueryStringParameters("abc+def" -> "uvw+xyz") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getUrl must beEqualTo("http://playframework.com/?abc+def=uvw+xyz") + assert(req.getUrl == "http://playframework.com/?abc+def=uvw+xyz") } "disable url encoding for specific request only" in withClient { client => @@ -586,7 +604,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withDisableUrlEncoding(disableUrlEncoding = true) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getUrl must beEqualTo("http://playframework.com/?abc+def=uvw+xyz") + assert(req.getUrl == "http://playframework.com/?abc+def=uvw+xyz") } "finite timeout" in withClient { client => @@ -595,7 +613,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withRequestTimeout(1000.millis) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (req.getRequestTimeout must be).equalTo(1000) + assert(req.getRequestTimeout == 1000) } "infinite timeout" in withClient { client => @@ -604,28 +622,30 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withRequestTimeout(Duration.Inf) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (req.getRequestTimeout must be).equalTo(-1) + assert(req.getRequestTimeout == -1) } "no negative timeout" in withClient { client => - client.url("http://playframework.com/").withRequestTimeout(-1.millis) should throwAn[IllegalArgumentException] + assertThrows[IllegalArgumentException] { client.url("http://playframework.com/").withRequestTimeout(-1.millis) } } "no timeout greater than Int.MaxValue" in withClient { client => - client - .url("http://playframework.com/") - .withRequestTimeout((Int.MaxValue.toLong + 1).millis) should throwAn[IllegalArgumentException] + assertThrows[IllegalArgumentException] { + client + .url("http://playframework.com/") + .withRequestTimeout((Int.MaxValue.toLong + 1).millis) + } } } - "Set Realm.UsePreemptiveAuth" in { + "Set Realm.UsePreemptiveAuth" should { "to false when WSAuthScheme.DIGEST being used" in withClient { client => val req = client .url("http://playframework.com/") .withAuth("usr", "pwd", WSAuthScheme.DIGEST) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getRealm.isUsePreemptiveAuth must beFalse + assert(req.getRealm.isUsePreemptiveAuth == false) } "to true when WSAuthScheme.DIGEST not being used" in withClient { client => @@ -634,7 +654,7 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withAuth("usr", "pwd", WSAuthScheme.BASIC) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getRealm.isUsePreemptiveAuth must beTrue + assert(req.getRealm.isUsePreemptiveAuth) } } @@ -646,10 +666,10 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - (new String(req.getByteData, "UTF-8")) must be_==("param1=value1") // should result in byte data. + assert((new String(req.getByteData, "UTF-8")) == "param1=value1") // should result in byte data. val headers = req.getHeaders - headers.get("Content-Length") must_== "9001" + assert(headers.get("Content-Length") == "9001") } "Remove a user defined content length header if we are parsing body explicitly when signed" in withClient { client => @@ -666,11 +686,11 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .buildRequest() val headers = req.getHeaders - req.getByteData must beNull // should NOT result in byte data. - req.getFormParams.asScala must containTheSameElementsAs( - List(new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1")) + assert(req.getByteData == null) // should NOT result in byte data. + assert( + req.getFormParams.asScala.toSet == List(new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1")).toSet ) - headers.get("Content-Length") must beNull // no content length! + assert(headers.get("Content-Length") == null) // no content length! } "Verify Content-Type header is passed through correctly" in withClient { client => @@ -681,7 +701,9 @@ class AhcWSRequestSpec extends Specification with AfterAll with DefaultBodyReada .withBody("HELLO WORLD") .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.getAll(HttpHeaderNames.CONTENT_TYPE.toString()).asScala must_== Seq("text/plain; charset=US-ASCII") + assert( + req.getHeaders.getAll(HttpHeaderNames.CONTENT_TYPE.toString()).asScala == Seq("text/plain; charset=US-ASCII") + ) } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSResponseSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSResponseSpec.scala index a55b0d73..166131ab 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSResponseSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/AhcWSResponseSpec.scala @@ -10,7 +10,8 @@ import java.util import akka.util.ByteString import org.mockito.Mockito.when import org.mockito.Mockito -import org.specs2.mutable.Specification +import org.scalatest.OptionValues +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.ws._ import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders import play.shaded.ahc.io.netty.handler.codec.http.cookie.DefaultCookie @@ -19,7 +20,7 @@ import play.shaded.ahc.org.asynchttpclient.{ Response => AHCResponse } import scala.reflect.ClassTag -class AhcWSResponseSpec extends Specification with DefaultBodyReadables with DefaultBodyWritables { +class AhcWSResponseSpec extends AnyWordSpec with DefaultBodyReadables with DefaultBodyWritables with OptionValues { private def mock[A](implicit a: ClassTag[A]): A = Mockito.mock(a.runtimeClass).asInstanceOf[A] @@ -39,13 +40,13 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def val cookies: Seq[WSCookie] = response.cookies val cookie = cookies.head - cookie.name must ===(name) - cookie.value must ===(value) - cookie.path must beSome(path) - cookie.domain must beSome(domain) - cookie.maxAge must beSome(maxAge) - cookie.secure must beFalse - cookie.httpOnly must beFalse + assert(cookie.name == name) + assert(cookie.value == value) + assert(cookie.path == Some(path)) + assert(cookie.domain == Some(domain)) + assert(cookie.maxAge == Some(maxAge)) + assert(cookie.secure == false) + assert(cookie.httpOnly == false) } "get a single cookie from an AHC response" in { @@ -58,16 +59,14 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def val response = StandaloneAhcWSResponse(ahcResponse) - val optionCookie = response.cookie("someName") - optionCookie must beSome[WSCookie].which { cookie => - cookie.name must ===(name) - cookie.value must ===(value) - cookie.path must beSome(path) - cookie.domain must beSome(domain) - cookie.maxAge must beSome(maxAge) - cookie.secure must beFalse - cookie.httpOnly must beFalse - } + val cookie = response.cookie("someName").value + assert(cookie.name == name) + assert(cookie.value == value) + assert(cookie.path == Some(path)) + assert(cookie.domain == Some(domain)) + assert(cookie.maxAge == Some(maxAge)) + assert(cookie.secure == false) + assert(cookie.httpOnly == false) } "return -1 values of expires and maxAge as None" in { @@ -78,10 +77,8 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def val response = StandaloneAhcWSResponse(ahcResponse) - val optionCookie = response.cookie("someName") - optionCookie must beSome[WSCookie].which { cookie => - cookie.maxAge must beNone - } + val cookie = response.cookie("someName").value + assert(cookie.maxAge.isEmpty) } "get the body as bytes from the AHC response" in { @@ -89,7 +86,7 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def val bytes = ByteString(-87, -72, 96, -63, -32, 46, -117, -40, -128, -7, 61, 109, 80, 45, 44, 30) when(ahcResponse.getResponseBodyAsBytes).thenReturn(bytes.toArray) val response = StandaloneAhcWSResponse(ahcResponse) - response.body[ByteString] must_== bytes + assert(response.body[ByteString] == bytes) } "get JSON body as a string from the AHC response" in { @@ -100,70 +97,70 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def when(ahcResponse.getHeaders).thenReturn(ahcHeaders) when(ahcResponse.getResponseBody(StandardCharsets.UTF_8)).thenReturn(json) val response = StandaloneAhcWSResponse(ahcResponse) - response.body[String] must_== json - } - - "get text body as a string from the AHC response" in { - val ahcResponse: AHCResponse = mock[AHCResponse] - val text = "Hello ☺" - when(ahcResponse.getContentType).thenReturn("text/plain") - when(ahcResponse.getResponseBody(StandardCharsets.ISO_8859_1)).thenReturn(text) - val response = StandaloneAhcWSResponse(ahcResponse) - response.body[String] must_== text + assert(response.body[String] == json) } + } - "get headers from an AHC response in a case insensitive map" in { - val ahcResponse: AHCResponse = mock[AHCResponse] - val ahcHeaders = new DefaultHttpHeaders(true) - ahcHeaders.add("Foo", "bar") - ahcHeaders.add("Foo", "baz") - ahcHeaders.add("Bar", "baz") - when(ahcResponse.getHeaders).thenReturn(ahcHeaders) - val response = StandaloneAhcWSResponse(ahcResponse) - val headers = response.headers - headers must beEqualTo(Map("Foo" -> Seq("bar", "baz"), "Bar" -> Seq("baz"))) - headers.contains("foo") must beTrue - headers.contains("Foo") must beTrue - headers.contains("BAR") must beTrue - headers.contains("Bar") must beTrue - } + "get text body as a string from the AHC response" in { + val ahcResponse: AHCResponse = mock[AHCResponse] + val text = "Hello ☺" + when(ahcResponse.getContentType).thenReturn("text/plain") + when(ahcResponse.getResponseBody(StandardCharsets.ISO_8859_1)).thenReturn(text) + val response = StandaloneAhcWSResponse(ahcResponse) + assert(response.body[String] == text) + } - "get a single header" in { - val ahcResponse: AHCResponse = mock[AHCResponse] - val ahcHeaders = new DefaultHttpHeaders(true) - ahcHeaders.add("Foo", "bar") - ahcHeaders.add("Foo", "baz") - ahcHeaders.add("Bar", "baz") - when(ahcResponse.getHeaders).thenReturn(ahcHeaders) - val response = StandaloneAhcWSResponse(ahcResponse) + "get headers from an AHC response in a case insensitive map" in { + val ahcResponse: AHCResponse = mock[AHCResponse] + val ahcHeaders = new DefaultHttpHeaders(true) + ahcHeaders.add("Foo", "bar") + ahcHeaders.add("Foo", "baz") + ahcHeaders.add("Bar", "baz") + when(ahcResponse.getHeaders).thenReturn(ahcHeaders) + val response = StandaloneAhcWSResponse(ahcResponse) + val headers = response.headers + assert(headers == Map("Foo" -> Seq("bar", "baz"), "Bar" -> Seq("baz"))) + assert(headers.contains("foo")) + assert(headers.contains("Foo")) + assert(headers.contains("BAR")) + assert(headers.contains("Bar")) + } - response.header("Foo") must beSome("bar") - response.header("Bar") must beSome("baz") - } + "get a single header" in { + val ahcResponse: AHCResponse = mock[AHCResponse] + val ahcHeaders = new DefaultHttpHeaders(true) + ahcHeaders.add("Foo", "bar") + ahcHeaders.add("Foo", "baz") + ahcHeaders.add("Bar", "baz") + when(ahcResponse.getHeaders).thenReturn(ahcHeaders) + val response = StandaloneAhcWSResponse(ahcResponse) + + assert(response.header("Foo") == Some("bar")) + assert(response.header("Bar") == Some("baz")) + } - "get none when header does not exists" in { - val ahcResponse: AHCResponse = mock[AHCResponse] - val ahcHeaders = new DefaultHttpHeaders(true) - ahcHeaders.add("Foo", "bar") - ahcHeaders.add("Foo", "baz") - ahcHeaders.add("Bar", "baz") - when(ahcResponse.getHeaders).thenReturn(ahcHeaders) - val response = StandaloneAhcWSResponse(ahcResponse) + "get none when header does not exists" in { + val ahcResponse: AHCResponse = mock[AHCResponse] + val ahcHeaders = new DefaultHttpHeaders(true) + ahcHeaders.add("Foo", "bar") + ahcHeaders.add("Foo", "baz") + ahcHeaders.add("Bar", "baz") + when(ahcResponse.getHeaders).thenReturn(ahcHeaders) + val response = StandaloneAhcWSResponse(ahcResponse) - response.header("Non") must beNone - } + assert(response.header("Non").isEmpty) + } - "get all values for a header" in { - val ahcResponse: AHCResponse = mock[AHCResponse] - val ahcHeaders = new DefaultHttpHeaders(true) - ahcHeaders.add("Foo", "bar") - ahcHeaders.add("Foo", "baz") - ahcHeaders.add("Bar", "baz") - when(ahcResponse.getHeaders).thenReturn(ahcHeaders) - val response = StandaloneAhcWSResponse(ahcResponse) + "get all values for a header" in { + val ahcResponse: AHCResponse = mock[AHCResponse] + val ahcHeaders = new DefaultHttpHeaders(true) + ahcHeaders.add("Foo", "bar") + ahcHeaders.add("Foo", "baz") + ahcHeaders.add("Bar", "baz") + when(ahcResponse.getHeaders).thenReturn(ahcHeaders) + val response = StandaloneAhcWSResponse(ahcResponse) - response.headerValues("Foo") must beEqualTo(Seq("bar", "baz")) - } + assert(response.headerValues("Foo") == Seq("bar", "baz")) } def asCookie( diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/AhcWSCacheSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/AhcWSCacheSpec.scala index 946708ce..cadbde65 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/AhcWSCacheSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/AhcWSCacheSpec.scala @@ -8,14 +8,15 @@ import java.net.URI import com.typesafe.play.cachecontrol.HttpDate._ import com.typesafe.play.cachecontrol._ -import org.specs2.mutable.Specification +import org.scalatest.OptionValues +import org.scalatest.wordspec.AnyWordSpec import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders import play.shaded.ahc.io.netty.handler.codec.http.HttpHeaders import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClientConfig import play.shaded.ahc.org.asynchttpclient.Request import play.shaded.ahc.org.asynchttpclient.RequestBuilder -class AhcWSCacheSpec extends Specification { +class AhcWSCacheSpec extends AnyWordSpec with OptionValues { "freshness heuristics flag" should { @@ -31,11 +32,9 @@ class AhcWSCacheSpec extends Specification { val response: CacheResponse = StoredResponse(uri, 200, Map(HeaderName("Last-Modified") -> Seq(lastModifiedDate)), "GET", Map()) - val actual = cache.calculateFreshnessFromHeuristic(request, response) + val actual = cache.calculateFreshnessFromHeuristic(request, response).value - actual must beSome[Seconds].which { case value => - value must be_==(Seconds.seconds(360)) // 0.1 hours - } + assert(actual == Seconds.seconds(360)) // 0.1 hours } "be disabled when set to false" in { @@ -52,7 +51,7 @@ class AhcWSCacheSpec extends Specification { val actual = cache.calculateFreshnessFromHeuristic(request, response) - actual must beNone + assert(actual.isEmpty) } } @@ -70,13 +69,10 @@ class AhcWSCacheSpec extends Specification { val request = generateRequest(url)(headers => headers.add("Accept-Encoding", "gzip")) val response = CacheableResponse(200, url, achConfig).withHeaders("Vary" -> "Accept-Encoding") - val actual = cache.calculateSecondaryKeys(request, response) - - actual must beSome[Map[HeaderName, Seq[String]]].which { d => - d must haveKey(HeaderName("Accept-Encoding")) - d(HeaderName("Accept-Encoding")) must be_==(Seq("gzip")) - } + val d = cache.calculateSecondaryKeys(request, response).value + assert(d.isDefinedAt(HeaderName("Accept-Encoding"))) + assert(d(HeaderName("Accept-Encoding")) == Seq("gzip")) } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/BackgroundAsyncHandlerSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/BackgroundAsyncHandlerSpec.scala index 38c57623..5d2ad89b 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/BackgroundAsyncHandlerSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/BackgroundAsyncHandlerSpec.scala @@ -4,9 +4,9 @@ package play.api.libs.ws.ahc.cache -import org.specs2.mutable.Specification +import org.scalatest.wordspec.AnyWordSpec -class BackgroundAsyncHandlerSpec extends Specification { +class BackgroundAsyncHandlerSpec extends AnyWordSpec { "BackgroundAsyncHandler" should { diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheAsyncHandlerSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheAsyncHandlerSpec.scala index 70a3ee8e..106b3392 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheAsyncHandlerSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheAsyncHandlerSpec.scala @@ -4,9 +4,9 @@ package play.api.libs.ws.ahc.cache -import org.specs2.mutable.Specification +import org.scalatest.wordspec.AnyWordSpec -class CacheAsyncHandlerSpec extends Specification { +class CacheAsyncHandlerSpec extends AnyWordSpec { "CacheAsyncHandlerSpec" should { diff --git a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheableResponseSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheableResponseSpec.scala index fd668627..f448d314 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheableResponseSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/api/libs/ws/ahc/cache/CacheableResponseSpec.scala @@ -4,38 +4,38 @@ package play.api.libs.ws.ahc.cache -import org.specs2.mutable.Specification +import org.scalatest.wordspec.AnyWordSpec import play.shaded.ahc.io.netty.handler.codec.http.HttpHeaders.Names._ import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClientConfig -class CacheableResponseSpec extends Specification { +class CacheableResponseSpec extends AnyWordSpec { val achConfig = new DefaultAsyncHttpClientConfig.Builder().build() "CacheableResponse" should { - "get body" in { + "get body" should { "when it is text/plain" in { val response = CacheableResponse(200, "https://playframework.com/", "PlayFramework Homepage", achConfig) .withHeaders(CONTENT_TYPE -> "text/plain") - response.getResponseBody must beEqualTo("PlayFramework Homepage") - response.getContentType must beEqualTo("text/plain") + assert(response.getResponseBody == "PlayFramework Homepage") + assert(response.getContentType == "text/plain") } "when it is application/json" in { val response = CacheableResponse(200, "https://playframework.com/", """{ "a": "b" }""", achConfig).withHeaders( "Content-Type" -> "application/json" ) - response.getResponseBody must beEqualTo("""{ "a": "b" }""") - response.getContentType must beEqualTo("application/json") + assert(response.getResponseBody == """{ "a": "b" }""") + assert(response.getContentType == "application/json") } "when it is application/json; charset=utf-8" in { val response = CacheableResponse(200, "https://playframework.com/", """{ "a": "b" }""", achConfig).withHeaders( "Content-Type" -> "application/json; charset=utf-8" ) - response.getResponseBody must beEqualTo("""{ "a": "b" }""") - response.getContentType must beEqualTo("application/json; charset=utf-8") + assert(response.getResponseBody == """{ "a": "b" }""") + assert(response.getContentType == "application/json; charset=utf-8") } } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSRequestSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSRequestSpec.scala index 24b14fb3..71836e3b 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSRequestSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSRequestSpec.scala @@ -9,7 +9,7 @@ import com.typesafe.config.ConfigFactory import java.time.Duration import java.util.Collections -import org.specs2.mutable._ +import org.scalatest.wordspec.AnyWordSpec import play.libs.oauth.OAuth import play.libs.ws._ import play.shaded.ahc.io.netty.handler.codec.http.HttpHeaderNames @@ -21,7 +21,7 @@ import scala.jdk.CollectionConverters._ import scala.collection.mutable import scala.jdk.OptionConverters._ -class AhcWSRequestSpec extends Specification with DefaultBodyReadables with DefaultBodyWritables { +class AhcWSRequestSpec extends AnyWordSpec with DefaultBodyReadables with DefaultBodyWritables { "AhcWSRequest" should { @@ -30,8 +30,8 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa AhcWSClientConfigFactory.forConfig(ConfigFactory.load(), this.getClass.getClassLoader), /*materializer*/ null ) val request = new StandaloneAhcWSRequest(client, "http://example.com", /*materializer*/ null) - request.getMethod must be_==("GET") - request.buildRequest().getMethod must be_==("GET") + assert(request.getMethod == "GET") + assert(request.buildRequest().getMethod == "GET") } "Set virtualHost appropriately" in { @@ -41,7 +41,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa val request = new StandaloneAhcWSRequest(client, "http://example.com", /*materializer*/ null) request.setVirtualHost("foo.com") val actual = request.buildRequest().getVirtualHost() - actual must beEqualTo("foo.com") + assert(actual == "foo.com") } "set the url" in { @@ -49,15 +49,13 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa AhcWSClientConfigFactory.forConfig(ConfigFactory.load(), this.getClass.getClassLoader), /*materializer*/ null ) val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null) - (req.getUrl must be_===("http://playframework.com/")).and { - val setReq = req.setUrl("http://example.com") - (setReq.getUrl must be_===("http://example.com")).and { - setReq must be_===(req) - } - } + assert(req.getUrl == "http://playframework.com/") + val setReq = req.setUrl("http://example.com") + assert(setReq.getUrl == "http://example.com") + assert(setReq == req) } - "For POST requests" in { + "For POST requests" should { "get method" in { val client = StandaloneAhcWSClient.create( @@ -66,7 +64,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null) .setMethod("POST") - req.getMethod must be_===("POST") + assert(req.getMethod == "POST") } "set text/plain content-types for text bodies" in { @@ -77,7 +75,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .setBody(body("HELLO WORLD")) .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getStringData must be_==("HELLO WORLD") + assert(req.getStringData == "HELLO WORLD") } "sets content type based on a body when its not explicitly set" in { @@ -89,8 +87,8 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() - req.getHeaders.get(HttpHeaderNames.CONTENT_TYPE) must be_==("text/plain; charset=UTF-8") - req.getStringData must be_==("HELLO WORLD") + assert(req.getHeaders.get(HttpHeaderNames.CONTENT_TYPE) == "text/plain; charset=UTF-8") + assert(req.getStringData == "HELLO WORLD") } "keep existing content type when setting body" in { @@ -104,11 +102,9 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .buildRequest() // preserve the content type - req.getHeaders.get(HttpHeaderNames.CONTENT_TYPE) must be_==( - "text/plain+hello; charset=UTF-8" - ) + assert(req.getHeaders.get(HttpHeaderNames.CONTENT_TYPE) == "text/plain+hello; charset=UTF-8") // should result in byte data. - req.getStringData must be_==("HELLO WORLD") + assert(req.getStringData == "HELLO WORLD") } "have form params when passing in map" in { @@ -122,11 +118,13 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .buildRequest() // Must set the form url encoding autoomatically. - req.getHeaders.get("Content-Type") must be_==("application/x-www-form-urlencoded") + assert(req.getHeaders.get("Content-Type") == "application/x-www-form-urlencoded") // Note we use getFormParams instead of getByteData here. - req.getFormParams.asScala must containTheSameElementsAs( - List(new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1")) + assert( + req.getFormParams.asScala.toSet == Set( + new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1") + ) ) } @@ -145,8 +143,10 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .asInstanceOf[StandaloneAhcWSRequest] .buildRequest() // Note we use getFormParams instead of getByteData here. - req.getFormParams.asScala must containTheSameElementsAs( - List(new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1")) + assert( + req.getFormParams.asScala.toSet == Set( + new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1") + ) ) } @@ -167,10 +167,12 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .buildRequest() val headers = req.getHeaders - req.getFormParams.asScala must containTheSameElementsAs( - List(new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1")) + assert( + req.getFormParams.asScala.toSet == Set( + new play.shaded.ahc.org.asynchttpclient.Param("param1", "value1") + ) ) - headers.get("Content-Length") must beNull // no content length! + assert(headers.get("Content-Length") == null) // no content length! } } @@ -188,32 +190,32 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa new StandaloneAhcWSRequest(client, "http://playframework.com/", null) .sign(calc) .buildRequest() - called must beTrue + assert(called) } "setRequestTimeout(java.time.Duration)" should { "support setting a request timeout to a duration" in { - requestWithTimeout(Duration.ofSeconds(1)) must beEqualTo(1000) + assert(requestWithTimeout(Duration.ofSeconds(1)) == 1000) } "support setting a request timeout duration to infinite using -1" in { - requestWithTimeout(Duration.ofMillis(-1)) must beEqualTo(-1) + assert(requestWithTimeout(Duration.ofMillis(-1)) == -1) } "support setting a request timeout duration to infinite using any negative duration" in { - requestWithTimeout(Duration.ofMillis(-2)) must beEqualTo(-1) - requestWithTimeout(Duration.ofMillis(-15)) must beEqualTo(-1) - requestWithTimeout(Duration.ofSeconds(-1)) must beEqualTo(-1) - requestWithTimeout(Duration.ofMillis(java.lang.Integer.MIN_VALUE)) must beEqualTo(-1) + assert(requestWithTimeout(Duration.ofMillis(-2)) == -1) + assert(requestWithTimeout(Duration.ofMillis(-15)) == -1) + assert(requestWithTimeout(Duration.ofSeconds(-1)) == -1) + assert(requestWithTimeout(Duration.ofMillis(java.lang.Integer.MIN_VALUE)) == -1) } "support setting a request timeout duration to Long.MAX_VALUE as infinite" in { - requestWithTimeout(Duration.ofMillis(java.lang.Long.MAX_VALUE)) must beEqualTo(-1) + assert(requestWithTimeout(Duration.ofMillis(java.lang.Long.MAX_VALUE)) == -1) } "not support setting a request timeout to null" in { - requestWithTimeout(null) must throwA[IllegalArgumentException] + assertThrows[IllegalArgumentException] { requestWithTimeout(null) } } } @@ -225,7 +227,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa request.setBody(body("HELLO WORLD", null)) // content type is not set request.addHeader("Content-Type", "application/json") // will be used as content type is not set with a body val req = request.buildRequest() - req.getHeaders.get("Content-Type") must be_==("application/json") + assert(req.getHeaders.get("Content-Type") == "application/json") } "ignore explicit Content-Type header if the BodyWritable already set the Content-Type" in { @@ -236,7 +238,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa request.setBody(body("HELLO WORLD")) request.addHeader("Content-Type", "application/json") // will be ignored since body already sets content type val req = request.buildRequest() - req.getHeaders.get("Content-Type") must be_==("text/plain; charset=UTF-8") + assert(req.getHeaders.get("Content-Type") == "text/plain; charset=UTF-8") } "only send first Content-Type header and keep the charset when setting the Content-Type multiple times" in { @@ -248,7 +250,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa request.addHeader("Content-Type", "application/xml") request.setBody(body("HELLO WORLD")) // content type is not overwritten here as its already set before val req = request.buildRequest() - req.getHeaders.get("Content-Type") must be_==("application/json; charset=US-ASCII") + assert(req.getHeaders.get("Content-Type") == "application/json; charset=US-ASCII") } "Set Realm.UsePreemptiveAuth to false when WSAuthScheme.DIGEST being used" in { @@ -258,7 +260,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa val request = new StandaloneAhcWSRequest(client, "http://example.com", /*materializer*/ null) request.setAuth("usr", "pwd", WSAuthScheme.DIGEST) val req = request.buildRequest() - req.getRealm.isUsePreemptiveAuth must beFalse + assert(req.getRealm.isUsePreemptiveAuth == false) } "Set Realm.UsePreemptiveAuth to true when WSAuthScheme.DIGEST not being used" in { @@ -268,10 +270,10 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa val request = new StandaloneAhcWSRequest(client, "http://example.com", /*materializer*/ null) request.setAuth("usr", "pwd", WSAuthScheme.BASIC) val req = request.buildRequest() - req.getRealm.isUsePreemptiveAuth must beTrue + assert(req.getRealm.isUsePreemptiveAuth) } - "For HTTP Headers" in { + "For HTTP Headers" should { "add a new header" in { val client = StandaloneAhcWSClient.create( @@ -279,11 +281,13 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa ) val request = new StandaloneAhcWSRequest(client, "http://example.com", /*materializer*/ null) - request - .addHeader("header1", "value1") - .buildRequest() - .getHeaders - .get("header1") must beEqualTo("value1") + assert( + request + .addHeader("header1", "value1") + .buildRequest() + .getHeaders + .get("header1") == "value1" + ) } "add new value for existing header" in { @@ -294,11 +298,11 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header1", "value1") .addHeader("header1", "value2") - request.getHeaders.get("header1").asScala.toSet must_== Set("value1", "value2") + assert(request.getHeaders.get("header1").asScala.toSet == Set("value1", "value2")) val ahcRequest = request.buildRequest() - ahcRequest.getHeaders.getAll("header1").asScala.toSet must_== Set("value1", "value2") + assert(ahcRequest.getHeaders.getAll("header1").asScala.toSet == Set("value1", "value2")) } "set all headers" in { @@ -307,11 +311,13 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa ) val request = new StandaloneAhcWSRequest(client, "http://example.com", /*materializer*/ null) - request - .setHeaders(Map("header1" -> Seq("value1").asJava, "header2" -> Seq("value2").asJava).asJava) - .buildRequest() - .getHeaders - .get("header1") must beEqualTo("value1") + assert( + request + .setHeaders(Map("header1" -> Seq("value1").asJava, "header2" -> Seq("value2").asJava).asJava) + .buildRequest() + .getHeaders + .get("header1") == "value1" + ) } "keep existing headers when adding a new one" in { @@ -325,8 +331,8 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header2", "value2") .buildRequest() - ahcReq.getHeaders.get("header1") must beEqualTo("value1") - ahcReq.getHeaders.get("header2") must beEqualTo("value2") + assert(ahcReq.getHeaders.get("header1") == "value1") + assert(ahcReq.getHeaders.get("header2") == "value2") } "treat header names case insensitively" in { @@ -338,7 +344,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("HEADER1", "value2") .buildRequest() - request.getHeaders.getAll("header1").asScala.toSet must_== Set("value1", "value2") + assert(request.getHeaders.getAll("header1").asScala.toSet == Set("value1", "value2")) } "get a single header" in { @@ -349,7 +355,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header1", "value1") .addHeader("header1", "value2") - request.getHeader("header1").toScala must beSome("value1") + assert(request.getHeader("header1").toScala == Some("value1")) } "get an empty optional when header is not present" in { @@ -360,7 +366,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header1", "value1") .addHeader("header1", "value2") - request.getHeader("non").toScala must beNone + assert(request.getHeader("non").toScala.isEmpty) } "get all values for a header" in { @@ -371,7 +377,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header1", "value1") .addHeader("header1", "value2") - request.getHeaderValues("header1").asScala must containTheSameElementsAs(Seq("value1", "value2")) + assert(request.getHeaderValues("header1").asScala.toSet == Set("value1", "value2")) } "get an empty list when header is not present" in { @@ -382,7 +388,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header1", "value1") .addHeader("header1", "value2") - request.getHeaderValues("Non").asScala must beEmpty + assert(request.getHeaderValues("Non").asScala.isEmpty) } "get all headers" in { @@ -395,13 +401,13 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addHeader("header2", "Value1ForHeader2") val headers = request.getHeaders.asScala - headers("header1").asScala must containTheSameElementsAs(Seq("Value1ForHeader1", "Value2ForHeader1")) - headers("header2").asScala must containTheSameElementsAs(Seq("Value1ForHeader2")) + assert(headers("header1").asScala.toSet == Set("Value1ForHeader1", "Value2ForHeader1")) + assert(headers("header2").asScala.toSet == Set("Value1ForHeader2")) } } - "For query string parameters" in { + "For query string parameters" should { "add query string parameter" in { val client = StandaloneAhcWSClient.create( @@ -411,7 +417,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("p1", "v1") .buildRequest() - request.getUrl must contain("p1=v1") + assert(request.getUrl.contains("p1=v1")) } "deterministic query param order a" in { @@ -423,7 +429,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("p2", "v2") .buildRequest() - request.getUrl must contain("p1=v1&p2=v2") + assert(request.getUrl.contains("p1=v1&p2=v2")) } "deterministic query param order b" in { @@ -435,7 +441,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("p1", "v1") .buildRequest() - request.getUrl must contain("p2=v2&p1=v1") + assert(request.getUrl.contains("p2=v2&p1=v1")) } "deterministic query param order for duplicate keys" in { @@ -449,7 +455,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("p1", "v4") .buildRequest() - request.getUrl must contain("p1=v1&p1=v3&p1=v4&p2=v2") + assert(request.getUrl.contains("p1=v1&p1=v3&p1=v4&p2=v2")) } "add new value for existing parameter" in { @@ -461,8 +467,8 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("p1", "v2") .buildRequest() - request.getUrl must contain("p1=v1") - request.getUrl must contain("p1=v2") + assert(request.getUrl.contains("p1=v1")) + assert(request.getUrl.contains("p1=v2")) } "keep existing parameters when adding a new one" in { @@ -474,8 +480,8 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("p2", "v2") .buildRequest() - request.getUrl must contain("p1=v1") - request.getUrl must contain("p2=v2") + assert(request.getUrl.contains("p1=v1")) + assert(request.getUrl.contains("p2=v2")) } "set all the parameters" in { @@ -486,35 +492,35 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .setQueryString(Map("p1" -> Seq("v1").asJava, "p2" -> Seq("v2").asJava).asJava) .buildRequest() - request.getUrl must contain("p1=v1") - request.getUrl must contain("p2=v2") + assert(request.getUrl.contains("p1=v1")) + assert(request.getUrl.contains("p2=v2")) } "set a query string appropriately" in { val queryParams = requestWithQueryString("q=playframework&src=typd") - queryParams.size must beEqualTo(2) - queryParams.exists(p => (p.getName == "q") && (p.getValue == "playframework")) must beTrue - queryParams.exists(p => (p.getName == "src") && (p.getValue == "typd")) must beTrue + assert(queryParams.size == 2) + assert(queryParams.exists(p => (p.getName == "q") && (p.getValue == "playframework"))) + assert(queryParams.exists(p => (p.getName == "src") && (p.getValue == "typd"))) } "support several query string values for a parameter" in { val queryParams = requestWithQueryString("q=scala&q=playframework&q=fp") - queryParams.size must beEqualTo(3) - queryParams.exists(p => (p.getName == "q") && (p.getValue == "scala")) must beTrue - queryParams.exists(p => (p.getName == "q") && (p.getValue == "playframework")) must beTrue - queryParams.exists(p => (p.getName == "q") && (p.getValue == "fp")) must beTrue - queryParams.count(p => p.getName == "q") must beEqualTo(3) + assert(queryParams.size == 3) + assert(queryParams.exists(p => (p.getName == "q") && (p.getValue == "scala"))) + assert(queryParams.exists(p => (p.getName == "q") && (p.getValue == "playframework"))) + assert(queryParams.exists(p => (p.getName == "q") && (p.getValue == "fp"))) + assert(queryParams.count(p => p.getName == "q") == 3) } "support a query string parameter without value" in { val queryParams = requestWithQueryString("q=playframework&src=") - queryParams.size must beEqualTo(2) - queryParams.exists(p => (p.getName == "q") && (p.getValue == "playframework")) must beTrue - queryParams.exists(p => (p.getName.equals("src")) && (p.getValue == null)) must beTrue + assert(queryParams.size == 2) + assert(queryParams.exists(p => (p.getName == "q") && (p.getValue == "playframework"))) + assert(queryParams.exists(p => (p.getName.equals("src")) && (p.getValue == null))) } "not support a query string with more than 2 = per part" in { - requestWithQueryString("q=scala=playframework&src=typd") must throwA[RuntimeException] + assertThrows[RuntimeException] { requestWithQueryString("q=scala=playframework&src=typd") } } "support a query string parameter with an encoded equals sign" in { @@ -526,12 +532,12 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa val queryParams = request.buildRequest().getQueryParams.asScala val p = queryParams(0) - p.getName must beEqualTo("bar") - p.getValue must beEqualTo("F%253Dma") + assert(p.getName == "bar") + assert(p.getValue == "F%253Dma") } "not support a query string if it starts with = and is empty" in { - requestWithQueryString("=&src=typd") must throwA[RuntimeException] + assertThrows[RuntimeException] { requestWithQueryString("=&src=typd") } } "enable url encoding by default" in { @@ -542,7 +548,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("abc+def", "uvw+xyz") .buildRequest() - request.getUrl must beEqualTo("http://example.com?abc%2Bdef=uvw%2Bxyz") + assert(request.getUrl == "http://example.com?abc%2Bdef=uvw%2Bxyz") } "disable url encoding globally via client config" in { @@ -555,7 +561,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addQueryParameter("abc+def", "uvw+xyz") .buildRequest() - request.getUrl must beEqualTo("http://example.com?abc+def=uvw+xyz") + assert(request.getUrl == "http://example.com?abc+def=uvw+xyz") } "disable url encoding for specific request only" in { @@ -567,11 +573,11 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .setDisableUrlEncoding(true) .buildRequest() - request.getUrl must beEqualTo("http://example.com?abc+def=uvw+xyz") + assert(request.getUrl == "http://example.com?abc+def=uvw+xyz") } } - "For Cookies" in { + "For Cookies" should { def cookie(name: String, value: String): WSCookie = { new WSCookieBuilder().setName(name).setValue(value).build() @@ -585,10 +591,10 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addCookie(cookie("cookie1", "value1")) val cookiesInRequest: mutable.Buffer[WSCookie] = request.getCookies.asScala - cookiesInRequest.size must beEqualTo(1) + assert(cookiesInRequest.size == 1) val cookieInRequest: WSCookie = cookiesInRequest.head - cookieInRequest.getName must beEqualTo("cookie1") - cookieInRequest.getValue must beEqualTo("value1") + assert(cookieInRequest.getName == "cookie1") + assert(cookieInRequest.getValue == "value1") } "add a new cookie" in { @@ -599,7 +605,7 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addCookie(cookie("cookie1", "value1")) .buildRequest() - request.getCookies.asScala.head.name must beEqualTo("cookie1") + assert(request.getCookies.asScala.head.name == "cookie1") } "add more than one cookie" in { @@ -610,9 +616,9 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addCookies(cookie("cookie1", "value1"), cookie("cookie2", "value2")) .buildRequest() - request.getCookies.asScala must size(2) - request.getCookies.asScala.head.name must beEqualTo("cookie1") - request.getCookies.asScala(1).name must beEqualTo("cookie2") + assert(request.getCookies.asScala.size == 2) + assert(request.getCookies.asScala.head.name == "cookie1") + assert(request.getCookies.asScala(1).name == "cookie2") } "keep existing cookies when adding a new one" in { @@ -624,9 +630,9 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .addCookie(cookie("cookie2", "value2")) .buildRequest() - request.getCookies.asScala must size(2) - request.getCookies.asScala.head.name must beEqualTo("cookie1") - request.getCookies.asScala(1).name must beEqualTo("cookie2") + assert(request.getCookies.asScala.size == 2) + assert(request.getCookies.asScala.head.name == "cookie1") + assert(request.getCookies.asScala(1).name == "cookie2") } "set all cookies" in { @@ -637,9 +643,9 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .setCookies(List(cookie("cookie1", "value1"), cookie("cookie2", "value2")).asJava) .buildRequest() - request.getCookies.asScala must size(2) - request.getCookies.asScala.head.name must beEqualTo("cookie1") - request.getCookies.asScala(1).name must beEqualTo("cookie2") + assert(request.getCookies.asScala.size == 2) + assert(request.getCookies.asScala.head.name == "cookie1") + assert(request.getCookies.asScala(1).name == "cookie2") } "discard old cookies when setting" in { @@ -651,9 +657,9 @@ class AhcWSRequestSpec extends Specification with DefaultBodyReadables with Defa .setCookies(List(cookie("cookie3", "value1"), cookie("cookie4", "value2")).asJava) .buildRequest() - request.getCookies.asScala must size(2) - request.getCookies.asScala.head.name must beEqualTo("cookie3") - request.getCookies.asScala(1).name must beEqualTo("cookie4") + assert(request.getCookies.asScala.size == 2) + assert(request.getCookies.asScala.head.name == "cookie3") + assert(request.getCookies.asScala(1).name == "cookie4") } } } diff --git a/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSResponseSpec.scala b/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSResponseSpec.scala index 9a08b435..61e8e0e1 100644 --- a/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSResponseSpec.scala +++ b/play-ahc-ws-standalone/src/test/scala/play/libs/ws/ahc/AhcWSResponseSpec.scala @@ -6,7 +6,7 @@ package play.libs.ws.ahc import org.mockito.Mockito.when import org.mockito.Mockito -import org.specs2.mutable._ +import org.scalatest.wordspec.AnyWordSpec import play.libs.ws._ import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders import play.shaded.ahc.org.asynchttpclient.Response @@ -15,7 +15,7 @@ import scala.jdk.CollectionConverters._ import scala.jdk.OptionConverters._ import scala.reflect.ClassTag -class AhcWSResponseSpec extends Specification with DefaultBodyReadables with DefaultBodyWritables { +class AhcWSResponseSpec extends AnyWordSpec with DefaultBodyReadables with DefaultBodyWritables { private def mock[A](implicit a: ClassTag[A]): A = Mockito.mock(a.runtimeClass).asInstanceOf[A] @@ -25,7 +25,7 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def "return the underlying response" in { val srcResponse = mock[Response] val response = new StandaloneAhcWSResponse(srcResponse) - response.getUnderlying must_== srcResponse + assert(response.getUnderlying == srcResponse) } } @@ -42,8 +42,8 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def when(srcResponse.getHeaders).thenReturn(srcHeaders) val response = new StandaloneAhcWSResponse(srcResponse) val headers = response.getHeaders - headers.get("foo").asScala must_== Seq("a", "b", "b") - headers.get("BAR").asScala must_== Seq("baz") + assert(headers.get("foo").asScala == Seq("a", "b", "b")) + assert(headers.get("BAR").asScala == Seq("baz")) } "get a single header" in { @@ -56,8 +56,8 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def when(srcResponse.getHeaders).thenReturn(srcHeaders) val response = new StandaloneAhcWSResponse(srcResponse) - response.getSingleHeader("Foo").toScala must beSome("a") - response.getSingleHeader("Bar").toScala must beSome("baz") + assert(response.getSingleHeader("Foo").toScala == Some("a")) + assert(response.getSingleHeader("Bar").toScala == Some("baz")) } "get an empty optional when header is not present" in { @@ -70,7 +70,7 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def when(srcResponse.getHeaders).thenReturn(srcHeaders) val response = new StandaloneAhcWSResponse(srcResponse) - response.getSingleHeader("Non").toScala must beNone + assert(response.getSingleHeader("Non").toScala.isEmpty) } "get all values for a header" in { @@ -83,7 +83,7 @@ class AhcWSResponseSpec extends Specification with DefaultBodyReadables with Def when(srcResponse.getHeaders).thenReturn(srcHeaders) val response = new StandaloneAhcWSResponse(srcResponse) - response.getHeaderValues("Foo").asScala must containTheSameElementsAs(Seq("a", "b", "b")) + assert(response.getHeaderValues("Foo").asScala.toSet == Set("a", "b", "b")) } } diff --git a/play-ws-standalone-json/src/test/scala/play/api/libs/ws/JsonBodyReadablesSpec.scala b/play-ws-standalone-json/src/test/scala/play/api/libs/ws/JsonBodyReadablesSpec.scala index 677940c7..5822d6ae 100644 --- a/play-ws-standalone-json/src/test/scala/play/api/libs/ws/JsonBodyReadablesSpec.scala +++ b/play-ws-standalone-json/src/test/scala/play/api/libs/ws/JsonBodyReadablesSpec.scala @@ -9,12 +9,11 @@ import java.nio.charset.StandardCharsets._ import akka.stream.scaladsl.Source import akka.util.ByteString -import org.specs2.matcher.MustMatchers -import org.specs2.mutable.Specification +import org.scalatest.wordspec.AnyWordSpec import play.api.libs.json.JsSuccess import play.api.libs.json.JsValue -class JsonBodyReadablesSpec extends Specification with MustMatchers { +class JsonBodyReadablesSpec extends AnyWordSpec { class StubResponse(byteArray: Array[Byte], charset: Charset = UTF_8) extends StandaloneWSResponse { override def uri: java.net.URI = ??? @@ -46,7 +45,7 @@ class JsonBodyReadablesSpec extends Specification with MustMatchers { val charsetName = "UTF-32BE" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charsetName), Charset.forName(charsetName))) - (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) + assert((value \ "menu" \ "id").validate[String] == JsSuccess("file")) } "read an encoding of UTF-32LE" in { @@ -55,7 +54,7 @@ class JsonBodyReadablesSpec extends Specification with MustMatchers { val charsetName = "UTF-32LE" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charsetName), Charset.forName(charsetName))) - (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) + assert((value \ "menu" \ "id").validate[String] == JsSuccess("file")) } "read an encoding of UTF-16BE" in { @@ -63,7 +62,7 @@ class JsonBodyReadablesSpec extends Specification with MustMatchers { val json = """{"menu": {"id": "file", "value": "File"} }""" val charset = UTF_16BE val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charset), charset)) - (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) + assert((value \ "menu" \ "id").validate[String] == JsSuccess("file")) } "read an encoding of UTF-16LE" in { @@ -71,28 +70,28 @@ class JsonBodyReadablesSpec extends Specification with MustMatchers { val json = """{"menu": {"id": "file", "value": "File"} }""" val charset = UTF_16LE val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(charset), charset)) - (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) + assert((value \ "menu" \ "id").validate[String] == JsSuccess("file")) } "read an encoding of UTF-8" in { val readables = new JsonBodyReadables() {} val json = """{"menu": {"id": "file", "value": "File"} }""" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(UTF_8))) - (value \ "menu" \ "id").validate[String] must beEqualTo(JsSuccess("file")) + assert((value \ "menu" \ "id").validate[String] == JsSuccess("file")) } "read an encoding of UTF-8 with empty object" in { val readables = new JsonBodyReadables() {} val json = "{}" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(UTF_8))) - value.toString() must beEqualTo("{}") + assert(value.toString() == "{}") } "read an encoding of UTF-8 with empty array" in { val readables = new JsonBodyReadables() {} val json = "[]" val value: JsValue = readables.readableAsJson.transform(new StubResponse(json.getBytes(UTF_8))) - value.toString() must beEqualTo("[]") + assert(value.toString() == "[]") } } diff --git a/play-ws-standalone/src/test/scala/play/api/libs/ws/WSConfigParserSpec.scala b/play-ws-standalone/src/test/scala/play/api/libs/ws/WSConfigParserSpec.scala index 7c71dc04..1e1a3a9b 100644 --- a/play-ws-standalone/src/test/scala/play/api/libs/ws/WSConfigParserSpec.scala +++ b/play-ws-standalone/src/test/scala/play/api/libs/ws/WSConfigParserSpec.scala @@ -4,12 +4,12 @@ package play.api.libs.ws -import org.specs2.mutable._ import com.typesafe.config.ConfigFactory +import org.scalatest.wordspec.AnyWordSpec import scala.concurrent.duration._ -class WSConfigParserSpec extends Specification { +class WSConfigParserSpec extends AnyWordSpec { "WSConfigParser" should { @@ -29,17 +29,17 @@ class WSConfigParserSpec extends Specification { |play.ws.useragent = "FakeUserAgent" """.stripMargin) - actual.connectionTimeout must_== 9999.millis - actual.idleTimeout must_== 666.millis - actual.requestTimeout must_== 1234.millis + assert(actual.connectionTimeout == 9999.millis) + assert(actual.idleTimeout == 666.millis) + assert(actual.requestTimeout == 1234.millis) // default: true - actual.followRedirects must beFalse + assert(actual.followRedirects == false) // default: true - actual.useProxyProperties must beFalse + assert(actual.useProxyProperties == false) - actual.userAgent must beSome[String].which(_ must_== "FakeUserAgent") + assert(actual.userAgent == Some("FakeUserAgent")) } } } diff --git a/project/Dependencies.scala b/project/Dependencies.scala index d93c7d5c..66ca7ae5 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -15,10 +15,7 @@ object Dependencies { val awaitility = Seq("org.awaitility" % "awaitility" % "4.2.0") - val specsVersion = "4.19.2" - val specsBuild = Seq( - "specs2-core", - ).map("org.specs2" %% _ % specsVersion) + val scalatest = Seq("org.scalatest" %% "scalatest-wordspec" % "3.2.15") val mockito = Seq("org.mockito" % "mockito-core" % "5.2.0") @@ -49,7 +46,7 @@ object Dependencies { val reactiveStreams = Seq("org.reactivestreams" % "reactive-streams" % "1.0.4") val testDependencies = - (mockito ++ specsBuild ++ junitInterface ++ assertj ++ awaitility ++ slf4jtest ++ logback).map(_ % Test) + (mockito ++ scalatest ++ junitInterface ++ assertj ++ awaitility ++ slf4jtest ++ logback).map(_ % Test) val standaloneApiWSDependencies = javaxInject ++ sslConfigCore ++ akkaStreams.map( _.exclude("com.typesafe", "*")