aboutsummaryrefslogtreecommitdiff
path: root/tests/src/test/scala/com/softwaremill/sttp/StreamingTests.scala
blob: b2b44a2bd4631d12ee14e5254465b8f2e93b148f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.softwaremill.sttp

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.softwaremill.sttp.streaming._
import com.softwaremill.sttp.testing.streaming.TestStreamingBackend
import com.typesafe.scalalogging.StrictLogging
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import scala.language.higherKinds

class StreamingTests
    extends FlatSpec
    with Matchers
    with BeforeAndAfterAll
    with StrictLogging
    with TestHttpServer
    with ForceWrapped {

  override val serverRoutes: Route =
    path("echo") {
      post {
        parameterMap { _ =>
          entity(as[String]) { body: String =>
            complete(body)
          }
        }
      }
    }

  override def port = 51824

  val body = "streaming test"

  var closeBackends: List[() => Unit] = Nil

  runTests("Akka Http", new AkkaHttpStreamingTests(actorSystem))
  runTests("Monix Async Http Client", new AsyncHttpClientMonixStreamingTests)
  runTests("Monix OkHttp", new OkHttpMonixStreamingTests)
  runTests("fs2 Async Http Client", new AsyncHttpClientFs2StreamingTests)

  def runTests[R[_], S](name: String, testStreamingBackend: TestStreamingBackend[R, S]): Unit = {
    import testStreamingBackend._

    closeBackends = (() => backend.close()) :: closeBackends

    name should "stream request body" in {
      val response = sttp
        .post(uri"$endpoint/echo")
        .streamBody(bodyProducer(body))
        .send()
        .force()

      response.unsafeBody shouldBe body
    }

    it should "receive a stream" in {
      val response = sttp
        .post(uri"$endpoint/echo")
        .body(body)
        .response(asStream[S])
        .send()
        .force()

      bodyConsumer(response.unsafeBody).force() shouldBe body
    }

    it should "receive a stream from an https site" in {
      val response = sttp
      // of course, you should never rely on the internet being available
      // in tests, but that's so much easier than setting up an https
      // testing server
        .get(uri"https://softwaremill.com")
        .response(asStream[S])
        .send()
        .force()

      bodyConsumer(response.unsafeBody).force() should include("</div>")
    }
  }

  override protected def afterAll(): Unit = {
    closeBackends.foreach(_())
    super.afterAll()
  }

}