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


Scala Helpers类代码示例

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


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

示例1: PlayWithFoodWithTestComponents

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

import config.ExampleComponents
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.components.OneServerPerTestWithComponents
import play.api.db.evolutions.Evolutions
import play.api.http.Status
import play.api.libs.ws.WSClient
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, Helpers, TestServer}
import play.api.{Application, Configuration}
import slick.dbio.DBIO

trait PlayWithFoodWithServerBaseTest extends PlaySpec
  with OneServerPerTestWithComponents
  with DefaultFutureDuration
  with DefaultExecutionContext
  with Status
  with DefaultAwaitTimeout
  with FutureAwaits
  with BeforeAndAfterEach {

  class PlayWithFoodWithTestComponents extends ExampleComponents(context) {

    override def configuration: Configuration = {
      val testConfig = Configuration.from(TestUtils.config)
      val config = super.configuration
      val testConfigMerged = config ++ testConfig
      config.toString
      testConfigMerged
    }

    implicit lazy val testWsClient: WSClient = wsClient
  }

  override def components: PlayWithFoodWithTestComponents = new PlayWithFoodWithTestComponents

  private def runServerAndCleanUpInMemDb(c: PlayWithFoodWithTestComponents) = {
    runServerAndExecute(c.application) {
      val dbapi = c.dbApi
      Evolutions.cleanupEvolutions(dbapi.database("default"))
    }
  }

  override protected def afterEach(): Unit = {
    runServerAndCleanUpInMemDb(components)
  }

  protected def runServerAndExecute[T](app: Application)(blockWithComponents: => T): T = {
    Helpers.running(TestServer(port, app))(blockWithComponents)
  }

  def runAndAwaitResult[T](action: DBIO[T])(implicit components: ExampleComponents): T = {
    TestUtils.runAndAwaitResult(action)(components.actionRunner, duration)
  }

} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:58,代码来源:PlayWithFoodWithServerBaseTest.scala

示例2: TestBuilder

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

import play.api.Application
import play.api.mvc.{AnyContentAsEmpty, Result}
import play.api.test.{FakeHeaders, FakeRequest, Helpers}
import play.mvc.Call

import scala.concurrent.Future

object TestBuilder {

  object anUser {

    import play.api.test.Helpers._
    def GET(call: Call)(implicit app: Application): Option[Future[Result]] =
      route(app, fakeUnauthenticatedRequest(Helpers.GET, call.url(), FakeHeaders(), AnyContentAsEmpty))

    def POST[A](call: Call)(body: A)(implicit w: play.api.http.Writeable[A], app: Application): Option[Future[Result]] =
      route(app, fakeUnauthenticatedRequest(Helpers.POST, call.url(), jsonHeaders, body))

    private def fakeUnauthenticatedRequest[A](method: String, uri: String, headers: FakeHeaders, body: A): FakeRequest[A] = FakeRequest(
      method,
      uri,
      withAjaxHeader(headers),
      body
    )

    private def jsonHeaders = FakeHeaders(
      Seq("Content-Type" -> "application/json")
    )

    private def withAjaxHeader(headers: FakeHeaders): FakeHeaders = headers.copy(data = headers.data :+ ("X-Requested-With" -> "XMLHttpRequest"))
  }

} 
开发者ID:fagossa,项目名称:play-reactive-couchbase,代码行数:36,代码来源:TestBuilder.scala

示例3: MyDIControllerTest

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

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.util.Timeout
import com.github.sample.services.MyService
import org.mockito.Matchers.any
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FunSpec, MustMatchers}
import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class MyDIControllerTest extends FunSpec with MustMatchers with MockitoSugar {

  describe("MyDIControllerTest") {

    implicit val timeout = Timeout(5000, TimeUnit.MILLISECONDS)

    it("controllerTest"){
      val mockService = mock[MyService]
      when(mockService.exec(any[String])) thenReturn Future{"str"}

      val actorSystem = ActorSystem.apply()
      val controller = new MyDIController(mockService, actorSystem)

      val result: Future[Result] = controller.message().apply(FakeRequest())
      Helpers.contentAsString(result) mustBe "str"
      Helpers.status(result) mustBe 200
    }
  }

} 
开发者ID:tm-sukehiro,项目名称:play2-sandbox,代码行数:39,代码来源:MyDIControllerTest.scala

