diff options
author | adamw <adam@warski.org> | 2018-02-20 12:24:10 +0100 |
---|---|---|
committer | adamw <adam@warski.org> | 2018-02-20 12:24:10 +0100 |
commit | 52017e118df6cf22b95f4c10b6abe4162801a1ef (patch) | |
tree | 4acefa1d7de60c212c39b98bd93242e3b3db2791 /core | |
parent | e8b583709c9654c0ba16944a6242814d2355d4db (diff) | |
download | sttp-52017e118df6cf22b95f4c10b6abe4162801a1ef.tar.gz sttp-52017e118df6cf22b95f4c10b6abe4162801a1ef.tar.bz2 sttp-52017e118df6cf22b95f4c10b6abe4162801a1ef.zip |
New scalafmt settings
Diffstat (limited to 'core')
17 files changed, 167 insertions, 367 deletions
diff --git a/core/src/main/scala/com/softwaremill/sttp/FollowRedirectsBackend.scala b/core/src/main/scala/com/softwaremill/sttp/FollowRedirectsBackend.scala index 942f792..96c0213 100644 --- a/core/src/main/scala/com/softwaremill/sttp/FollowRedirectsBackend.scala +++ b/core/src/main/scala/com/softwaremill/sttp/FollowRedirectsBackend.scala @@ -4,15 +4,13 @@ import java.net.URI import scala.language.higherKinds -class FollowRedirectsBackend[R[_], S](delegate: SttpBackend[R, S]) - extends SttpBackend[R, S] { +class FollowRedirectsBackend[R[_], S](delegate: SttpBackend[R, S]) extends SttpBackend[R, S] { def send[T](request: Request[T, S]): R[Response[T]] = { sendWithCounter(request, 0) } - private def sendWithCounter[T](request: Request[T, S], - redirects: Int): R[Response[T]] = { + private def sendWithCounter[T](request: Request[T, S], redirects: Int): R[Response[T]] = { // if there are nested follow redirect backends, disabling them and handling redirects here val resp = delegate.send(request.followRedirects(false)) if (request.options.followRedirects) { @@ -28,14 +26,11 @@ class FollowRedirectsBackend[R[_], S](delegate: SttpBackend[R, S]) } } - private def followRedirect[T](request: Request[T, S], - response: Response[T], - redirects: Int): R[Response[T]] = { + private def followRedirect[T](request: Request[T, S], response: Response[T], redirects: Int): R[Response[T]] = { response.header(LocationHeader).fold(responseMonad.unit(response)) { loc => if (redirects >= FollowRedirectsBackend.MaxRedirects) { - responseMonad.unit( - Response(Left("Too many redirects"), 0, "", Nil, Nil)) + responseMonad.unit(Response(Left("Too many redirects"), 0, "", Nil, Nil)) } else { followRedirect(request, response, redirects, loc) } diff --git a/core/src/main/scala/com/softwaremill/sttp/HttpURLConnectionBackend.scala b/core/src/main/scala/com/softwaremill/sttp/HttpURLConnectionBackend.scala index 113ce48..4eca5dd 100644 --- a/core/src/main/scala/com/softwaremill/sttp/HttpURLConnectionBackend.scala +++ b/core/src/main/scala/com/softwaremill/sttp/HttpURLConnectionBackend.scala @@ -13,9 +13,7 @@ import scala.collection.JavaConverters._ import scala.concurrent.duration.Duration import scala.io.Source -class HttpURLConnectionBackend private ( - opts: SttpBackendOptions, - customizeConnection: HttpURLConnection => Unit) +class HttpURLConnectionBackend private (opts: SttpBackendOptions, customizeConnection: HttpURLConnection => Unit) extends SttpBackend[Id, Nothing] { override def send[T](r: Request[T, Nothing]): Response[T] = { @@ -66,8 +64,7 @@ class HttpURLConnectionBackend private ( conn.asInstanceOf[HttpURLConnection] } - private def writeBody(body: RequestBody[Nothing], - c: HttpURLConnection): Option[OutputStream] = { + private def writeBody(body: RequestBody[Nothing], c: HttpURLConnection): Option[OutputStream] = { body match { case NoBody => // skip @@ -118,8 +115,7 @@ class HttpURLConnectionBackend private ( private val BoundaryChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray - private def setMultipartBody(mp: MultipartBody, - c: HttpURLConnection): Option[OutputStream] = { + private def setMultipartBody(mp: MultipartBody, c: HttpURLConnection): Option[OutputStream] = { val boundary = { val tlr = ThreadLocalRandom.current() List @@ -160,16 +156,14 @@ class HttpURLConnectionBackend private ( val headersLen = headers.getBytes(Iso88591).length - bodyLen.map(bl => - dashesLen + boundaryLen + crLfLen + headersLen + crLfLen + crLfLen + bl + crLfLen) + bodyLen.map(bl => dashesLen + boundaryLen + crLfLen + headersLen + crLfLen + crLfLen + bl + crLfLen) } .foldLeft(Option(finalBoundaryLen)) { case (Some(acc), Some(l)) => Some(acc + l) case _ => None } - c.setRequestProperty(ContentTypeHeader, - "multipart/form-data; boundary=" + boundary) + c.setRequestProperty(ContentTypeHeader, "multipart/form-data; boundary=" + boundary) contentLength.foreach { cl => c.setFixedLengthStreamingMode(cl) @@ -205,10 +199,9 @@ class HttpURLConnectionBackend private ( Some(os) } - private def readResponse[T]( - c: HttpURLConnection, - is: InputStream, - responseAs: ResponseAs[T, Nothing]): Response[T] = { + private def readResponse[T](c: HttpURLConnection, + is: InputStream, + responseAs: ResponseAs[T, Nothing]): Response[T] = { val headers = c.getHeaderFields.asScala.toVector .filter(_._1 != null) @@ -229,9 +222,7 @@ class HttpURLConnectionBackend private ( Response(body, code, c.getResponseMessage, headers, Nil) } - private def readResponseBody[T](is: InputStream, - responseAs: ResponseAs[T, Nothing], - charset: Option[String]): T = { + private def readResponseBody[T](is: InputStream, responseAs: ResponseAs[T, Nothing], charset: Option[String]): T = { def asString(enc: String) = Source.fromInputStream(is, charset.getOrElse(enc)).mkString @@ -266,8 +257,7 @@ class HttpURLConnectionBackend private ( else is - private def wrapInput(contentEncoding: Option[String], - is: InputStream): InputStream = + private def wrapInput(contentEncoding: Option[String], is: InputStream): InputStream = contentEncoding.map(_.toLowerCase) match { case None => is case Some("gzip") => new GZIPInputStream(is) @@ -281,10 +271,9 @@ class HttpURLConnectionBackend private ( object HttpURLConnectionBackend { - def apply(options: SttpBackendOptions = SttpBackendOptions.Default, - customizeConnection: HttpURLConnection => Unit = { _ => - () - }): SttpBackend[Id, Nothing] = - new FollowRedirectsBackend[Id, Nothing]( - new HttpURLConnectionBackend(options, customizeConnection)) + def apply(options: SttpBackendOptions = SttpBackendOptions.Default, customizeConnection: HttpURLConnection => Unit = { + _ => + () + }): SttpBackend[Id, Nothing] = + new FollowRedirectsBackend[Id, Nothing](new HttpURLConnectionBackend(options, customizeConnection)) } diff --git a/core/src/main/scala/com/softwaremill/sttp/MonadError.scala b/core/src/main/scala/com/softwaremill/sttp/MonadError.scala index 5751382..a783765 100644 --- a/core/src/main/scala/com/softwaremill/sttp/MonadError.scala +++ b/core/src/main/scala/com/softwaremill/sttp/MonadError.scala @@ -10,8 +10,7 @@ trait MonadError[R[_]] { def flatMap[T, T2](fa: R[T])(f: T => R[T2]): R[T2] def error[T](t: Throwable): R[T] - protected def handleWrappedError[T](rt: R[T])( - h: PartialFunction[Throwable, R[T]]): R[T] + protected def handleWrappedError[T](rt: R[T])(h: PartialFunction[Throwable, R[T]]): R[T] def handleError[T](rt: => R[T])(h: PartialFunction[Throwable, R[T]]): R[T] = { Try(rt) match { case Success(v) => handleWrappedError(v)(h) @@ -38,8 +37,7 @@ object IdMonad extends MonadError[Id] { override def flatMap[T, T2](fa: Id[T])(f: (T) => Id[T2]): Id[T2] = f(fa) override def error[T](t: Throwable): Id[T] = throw t - override protected def handleWrappedError[T](rt: Id[T])( - h: PartialFunction[Throwable, Id[T]]): Id[T] = rt + override protected def handleWrappedError[T](rt: Id[T])(h: PartialFunction[Throwable, Id[T]]): Id[T] = rt } object TryMonad extends MonadError[Try] { override def unit[T](t: T): Try[T] = Success(t) @@ -48,11 +46,10 @@ object TryMonad extends MonadError[Try] { fa.flatMap(f) override def error[T](t: Throwable): Try[T] = Failure(t) - override protected def handleWrappedError[T](rt: Try[T])( - h: PartialFunction[Throwable, Try[T]]): Try[T] = rt.recoverWith(h) + override protected def handleWrappedError[T](rt: Try[T])(h: PartialFunction[Throwable, Try[T]]): Try[T] = + rt.recoverWith(h) } -class FutureMonad(implicit ec: ExecutionContext) - extends MonadAsyncError[Future] { +class FutureMonad(implicit ec: ExecutionContext) extends MonadAsyncError[Future] { override def unit[T](t: T): Future[T] = Future.successful(t) override def map[T, T2](fa: Future[T])(f: (T) => T2): Future[T2] = fa.map(f) @@ -60,11 +57,10 @@ class FutureMonad(implicit ec: ExecutionContext) fa.flatMap(f) override def error[T](t: Throwable): Future[T] = Future.failed(t) - override protected def handleWrappedError[T](rt: Future[T])( - h: PartialFunction[Throwable, Future[T]]): Future[T] = rt.recoverWith(h) + override protected def handleWrappedError[T](rt: Future[T])(h: PartialFunction[Throwable, Future[T]]): Future[T] = + rt.recoverWith(h) - override def async[T]( - register: ((Either[Throwable, T]) => Unit) => Unit): Future[T] = { + override def async[T](register: ((Either[Throwable, T]) => Unit) => Unit): Future[T] = { val p = Promise[T]() register { case Left(t) => p.failure(t) diff --git a/core/src/main/scala/com/softwaremill/sttp/RequestBody.scala b/core/src/main/scala/com/softwaremill/sttp/RequestBody.scala index a8be76b..a95a38b 100644 --- a/core/src/main/scala/com/softwaremill/sttp/RequestBody.scala +++ b/core/src/main/scala/com/softwaremill/sttp/RequestBody.scala @@ -45,8 +45,7 @@ case class StreamBody[S](s: S) extends RequestBody[S] case class MultipartBody(parts: Seq[Multipart]) extends RequestBody[Nothing] object RequestBody { - private[sttp] def paramsToStringBody(fs: Seq[(String, String)], - encoding: String): StringBody = { + private[sttp] def paramsToStringBody(fs: Seq[(String, String)], encoding: String): StringBody = { val b = fs .map { diff --git a/core/src/main/scala/com/softwaremill/sttp/RequestT.scala b/core/src/main/scala/com/softwaremill/sttp/RequestT.scala index 320efef..26eb0f1 100644 --- a/core/src/main/scala/com/softwaremill/sttp/RequestT.scala +++ b/core/src/main/scala/com/softwaremill/sttp/RequestT.scala @@ -55,14 +55,10 @@ case class RequestT[U[_], T, +S]( def contentType(ct: String): RequestT[U, T, S] = header(ContentTypeHeader, ct, replaceExisting = true) def contentType(ct: String, encoding: String): RequestT[U, T, S] = - header(ContentTypeHeader, - contentTypeWithEncoding(ct, encoding), - replaceExisting = true) + header(ContentTypeHeader, contentTypeWithEncoding(ct, encoding), replaceExisting = true) def contentLength(l: Long): RequestT[U, T, S] = header(ContentLengthHeader, l.toString, replaceExisting = true) - def header(k: String, - v: String, - replaceExisting: Boolean = false): RequestT[U, T, S] = { + def header(k: String, v: String, replaceExisting: Boolean = false): RequestT[U, T, S] = { val current = if (replaceExisting) headers.filterNot(_._1.equalsIgnoreCase(k)) @@ -233,8 +229,7 @@ case class RequestT[U[_], T, +S]( def tag(k: String): Option[Any] = tags.get(k) - def send[R[_]]()(implicit backend: SttpBackend[R, S], - isIdInRequest: IsIdInRequest[U]): R[Response[T]] = { + def send[R[_]]()(implicit backend: SttpBackend[R, S], isIdInRequest: IsIdInRequest[U]): R[Response[T]] = { // we could avoid the asInstanceOf by creating an artificial copy // changing the method & url fields using `isIdInRequest`, but that // would be only to satisfy the type checker, and a needless copy at @@ -263,8 +258,7 @@ case class RequestT[U[_], T, +S]( private def setContentLengthIfMissing(l: => Long): RequestT[U, T, S] = if (hasContentLength) this else contentLength(l) - private def formDataBody(fs: Seq[(String, String)], - encoding: String): RequestT[U, T, S] = { + private def formDataBody(fs: Seq[(String, String)], encoding: String): RequestT[U, T, S] = { val b = RequestBody.paramsToStringBody(fs, encoding) setContentTypeIfMissing(ApplicationFormContentType) .setContentLengthIfMissing(b.s.getBytes(encoding).length) @@ -274,9 +268,7 @@ case class RequestT[U[_], T, +S]( class SpecifyAuthScheme[U[_], T, +S](hn: String, rt: RequestT[U, T, S]) { def basic(user: String, password: String): RequestT[U, T, S] = { - val c = new String( - Base64.getEncoder.encode(s"$user:$password".getBytes(Utf8)), - Utf8) + val c = new String(Base64.getEncoder.encode(s"$user:$password".getBytes(Utf8)), Utf8) rt.header(hn, s"Basic $c") } diff --git a/core/src/main/scala/com/softwaremill/sttp/Response.scala b/core/src/main/scala/com/softwaremill/sttp/Response.scala index e38ae4a..5762845 100644 --- a/core/src/main/scala/com/softwaremill/sttp/Response.scala +++ b/core/src/main/scala/com/softwaremill/sttp/Response.scala @@ -105,8 +105,7 @@ object Cookie { * Modified version of `HttpCookie.expiryDate2DeltaSeconds` to return a * `ZonedDateTime`, not a second-delta. */ - private def expiryDate2ZonedDateTime( - dateString: String): Option[ZonedDateTime] = { + private def expiryDate2ZonedDateTime(dateString: String): Option[ZonedDateTime] = { val cal = new GregorianCalendar(Gmt) CookieDateFormats.foreach { format => val df = new SimpleDateFormat(format, Locale.US) diff --git a/core/src/main/scala/com/softwaremill/sttp/ResponseAs.scala b/core/src/main/scala/com/softwaremill/sttp/ResponseAs.scala index 2bf4c35..2916043 100644 --- a/core/src/main/scala/com/softwaremill/sttp/ResponseAs.scala +++ b/core/src/main/scala/com/softwaremill/sttp/ResponseAs.scala @@ -25,44 +25,35 @@ sealed trait BasicResponseAs[T, +S] extends ResponseAs[T, S] { } case object IgnoreResponse extends BasicResponseAs[Unit, Nothing] -case class ResponseAsString(encoding: String) - extends BasicResponseAs[String, Nothing] +case class ResponseAsString(encoding: String) extends BasicResponseAs[String, Nothing] case object ResponseAsByteArray extends BasicResponseAs[Array[Byte], Nothing] -case class ResponseAsStream[T, S]()(implicit val responseIsStream: S =:= T) - extends BasicResponseAs[T, S] +case class ResponseAsStream[T, S]()(implicit val responseIsStream: S =:= T) extends BasicResponseAs[T, S] -case class MappedResponseAs[T, T2, S](raw: BasicResponseAs[T, S], g: T => T2) - extends ResponseAs[T2, S] { +case class MappedResponseAs[T, T2, S](raw: BasicResponseAs[T, S], g: T => T2) extends ResponseAs[T2, S] { override def map[T3](f: T2 => T3): ResponseAs[T3, S] = MappedResponseAs[T, T3, S](raw, g andThen f) } -case class ResponseAsFile(output: File, overwrite: Boolean) - extends BasicResponseAs[File, Nothing] +case class ResponseAsFile(output: File, overwrite: Boolean) extends BasicResponseAs[File, Nothing] object ResponseAs { - private[sttp] def parseParams(s: String, - encoding: String): Seq[(String, String)] = { + private[sttp] def parseParams(s: String, encoding: String): Seq[(String, String)] = { s.split("&") .toList .flatMap(kv => kv.split("=", 2) match { case Array(k, v) => - Some( - (URLDecoder.decode(k, encoding), URLDecoder.decode(v, encoding))) + Some((URLDecoder.decode(k, encoding), URLDecoder.decode(v, encoding))) case _ => None }) } - private[sttp] def saveFile(file: File, - is: InputStream, - overwrite: Boolean): File = { + private[sttp] def saveFile(file: File, is: InputStream, overwrite: Boolean): File = { if (!file.exists()) { file.getParentFile.mkdirs() file.createNewFile() } else if (!overwrite) { - throw new IOException( - s"File ${file.getAbsolutePath} exists - overwriting prohibited") + throw new IOException(s"File ${file.getAbsolutePath} exists - overwriting prohibited") } val os = new FileOutputStream(file) @@ -80,8 +71,7 @@ object ResponseAs { private[sttp] trait EagerResponseHandler[S] { def handleBasic[T](bra: BasicResponseAs[T, S]): Try[T] - def handle[T, R[_]](responseAs: ResponseAs[T, S], - responseMonad: MonadError[R]): R[T] = { + def handle[T, R[_]](responseAs: ResponseAs[T, S], responseMonad: MonadError[R]): R[T] = { responseAs match { case mra @ MappedResponseAs(raw, g) => diff --git a/core/src/main/scala/com/softwaremill/sttp/SttpBackendOptions.scala b/core/src/main/scala/com/softwaremill/sttp/SttpBackendOptions.scala index 026d4d0..89fb542 100644 --- a/core/src/main/scala/com/softwaremill/sttp/SttpBackendOptions.scala +++ b/core/src/main/scala/com/softwaremill/sttp/SttpBackendOptions.scala @@ -56,10 +56,7 @@ object SttpBackendOptions { Empty.socksProxy(host, port) private def loadSystemProxy: Option[Proxy] = { - def system(hostProp: String, - portProp: String, - make: (String, Int) => Proxy, - defaultPort: Int) = { + def system(hostProp: String, portProp: String, make: (String, Int) => Proxy, defaultPort: Int) = { val host = Option(System.getProperty(hostProp)) def port = Try(System.getProperty(portProp).toInt).getOrElse(defaultPort) host.map(make(_, port)) diff --git a/core/src/main/scala/com/softwaremill/sttp/TryBackend.scala b/core/src/main/scala/com/softwaremill/sttp/TryBackend.scala index 58e9548..9e56aef 100644 --- a/core/src/main/scala/com/softwaremill/sttp/TryBackend.scala +++ b/core/src/main/scala/com/softwaremill/sttp/TryBackend.scala @@ -21,8 +21,6 @@ class TryBackend[-S](delegate: SttpBackend[Id, S]) extends SttpBackend[Try, S] { object TryHttpURLConnectionBackend { def apply(options: SttpBackendOptions = SttpBackendOptions.Default, - customizeConnection: HttpURLConnection => Unit = _ => ()) - : SttpBackend[Try, Nothing] = - new TryBackend[Nothing]( - HttpURLConnectionBackend(options, customizeConnection)) + customizeConnection: HttpURLConnection => Unit = _ => ()): SttpBackend[Try, Nothing] = + new TryBackend[Nothing](HttpURLConnectionBackend(options, customizeConnection)) } diff --git a/core/src/main/scala/com/softwaremill/sttp/Uri.scala b/core/src/main/scala/com/softwaremill/sttp/Uri.scala index 16936cc..7ae0013 100644 --- a/core/src/main/scala/com/softwaremill/sttp/Uri.scala +++ b/core/src/main/scala/com/softwaremill/sttp/Uri.scala @@ -96,30 +96,26 @@ case class Uri(scheme: String, override def toString: String = { def encodeUserInfo(ui: UserInfo): String = - encode(Rfc3986.UserInfo)(ui.username) + ui.password.fold("")( - ":" + encode(Rfc3986.UserInfo)(_)) + encode(Rfc3986.UserInfo)(ui.username) + ui.password.fold("")(":" + encode(Rfc3986.UserInfo)(_)) @tailrec - def encodeQueryFragments(qfs: List[QueryFragment], - previousWasPlain: Boolean, - sb: StringBuilder): String = qfs match { - case Nil => sb.toString() - - case Plain(v, re) :: t => - encodeQueryFragments(t, - previousWasPlain = true, - sb.append(encodeQuery(v, re))) - - case Value(v, re) :: t => - if (!previousWasPlain) sb.append("&") - sb.append(encodeQuery(v, re)) - encodeQueryFragments(t, previousWasPlain = false, sb) - - case KeyValue(k, v, reK, reV) :: t => - if (!previousWasPlain) sb.append("&") - sb.append(encodeQuery(k, reK)).append("=").append(encodeQuery(v, reV)) - encodeQueryFragments(t, previousWasPlain = false, sb) - } + def encodeQueryFragments(qfs: List[QueryFragment], previousWasPlain: Boolean, sb: StringBuilder): String = + qfs match { + case Nil => sb.toString() + + case Plain(v, re) :: t => + encodeQueryFragments(t, previousWasPlain = true, sb.append(encodeQuery(v, re))) + + case Value(v, re) :: t => + if (!previousWasPlain) sb.append("&") + sb.append(encodeQuery(v, re)) + encodeQueryFragments(t, previousWasPlain = false, sb) + + case KeyValue(k, v, reK, reV) :: t => + if (!previousWasPlain) sb.append("&") + sb.append(encodeQuery(k, reK)).append("=").append(encodeQuery(v, reV)) + encodeQueryFragments(t, previousWasPlain = false, sb) + } val schemeS = encode(Rfc3986.Scheme)(scheme) val userInfoS = userInfo.fold("")(encodeUserInfo(_) + "@") @@ -129,9 +125,7 @@ case class Uri(scheme: String, val pathS = path.map(encode(Rfc3986.PathSegment)).mkString("/") val queryPrefixS = if (queryFragments.isEmpty) "" else "?" - val queryS = encodeQueryFragments(queryFragments.toList, - previousWasPlain = true, - new StringBuilder()) + val queryS = encodeQueryFragments(queryFragments.toList, previousWasPlain = true, new StringBuilder()) // https://stackoverflow.com/questions/2053132/is-a-colon-safe-for-friendly-url-use/2053640#2053640 val fragS = fragment.fold("")("#" + encode(Rfc3986.Fragment)(_)) @@ -143,9 +137,7 @@ case class Uri(scheme: String, e match { case QueryFragmentEncoding.All => URLEncoder.encode(s, "UTF-8") case QueryFragmentEncoding.Standard => - encode(Rfc3986.QueryNoStandardDelims, - spaceAsPlus = true, - encodePlus = true)(s) + encode(Rfc3986.QueryNoStandardDelims, spaceAsPlus = true, encodePlus = true)(s) case QueryFragmentEncoding.Relaxed => encode(Rfc3986.Query, spaceAsPlus = true)(s) } @@ -182,9 +174,8 @@ case class Uri(scheme: String, * @param encodePlus Should `+` (which is the encoded form of space * in the query) be %-encoded. */ - private def encode(allowedCharacters: Set[Char], - spaceAsPlus: Boolean = false, - encodePlus: Boolean = false)(s: String): String = { + private def encode(allowedCharacters: Set[Char], spaceAsPlus: Boolean = false, encodePlus: Boolean = false)( + s: String): String = { val sb = new StringBuilder() // based on https://gist.github.com/teigen/5865923 for (c <- s) { @@ -226,19 +217,16 @@ object Uri { * @param keyEncoding See [[Plain.encoding]] * @param valueEncoding See [[Plain.encoding]] */ - case class KeyValue( - k: String, - v: String, - keyEncoding: QueryFragmentEncoding = QueryFragmentEncoding.Standard, - valueEncoding: QueryFragmentEncoding = QueryFragmentEncoding.Standard) + case class KeyValue(k: String, + v: String, + keyEncoding: QueryFragmentEncoding = QueryFragmentEncoding.Standard, + valueEncoding: QueryFragmentEncoding = QueryFragmentEncoding.Standard) extends QueryFragment /** * A query fragment which contains only the value, without a key. */ - case class Value(v: String, - relaxedEncoding: QueryFragmentEncoding = - QueryFragmentEncoding.Standard) + case class Value(v: String, relaxedEncoding: QueryFragmentEncoding = QueryFragmentEncoding.Standard) extends QueryFragment /** @@ -256,10 +244,7 @@ object Uri { * [[https://stackoverflow.com/questions/2322764/what-characters-must-be-escaped-in-an-http-query-string]] * [[https://stackoverflow.com/questions/2366260/whats-valid-and-whats-not-in-a-uri-query]] */ - case class Plain(v: String, - encoding: QueryFragmentEncoding = - QueryFragmentEncoding.Standard) - extends QueryFragment + case class Plain(v: String, encoding: QueryFragmentEncoding = QueryFragmentEncoding.Standard) extends QueryFragment } sealed trait QueryFragmentEncoding diff --git a/core/src/main/scala/com/softwaremill/sttp/UriInterpolator.scala b/core/src/main/scala/com/softwaremill/sttp/UriInterpolator.scala index 8d0024a..be3edb6 100644 --- a/core/src/main/scala/com/softwaremill/sttp/UriInterpolator.scala +++ b/core/src/main/scala/com/softwaremill/sttp/UriInterpolator.scala @@ -27,8 +27,7 @@ object UriInterpolator { } if (leftTokens.nonEmpty) { - throw new IllegalStateException( - s"Tokens left after building the whole uri: $leftTokens, result so far: $uri") + throw new IllegalStateException(s"Tokens left after building the whole uri: $leftTokens, result so far: $uri") } uri @@ -50,8 +49,7 @@ object UriInterpolator { // way it's possible to extend existing URIs. Without special-casing // the embedded URI would be escaped and become part of the host // as a whole. - if (tokens == Vector(StringToken("")) && nextExpressionStr.contains( - "://")) { + if (tokens == Vector(StringToken("")) && nextExpressionStr.contains("://")) { def tokenizeExpressionAsString(): Unit = { val (nextTokenizer, nextTokens) = tokenizer.tokenize(nextExpression.toString) @@ -145,9 +143,7 @@ object UriInterpolator { s, this, Set('/', '?', '#'), - Map(':' -> ColonInAuthority, - '@' -> AtInAuthority, - '.' -> DotInAuthority), + Map(':' -> ColonInAuthority, '@' -> AtInAuthority, '.' -> DotInAuthority), ipv6parser ) } @@ -193,8 +189,7 @@ object UriInterpolator { current: Tokenizer, terminators: Set[Char], separatorsToTokens: Map[Char, Token], - extraFragmentParser: String => Option[Vector[Token]] = _ => None) - : (Tokenizer, Vector[Token]) = { + extraFragmentParser: String => Option[Vector[Token]] = _ => None): (Tokenizer, Vector[Token]) = { def tokenizeFragment(f: String): Vector[Token] = { extraFragmentParser(f) match { @@ -222,26 +217,23 @@ object UriInterpolator { } } - private def tokenizeAfterSeparator( - beforeSeparatorTokens: Vector[Token], - separator: Char, - s: String): (Tokenizer, Vector[Token]) = { + private def tokenizeAfterSeparator(beforeSeparatorTokens: Vector[Token], + separator: Char, + s: String): (Tokenizer, Vector[Token]) = { val (next, separatorToken) = separatorTokenizerAndToken(separator) val (nextNext, nextTokens) = next.tokenize(s) (nextNext, beforeSeparatorTokens ++ Vector(separatorToken) ++ nextTokens) } - private def separatorTokenizerAndToken( - separator: Char): (Tokenizer, Token) = + private def separatorTokenizerAndToken(separator: Char): (Tokenizer, Token) = separator match { case '/' => (Path, PathStart) case '?' => (Query, QueryStart) case '#' => (Fragment, FragmentStart) } - private def splitPreserveSeparators(s: String, - sep: Set[Char]): Vector[String] = { + private def splitPreserveSeparators(s: String, sep: Set[Char]): Vector[String] = { @tailrec def doSplit(s: String, acc: Vector[String]): Vector[String] = { split(s, sep) match { @@ -254,9 +246,7 @@ object UriInterpolator { doSplit(s, Vector.empty) } - private def split( - s: String, - sep: Set[Char]): Either[String, (String, Char, String)] = { + private def split(s: String, sep: Set[Char]): Either[String, (String, Char, String)] = { val i = s.indexWhere(sep.contains) if (i == -1) Left(s) else Right((s.substring(0, i), s.charAt(i), s.substring(i + 1))) @@ -270,8 +260,7 @@ object UriInterpolator { object UriBuilder { case object Scheme extends UriBuilder { - override def fromTokens(u: Uri, - t: Vector[Token]): (Uri, Vector[Token]) = { + override def fromTokens(u: Uri, t: Vector[Token]): (Uri, Vector[Token]) = { split(t, Set[Token](SchemeEnd)) match { case Left(tt) => (u.scheme("http"), tt) case Right((schemeTokens, _, otherTokens)) => @@ -282,8 +271,7 @@ object UriInterpolator { } case object UserInfo extends UriBuilder { - override def fromTokens(u: Uri, - t: Vector[Token]): (Uri, Vector[Token]) = { + override def fromTokens(u: Uri, t: Vector[Token]): (Uri, Vector[Token]) = { split(t, Set[Token](AtInAuthority)) match { case Left(tt) => (u, tt) case Right((uiTokens, _, otherTokens)) => @@ -303,9 +291,7 @@ object UriInterpolator { } } - private def uiFromTokens(u: Uri, - usernameTokens: Vector[Token], - passwordTokens: Vector[Token]): Uri = { + private def uiFromTokens(u: Uri, usernameTokens: Vector[Token], passwordTokens: Vector[Token]): Uri = { (tokensToStringOpt(usernameTokens), tokensToStringOpt(passwordTokens)) match { case (Some(un), Some(p)) => u.userInfo(un, p) @@ -317,8 +303,7 @@ object UriInterpolator { } case object HostPort extends UriBuilder { - override def fromTokens(u: Uri, - t: Vector[Token]): (Uri, Vector[Token]) = { + override def fromTokens(u: Uri, t: Vector[Token]): (Uri, Vector[Token]) = { split(t, Set[Token](PathStart, QueryStart, FragmentStart)) match { case Left(tt) => (hostPortFromTokens(u, tt), Vector.empty) @@ -327,8 +312,7 @@ object UriInterpolator { } } - private def hostPortFromTokens(u: Uri, - rawHpTokens: Vector[Token]): Uri = { + private def hostPortFromTokens(u: Uri, rawHpTokens: Vector[Token]): Uri = { // Special case: if the host/port part contains an expression token, // which has a string representation which contains a colon (:), then // we assume that the intention was to embed the port and host separately, @@ -367,11 +351,7 @@ object UriInterpolator { case object Path extends UriBuilder { override def fromTokens(u: Uri, t: Vector[Token]): (Uri, Vector[Token]) = - fromStartingToken(u, - t, - PathStart, - Set[Token](QueryStart, FragmentStart), - pathFromTokens) + fromStartingToken(u, t, PathStart, Set[Token](QueryStart, FragmentStart), pathFromTokens) private def pathFromTokens(u: Uri, tokens: Vector[Token]): Uri = { u.path(tokensToStringSeq(tokens)) @@ -383,11 +363,7 @@ object UriInterpolator { import com.softwaremill.sttp.Uri.{QueryFragment => QF} override def fromTokens(u: Uri, t: Vector[Token]): (Uri, Vector[Token]) = - fromStartingToken(u, - t, - QueryStart, - Set[Token](FragmentStart), - queryFromTokens) + fromStartingToken(u, t, QueryStart, Set[Token](FragmentStart), queryFromTokens) private def queryFromTokens(u: Uri, tokens: Vector[Token]): Uri = { val qfs = @@ -398,8 +374,7 @@ object UriInterpolator { } private def queryMappingsFromTokens(tokens: Vector[Token]): Vector[QF] = { - def expressionPairToQueryFragment(ke: Any, - ve: Any): Option[QF.KeyValue] = + def expressionPairToQueryFragment(ke: Any, ve: Any): Option[QF.KeyValue] = for { k <- anyToStringOpt(ke) v <- anyToStringOpt(ve) @@ -431,8 +406,7 @@ object UriInterpolator { } case object Fragment extends UriBuilder { - override def fromTokens(u: Uri, - t: Vector[Token]): (Uri, Vector[Token]) = { + override def fromTokens(u: Uri, t: Vector[Token]): (Uri, Vector[Token]) = { t match { case FragmentStart +: tt => (u.fragment(tokensToStringOpt(tt)), Vector.empty) @@ -449,13 +423,11 @@ object UriInterpolator { * * The component is terminated by any of `nextComponentTokens`. */ - private def fromStartingToken( - u: Uri, - t: Vector[Token], - startingToken: Token, - nextComponentTokens: Set[Token], - componentFromTokens: (Uri, Vector[Token]) => Uri) - : (Uri, Vector[Token]) = { + private def fromStartingToken(u: Uri, + t: Vector[Token], + startingToken: Token, + nextComponentTokens: Set[Token], + componentFromTokens: (Uri, Vector[Token]) => Uri): (Uri, Vector[Token]) = { t match { case `startingToken` +: tt => @@ -536,9 +508,7 @@ object UriInterpolator { } .mkString("") - private def split[T]( - v: Vector[T], - sep: Set[T]): Either[Vector[T], (Vector[T], T, Vector[T])] = { + private def split[T](v: Vector[T], sep: Set[T]): Either[Vector[T], (Vector[T], T, Vector[T])] = { val i = v.indexWhere(sep.contains) if (i == -1) Left(v) else Right((v.take(i), v(i), v.drop(i + 1))) } @@ -567,8 +537,7 @@ object UriInterpolator { * These empty string tokens need to be removed so that e.g. extra key-value * mappings are not generated. */ - private def removeEmptyTokensAroundExp( - tokens: Vector[Token]): Vector[Token] = { + private def removeEmptyTokensAroundExp(tokens: Vector[Token]): Vector[Token] = { def doRemove(t: Vector[Token], acc: Vector[Token]): Vector[Token] = t match { case StringToken("") +: (e: ExpressionToken) +: tail => diff --git a/core/src/main/scala/com/softwaremill/sttp/package.scala b/core/src/main/scala/com/softwaremill/sttp/package.scala index f47e113..8bd6a4b 100644 --- a/core/src/main/scala/com/softwaremill/sttp/package.scala +++ b/core/src/main/scala/com/softwaremill/sttp/package.scala @@ -59,14 +59,13 @@ package object sttp { * An empty request with no headers. */ val emptyRequest: RequestT[Empty, String, Nothing] = - RequestT[Empty, String, Nothing]( - None, - None, - NoBody, - Vector(), - asString, - RequestOptions(followRedirects = true, readTimeout = DefaultReadTimeout), - Map()) + RequestT[Empty, String, Nothing](None, + None, + NoBody, + Vector(), + asString, + RequestOptions(followRedirects = true, readTimeout = DefaultReadTimeout), + Map()) /** * A starting request, with the following modifications comparing to @@ -109,12 +108,10 @@ package object sttp { def asStream[S]: ResponseAs[S, S] = ResponseAsStream[S, S]() - def asFile(file: File, - overwrite: Boolean = false): ResponseAs[File, Nothing] = + def asFile(file: File, overwrite: Boolean = false): ResponseAs[File, Nothing] = ResponseAsFile(file, overwrite) - def asPath(path: Path, - overwrite: Boolean = false): ResponseAs[Path, Nothing] = + def asPath(path: Path, overwrite: Boolean = false): ResponseAs[Path, Nothing] = ResponseAsFile(path.toFile, overwrite).map(_.toPath) // multipart factory methods @@ -124,47 +121,35 @@ package object sttp { * overridden later using the `contentType` method. */ def multipart(name: String, data: String): Multipart = - Multipart(name, - StringBody(data, Utf8), - contentType = - Some(contentTypeWithEncoding(TextPlainContentType, Utf8))) + Multipart(name, StringBody(data, Utf8), contentType = Some(contentTypeWithEncoding(TextPlainContentType, Utf8))) /** * Content type will be set to `text/plain` with `utf-8` encoding, can be * overridden later using the `contentType` method. */ def multipart(name: String, data: String, encoding: String): Multipart = - Multipart(name, - StringBody(data, encoding), - contentType = - Some(contentTypeWithEncoding(TextPlainContentType, Utf8))) + Multipart(name, StringBody(data, encoding), contentType = Some(contentTypeWithEncoding(TextPlainContentType, Utf8))) /** * Content type will be set to `application/octet-stream`, can be overridden * later using the `contentType` method. */ def multipart(name: String, data: Array[Byte]): Multipart = - Multipart(name, - ByteArrayBody(data), - contentType = Some(ApplicationOctetStreamContentType)) + Multipart(name, ByteArrayBody(data), contentType = Some(ApplicationOctetStreamContentType)) /** * Content type will be set to `application/octet-stream`, can be overridden * later using the `contentType` method. */ def multipart(name: String, data: ByteBuffer): Multipart = - Multipart(name, - ByteBufferBody(data), - contentType = Some(ApplicationOctetStreamContentType)) + Multipart(name, ByteBufferBody(data), contentType = Some(ApplicationOctetStreamContentType)) /** * Content type will be set to `application/octet-stream`, can be overridden * later using the `contentType` method. */ def multipart(name: String, data: InputStream): Multipart = - Multipart(name, - InputStreamBody(data), - contentType = Some(ApplicationOctetStreamContentType)) + Multipart(name, InputStreamBody(data), contentType = Some(ApplicationOctetStreamContentType)) /** * Content type will be set to `application/octet-stream`, can be overridden @@ -194,9 +179,7 @@ package object sttp { * overridden later using the `contentType` method. */ def multipart(name: String, fs: Map[String, String]): Multipart = - Multipart(name, - RequestBody.paramsToStringBody(fs.toList, Utf8), - contentType = Some(ApplicationFormContentType)) + Multipart(name, RequestBody.paramsToStringBody(fs.toList, Utf8), contentType = Some(ApplicationFormContentType)) /** * Encodes the given parameters as form data. @@ -204,12 +187,8 @@ package object sttp { * Content type will be set to `application/x-www-form-urlencoded`, can be * overridden later using the `contentType` method. */ - def multipart(name: String, - fs: Map[String, String], - encoding: String): Multipart = - Multipart(name, - RequestBody.paramsToStringBody(fs.toList, encoding), - contentType = Some(ApplicationFormContentType)) + def multipart(name: String, fs: Map[String, String], encoding: String): Multipart = + Multipart(name, RequestBody.paramsToStringBody(fs.toList, encoding), contentType = Some(ApplicationFormContentType)) /** * Encodes the given parameters as form data using `utf-8`. @@ -218,9 +197,7 @@ package object sttp { * overridden later using the `contentType` method. */ def multipart(name: String, fs: Seq[(String, String)]): Multipart = - Multipart(name, - RequestBody.paramsToStringBody(fs, Utf8), - contentType = Some(ApplicationFormContentType)) + Multipart(name, RequestBody.paramsToStringBody(fs, Utf8), contentType = Some(ApplicationFormContentType)) /** * Encodes the given parameters as form data. @@ -228,21 +205,15 @@ package object sttp { * Content type will be set to `application/x-www-form-urlencoded`, can be * overridden later using the `contentType` method. */ - def multipart(name: String, - fs: Seq[(String, String)], - encoding: String): Multipart = - Multipart(name, - RequestBody.paramsToStringBody(fs, encoding), - contentType = Some(ApplicationFormContentType)) + def multipart(name: String, fs: Seq[(String, String)], encoding: String): Multipart = + Multipart(name, RequestBody.paramsToStringBody(fs, encoding), contentType = Some(ApplicationFormContentType)) /** * Content type will be set to `application/octet-stream`, can be * overridden later using the `contentType` method. */ def multipart[B: BodySerializer](name: String, b: B): Multipart = - Multipart(name, - implicitly[BodySerializer[B]].apply(b), - contentType = Some(ApplicationOctetStreamContentType)) + Multipart(name, implicitly[BodySerializer[B]].apply(b), contentType = Some(ApplicationOctetStreamContentType)) // util @@ -278,8 +249,7 @@ package object sttp { private[sttp] def codeIsSuccess(c: Int): Boolean = c >= 200 && c < 300 - private[sttp] def concatByteBuffers(bb1: ByteBuffer, - bb2: ByteBuffer): ByteBuffer = + private[sttp] def concatByteBuffers(bb1: ByteBuffer, bb2: ByteBuffer): ByteBuffer = ByteBuffer .allocate(bb1.array().length + bb2.array().length) .put(bb1) diff --git a/core/src/main/scala/com/softwaremill/sttp/testing/SttpBackendStub.scala b/core/src/main/scala/com/softwaremill/sttp/testing/SttpBackendStub.scala index 36df795..d7d1034 100644 --- a/core/src/main/scala/com/softwaremill/sttp/testing/SttpBackendStub.scala +++ b/core/src/main/scala/com/softwaremill/sttp/testing/SttpBackendStub.scala @@ -26,10 +26,9 @@ import scala.util.{Failure, Success, Try} * or headers. A [[ClassCastException]] might occur if for a given request, * a response is specified with the incorrect or inconvertible body type. */ -class SttpBackendStub[R[_], S] private ( - rm: MonadError[R], - matchers: PartialFunction[Request[_, _], R[Response[_]]], - fallback: Option[SttpBackend[R, S]]) +class SttpBackendStub[R[_], S] private (rm: MonadError[R], + matchers: PartialFunction[Request[_, _], R[Response[_]]], + fallback: Option[SttpBackend[R, S]]) extends SttpBackend[R, S] { /** @@ -57,9 +56,7 @@ class SttpBackendStub[R[_], S] private ( * Note that the stubs are immutable, and each new * specification that is added yields a new stub instance. */ - def whenRequestMatchesPartial( - partial: PartialFunction[Request[_, _], Response[_]]) - : SttpBackendStub[R, S] = { + def whenRequestMatchesPartial(partial: PartialFunction[Request[_, _], Response[_]]): SttpBackendStub[R, S] = { val wrappedPartial = partial.andThen(rm.unit) new SttpBackendStub(rm, matchers.orElse(wrappedPartial), fallback) } @@ -67,18 +64,11 @@ class SttpBackendStub[R[_], S] private ( override def send[T](request: Request[T, S]): R[Response[T]] = { Try(matchers.lift(request)) match { case Success(Some(response)) => - tryAdjustResponseType(rm, - request.response, - response.asInstanceOf[R[Response[T]]]) + tryAdjustResponseType(rm, request.response, response.asInstanceOf[R[Response[T]]]) case Success(None) => fallback match { case None => - wrapResponse( - Response[Nothing](Left("Not Found: " + request.uri), - 404, - "Not Found", - Nil, - Nil)) + wrapResponse(Response[Nothing](Left("Not Found: " + request.uri), 404, "Not Found", Nil, Nil)) case Some(fb) => fb.send(request) } case Failure(e) => rm.error(e) @@ -99,8 +89,7 @@ class SttpBackendStub[R[_], S] private ( thenRespondWithCode(404, "Not found") def thenRespondServerError(): SttpBackendStub[R, S] = thenRespondWithCode(500, "Internal server error") - def thenRespondWithCode(code: Int, - msg: String = ""): SttpBackendStub[R, S] = { + def thenRespondWithCode(code: Int, msg: String = ""): SttpBackendStub[R, S] = { val body = if (code >= 200 && code < 300) Right(msg) else Left(msg) thenRespond(Response(body, code, msg, Nil, Nil)) } @@ -136,9 +125,7 @@ object SttpBackendStub { */ def asynchronousFuture: SttpBackendStub[Future, Nothing] = { import scala.concurrent.ExecutionContext.Implicits.global - new SttpBackendStub[Future, Nothing](new FutureMonad(), - PartialFunction.empty, - None) + new SttpBackendStub[Future, Nothing](new FutureMonad(), PartialFunction.empty, None) } /** @@ -162,11 +149,8 @@ object SttpBackendStub { * 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, - PartialFunction.empty, - Some(fallback)) + def withFallback[R[_], S, S2 <: S](fallback: SttpBackend[R, S]): SttpBackendStub[R, S2] = + new SttpBackendStub[R, S2](fallback.responseMonad, PartialFunction.empty, Some(fallback)) private[sttp] def tryAdjustResponseType[DesiredRType, RType, M[_]]( rm: MonadError[M], @@ -177,15 +161,12 @@ object SttpBackendStub { case Left(_) => r.asInstanceOf[Response[DesiredRType]] case Right(body) => val newBody: Any = tryAdjustResponseBody(ra, body).getOrElse(body) - r.copy( - body = - Right[String, DesiredRType](newBody.asInstanceOf[DesiredRType])) + r.copy(body = Right[String, DesiredRType](newBody.asInstanceOf[DesiredRType])) } } } - private[sttp] def tryAdjustResponseBody[T, U](ra: ResponseAs[T, _], - b: U): Option[T] = { + private[sttp] def tryAdjustResponseBody[T, U](ra: ResponseAs[T, _], b: U): Option[T] = { ra match { case IgnoreResponse => Some(()) case ResponseAsString(enc) => diff --git a/core/src/test/scala/com/softwaremill/sttp/RequestTests.scala b/core/src/test/scala/com/softwaremill/sttp/RequestTests.scala index 5fc9d50..828fdb2 100644 --- a/core/src/test/scala/com/softwaremill/sttp/RequestTests.scala +++ b/core/src/test/scala/com/softwaremill/sttp/RequestTests.scala @@ -31,11 +31,7 @@ class RequestTests extends FlatSpec with Matchers { it should "set cookies from a response" in { val response = - Response(Right(()), - 0, - "", - List((SetCookieHeader, "k1=v1"), (SetCookieHeader, "k2=v2")), - Nil) + Response(Right(()), 0, "", List((SetCookieHeader, "k1=v1"), (SetCookieHeader, "k2=v2")), Nil) sttp .cookies(response) .headers diff --git a/core/src/test/scala/com/softwaremill/sttp/UriInterpolatorTests.scala b/core/src/test/scala/com/softwaremill/sttp/UriInterpolatorTests.scala index e417233..69290b0 100644 --- a/core/src/test/scala/com/softwaremill/sttp/UriInterpolatorTests.scala +++ b/core/src/test/scala/com/softwaremill/sttp/UriInterpolatorTests.scala @@ -22,14 +22,11 @@ class UriInterpolatorTests extends FunSuite with Matchers { (uri"http://example.com?x=y", "http://example.com?x=y"), (uri"http://example.com/a/b/c", "http://example.com/a/b/c"), (uri"http://example.com/a/b/c/", "http://example.com/a/b/c/"), - (uri"http://example.com/a/b/c?x=y&h=j", - "http://example.com/a/b/c?x=y&h=j") + (uri"http://example.com/a/b/c?x=y&h=j", "http://example.com/a/b/c?x=y&h=j") ), "scheme" -> List( - (uri"http${if (secure) "s" else ""}://example.com", - s"https://example.com"), - (uri"${if (secure) "https" else "http"}://example.com", - s"https://example.com"), + (uri"http${if (secure) "s" else ""}://example.com", s"https://example.com"), + (uri"${if (secure) "https" else "http"}://example.com", s"https://example.com"), (uri"example.com?a=$v2", s"http://example.com?a=$v2queryEncoded") ), "user info" -> List( @@ -47,10 +44,8 @@ class UriInterpolatorTests extends FunSuite with Matchers { (uri"http://$None.example.com", s"http://example.com"), (uri"http://$None.$None.example.com", s"http://example.com"), (uri"http://${Some("sub")}.example.com", s"http://sub.example.com"), - (uri"http://${Some("sub1.sub2")}.example.com", - s"http://sub1.sub2.example.com"), - (uri"http://${List("sub1", "sub2")}.example.com", - s"http://sub1.sub2.example.com"), + (uri"http://${Some("sub1.sub2")}.example.com", s"http://sub1.sub2.example.com"), + (uri"http://${List("sub1", "sub2")}.example.com", s"http://sub1.sub2.example.com"), (uri"http://${List("sub", "example", "com")}", s"http://sub.example.com") ), "authority with parameters" -> List( @@ -78,18 +73,13 @@ class UriInterpolatorTests extends FunSuite with Matchers { (uri"http://example.com/$v1/", s"http://example.com/$v1/"), (uri"http://example.com/$v2", s"http://example.com/$v2encoded"), (uri"http://example.com/$v2/$v1", s"http://example.com/$v2encoded/$v1"), - (uri"http://example.com/$v1/p/$v4", - s"http://example.com/$v1/p/$v4encoded"), - (uri"http://example.com/a/${List(v2, "c", v4)}/b", - s"http://example.com/a/$v2encoded/c/$v4encoded/b"), - (uri"http://example.com/${"a/b/c".split('/')}", - s"http://example.com/a/b/c") + (uri"http://example.com/$v1/p/$v4", s"http://example.com/$v1/p/$v4encoded"), + (uri"http://example.com/a/${List(v2, "c", v4)}/b", s"http://example.com/a/$v2encoded/c/$v4encoded/b"), + (uri"http://example.com/${"a/b/c".split('/')}", s"http://example.com/a/b/c") ), "path with parameters" -> List( - (uri"http://example.com/$v1?x=$v2", - s"http://example.com/$v1?x=$v2queryEncoded"), - (uri"http://example.com/$v1/$v2?x=$v2", - s"http://example.com/$v1/$v2encoded?x=$v2queryEncoded") + (uri"http://example.com/$v1?x=$v2", s"http://example.com/$v1?x=$v2queryEncoded"), + (uri"http://example.com/$v1/$v2?x=$v2", s"http://example.com/$v1/$v2encoded?x=$v2queryEncoded") ), "query parameter values" -> List( (uri"http://example.com?x=$v1", s"http://example.com?x=$v1"), @@ -101,31 +91,24 @@ class UriInterpolatorTests extends FunSuite with Matchers { ), "query parameter without value" -> List( (uri"http://example.com?$v1", s"http://example.com?$v1"), - (uri"http://example.com?$v1&$v2", - s"http://example.com?$v1&$v2queryEncoded") + (uri"http://example.com?$v1&$v2", s"http://example.com?$v1&$v2queryEncoded") ), "optional query parameters" -> List( (uri"http://example.com?a=$None", s"http://example.com"), (uri"http://example.com?a=b&c=$None", s"http://example.com?a=b"), (uri"http://example.com?a=b&c=$None&e=f", s"http://example.com?a=b&e=f"), (uri"http://example.com?a=${Some(v1)}", s"http://example.com?a=$v1"), - (uri"http://example.com?a=${Some(v1)}&c=d", - s"http://example.com?a=$v1&c=d") + (uri"http://example.com?a=${Some(v1)}&c=d", s"http://example.com?a=$v1&c=d") ), "parameter collections" -> List( (uri"http://example.com?${Seq("a" -> "b", v2 -> v1, v1 -> v2)}", s"http://example.com?a=b&$v2queryEncoded=$v1&$v1=$v2queryEncoded"), - (uri"http://example.com?${Seq("a" -> "b", "a" -> "c")}", - s"http://example.com?a=b&a=c"), + (uri"http://example.com?${Seq("a" -> "b", "a" -> "c")}", s"http://example.com?a=b&a=c"), (uri"http://example.com?${Map("a" -> "b")}", s"http://example.com?a=b"), - (uri"http://example.com?x=y&${Map("a" -> "b")}", - s"http://example.com?x=y&a=b"), - (uri"http://example.com?x=y&${Map("a" -> None)}", - s"http://example.com?x=y"), - (uri"http://example.com?x=y&${Map("a" -> Some("b"))}", - s"http://example.com?x=y&a=b"), - (uri"http://example.com?x=y&${Seq("a" -> None)}", - s"http://example.com?x=y") + (uri"http://example.com?x=y&${Map("a" -> "b")}", s"http://example.com?x=y&a=b"), + (uri"http://example.com?x=y&${Map("a" -> None)}", s"http://example.com?x=y"), + (uri"http://example.com?x=y&${Map("a" -> Some("b"))}", s"http://example.com?x=y&a=b"), + (uri"http://example.com?x=y&${Seq("a" -> None)}", s"http://example.com?x=y") ), "fragments" -> List( (uri"http://example.com#$v1", s"http://example.com#$v1"), @@ -137,8 +120,7 @@ class UriInterpolatorTests extends FunSuite with Matchers { ), "embed whole url" -> List( (uri"${"http://example.com:123/a"}/b/c", "http://example.com:123/a/b/c"), - (uri"${uri"http://example.com/$v1?p=$v2"}", - s"http://example.com/$v1?p=$v2queryEncoded") + (uri"${uri"http://example.com/$v1?p=$v2"}", s"http://example.com/$v1?p=$v2queryEncoded") ) ) @@ -152,19 +134,14 @@ class UriInterpolatorTests extends FunSuite with Matchers { } val validationTestData = List( - ("uri with two ports", - () => uri"http://example.com:80:80", - "port specified multiple times"), - ("uri with embedded host+port and port", - () => uri"http://${"example.com:80"}:80", - "port specified multiple times") + ("uri with two ports", () => uri"http://example.com:80:80", "port specified multiple times"), + ("uri with embedded host+port and port", () => uri"http://${"example.com:80"}:80", "port specified multiple times") ) for { (name, createUri, expectedException) <- validationTestData } { - test( - s"""$name should validate and throw "$expectedException" if not valid""") { + test(s"""$name should validate and throw "$expectedException" if not valid""") { val caught = intercept[IllegalArgumentException] { createUri() } diff --git a/core/src/test/scala/com/softwaremill/sttp/UriTests.scala b/core/src/test/scala/com/softwaremill/sttp/UriTests.scala index b94ac72..5250303 100644 --- a/core/src/test/scala/com/softwaremill/sttp/UriTests.scala +++ b/core/src/test/scala/com/softwaremill/sttp/UriTests.scala @@ -2,11 +2,7 @@ package com.softwaremill.sttp import java.net.URI -import com.softwaremill.sttp.Uri.{ - QueryFragment, - QueryFragmentEncoding, - UserInfo -} +import com.softwaremill.sttp.Uri.{QueryFragment, QueryFragmentEncoding, UserInfo} import org.scalatest.{FunSuite, Matchers} class UriTests extends FunSuite with Matchers { @@ -23,13 +19,7 @@ class UriTests extends FunSuite with Matchers { List(QF.KeyValue("p1", "v1"), QF.KeyValue("p2", "v2")), Some("f")) -> "https://sub.example.com:8080/a/b/xyz?p1=v1&p2=v2#f", - Uri("http", - None, - "example.com", - None, - List(""), - List(QF.KeyValue("p", "v"), QF.KeyValue("p", "v")), - None) -> "http://example.com/?p=v&p=v", + Uri("http", None, "example.com", None, List(""), List(QF.KeyValue("p", "v"), QF.KeyValue("p", "v")), None) -> "http://example.com/?p=v&p=v", Uri("http", None, "exa mple.com", @@ -38,13 +28,7 @@ class UriTests extends FunSuite with Matchers { List(QF.KeyValue("p:1", "v&v"), QF.KeyValue("p2", "v v")), None) -> "http://exa%20mple.com/a%20b/z/%C4%85:%C4%99?p:1=v%26v&p2=v+v", - Uri("http", - Some(UserInfo("us&e/r", Some("pa ss"))), - "example.com", - None, - Nil, - Nil, - None) -> + Uri("http", Some(UserInfo("us&e/r", Some("pa ss"))), "example.com", None, Nil, Nil, None) -> "http://us&e%2Fr:pa%20ss@example.com", Uri("http", None, "example.com", None, Nil, Nil, Some("f:g/h i")) -> "http://example.com#f:g/h%20i", @@ -79,24 +63,16 @@ class UriTests extends FunSuite with Matchers { } val queryFragmentsTestData = List( - List(QF.KeyValue("k1", "v1"), - QF.KeyValue("k2", "v2"), - QF.KeyValue("k3", "v3"), - QF.KeyValue("k4", "v4")) -> "k1=v1&k2=v2&k3=v3&k4=v4", + List(QF.KeyValue("k1", "v1"), QF.KeyValue("k2", "v2"), QF.KeyValue("k3", "v3"), QF.KeyValue("k4", "v4")) -> "k1=v1&k2=v2&k3=v3&k4=v4", List(QF.KeyValue("k1", "v1"), QF.KeyValue("k2", "v2"), QF.Plain("-abc-"), QF.KeyValue("k3", "v3"), QF.KeyValue("k4", "v4")) -> "k1=v1&k2=v2-abc-k3=v3&k4=v4", List(QF.KeyValue("k1", "v1"), QF.Plain("&abc&"), QF.KeyValue("k2", "v2")) -> "k1=v1%26abc%26k2=v2", - List( - QF.KeyValue("k1", "v1"), - QF.Plain("&abc&", encoding = QueryFragmentEncoding.Relaxed)) -> "k1=v1&abc&", + List(QF.KeyValue("k1", "v1"), QF.Plain("&abc&", encoding = QueryFragmentEncoding.Relaxed)) -> "k1=v1&abc&", List(QF.KeyValue("k1&", "v1&", keyEncoding = QueryFragmentEncoding.Relaxed)) -> "k1&=v1%26", - List(QF.KeyValue( - "k1&", - "v1&", - valueEncoding = QueryFragmentEncoding.Relaxed)) -> "k1%26=v1&", + List(QF.KeyValue("k1&", "v1&", valueEncoding = QueryFragmentEncoding.Relaxed)) -> "k1%26=v1&", List(QF.Plain("ą/ę&+;?", encoding = QueryFragmentEncoding.Relaxed)) -> "%C4%85/%C4%99&+;?", List(QF.KeyValue("k", "v1,v2", valueEncoding = QueryFragmentEncoding.All)) -> "k=v1%2Cv2", List(QF.KeyValue("k", "v1,v2")) -> "k=v1,v2", diff --git a/core/src/test/scala/com/softwaremill/sttp/testing/SttpBackendStubTests.scala b/core/src/test/scala/com/softwaremill/sttp/testing/SttpBackendStubTests.scala index 92c62f7..1299cae 100644 --- a/core/src/test/scala/com/softwaremill/sttp/testing/SttpBackendStubTests.scala +++ b/core/src/test/scala/com/softwaremill/sttp/testing/SttpBackendStubTests.scala @@ -19,13 +19,9 @@ class SttpBackendStubTests extends FlatSpec with Matchers with ScalaFutures { .whenRequestMatches(_.method == Method.GET) .thenRespondServerError() .whenRequestMatchesPartial({ - case r - if r.method == Method.POST && r.uri.path.endsWith( - List("partial10")) => + case r if r.method == Method.POST && r.uri.path.endsWith(List("partial10")) => Response(Right(10), 200, "OK", Nil, Nil) - case r - if r.method == Method.POST && r.uri.path.endsWith( - List("partialAda")) => + case r if r.method == Method.POST && r.uri.path.endsWith(List("partialAda")) => Response(Right("Ada"), 200, "OK", Nil, Nil) }) .whenRequestMatches(_.uri.port.exists(_ == 8080)) @@ -210,13 +206,9 @@ class SttpBackendStubTests extends FlatSpec with Matchers with ScalaFutures { (s, IgnoreResponse, Some(())), (s, ResponseAsString(Utf8), Some(s)), (s.getBytes(Utf8), ResponseAsString(Utf8), Some(s)), - (new ByteArrayInputStream(s.getBytes(Utf8)), - ResponseAsString(Utf8), - Some(s)), + (new ByteArrayInputStream(s.getBytes(Utf8)), ResponseAsString(Utf8), Some(s)), (10, ResponseAsString(Utf8), None), - ("10", - MappedResponseAs(ResponseAsString(Utf8), (_: String).toInt), - Some(10)), + ("10", MappedResponseAs(ResponseAsString(Utf8), (_: String).toInt), Some(10)), (10, MappedResponseAs(ResponseAsString(Utf8), (_: String).toInt), None) ) @@ -226,8 +218,7 @@ class SttpBackendStubTests extends FlatSpec with Matchers with ScalaFutures { (body, responseAs, expectedResult) <- adjustTestData } { it should s"adjust $body to $expectedResult when specified as $responseAs" in { - SttpBackendStub.tryAdjustResponseBody(responseAs, body) should be( - expectedResult) + SttpBackendStub.tryAdjustResponseBody(responseAs, body) should be(expectedResult) } } } |