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


Scala AsResult类代码示例

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


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

示例1: HelloWorldTestSpecs

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

import net.liftweb._
import http._
import net.liftweb.util._
import net.liftweb.common._
import Helpers._
import lib._
import org.specs2.mutable.Specification
import org.specs2.specification.AroundExample
import org.specs2.execute.AsResult


object HelloWorldTestSpecs extends Specification with AroundExample{
  val session = new LiftSession("", randomString(20), Empty)
  val stableTime = now

  
  def around[T : AsResult](body: =>T) = {
    S.initIfUninitted(session) {
      DependencyFactory.time.doWith(stableTime) {
        AsResult( body)  // execute t inside a http session
      }
    }
  }

  "HelloWorld Snippet" should {
    "Put the time in the node" in {
      val hello = new HelloWorld
      Thread.sleep(1000) // make sure the time changes

      val str = hello.howdy(<span>Welcome to your Lift app at <span id="time">Time goes here</span></span>).toString

      str.indexOf(stableTime.toString) must be >= 0
      str must startWith("<span>Welcome to")
    }
  }
} 
开发者ID:EasterTheBunny,项目名称:ourdistrict,代码行数:40,代码来源:HelloWorldTest.scala

示例2: HomeControllerSpec

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

import models.UsersRepository
import org.specs2.execute.{AsResult, Result}
import org.specs2.mutable.Around
import org.specs2.specification.Scope
import play.api.Application
import play.api.mvc._
import play.api.test.{FakeRequest, PlaySpecification}

class HomeControllerSpec extends PlaySpecification with Results {

  abstract class WithTestApplication extends Around with Scope with TestEnvironment {
    lazy val app: Application = fakeApp
    lazy val controller = new HomeController(knolxControllerComponent)

    override def around[T: AsResult](t: => T): Result = {
      TestHelpers.running(app)(AsResult.effectively(t))
    }
  }

  "HomeController" should {

    "redirect index page to sessions page" in new WithTestApplication {
      val result = controller.index(FakeRequest())

      status(result) must be equalTo SEE_OTHER
    }

  }

} 
开发者ID:knoldus,项目名称:knolx-portal,代码行数:33,代码来源:HomeControllerSpec.scala

示例3: around

//设置package包名称以及导入依赖的类
package se.digiplant.imagemagick.plugin

import org.specs2.mutable.Around
import org.specs2.specification.Scope
import org.specs2.execute.{AsResult, Result}
import play.api.test._
import play.api.test.Helpers._
import java.io.File
import org.apache.commons.io.FileUtils
import util.Random

trait ScalrContext extends Around with TempFile {

  implicit val app: FakeApplication = new FakeApplication(
    additionalConfiguration = Map(
      "res.default" -> "tmp/default",
      "res.imagemagickcache" -> "tmp/imagemagickcache",
      "imagemagick.cache" -> "imagemagickcache",
      "imagemagick.cachedir" -> "tmp/imagemagickcachedir"
    )
  )

  def around[T : AsResult](t: =>T) = Helpers.running(app) {
    val result = AsResult.effectively(t)

    tmp.delete()

    result
  }
}

trait TempFile extends Scope {
  lazy val tmp = new File("tmp")
  lazy val logo = new File("test/resources/digiplant.jpg")
  lazy val LargeLogo = new File("test/resources/digiplant_large.jpg")

  def testFile: File = {
    tmp.mkdir()
    val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('1' to '9')
    val rand = (1 to 20).map(x => chars(Random.nextInt(chars.length))).mkString
    val tmpFile = new File("tmp", rand + ".jpg")
    FileUtils.copyFile(logo, tmpFile)
    tmpFile
  }
  def largeTestFile: File = {
    tmp.mkdir()
    val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('1' to '9')
    val rand = (1 to 20).map(x => chars(Random.nextInt(chars.length))).mkString
    val tmpFile = new File("tmp", rand + ".jpg")
    FileUtils.copyFile(LargeLogo, tmpFile)
    tmpFile
  }
} 
开发者ID:digiPlant,项目名称:play-imagemagick,代码行数:54,代码来源:Spec.scala

示例4: CaseworkerMongoSpec

//设置package包名称以及导入依赖的类
package uk.gov.homeoffice.mongo.salat

import org.specs2.execute.{AsResult, Result}
import org.specs2.matcher.Scope
import org.specs2.mutable.Specification
import uk.gov.homeoffice.mongo.casbah.{CaseworkerMongo, EmbeddedMongoSpecification}

class CaseworkerMongoSpec extends Specification with EmbeddedMongoSpecification {
  trait Context extends Scope {
    val repository = new Repository[Test] with CaseworkerMongo {
      val collectionName = "tests"
    }

    def withMongoConfiguration[R: AsResult](r: => R): Result = try {
      System.setProperty("caseworker.mongodb", s"mongodb://${mongoClient.connectPoint}/$database")
      AsResult(r)
    } finally {
      System.clearProperty("caseworker.mongodb")
    }
  }

  "Caseworker Mongo" should {
    "exist via the configuration 'caseworker.mongodb'" in new Context {
      withMongoConfiguration {
        val test = Test("test-me")
        repository save test

        repository.findAll.toSeq must contain(exactly(test))
      }
    }
  }
}

case class Test(id: String) 
开发者ID:UKHomeOffice,项目名称:rtp-caseworker-mongo-lib,代码行数:35,代码来源:CaseworkerMongoSpec.scala

示例5: jre

//设置package包名称以及导入依赖的类
package eu.shiftforward.apso

import org.specs2.execute.{ AsResult, Result, Skipped }
import JreVersionTestHelper._
import scala.math.Ordering.Implicits._

trait JreVersionTestHelper {
  def jre[T](major: Int, minor: Int)(r: => T)(implicit evidence: AsResult[T]): Result = {
    System.getProperty("java.version") match {
      case VersionRegex(ma, mi) if (ma.toInt, mi.toInt) >= (major, minor) => evidence.asResult(r)
      case _ => Skipped(s"This test requires JRE >= $major.$minor")
    }
  }
}

object JreVersionTestHelper extends JreVersionTestHelper {
  val VersionRegex = """^([\d]+)\.([\d]+).*$""".r
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:19,代码来源:JreVersionTestHelper.scala

示例6: ControllerFixture

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

import events._
import eventstore._
import models._
import play.api.test._
import org.specs2.mutable.Around
import org.specs2.execute.Result
import org.specs2.execute.AsResult

object ControllerFixture {
  val password = Password.fromPlainText("password")
}
trait ControllerFixture extends Around {
  val application = FakeApplication(additionalConfiguration = Map("eventstore.implementation" -> "fake", "application.secret" -> "12345"))

  val eventStore: EventStore[DomainEvent] = new fake.FakeEventStore

  var initialStoreRevision = eventStore.reader.storeRevision
  def given[StreamId, Event <: DomainEvent](events: Event*)(implicit eventStreamType: EventStreamType[StreamId, Event]) = {
    for (event <- events) {
      val revision = eventStore.reader.streamRevision(eventStreamType.streamId(event))
      eventStore.committer.tryCommit(Changes(revision, event))
    }
    initialStoreRevision = eventStore.reader.storeRevision
  }

  val memoryImage = MemoryImage[ApplicationState, DomainEvent](eventStore)(ApplicationState()) {
    (state, commit) => state.updateMany(commit.eventsWithRevision)
  }

  val currentUserId = UserId.generate()
  val authenticationToken = AuthenticationToken.generate()

  given(
    UserRegistered(currentUserId, EmailAddress("[email protected]"), "Joe", ControllerFixture.password): UserEvent,
    UserLoggedIn(currentUserId, authenticationToken))
  val registeredUser = memoryImage.get.users.findByAuthenticationToken(authenticationToken) getOrElse (sys.error("user not authenticated"))

  def unauthenticatedRequest = FakeRequest()
  def authenticatedRequest = FakeRequest().withSession("authenticationToken" -> authenticationToken.toString)

  def commits: Stream[eventstore.Commit[DomainEvent]] = eventStore.reader.readCommits[DomainEvent](initialStoreRevision, StoreRevision.Maximum)
  def changes: Seq[DomainEvent] = commits.flatMap(_.events).toSeq