示例4: MyDIControllerTest

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

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.util.Timeout
import com.github.uryyyyyyy.services.MyService
import org.scalatest.{FunSpec, MustMatchers}
import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class MyDIControllerTest extends FunSpec with MustMatchers  {

  describe("MyDIControllerTest") {

    implicit val timeout = Timeout(5000, TimeUnit.MILLISECONDS)

    it("controllerTest"){
      val myService = new MyService(){
        override def exec(str: String): Future[String] = Future{ "str"}
      }
      val actorSystem = ActorSystem.apply()
      val controller = new MyDIController(myService, actorSystem)

      val result: Future[Result] = controller.message().apply(FakeRequest())
      Helpers.contentAsString(result) mustBe "str"
      Helpers.status(result) mustBe 200
    }
  }

} 
开发者ID:uryyyyyyy,项目名称:play2sample,代码行数:36,代码来源:MyDIControllerTest.scala

示例5: withMockServer

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

import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.routing.Router
import play.api.test.{ Helpers, TestServer }

trait WithMockServer {

  def withMockServer(router: Router)(block: (Application => Unit)) {
    val server: TestServer = testServer(router)
    Helpers.running(server) {
      block(server.application)
    }
  }

  // the mock server
  def testServer(router: Router): TestServer = {
    val port = 9999
    val app = GuiceApplicationBuilder()
      .configure(
        "reddit.tokenUrl" -> s"http://localhost:$port/token",
        "reddit.api.clientId" -> "Client-Id",
        "reddit.api.secret" -> "Secret"
      )
      .router(router)
      .build()
    TestServer(port, app)
  }
} 
开发者ID:marcospereira,项目名称:reddit-bot,代码行数:31,代码来源:WithMockServer.scala

示例6: AdvertiserControllerSpec

//设置package包名称以及导入依赖的类
package scala.controllers.advert

import models.advert.{Advertiser, AdvertiserBusinessUpdate}
import models.social.{M8User, M8UserList, M8UserPosition}
import play.api.http.Status
import play.api.libs.json.Json
import play.api.test.Helpers._
import play.api.test.{FakeHeaders, FakeRequest, Helpers}
import utils._

class AdvertiserControllerSpec extends UnitSpec {
  "AdvertiserController" must {
    "get the advert by id" in {
      val vladResult = registerVlad.get
      val advertiserResult = registerWeiZhengAsAdvertiser.get

      M8User.updatePosition(vladResult.userId, M8UserPosition(-25.274398, 133.775126))
      Advertiser.confirmEmail(advertiserResult.advertiserId, advertiserResult.emailConfirmToken)
      activeAdvertiser(advertiserResult.advertiserId)

      Advertiser.updateBusiness(advertiserResult.advertiserId,
        AdvertiserBusinessUpdate("Crazydog Apps", Some("012345678"),
          Some("www.crazydog.com.au"), "4/15 Robinson Street", -25.274398, 133.775136, "We are a software company"))

      val result = M8User.listAdvertsNearby(vladResult.userId, M8UserList(None, None, 0, 10))
      val fakeRequest = FakeRequest(Helpers.GET,
        controllers.advert.routes.AdvertiserController.getAdvert(result.get(0).advertId).url,
        FakeHeaders(Seq(MobileApiTokenHeader -> Seq(mobileApiToken),
          MobileAccessTokenHeader -> Seq(vladResult.accessToken))),
        Json.obj()
      )

      verifyHttpResult(route(fakeRequest).get, Status.OK, "Crazydog Apps")
    }
  }
} 
开发者ID:pro-zw,项目名称:m8chat,代码行数:37,代码来源:AdvertiserControllerSpec.scala

示例7: randomLinked

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

import akka.util.Timeout
import auth.api.model.core.UserToken
import auth.core.testkit.AuthCoreGenerators
import auth.direct.testkit.Linker
import org.scalacheck.Gen
import play.api.http.{HeaderNames, HttpVerbs}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.mvc.{AnyContentAsEmpty, Result}
import play.api.test.{FakeRequest, Helpers, ResultExtractors}
import testkit.{ModelGenerators, ModelLinkers}

