Last active
August 29, 2015 14:01
-
-
Save magro/d275a71d97f330014126 to your computer and use it in GitHub Desktop.
Scalatest Plus Play Spec to test the WSMultipartHandler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package wsmultipart | |
import org.scalatestplus.play.{PlaySpec, OneServerPerSuite} | |
import org.scalatest.EitherValues | |
import play.api.mvc.Action | |
import play.api.mvc.Results._ | |
import play.api.libs.iteratee.{Done, Input, Cont, Iteratee, Enumerator} | |
import play.api.test.Helpers._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.collection.mutable | |
import play.api.test.FakeApplication | |
import play.api.libs.ws.WS | |
import WSMultipartHandler._ | |
class WSMultipartHandlerSpec extends PlaySpec with OneServerPerSuite with EitherValues { | |
private val multipartContent = | |
"""--frontier | |
|Content-Disposition: inline | |
|Content-Transfer-Encoding: 8bit | |
|Content-Type: text/plain | |
| | |
|foo | |
|--frontier | |
|Content-Disposition: inline | |
|Content-Transfer-Encoding: 8bit | |
|Content-Type: text/plain | |
| | |
|bar | |
|--frontier-- | |
""".stripMargin.trim().replaceAll("\n", "\r\n") | |
implicit override lazy val app: FakeApplication = | |
FakeApplication( | |
withRoutes = { | |
case ("GET", "/") => Action { | |
Ok(multipartContent).as("multipart/package; boundary=\"frontier\"") | |
} | |
} | |
) | |
"WSMultipartHandler" should { | |
"consume multipart response for WS.get" in { | |
val parts = mutable.ArrayBuffer[String]() | |
def partConsumer(headers: Map[String, String]): Iteratee[Array[Byte], Unit] = { | |
if(headers.isEmpty) Done((), Input.Empty) | |
else { | |
var buffer = Array[Byte]() | |
lazy val it: Iteratee[Array[Byte], Unit] = Cont { | |
case [email protected] => | |
parts += new String(buffer, "utf-8") | |
Done((), e) | |
case Input.El(data) => | |
buffer ++= data | |
it | |
case Input.Empty => it | |
} | |
it | |
} | |
} | |
val futureResponse = WS.url(s"http://localhost:$port") | |
.get(consumeMultipart(partConsumer)) | |
.flatMap(_.run) | |
val response = await(futureResponse) | |
response.right.value._1.status mustBe OK | |
response.right.value._2 mustBe 2 | |
parts mustBe mutable.ArrayBuffer("foo", "bar") | |
} | |
"check response status and reject non-200s" in { | |
val futureResponse = WS.url(s"http://localhost:$port/missingRoute").get( | |
consumeMultipart(ps => /*unused*/ ???) | |
).flatMap(_.run) | |
val response = await(futureResponse) | |
response.left.value.status mustBe NOT_FOUND | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment