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


Scala ScalatestRouteTest类代码示例

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


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

示例1: ApiSpec

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import ch.qos.logback.classic.{Level, Logger}
import org.flywaydb.core.Flyway
import org.scalatest.Matchers
import org.scalatest.fixture.FunSpec
import org.slf4j.LoggerFactory

import scala.concurrent.duration._
import scalikejdbc._

abstract class ApiSpec extends FunSpec with ScalatestRouteTest with Matchers with Protocols with SprayJsonSupport {
  case class FixtureParam(api: Api, webHookActorProbe: TestProbe)

  val databaseUrl = Option(System.getenv("npm_package_config_databaseUrl")).getOrElse("jdbc:postgresql://localhost:5432/postgres")

  // Stop Flyway from producing so much spam that Travis terminates the process.
  LoggerFactory.getLogger("org.flywaydb").asInstanceOf[Logger].setLevel(Level.WARN)

  val flyway = new Flyway()
  flyway.setDataSource(databaseUrl, "postgres", "")
  flyway.setSchemas("test")
  flyway.setLocations("classpath:/sql")

  override def testConfigSource =
    s"""
      |db.default.url = "${databaseUrl}?currentSchema=test"
      |authorization.skip = true
      |akka.loglevel = INFO
    """.stripMargin

  override def withFixture(test: OneArgTest) = {
    val webHookActorProbe = TestProbe()
    val api = new Api(webHookActorProbe.ref, testConfig, system, executor, materializer)

    webHookActorProbe.expectMsg(1 millis, WebHookActor.Process)

    DB localTx { implicit session =>
      sql"DROP SCHEMA IF EXISTS test CASCADE".update.apply()
      sql"CREATE SCHEMA test".update.apply()
    }

    flyway.migrate()

    super.withFixture(test.toNoArgTest(FixtureParam(api, webHookActorProbe)))
  }
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:51,代码来源:ApiSpec.scala

示例2: transportName

//设置package包名称以及导入依赖的类
package com.softwaremill.session

import akka.http.scaladsl.model.{DateTime, HttpHeader}
import akka.http.scaladsl.model.headers.{RawHeader, HttpCookie, Cookie, `Set-Cookie`}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.softwaremill.session.SessionOptions._
import com.softwaremill.session.TestData._

trait MultipleTransportTest { this: ScalatestRouteTest =>

  trait TestUsingTransport {
    def transportName: String

    def getSession: Option[String]
    def setSessionHeader(s: String): HttpHeader
    def isSessionExpired: Boolean

    def getRefreshToken: Option[String]
    def setRefreshTokenHeader(s: String): HttpHeader
    def isRefreshTokenExpired: Boolean

    def getSessionTransport: GetSessionTransport
    def setSessionTransport: SetSessionTransport
  }

  object TestUsingCookies extends TestUsingTransport {
    val sessionCookieName = sessionConfig.sessionCookieConfig.name
    val refreshTokenCookieName = sessionConfig.refreshTokenCookieConfig.name

    val transportName = "cookies"

    def cookiesMap: Map[String, HttpCookie] = headers
      .collect { case `Set-Cookie`(cookie) => cookie.name -> cookie }.toMap

    def getSession = cookiesMap.get(sessionCookieName).map(_.value)
    def setSessionHeader(s: String) = Cookie(sessionCookieName, s)
    def isSessionExpired = cookiesMap.get(sessionCookieName).flatMap(_.expires).contains(DateTime.MinValue)

    def getRefreshToken = cookiesMap.get(refreshTokenCookieName).map(_.value)
    def setRefreshTokenHeader(s: String) = Cookie(refreshTokenCookieName, s)
    def isRefreshTokenExpired = cookiesMap.get(refreshTokenCookieName).flatMap(_.expires).contains(DateTime.MinValue)

    def getSessionTransport = usingCookies
    def setSessionTransport = usingCookies
  }

  object TestUsingHeaders extends TestUsingTransport {
    val transportName = "headers"

    def getSession = header(sessionConfig.sessionHeaderConfig.sendToClientHeaderName).map(_.value)
    def setSessionHeader(s: String) = RawHeader(sessionConfig.sessionHeaderConfig.getFromClientHeaderName, s)
    def isSessionExpired = getSession.contains("")

    def getRefreshToken = header(sessionConfig.refreshTokenHeaderConfig.sendToClientHeaderName).map(_.value)
    def setRefreshTokenHeader(s: String) = RawHeader(sessionConfig.refreshTokenHeaderConfig.getFromClientHeaderName, s)
    def isRefreshTokenExpired = getRefreshToken.contains("")

    def getSessionTransport = usingHeaders
    def setSessionTransport = usingHeaders
  }
} 
开发者ID:adamw,项目名称:testpr,代码行数:62,代码来源:MultipleTransportTest.scala

示例3: SparkServicesSpec

//设置package包名称以及导入依赖的类
package com.knoldus.couchbaseServices

import java.util.UUID

import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.couchbase.client.java.document.json.JsonObject
import com.knoldus.couchbaseServices.routes.SparkService
import org.scalatest.{Matchers, WordSpec}

class SparkServicesSpec extends WordSpec with Matchers with ScalatestRouteTest with SparkService {

  val documentId = "user::" + UUID.randomUUID().toString
  val jsonObject = JsonObject.create().put("name", "Shivansh").put("email", "[email protected]")
  val jsonDocument = persistOrUpdate(documentId, jsonObject)
  "The service" should {

    "be able to insert data in the couchbase" in {
      Get("/insert/name/Shivansh/email/[email protected]") ~> sparkRoutes ~> check {
        responseAs[String].contains("Data is successfully persisted with id") shouldEqual true
      }
    }

    "to be able to retrieve data via N1Ql" in {
      Get("/getViaN1Ql/name/Shivansh") ~> sparkRoutes ~> check {
        responseAs[String].contains("[email protected]") shouldEqual true
      }
    }
    "be able to retrieve data via View query" in {
      Get("/getViaView/name/Shivansh") ~> sparkRoutes ~> check {
        responseAs[String].contains("[email protected]") shouldEqual true
      }
    }

    "be able to retrieve data via KV operation" in {
      Get(s"/getViaKV/id/$documentId") ~> sparkRoutes ~> check {
        responseAs[String].contains("[email protected]") shouldEqual true
      }
    }
    "be able to update data via KV operation" in {
      Get(s"/updateViaKV/name/Shivansh/email/[email protected]/id/$documentId") ~> sparkRoutes ~> check {
        responseAs[String].contains("Data is successfully persisted with id") shouldEqual true
      }
    }
  }
} 
开发者ID:couchbase-guides,项目名称:spark-akka,代码行数:46,代码来源:SparkServicesSpec.scala

示例4: SparkServicesSpec

//设置package包名称以及导入依赖的类
package com.knoldus.couchbaseServices

import java.util.UUID

import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.knoldus.domain.User
import com.knoldus.routes.SparkService
import org.scalatest.{Matchers, WordSpec}

class SparkServicesSpec extends WordSpec with Matchers with ScalatestRouteTest with SparkService {

  val documentId = "user::" + UUID.randomUUID().toString
  val jsonObject = User("1", "Shivansh", "[email protected]")
  create(jsonObject)
  "The service" should {

    "be able to insert data in the couchbase" in {
      Get("/create/name/Shivansh/email/[email protected]") ~> sparkRoutes ~> check {
        responseAs[String].contains("Data is successfully persisted with id") shouldEqual true
      }
    }

    "to be able to retrieve data via N1Ql" in {
      Get("/retrieve/id/1") ~> sparkRoutes ~> check {
        responseAs[String].contains("[email protected]") shouldEqual true
      }
    }}} 
开发者ID:scott858,项目名称:sparkCassandra,代码行数:28,代码来源:SparkServicesSpec.scala

示例5: MethodDDirectivesSpec

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

import DDirectives._
import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec

class MethodDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {

  private def check(m: MethodDDirective): Unit = m.toString must {
    "be applied to documentation" in {
      m.describe(RouteDocumentation()).method mustBe Some(m.toString)
    }
    "be counted during request handling" in {
      val route = m {complete("ok")}
      Get()     ~> route ~> check {handled must be (m == GET)}
      Post()    ~> route ~> check {handled must be (m == POST)}
      Delete()  ~> route ~> check {handled must be (m == DELETE)}
      Put()     ~> route ~> check {handled must be (m == PUT)}
      Head()    ~> route ~> check {handled must be (m == HEAD)}
      Options() ~> route ~> check {handled must be (m == OPTIONS)}
      Patch()   ~> route ~> check {handled must be (m == PATCH)}
    }
  }

  check(GET)
  check(POST)
  check(DELETE)
  check(PUT)
  check(HEAD)
  check(OPTIONS)
  check(PATCH)

} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:36,代码来源:MethodDDirectivesSpec.scala

示例6: ParameterDDirectivesSpec

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

import DDirectives._
import akka.http.documenteddsl.documentation.{JsonSchema, ParamDocumentation, RouteDocumentation}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec

class ParameterDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {

  "Param" must {
    "be applied to route documentation" in {
      Param[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
        name = "xxx",
        schema = JsonSchema.string,
        required = true,
        origin = ParamDocumentation.Origin.Query)))
    }
    "be counted during request processing" in {
      val route = Param[String]("xxx") apply {x => complete(s"$x")}
      Get("/?xxx=zzz") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "zzz"}
    }

    "be preprocessed" in {
      implicit val preprocess = new Preprocess[String] {
        override def apply(x: String): String = 11 + x
      }
      val route = Param[String]("xxx") apply {x => complete(s"$x")}
      Get("/?xxx=zzz") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "11zzz"}
    }
  }

  "OptParam" must {
    "be applied to route documentation" in {
      OptParam[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
        name = "xxx",
        schema = JsonSchema.string,
        required = false,
        origin = ParamDocumentation.Origin.Query)))
    }
    "be counted during request processing" in {
      val route = OptParam[String]("xxx") apply {x => complete(s"$x")}
      Get("/?xxx=zzz") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "Some(zzz)"}
      Get("/") ~> route ~> check {handled mustBe true; responseAs[String] mustBe "None"}
    }
  }

} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:49,代码来源:ParameterDDirectivesSpec.scala

示例7: UnmarshallingDDirectivesSpec

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

import java.time.LocalDate

import akka.http.documenteddsl.directives.UnmarshallingDDirectives._
import akka.http.documenteddsl.documentation.OutDocumentation._
import akka.http.documenteddsl.documentation.{JsonSchema, OutDocumentation, RouteDocumentation}
import akka.http.scaladsl.model.{ContentTypes, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec
import play.api.libs.json.{Format, Json}

class UnmarshallingDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {
  import UnmarshallingDDirectivesSpec._

  "Out" must {
    val now = LocalDate.now()

    "be applied to route documentation" in {
      Out[TestOut].describe(RouteDocumentation()).out mustBe Some(OutDocumentation(
        success = List(
          Payload.Success(
            status = Status(StatusCodes.OK),
            contentType = "application/json",
            schema = JsonSchema.resolveSchema[TestOut],
            example = None))))
    }
    "be applied to route documentation (concatenated)" in {
      val out = Out(StatusCodes.Created, TestOut("id", Some("name"), now)) & Out(StatusCodes.NotFound, "entity not found")
      out.describe(RouteDocumentation()).out mustBe Some(OutDocumentation(
        failure = List(
          Payload.Failure(
            status = Status(StatusCodes.NotFound),
            contentType = None,
            description = Some("entity not found"))),
        success = List(
          Payload.Success(
            status = Status(StatusCodes.Created),
            contentType = "application/json",
            schema = JsonSchema.resolveSchema[TestOut],
            example = Some(Json toJson TestOut("id", Some("name"), now))))))
    }
  }

}

object UnmarshallingDDirectivesSpec {
  case class TestOut(id: String, name: Option[String], createdAt: LocalDate)
  implicit val testInFormat: Format[TestOut] = Json.format[TestOut]
} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:52,代码来源:UnmarshallingDDirectivesSpec.scala

示例8: FormFieldDDirectivesSpec

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

import DDirectives._
import akka.http.documenteddsl.documentation.{JsonSchema, ParamDocumentation, RouteDocumentation}
import akka.http.scaladsl.model.FormData
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.MustMatchers._
import org.scalatest.WordSpec

class FormFieldDDirectivesSpec extends WordSpec with DDirectivesSpec with ScalatestRouteTest {

  "FormField" must {
    "be applied to route documentation" in {
      FormField[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
        name = "xxx",
        schema = JsonSchema.string,
        required = true,
        origin = ParamDocumentation.Origin.Form)))
    }
    "be counted during request processing" in {
      val route = FormField[String]("xxx") apply {x => complete(s"$x")}
      val formData = FormData("xxx" -> "zzz")
      Post("/", formData) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "zzz"}
    }
    "be preprocessed" in {
      implicit val preprocess = new Preprocess[String] {
        override def apply(x: String): String = 11 + x
      }
      val route = FormField[String]("xxx") apply {x => complete(s"$x")}
      val formData = FormData("xxx" -> "zzz")
      Post("/", formData) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "11zzz"}
    }
  }

  "OptFormField" must {
    "be applied to route documentation" in {
      OptFormField[String]("xxx").describe(RouteDocumentation()).parameters mustBe Some(List(ParamDocumentation(
        name = "xxx",
        schema = JsonSchema.string,
        required = false,
        origin = ParamDocumentation.Origin.Form)))
    }
    "be counted during request processing" in {
      val route = OptFormField[String]("xxx") apply {x => complete(s"$x")}
      Post("/", FormData("xxx" -> "zzz")) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "Some(zzz)"}
      Post("/", FormData()) ~> route ~> check {handled mustBe true; responseAs[String] mustBe "None"}
    }
  }

} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:51,代码来源:FormFieldDDirectivesSpec.scala

示例9: TapStreamRouteSpec

//设置package包名称以及导入依赖的类
import org.scalatest.{Matchers, WordSpec}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.http.scaladsl.server._
import Directives._
import org.goingok.httpServer.{ResponseMessage, GenericApi, GoingOkAPI}
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._

class TapStreamRouteSpec extends WordSpec with Matchers with ScalatestRouteTest with GoingOkAPI with Json4sSupport {


  "The service" should {

    "return a greeting for GET requests to the root path" in {
      // tests:
      Get() ~> routes ~> check {
        responseAs[ResponseMessage].message shouldEqual "The current version of this API can be found at /v1"
      }
    }

    "return an 'ok' message for GET requests to /v1/health" in {
      // tests:
      Get("/v1/health") ~> routes ~> check {
        responseAs[ResponseMessage].message shouldEqual "ok"
      }
    }

    "leave GET requests to other paths unhandled" in {
      // tests:
      Get("/someOtherPath") ~> routes ~> check {
        handled shouldBe false
      }
    }

    "return a MethodNotAllowed error for PUT requests to the root path" in {
      // tests:
      Put() ~> Route.seal(routes) ~> check {
        status === StatusCodes.MethodNotAllowed
        import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers.stringUnmarshaller
        responseAs[String] shouldEqual "HTTP method not allowed, supported methods: GET"
      }
    }
  }
} 
开发者ID:GoingOK,项目名称:goingok-server,代码行数:46,代码来源:TapStreamRouteSpec.scala

示例10: SampleRoutesSpec

//设置package包名称以及导入依赖的类
package routes

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.queirozf.routes.SampleRoutes
import com.queirozf.utils.{CustomExceptionHandling, CustomRejectionHandling}
import org.scalatest.{Matchers, WordSpec}

class SampleRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest {

  implicit val exceptionHandler = CustomExceptionHandling.handler
  implicit val rejectionHandler = CustomRejectionHandling.handler

  val sampleRoutes = new SampleRoutes().routes

  "sampleRoutes" can {

    "test" should {

      "respond 200 with correct payload for test route" in {

        // see http://doc.akka.io/docs/akka-http/current/scala/http/routing-dsl/testkit.html#testing-sealed-routes
        Get(s"/999/test") ~> Route.seal(sampleRoutes) ~> check {
          status shouldEqual StatusCodes.OK
          responseAs[String] shouldEqual "999"
        }

      }
    }
  }
} 
开发者ID:queirozfcom,项目名称:akka-http-docker-aws-code-pipeline-beanstalk,代码行数:33,代码来源:SampleRoutesSpec.scala

示例11: EchoBotSpec

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.{MessageReplier, SignatureVerifier}
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}

import scala.concurrent.Future

class EchoBotSpec
  extends FlatSpec
    with Matchers
    with ScalatestRouteTest
    with EventsJsonSupport
    with MockFactory {

  def createBot(
                 sv: SignatureVerifier = mock[SignatureVerifier],
                 mr: MessageReplier = mock[MessageReplier]
               ): EchoLineBot = new EchoLineBot(
    channelSecret = "channelSecret",
    signatureVerifier = sv,
    messageReplier = mr
  )

  it should "reply text message as reveived" in {
    val signatureVerifier = stub[SignatureVerifier]
    (signatureVerifier.isValid _).when(*, *, *) returns true
    val messageReplier = stub[MessageReplier]
    (messageReplier.replyMessage _).when(*, *).returns(Future.successful(Unit))

    val bot = createBot(
      signatureVerifier,
      messageReplier
    )
    val event = MessageEvent(
      replyToken = "replyToken",
      timestamp = 0,
      source = UserSource(id = "1"),
      message = TextMessage(id = "2", text = "test message")
    )
    val body = Events(List(event))
    val header = RawHeader("X-Line-Signature", "signature")

    Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
      status shouldBe StatusCodes.OK
      responseAs[String] shouldBe "OK"
    }
    (signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
    (messageReplier.replyMessage _).verify("replyToken", "test message").once
  }

} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:58,代码来源:EchoBotSpec.scala

示例12: BaseLineBotSpec

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.SignatureVerifier
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}

class BaseLineBotSpec
  extends FlatSpec
    with Matchers
    with ScalatestRouteTest
    with EventsJsonSupport
    with MockFactory {

  def createBot(
                 sv: SignatureVerifier = mock[SignatureVerifier],
                 rv:List[Event] => Unit
               ): BaseLineBot[Unit] = new BaseLineBot[Unit] {
    override val channelSecret: String = "channelSecret"
    override val signatureVerifier: SignatureVerifier = sv

    override def receive(events: List[Event]): Unit = rv(events)
  }

  it should "Verify signature" in {
    val signatureVerifier = stub[SignatureVerifier]
    (signatureVerifier.isValid _).when(*, *, *) returns true
    val receive = stubFunction[List[Event], Unit]
    receive.when(*).returns(Unit)
    val bot = createBot(
      signatureVerifier,
      receive
    )
    val event = MessageEvent(
      replyToken = "replyToken",
      timestamp = 0,
      source = UserSource(id = "1"),
      message = TextMessage(id = "2", text = "test message")
    )
    val body = Events(List(event))
    val header = RawHeader("X-Line-Signature", "signature")

    Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
      status shouldBe StatusCodes.OK
      responseAs[String] shouldBe "OK"
    }
    (signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
    receive.verify(body.events).once
  }

} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:56,代码来源:BaseLineBotSpec.scala

示例13: WebServerTest

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

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Ignore, Matchers, WordSpec}
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat
import wow.auth.data.AccountAPI.AccountReq
import wow.utils.Reflection


@Ignore
class WebServerTest extends WordSpec with Matchers with ScalatestRouteTest {
  Reflection.eagerLoadClasses()

  implicit val userFormat: RootJsonFormat[AccountReq] = jsonFormat2(AccountReq.apply)

  "The service" should {
    "return a creation success code when an account is create" in {
      Post("/account/create", AccountReq("myName", "myPass")) ~> WebServer.route ~> check {
        status shouldEqual StatusCodes.Created
      }
    }
    "return a success code when an account is deleted" in {
      Post("/account/delete", "myName") ~> WebServer.route ~> check {
        status shouldEqual StatusCodes.OK
      }
    }
    "return a success code when a password is reinitialized" in {
      Put("/account/reinitialize", AccountReq("myName", "myPass")) ~> WebServer.route ~> check {
        status shouldEqual StatusCodes.OK
      }
    }
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:37,代码来源:WebServerTest.scala

示例14: canAccessRoute

//设置package包名称以及导入依赖的类
package co.horn.alkes.auth

import akka.http.scaladsl.model.HttpMethod
import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST, PUT}
import akka.http.scaladsl.model.StatusCodes.{Forbidden, ServerError}
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import co.horn.alkes.config.Configuration
import co.horn.alkes.dao.DataHandler
import co.horn.alkes.dao.implementations.riak.RiakDataHandler
import co.horn.alkes.log.Logger
import co.horn.alkes.rest.Routes
import org.scalatest.{FunSpec, Matchers}
import org.scalatest.concurrent.Eventually

trait AuthTest extends FunSpec with Matchers with Eventually with ScalatestRouteTest with Routes {
  val config: Configuration = Configuration.get
  val dao: DataHandler      = new RiakDataHandler(config)
  val log: Logger           = config.log.tests

  // TODO: Define these all in just ONE spot. Need to keep DRY!
  val BASE_PATH: String  = "/" + config.app.name
  val FILE_PATH: String  = BASE_PATH + "/share/file"
  val LIST_PATH: String  = BASE_PATH + "/share/filelist"
  val META_PATH: String  = BASE_PATH + "/share/metadata"
  val THUMB_PATH: String = BASE_PATH + "/share/thumbnail"

  
  def canAccessRoute(token: OAuth2BearerToken, route: String, method: HttpMethod): Boolean = {
    method match {
      case GET =>
        Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case PUT =>
        Put(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case DELETE =>
        Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case POST =>
        Post(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case m => throw new IllegalArgumentException(s"$m is not an HttpMethod accepted by Alkes.")
    }
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:56,代码来源:AuthTest.scala

示例15: provisionUsersList

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

import akka.http.scaladsl.testkit.ScalatestRouteTest
import de.heikoseeberger.akkahttpcirce.CirceSupport
import com.noedominguez.class_orchestration.restapi.http.HttpService
import com.noedominguez.class_orchestration.restapi.models.UserEntity
import com.noedominguez.class_orchestration.restapi.services.{AuthService, ExplorationsService, ExplorationEventsService, TeamsService, UsersService, ExplorationObjectsService}
import com.noedominguez.class_orchestration.restapi.utils.DatabaseService
import com.arisanet.utils.InMemoryPostgresStorage._
import org.scalatest._

import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.Random

trait BaseServiceTest extends WordSpec with Matchers with ScalatestRouteTest with CirceSupport {

  dbProcess.getProcessId

  private val databaseService = new DatabaseService(jdbcUrl, dbUser, dbPassword)

  val usersService = new UsersService(databaseService)
  val authService = new AuthService(databaseService)(usersService)
  val teamsService = new TeamsService(databaseService)
  val explorationsService = new ExplorationsService(databaseService)
  val explorationEventsService = new ExplorationEventsService(databaseService)
  val explorationObjectsService = new ExplorationObjectsService(databaseService)
  val httpService = new HttpService(usersService, authService, teamsService, explorationsService, explorationEventsService, explorationObjectsService)

  def provisionUsersList(size: Int): Seq[UserEntity] = {
    val savedUsers = (1 to size).map { _ =>
      UserEntity(Some(Random.nextLong()),
                  Random.nextString(10),
                  Random.nextString(10),
                  Random.nextBoolean(),
                  Some(0L))
    }.map(usersService.createUser)

    Await.result(Future.sequence(savedUsers), 10.seconds)
  }

  def provisionTokensForUsers(usersList: Seq[UserEntity]) = {
    val savedTokens = usersList.map(authService.createToken)
    Await.result(Future.sequence(savedTokens), 10.seconds)
  }

} 
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:48,代码来源:BaseServiceTest.scala


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