import scala.concurrent.Future
import play.api.libs.json.Json
import play.api.test.Helpers._

trait AuthSpecHelpers extends AuthCoreGenerators with ModelGenerators with ModelLinkers {
  implicit val ec = scala.concurrent.ExecutionContext.global

  
  def randomLinked[R, A]()(implicit genR: Gen[R], genA: Gen[A], linkAtoR: Linker[R, A]): (R, A) = {
    val r = genR.sample.get
    val a = genA.sample.get
    (r, linkAtoR.link(r, a))
  }

  def FakePostRequest(): FakeRequest[AnyContentAsEmpty.type] = FakeRequest(POST, "")
  def FakeGetRequest(): FakeRequest[AnyContentAsEmpty.type] = FakeRequest(GET, "")
  def FakePutRequest(): FakeRequest[AnyContentAsEmpty.type] = FakeRequest(PUT, "")
  def FakeDeleteRequest(): FakeRequest[AnyContentAsEmpty.type] = FakeRequest(DELETE, "")
} 
开发者ID:KadekM,项目名称:play-slick-silhouette-auth-api,代码行数:33,代码来源:AuthSpecHelpers.scala

示例8: HotelFileReaderTest

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

import model.Hotel
import org.scalatest.{FunSpec, Matchers}
import play.api.Play
import play.api.Play.current
import play.api.test.{FakeApplication, Helpers}

class HotelFileReaderTest extends FunSpec with Matchers{

  describe("Hotel File Reader"){

    it("should read File and return hotels"){
      Helpers.running(FakeApplication()) {
        val filePath = Play.application.classloader.getResource("test.csv").getPath
        val reader = new HotelFileInputReader(filePath)
        val hotels = reader.read()

        hotels.size should be(4)

        hotels(0) should be(Hotel("Bangkok",1,"Deluxe",1000))
        hotels(2) should be(Hotel("Ashburn",3,"Sweet Suite",1300))
      }
    }
  }
} 
开发者ID:atiqsayyed,项目名称:request_throttling_hotel,代码行数:27,代码来源:HotelFileReaderTest.scala

示例9: ToggledController

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

import javax.inject.Inject

import play.api.mvc.Action
import play.api.test.Helpers
import toguru.api.{Activations, Toggle}
import toguru.test.TestActivations
import play.api.mvc._

trait ControllerHelpers {
  this: RequestHelpers =>
  val toggle = Toggle("toggle-1")

  // you will write such a class in your play app to automatically convert from Play's RequestHeader to ClientInfo
  abstract class ToggledController(toguru: PlayToguruClient, cc: ControllerComponents)
    extends AbstractController(cc) {
    val ToggledAction = PlaySupport.ToggledAction(toguru, cc.parsers.defaultBodyParser)
  }

  class MyController @Inject()(toguru: PlayToguruClient, cc: ControllerComponents)
    extends ToggledController(toguru, cc) {

    def myAction = ToggledAction { implicit request =>
      if (toggle.isOn)
        Ok("Toggle is on")
      else
        Ok("Toggle is off")
    }
  }

  class MyControllerWithOwnTogglingInfo @Inject()(toguru: PlayToguruClient, cc: ControllerComponents)
    extends AbstractController(cc) {

    def myAction = Action { request =>
      implicit val toggling = toguru(request)

      if (toggle.isOn)
        Ok("Toggle is on")
      else
        Ok("Toggle is off")
    }
  }

  def createToggledController(
      provider: Activations.Provider = TestActivations()()) = {

    val toguruClient = PlaySupport.testToguruClient(client, provider)

    new ToggledController(toguruClient, Helpers.stubControllerComponents()) {}
  }

  def createMyController(toguru: PlayToguruClient) = {
    new MyController(toguru, Helpers.stubControllerComponents())
  }

  def createMyControllerWithOwnTogglingInfo(toguru: PlayToguruClient) = {
    new MyControllerWithOwnTogglingInfo(toguru,
                                        Helpers.stubControllerComponents())
  }
} 
开发者ID:AutoScout24,项目名称:toguru-scala-client,代码行数:62,代码来源:ControllerHelpers.scala


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