本文整理汇总了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")
}
}
}
示例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
}
}
}
示例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
}
}
示例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)
示例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
}
示例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
}
示例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
}
)
}
}
}
示例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)
}
示例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()
}
}
示例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)
}
示例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
}
}
}
示例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)) }
}
}
示例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))
}
}
}
示例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()))
}
}
}
示例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))
}
}
}