aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/scala/com/softwaremill/sttp/testing/SttpBackendStub.scala
blob: f62959fd8f4f3534339057948ce928bb36c14d60 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.softwaremill.sttp.testing

import com.softwaremill.sttp.testing.SttpBackendStub._
import com.softwaremill.sttp.{MonadError, Request, Response, SttpBackend}

import scala.language.higherKinds

/**
  * A stub backend to use in tests.
  *
  * The stub can be configured to respond with a given response if the
  * request matches a predicate (see the [[whenRequestMatches()]] method).
  *
  * Note however, that this is not type-safe with respect to the type of the
  * response body - the stub doesn't have a way to check if the type of the
  * body in the configured response is the same as the one specified by the
  * request. Hence, the predicates can match requests basing on the URI
  * or headers. A [[ClassCastException]] might occur if for a given request,
  * a response is specified with the incorrect body type.
  */
class SttpBackendStub[R[_], S] private (rm: MonadError[R],
                                        matchers: Vector[Matcher[_]],
                                        fallback: Option[SttpBackend[R, S]])
    extends SttpBackend[R, S] {

  /**
    * Specify how the stub backend should respond to requests matching the
    * given predicate. Note that the stubs are immutable, and each new
    * specification that is added yields a new stub instance.
    */
  def whenRequestMatches(p: Request[_, _] => Boolean): WhenRequest =
    new WhenRequest(p)

  def whenRequestMatchesPartial(
      partial: PartialFunction[Request[_, _], Response[_]]) = {
    val m = Matcher(partial)
    val vector: Vector[Matcher[_]] = matchers :+ m
    new SttpBackendStub(rm, vector, fallback)
  }

  override def send[T](request: Request[T, S]): R[Response[T]] = {
    matchers
      .collectFirst {
        case matcher: Matcher[T @unchecked] if matcher(request) =>
          matcher.response(request).get
      } match {
      case Some(response) => wrapResponse(response)
      case None =>
        fallback match {
          case None     => wrapResponse(DefaultResponse)
          case Some(fb) => fb.send(request)
        }
    }
  }

  private def wrapResponse[T](r: Response[_]): R[Response[T]] =
    rm.unit(r.asInstanceOf[Response[T]])

  override def close(): Unit = {}

  override def responseMonad: MonadError[R] = rm

  class WhenRequest(p: Request[_, _] => Boolean) {
    def thenRespondOk(): SttpBackendStub[R, S] =
      thenRespondWithCode(200)
    def thenRespondNotFound(): SttpBackendStub[R, S] =
      thenRespondWithCode(404, "Not found")
    def thenRespondServerError(): SttpBackendStub[R, S] =
      thenRespondWithCode(500, "Internal server error")
    def thenRespondWithCode(code: Int,
                            msg: String = ""): SttpBackendStub[R, S] =
      thenRespond(Response[Nothing](Left(msg), code, Nil, Nil))
    def thenRespond[T](body: T): SttpBackendStub[R, S] =
      thenRespond(Response[T](Right(body), 200, Nil, Nil))
    def thenRespond[T](resp: Response[T]): SttpBackendStub[R, S] = {
      val m = Matcher[T](p, resp)
      new SttpBackendStub(rm, matchers :+ m, fallback)

    }
  }
}

object SttpBackendStub {

  /**
    * Create a stub backend for testing, which uses the same response wrappers
    * and supports the same stream type as the given "real" backend.
    *
    * @tparam S2 This is a work-around for the problem described here:
    *            [[https://stackoverflow.com/questions/46642623/cannot-infer-contravariant-nothing-type-parameter]].
    */
  def apply[R[_], S, S2 <: S](c: SttpBackend[R, S]): SttpBackendStub[R, S2] =
    new SttpBackendStub[R, S2](c.responseMonad, Vector.empty, None)

  /**
    * Create a stub backend using the given response monad (which determines
    * how requests are wrapped), and any stream type.
    */
  def apply[R[_], S](responseMonad: MonadError[R]): SttpBackendStub[R, S] =
    new SttpBackendStub[R, S](responseMonad, Vector.empty, None)

  /**
    * Create a stub backend which delegates send requests to the given fallback
    * backend, if the request doesn't match any of the specified predicates.
    */
  def withFallback[R[_], S, S2 <: S](
      fallback: SttpBackend[R, S]): SttpBackendStub[R, S2] =
    new SttpBackendStub[R, S2](fallback.responseMonad,
                               Vector.empty,
                               Some(fallback))

  private val DefaultResponse =
    Response[Nothing](Left("Not Found"), 404, Nil, Nil)

  private case class Matcher[T](
      p: PartialFunction[Request[T, _], Response[_]]) {

    def apply(request: Request[T, _]): Boolean =
      p.isDefinedAt(request)

    def response[S](request: Request[T, S]): Option[Response[T]] = {
      p.lift(request).asInstanceOf[Option[Response[T]]]
    }
  }

  private object Matcher {

    def apply[T](p: Request[T, _] => Boolean, response: Response[T]) = {
      new Matcher[T]({
        case r if p(r) => response
      })
    }
  }
}