当前位置: 首页>>代码示例>>Scala>>正文


Scala MediaTypes类代码示例

本文整理汇总了Scala中akka.http.scaladsl.model.MediaTypes的典型用法代码示例。如果您正苦于以下问题:Scala MediaTypes类的具体用法?Scala MediaTypes怎么用?Scala MediaTypes使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了MediaTypes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: Marshalling

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import java.time.Instant

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.alpakka.s3.scaladsl.ListBucketResultContents

import scala.xml.NodeSeq

private[alpakka] object Marshalling {
  import ScalaXmlSupport._

  implicit val multipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text,
          (x \ "Key").text,
          (x \ "ETag").text.drop(1).dropRight(1)
        )
    }
  }

  val isTruncated = "IsTruncated"
  val continuationToken = "NextContinuationToken"

  implicit val listBucketResultUnmarshaller: FromEntityUnmarshaller[ListBucketResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`).map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        ListBucketResult(
          (x \ isTruncated).text == "true",
          Some(x \ continuationToken).filter(_.nonEmpty).map(_.text),
          (x \\ "Contents").map { c =>
            ListBucketResultContents(
              (x \ "Name").text,
              (c \ "Key").text,
              (c \ "ETag").text.drop(1).dropRight(1),
              (c \ "Size").text.toLong,
              Instant.parse((c \ "LastModified").text),
              (c \ "StorageClass").text
            )
          }
        )
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:60,代码来源:Marshalling.scala

示例2: postRequest

//设置package包名称以及导入依赖的类
package se.meldrum.machine

import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Matchers, WordSpec}
import PostgresTestDb._
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpEntity, HttpMethods, HttpRequest, MediaTypes}
import akka.stream.ActorMaterializer
import akka.util.ByteString
import se.meldrum.machine.http.RestService
import slick.driver.PostgresDriver.api._

import scala.concurrent.ExecutionContext

trait BaseSpec extends WordSpec with Matchers with ScalatestRouteTest {
  dbProcess.getProcessId
  implicit val db = Database.forConfig("postgres-test")
  implicit val sys = ActorSystem("machine")
  implicit val ec = ExecutionContext
  implicit val mat = ActorMaterializer()
  val restService = new RestService()
  val route = restService.route

  def postRequest(path: String, json: ByteString): HttpRequest =
    HttpRequest(HttpMethods.POST,
      uri = path,
      entity = HttpEntity(MediaTypes.`application/json`, json)
    )


  def userJsonRequest(name: String, pass: String, email: String): ByteString =
    ByteString(
      s"""
       |{
       |    "name":"$name",
       |    "password":"$pass",
       |    "email":"$email"
       |}
        """.stripMargin)


  def createTestUsers(): Seq[HttpRequest] = {
    val userOne = userJsonRequest("testuser", "secret", "[email protected]")
    val userTwo = userJsonRequest("testuser2", "secret", "[email protected]")
    val userThree = userJsonRequest("testuser3", "secret", "[email protected]")

    val requests = Seq(
      postRequest("/v1/user/create", userOne),
      postRequest("/v1/user/create", userTwo),
      postRequest("/v1/user/create", userThree)
    )
    requests
  }
} 
开发者ID:Max-Meldrum,项目名称:machine,代码行数:56,代码来源:BaseSpec.scala

示例3: unmarshaller

//设置package包名称以及导入依赖的类
package com.github.bots4s.telegramkit.client

import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToEntityMarshaller}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, MediaTypes, Multipart}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}

import com.github.bots4s.telegramkit.marshalling.{BotMarshaller, BotUnmarshaller}
import com.github.bots4s.telegramkit.method.{BotApiRequest, BotApiRequestJson, BotApiRequestMultipart}
import com.github.bots4s.telegramkit.model._


private[client] trait HttpMarshalling { this: BotApiClient =>
  implicit def unmarshaller[T: Manifest](implicit um: BotUnmarshaller[T]): FromEntityUnmarshaller[T] = {
    Unmarshaller.stringUnmarshaller.map(body => um(body))
  }

  implicit def marshaller[T](implicit m: BotMarshaller[BotApiRequestJson[T]]): ToEntityMarshaller[BotApiRequest[T]] = {
    Marshaller.strict {
      case request: BotApiRequestJson[T] =>
        val content = m(request)
        Marshalling.Opaque(() => HttpEntity(ContentTypes.`application/json`, content))
      case request: BotApiRequestMultipart[T] =>
        def flatten(value: Any): Any = value match {
          case Some(x) => flatten(x)
          case e: Either[_, _] => flatten(e.fold(identity, identity))
          case _ => value
        }
        val fields = request.getClass.getDeclaredFields.iterator.zip(request.productIterator).map {
          case (k, v) => HttpMarshalling.snakeCase(k.getName) -> flatten(v)
        }.filterNot(_._2 == None)

        if (fields.isEmpty) {
          Marshalling.Opaque(() => HttpEntity.empty(ContentTypes.`application/octet-stream`))
        } else {
          val parts = fields map {
            case (k, v @ (_: String | _: Boolean | _: Long | _: Float)) =>
              Multipart.FormData.BodyPart(k, HttpEntity(v.toString))
            case (k, InputFile.InputFilePath(path)) =>
              Multipart.FormData.BodyPart.fromPath(k, MediaTypes.`application/octet-stream`, path)
            case (k, InputFile.InputFileData(filename, bs)) =>
              Multipart.FormData.BodyPart(k, HttpEntity(ContentTypes.`application/octet-stream`, bs), Map("filename" -> filename))
            case (k, other) =>
              log.warning(s"unexpected field in multipart request, $k: $other")
              Multipart.FormData.BodyPart(k, HttpEntity(""))
          }
          Marshalling.Opaque(() => Multipart.FormData(parts.toSeq: _*).toEntity())
        }
    }
  }
}

private[client] object HttpMarshalling {
  private val CapitalLetter = "[A-Z]".r
  def snakeCase(s: String): String =
    CapitalLetter.replaceAllIn(s, { "_" + _.group(0).toLowerCase })
} 
开发者ID:bots4s,项目名称:TelegramKit,代码行数:57,代码来源:HttpMarshalling.scala

示例4: MessageParts

//设置package包名称以及导入依赖的类
package com.jatescher.layer.models

import akka.http.scaladsl.model.{ MediaType, MediaTypes }

sealed trait MessagePart {
  val mimeType: MediaType
}

object MessageParts {

  // Simple text message part
  case class TextMessagePart(body: String) extends MessagePart {
    val mimeType = MediaTypes.`text/plain`
  }

  // Custom content message part
  case class ImageMessagePart(content: MessagePartContent) extends MessagePart {
    val mimeType = content.mimeType
  }

} 
开发者ID:jtescher,项目名称:layer-scala,代码行数:22,代码来源:MessagePart.scala

示例5: MediaTypeFormatSpec

//设置package包名称以及导入依赖的类
package com.jatescher.layer.marshalling

import akka.http.scaladsl.model.{ MediaType, MediaTypes }
import com.jatescher.layer.marshalling.v1.MediaTypeFormat._
import org.scalatest.{ Matchers, WordSpec }
import spray.json._

class MediaTypeFormatSpec extends WordSpec with Matchers {
  val mediaTypeString = "image/png"
  val mediaType: MediaType = MediaTypes.`image/png`

  "#write" should {
    "marshall the media type as string" in {
      mediaType.toJson shouldBe mediaTypeString.toJson
    }
  }

  "#read" should {
    "unmarshall media types" in {
      JsString(mediaTypeString).convertTo[MediaType] shouldBe mediaType
    }

    "raise an exception if the media type is not a string" in {
      intercept[DeserializationException] {
        JsNumber(1).convertTo[MediaType]
      }
    }

    "raise an exception if the media type is not valid" in {
      intercept[DeserializationException] {
        JsString("non-media-type").convertTo[MediaType]
      }
    }
  }

} 
开发者ID:jtescher,项目名称:layer-scala,代码行数:37,代码来源:MediaTypeFormatSpec.scala

示例6: MessagePartFactory

//设置package包名称以及导入依赖的类
package com.jatescher.layer.factories

import akka.http.scaladsl.model.MediaTypes
import com.jatescher.layer.models.MessagePartContents.ImageMessagePartContent
import com.jatescher.layer.models.MessageParts.{ ImageMessagePart, TextMessagePart }

object MessagePartFactory {

  def buildTextMessagePart(): TextMessagePart = TextMessagePart("Hello, World!")

  def buildImageMessagePart(): ImageMessagePart = ImageMessagePart(ImageMessagePartContent(
    id = "layer:///content/940de862-3c96-11e4-baad-164230d1df60",
    downloadUrl = "http://google-testbucket.storage.googleapis.com/some/download/path",
    expiration = "2014-09-09T04:44:47+00:00",
    refreshUrl = "https://api.layer.com/apps/082d4684-0992-11e5-a6c0-1697f925ec7b/content/7a0aefb8-3c97-11e4-baad-164230d1df60",
    size = 172114124,
    mimeType = MediaTypes.`image/png`
  ))

} 
开发者ID:jtescher,项目名称:layer-scala,代码行数:21,代码来源:MessagePartFactory.scala

示例7: ClientsServiceTest

//设置package包名称以及导入依赖的类
package gateway.restapi

import akka.http.scaladsl.model.{HttpEntity, MediaTypes}
import gateway.restapi.domain.ClientEnitity
import io.circe.generic.auto._
import org.scalatest.concurrent.ScalaFutures

class ClientsServiceTest extends BaseServiceTest with ScalaFutures {

  trait Context {
    val cleanUp = cleanContext
    val testClients = provisionClientsList(5)
    val route = httpService.clientsRouter.route
  }

  "Users service" should {

    "retrieve empty clients list" in new Context {
      cleanContext
      Get("/clients") ~> route ~> check {
        responseAs[Seq[ClientEnitity]].length should be(0)
      }
    }

    "retrieve clients list" in new Context {
      Get("/clients") ~> route ~> check {
        responseAs[Seq[ClientEnitity]].length should be(5)
      }
    }

    "retrieve client by id" in new Context {
      val testClient = testClients(4)
      Get(s"/clients/${testClient.id.get}") ~> route ~> check {
        responseAs[ClientEnitity] should be(testClient)
      }
    }

    "create a new client" in new Context {
      val newClientName = "Smith Test"
      val requestEntity = HttpEntity(MediaTypes.`application/json`, s"""{"name": "$newClientName"}""")
      Post("/clients/", requestEntity) ~> route ~> check {
        responseAs[ClientEnitity].name should be(newClientName)
      }
    }
  }
} 
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:47,代码来源:ClientsServiceTest.scala

示例8: extractFormData

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives

import java.io.File

import akka.Done
import akka.http.scaladsl.model.{HttpEntity, MediaTypes, Multipart}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import akka.stream.scaladsl.FileIO
import com.flipkart.connekt.commons.utils.StringUtils._
import com.flipkart.connekt.receptors.directives.MultiPartFormData._

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try


  def extractFormData: Directive1[Map[Name,  Either[Value, FileInfo]]] = {
    Directive[Tuple1[Map[Name,  Either[Value, FileInfo]]]] { inner =>
      extractMaterializer { implicit mat =>
        extractExecutionContext { implicit ec =>
          uploadFileImpl(mat, ec) { filesFuture =>
            ctx => {
              filesFuture.map(map => inner(Tuple1(map))).flatMap(route => route(ctx))
            }
          }
        }
      }
    }
  }

  def downloadFile(file: String): Route = {
    val f = new File(file)
    val responseEntity = HttpEntity(
      MediaTypes.`application/octet-stream`,
      f.length,
      FileIO.fromFile(f, chunkSize = 262144))
    complete(responseEntity)
  }
}


object MultiPartFormData {

  //form field name
  type Name = String
  type Value = String

  case class FileInfo(fileName: String, tmpFilePath: String, status: Try[Done])
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:51,代码来源:FileDirective.scala

示例9: GenericJsonSupport

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.wire

import akka.http.scaladsl.marshalling.{PredefinedToEntityMarshallers, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers}
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.flipkart.connekt.receptors.wire.GenericJsonSupport._
import scala.collection.mutable
import scala.reflect.ClassTag


object GenericJsonSupport {

  val jacksonModules = Seq(DefaultScalaModule)

  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModules(jacksonModules: _*)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  val m: mutable.Map[Class[_], ToEntityMarshaller[_]] = mutable.Map.empty[Class[_], ToEntityMarshaller[_]]
  val um: mutable.Map[Class[_], FromEntityUnmarshaller[_]] = mutable.Map.empty[Class[_], FromEntityUnmarshaller[_]]
}

trait JsonToEntityMarshaller extends PredefinedToEntityMarshallers {

  implicit def findMarshaller[T](implicit cTag: ClassTag[T]): ToEntityMarshaller[T] =
    m.getOrElseUpdate(cTag.runtimeClass, genericMarshaller[T]).asInstanceOf[ToEntityMarshaller[T]]

  def genericMarshaller[T]: ToEntityMarshaller[T] =
    stringMarshaller(MediaTypes.`application/json`)
      .compose[T](mapper.writeValueAsString)
}

trait JsonFromEntityUnmarshaller extends PredefinedFromEntityUnmarshallers {

  implicit def findUnmarshaller[T](implicit cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
    um.getOrElseUpdate(cTag.runtimeClass, genericUnmarshaller[T](cTag)).asInstanceOf[FromEntityUnmarshaller[T]]

  def genericUnmarshaller[T](cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
    stringUnmarshaller.forContentTypes(MediaTypes.`application/json`)
      .map(mapper.readValue(_, cTag.runtimeClass).asInstanceOf[T])
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:45,代码来源:JsonToEntityMarshaller.scala

示例10: CallbackRouteTest

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.tests.routes.callbacks

import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes}
import com.flipkart.connekt.receptors.routes.callbacks.CallbackRoute
import com.flipkart.connekt.receptors.tests.routes.BaseRouteTest

class CallbackRouteTest extends BaseRouteTest {

  val mssgId = "7a4df25c383d4c7a9438c478ddcadd1f2"
  val deviceId = "d7ae09474408d039ecad4534ed040f4a"
  val appName = "RetailApp"
  val mobilePlatform = "android"

  "Callback Test " should "return Ok" in {
    val callbackRoute = new CallbackRoute().route
    val payload =
      s"""
         |{
         |	"type": "PN",
         |	"eventType": "received",
         |	"timestamp": 1449597968,
         |	"messageId": "$mssgId",
         |	"contextId": "connekt-wx-01"
         |}
      """.stripMargin

    Post(s"/v1/push/callback/$mobilePlatform/$appName/$deviceId", HttpEntity(MediaTypes.`application/json`, payload)).addHeader(header) ~>
      callbackRoute ~>
      check {
        status shouldEqual StatusCodes.OK
      }

    Delete(s"/v1/push/callback/$mobilePlatform/$appName/$deviceId/$mssgId").addHeader(header) ~> callbackRoute ~>
      check {
        status shouldEqual StatusCodes.OK
      }
  }

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:40,代码来源:CallbackRouteTest.scala

示例11: UserAuthRouteTest

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.tests.routes.push

import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes}
import com.flipkart.connekt.receptors.routes.common.UserAuthRoute
import com.flipkart.connekt.receptors.tests.routes.BaseRouteTest

class UserAuthRouteTest extends BaseRouteTest {

  val ldapAuthentication = new UserAuthRoute().route
  "LdapAuthentication test" should "return Ok for save " in {

    val payload =
      s"""
         |{
         |	"username": "123",
         |	"password": "123"
         |}
      """.stripMargin

    Post(s"/v1/auth/ldap", HttpEntity(MediaTypes.`application/json`, payload)).addHeader(header) ~>
      ldapAuthentication ~>
      check {
        status shouldEqual StatusCodes.Unauthorized
      }

  }

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:29,代码来源:UserAuthRouteTest.scala

示例12: GetRetreiveRoute

//设置package包名称以及导入依赖的类
package org.nephtys.keepaseat.internal

import akka.http.scaladsl.model.{ContentType, HttpEntity, HttpResponse, MediaTypes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import org.nephtys.keepaseat.Databaseable
import org.nephtys.keepaseat.filter.XSSCleaner
import org.nephtys.keepaseat.internal.configs.{Authenticators, PasswordConfig}
import upickle.default._



class GetRetreiveRoute(implicit passwordConfig: PasswordConfig, database: Databaseable,
                       xssCleaner: XSSCleaner) {

  def receivePathWithoutSlashes = """events"""

  def receivePath: String = "/" + receivePathWithoutSlashes

  def extractRoute: Route = path(receivePathWithoutSlashes) {
      Authenticators.BasicAuthOrPass(passwordConfig, onlySuperusers = false) { () =>
        parameters('from.as[Long], 'to.as[Long]) { (from, to) => {
          onSuccess(database.retrieve(from, to)) { a => {
            complete {
              HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), write(a.sortBy(_.elements.map(_.from).min).map(_.cleanHTML))))
            }
          }
          }
        }
        }
      }
  }


} 
开发者ID:n3phtys,项目名称:keep-a-seat,代码行数:36,代码来源:GetRetreiveRoute.scala

示例13: AuthServiceTest

//设置package包名称以及导入依赖的类
package me.archdev

import akka.http.scaladsl.model.{ StatusCodes, MediaTypes, HttpEntity }
import me.archdev.restapi.http.routes.AuthServiceRoute
import me.archdev.restapi.models.{ TokenEntity, UserEntity }
import spray.json._

class AuthServiceTest extends BaseServiceTest {
  val newUser = UserEntity(username = "NewUser", password = "test")
  var signUpToken: Option[TokenEntity] = None
  var signInToken: Option[TokenEntity] = None

  "Auth service" should {
    "register users and retrieve token" in {
      val requestEntity = HttpEntity(MediaTypes.`application/json`, newUser.toJson.toString())
      Post("/auth/signUp", requestEntity) ~> authRoute ~> check {
        response.status should be(StatusCodes.Created)
        signUpToken = Some(tokenFormat.read(responseAs[JsValue]))
      }
    }

    "authorize users by login and password and retrieve token" in {
      val requestEntity = HttpEntity(MediaTypes.`application/json`, JsObject("login" -> JsString(newUser.username), "password" -> JsString(newUser.password)).toString())
      Post("/auth/signIn", requestEntity) ~> authRoute ~> check {
        signInToken = Some(tokenFormat.read(responseAs[JsValue]))
      }
    }

    "retrieve same tokens during registration and authorization" in {
      signUpToken should be(signInToken)
    }
  }

} 
开发者ID:samuelmartingc,项目名称:Akka-REST-service,代码行数:35,代码来源:AuthServiceTest.scala

示例14: upickleJsValueMarshaller

//设置package包名称以及导入依赖的类
package com.thoughtworks.akka.http

import akka.http.scaladsl.model.{MediaTypes, _}
import akka.http.scaladsl.server.Directives._
import com.thoughtworks.Extractor._

import scala.concurrent.Future
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.unmarshalling.Unmarshaller


trait RpcSupport extends autowire.Server[upickle.Js.Value, upickle.default.Reader, upickle.default.Writer] {

  implicit private def upickleJsValueMarshaller = {
    Marshaller.StringMarshaller.wrap[upickle.Js.Value, MessageEntity](MediaTypes.`application/json`)(_.toString)
  }

  implicit private def upickleJsValueUnmarshaller = {
    Unmarshaller.stringUnmarshaller.map(upickle.json.read)
  }

  final def write[Result](r: Result)(implicit writer: upickle.default.Writer[Result]) = {
    writer.write(r)
  }

  final def read[Result](p: upickle.Js.Value)(implicit reader: upickle.default.Reader[Result]) = {
    reader.read(p)
  }

  final def rpc(packagePrefix: String*)(routes: PartialFunction[Request, Future[upickle.Js.Value]]) = {
    path(Segments) { segments =>
      entity(as[upickle.Js.Value]) {
        case upickle.Js.Obj([email protected]_*) =>
          autowire.Core.Request(packagePrefix ++ segments, keyValuePairs.toMap) match {
            case routes.extract(response) =>
              complete {
                response
              }
            case _ =>
              reject
          }
        case _ =>
          complete(HttpResponse(StatusCodes.BadRequest))
      }
    }
  }

}

object RpcSupport extends RpcSupport 
开发者ID:ThoughtWorksInc,项目名称:akka-http-rpc,代码行数:51,代码来源:RpcSupport.scala

示例15: AuthServiceTest

//设置package包名称以及导入依赖的类
package de.thepiwo.lifelogging

import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes}
import akka.http.scaladsl.server
import de.thepiwo.lifelogging.restapi.models.{TokenEntity, UserEntity}
import de.thepiwo.lifelogging.restapi.utils.LoginPassword
import de.thepiwo.lifelogging.utils.TestUserEntity
import spray.json._


class AuthServiceTest extends BaseServiceTest {

  trait Context {
    val testUsers = provisionUsersList(2)
    val route = httpService.authRouter.route
  }

  "Auth service" should {

    "register users and retrieve token" in new Context {
      val testUser = testUsers.head
      signUpUser(testUser.user, route) {
        response.status should be(StatusCodes.Created)
      }
    }

    "authorize users by login and password and retrieve token" in new Context {
      val testUser = testUsers(1)
      signInUser(testUser, route) {
        responseAs[TokenEntity] should be
      }
    }

  }

  private def signUpUser(user: UserEntity, route: server.Route)(action: => Unit) = {
    val requestEntity = HttpEntity(MediaTypes.`application/json`, user.toJson.compactPrint)
    Post("/auth/signUp", requestEntity) ~> route ~> check(action)
  }

  private def signInUser(testUser: TestUserEntity, route: server.Route)(action: => Unit) = {
    val requestEntity = HttpEntity(
      MediaTypes.`application/json`,
      LoginPassword(testUser.user.username, testUser.password).toJson.compactPrint
    )
    Post("/auth/signIn", requestEntity) ~> route ~> check(action)
  }

} 
开发者ID:thepiwo,项目名称:open-lifelogging,代码行数:50,代码来源:AuthServiceTest.scala


注:本文中的akka.http.scaladsl.model.MediaTypes类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。