  override def around[T: AsResult](t: => T) = try implicitly[AsResult[T]].asResult(Helpers.running(application)(t)) finally eventStore.close
} 
开发者ID:cubean,项目名称:play-blog-example,代码行数:48,代码来源:ControllerFixture.scala

示例7: foreach

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

import java.io.IOException
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.{FileVisitResult, FileVisitor, Files, Path}

import org.specs2.execute.{AsResult, Result}
import org.specs2.specification.ForEach


trait TemporaryDirectoryContext extends ForEach[Path] {
  override protected def foreach[R: AsResult](f: (Path) => R): Result = {
    val tempDirectory = Files.createTempDirectory(getClass.getName)
    try {
      AsResult(f(tempDirectory))
    } finally {
      Files.walkFileTree(
        tempDirectory,
        new FileVisitor[Path] {
          override def postVisitDirectory(dir: Path, exc: IOException): FileVisitResult = {
            Files.delete(dir)
            FileVisitResult.CONTINUE
          }

          override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = {
            Files.delete(file)
            FileVisitResult.CONTINUE
          }

          override def visitFileFailed(file: Path, exc: IOException): FileVisitResult = throw exc

          override def preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult =
            FileVisitResult.CONTINUE
        }
      )
    }
  }
} 
开发者ID:FRosner,项目名称:cluster-broccoli,代码行数:39,代码来源:TemporaryDirectoryContext.scala

示例8: WithLoggedUser

//设置package包名称以及导入依赖的类
// Based on https://github.com/jaliss/securesocial/commit/77ce2f94d6a0e1f0fb032dbdec344c953dea7771

package securesocialtest

import org.specs2.execute.{ AsResult, Result }
import org.specs2.mock.Mockito
import play.api.test._
import securesocial.core._

abstract class WithLoggedUser(override val app: FakeApplication = FakeApplication(), val identity: Option[Identity] = None) extends WithApplication(app) with Mockito {

  lazy val user = identity getOrElse SocialUserGenerator.socialUser()
  lazy val mockUserService = mock[UserService]

  def cookie = {
    println("cookie"); Authenticator.create(user) match {
      case Right(authenticator) => authenticator.toCookie
      case _ => throw new IllegalArgumentException("Your FakeApplication _must_ configure a working AuthenticatorStore")
    }
  }

  override def around[T: AsResult](t: => T): org.specs2.execute.Result = super.around {
    mockUserService.find(user.identityId) returns Some(user)
    println("setting service")
    UserService.setService(mockUserService)
    t
  }
}

object WithLoggedUser {
  val excludedPlugins = List("securesocial.core.DefaultAuthenticatorStore")
  val includedPlugins = List("securesocialtest.FakeAuthenticatorStore")
  def minimalApp = new FakeApplication(withoutPlugins = excludedPlugins, additionalPlugins = includedPlugins)
} 
开发者ID:epidataio,项目名称:epidata-community,代码行数:35,代码来源:WithLoggedUser.scala

示例9: around

//设置package包名称以及导入依赖的类
package uk.gov.homeoffice.aws.sqs

import java.net.URL
import java.util.UUID
import com.amazonaws.auth.BasicAWSCredentials
import org.elasticmq.rest.sqs.SQSRestServerBuilder
import org.specs2.execute.{AsResult, Result}
import org.specs2.matcher.Scope
import de.flapdoodle.embed.process.runtime.Network._
import uk.gov.homeoffice.specs2.ComposableAround

trait SQSServerEmbedded extends SQSServer with QueueCreation with Scope with ComposableAround {
  val sqsHost = new URL(s"http://127.0.0.1:$getFreeServerPort")

  val sqsServer = SQSRestServerBuilder withInterface sqsHost.getHost withPort sqsHost.getPort start()

  implicit val sqsClient = new SQSClient(new URL(s"$sqsHost/queue"), new BasicAWSCredentials("x", "x"))

  val createMessage: String => Message =
    message => {
      val queue = create(new Queue(UUID.randomUUID().toString))
      val sqs = new SQS(queue)

      sqs publish message
      sqs.receive.head
    }

  override def around[R: AsResult](r: => R): Result = try {
    sqsServer waitUntilStarted()
    info(s"Started SQS $sqsHost")
    super.around(r)
  } finally {
    info(s"Stopping SQS $sqsHost")
    sqsServer stopAndWait()
  }
} 
开发者ID:UKHomeOffice,项目名称:aws-scala-lib,代码行数:37,代码来源:SQSServerEmbedded.scala

示例10: forEachGraph

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

import com.orientechnologies.orient.core.sql.OCommandSQL
import gremlin.scala._
import io.mediachain.util.GremlinUtils.withTransaction
import io.mediachain.util.orient.MigrationHelper
import org.apache.tinkerpop.gremlin.orientdb.OrientGraphFactory
import org.specs2.execute.{AsResult, Failure, Result, Success}
import org.specs2.specification.{Around, Context}
import org.specs2.specification.core.Env
import org.specs2.specification.create.{ContextualFragmentFactory, FragmentsFactory}

trait ForEachGraph[T] extends FragmentsFactory { outer =>

  protected lazy val graphFactory: OrientGraphFactory =
    MigrationHelper.newInMemoryGraphFactory()


  protected def forEachGraph(graph: Graph): T


  protected def foreachContext: Env => Context = (env: Env) => new Around {
    def around[R : AsResult](r: =>R) = AsResult(r)
  }

  protected def withNewGraph[R: AsResult](f: T => R): R = {
    val graph = graphFactory.getTx
    try {
      val t = forEachGraph(graph)
      f(t)
    } finally {
      val db = graph.getRawDatabase
      // about the UNSAFE here... normally you'd use
      // DELETE VERTEX instead of plain DELETE, so that you're
      // not left with disconnected edges.  But we want to wipe out
      // everything from all vertex and edge classes, so we're not
      // concerned about that.
      db.command(new OCommandSQL("DELETE FROM V UNSAFE")).execute[Long]()
      db.command(new OCommandSQL("DELETE FROM E UNSAFE")).execute[Long]()
    }
  }

  implicit def foreachFunctionToResult[R : AsResult]: AsResult[T => R] =
    new AsResult[T => R] {
      def asResult(f: =>T => R): Result =
        AsResult(withNewGraph(f))
    }

  override protected def fragmentFactory =
    new ContextualFragmentFactory(super.fragmentFactory, foreachContext)
} 
开发者ID:mediachain,项目名称:L-SPACE,代码行数:52,代码来源:ForEachGraph.scala

示例11: WithDbData

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

import models.database.ReportsDatabase._
import play.api.test._
import play.api.test.Helpers._
import org.specs2.mutable._
import org.specs2.execute.{Result, AsResult}
import play.api.db.slick._
import play.api.db.slick.Config.driver.simple._

abstract class WithDbData extends WithApplication(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
  override def around[T: AsResult](callback: => T): Result = super.around {
    prepareDbWithData()
    callback
  }

  def prepareDbWithData() = DB.withSession {
    implicit session => reports ++= TestData.inputData
  }
}

class ReportSpec extends Specification {
  "Reports Controller" should {
    "on worldsList return list of worlds" in new WithDbData {
      val result = route(FakeRequest(GET, "/reports/worldsList")).get

      status(result) must equalTo(OK)
      contentType(result) must beSome("application/json")
      contentAsJson(result) mustEqual TestData.expectedWorldsList
    }

    "on reports return list of reports" in new WithDbData {
      val result = route(FakeRequest(GET, "/reports")).get

      status(result) must equalTo(OK)
      contentType(result) must beSome("application/json")
      contentAsJson(result) mustEqual TestData.expectedReportsAll
    }

    "on reports return list of reports with date filter and sort" in new WithDbData {
      val result = route(FakeRequest(GET, "/reports?fromDate=2014-07-02&toDate=2014-07-04&field=detected&sort=asc")).get

      status(result) must equalTo(OK)
      contentType(result) must beSome("application/json")
      contentAsJson(result) mustEqual TestData.expectedReportsWithDateAndSort
    }

    "on reports return list of reports with world filter" in new WithDbData {
      val result = route(FakeRequest(GET, "/reports?world=ua")).get

      status(result) must equalTo(OK)
      contentType(result) must beSome("application/json")
      contentAsJson(result) mustEqual TestData.expectedReportsWithWorld
    }
  }
} 
开发者ID:mahmoudabbasi,项目名称:PlaySlickAngularBootstrapH2TestsExample,代码行数:57,代码来源:ReportSpec.scala

示例12: DragonServletTest

//设置package包名称以及导入依赖的类
package org.blinkmob.scalatraseed

import org.junit.runner.RunWith
import org.scalatra.test.specs2.ScalatraSpec
import org.specs2.runner.JUnitRunner
import org.json4s.jackson.Serialization._
import org.json4s.DefaultFormats
import org.json4s.Formats
import org.blinkmob.models.Dragon
import org.specs2.specification.ForEach
import org.specs2.execute.AsResult
import org.specs2.execute.Result
import java.sql.Connection
import org.scalatra.test.specs2.MutableScalatraSpec
import org.blinkmob.scalatraseed.utils.DB

@RunWith(classOf[JUnitRunner])
class DragonServletTest extends MutableScalatraSpec {
  implicit val jsonFormats: Formats = DefaultFormats
  
      
  addServlet(new DragonServlet, "/dragon")
  
  "GET / on HelloWorldServlet" should {
    "return status 200" in {
      get("/dragon"){
        val resp = read[List[Dragon]](response.body)
        resp must contain(Dragon(1, "BLUE", "Saphira"), Dragon(2, "GREEN", "Puff"))
      }
    }
  }
  
}



trait DatabaseContext extends ForEach[Connection] {
  // you need to define the "foreach" method
  def foreach[R: AsResult](f: Connection => R): Result = {
    DB.rbtx { c => AsResult(f(c)) }
  }
} 
开发者ID:gnomff,项目名称:ScalatraSeed,代码行数:43,代码来源:DragonServletTest.scala

示例13: foreach

//设置package包名称以及导入依赖的类
package org.eclipse.jgit
package lib
package test

import org.eclipse.jgit.lib.Repository

import org.specs2.specification.ForEach
import org.specs2.execute.AsResult
import org.specs2.execute.Result

trait RepositoryTestCase
    extends ForEach[Repository]
    with RepositoryProvider {

  def foreach[R: AsResult](f: Repository => R): Result = {

    withRepository { repository => 

      AsResult(f(repository))
    }
  }
} 
开发者ID:ashawley,项目名称:jgit-scalacheck,代码行数:23,代码来源:RepositoryTestCase.scala

示例14: foreach

//设置package包名称以及导入依赖的类
package org.eclipse.jgit
package api
package test

import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.test.RepositoryProvider

import org.specs2.specification.ForEach
import org.specs2.execute.AsResult
import org.specs2.execute.Result

trait MergeCommandTestCase
    extends ForEach[MergeCommand]
    with RepositoryProvider {

  def foreach[R: AsResult](f: MergeCommand => R): Result = {

    withRepository { repository: Repository =>

      val git = new Git(repository)

      AsResult(f(git.merge()))
    }
  }
} 
开发者ID:ashawley,项目名称:jgit-scalacheck,代码行数:26,代码来源:MergeCommandTestCase.scala

示例15: foreach

//设置package包名称以及导入依赖的类
package org.eclipse.jgit
package api
package test

import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.test.RepositoryProvider

import org.specs2.specification.ForEach
import org.specs2.execute.AsResult
import org.specs2.execute.Result

trait CheckoutCommandTestCase
    extends ForEach[CheckoutCommand]
    with RepositoryProvider {

  def foreach[R: AsResult](f: CheckoutCommand => R): Result = {

    withRepository { repository: Repository =>

      val git = new Git(repository)

      AsResult(f(git.checkout))
    }
  }
} 
开发者ID:ashawley,项目名称:jgit-scalacheck,代码行数:26,代码来源:CheckoutCommandTestCase.scala


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