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


Scala Result类代码示例

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


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

示例1: PerceptronTest

//设置package包名称以及导入依赖的类
package com.danylchuk.swiftlearner.nn.perceptron

import com.danylchuk.swiftlearner.coll.TraversableOp._
import com.typesafe.scalalogging.LazyLogging
import org.specs2.execute.Result
import org.specs2.mutable.Specification


class PerceptronTest extends Specification with LazyLogging {
  def learnAndTest(examples: Seq[(Vector[Double], Boolean)], times: Int) = {
    val p = new Perceptron(Vector(0.0, 0.0))
    val learned = p.learn(examples.repeat(times))
    Result.foreach(examples) { example =>
      learned.f(example._1) must_== example._2
    }
  }

  "Perceptron" should {
    "calculate the activation function correctly" >> {
      val p = new Perceptron(Vector(2.0, 3.0), -25.0)
      p.f(Vector(4.0, 5.0)) must beFalse
      p.f(Vector(4.0, 6.0)) must beTrue
    }

    "learn the AND function" >> {
      val AndExamples = Seq(
        (Vector[Double](0, 0), false),
        (Vector[Double](0, 1), false),
        (Vector[Double](1, 0), false),
        (Vector[Double](1, 1), true))

      learnAndTest(AndExamples, 10)
    }

    "learn the OR function" >> {
      val OrExamples = Seq(
        (Vector[Double](0, 0), false),
        (Vector[Double](0, 1), true),
        (Vector[Double](1, 0), true),
        (Vector[Double](1, 1), true))

      learnAndTest(OrExamples, 10)
    }
  }
} 
开发者ID:valdanylchuk,项目名称:swiftlearner,代码行数:46,代码来源:PerceptronTest.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: CodecTest

//设置package包名称以及导入依赖的类
package at.hazm.quebic

import org.specs2.Specification
import org.specs2.execute.Result
import org.specs2.specification.core.SpecStructure

import scala.util.Random

class CodecTest extends Specification {
  override def is:SpecStructure =
    s2"""
none codec: ${randomDecode(53, 1024, Codec.PLAIN)}
gzip codec: ${randomDecode(53, 1024, Codec.GZIP)}
"""

  def randomDecode(seed:Long, length:Int, codec:Codec):Result = {
    val random = new Random(seed)
    val binary1 = new Array[Byte](length)
    random.nextBytes(binary1)
    val encoded = codec.encode(binary1)
    val binary2 = codec.decode(encoded)
    System.out.println(f"${codec.name.toUpperCase}: ${binary1.length}%,dB -> ${encoded.length}%,dB")
    binary1 === binary2
  }

} 
开发者ID:torao,项目名称:quebic,代码行数:27,代码来源:CodecTest.scala

示例6: GeneratorSpec

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

import org.specs2.mutable.Specification
import org.specs2.execute.Result

object GeneratorSpec extends Specification {
  import Generator._

  "validateSolution()" >> {
    "passes a known valid solution" >> {
      validate(knownValidSolution) must beTrue
    }

    "fails a known invalid solution" >> {
      val wrongAnswer: Vector[Int] =
        knownValidSolution.updated(0, 1).updated(1, 1)

      validate(wrongAnswer) must beFalse
    }
  }

  "generateRandomSolution()" >> {
    "generates 100 valid solutions" >> {
      Result.foreach(1 to 100) { _ =>
        val s = generateRandomSolution()
        validate(s) must beTrue
      }
    }
  }
} 
开发者ID:fishyfriend,项目名称:sudoku,代码行数:31,代码来源:GeneratorSpec.scala

示例7: SolverSpec

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

import org.specs2.mutable.Specification
import org.specs2.execute.Result
import Generator._, Solver._

object SolverSpec extends Specification {
  import random._

  "Solver" >> {
    "correctly solves a known puzzle" >> {
      val input = Vector(
        0, 0, 0, 2, 6, 0, 7, 0, 1,
        6, 8, 0, 0, 7, 0, 0, 9, 0,
        1, 9, 0, 0, 0, 4, 5, 0, 0,
        8, 2, 0, 1, 0, 0, 0, 4, 0,
        0, 0, 4, 6, 0, 2, 9, 0, 0,
        0, 5, 0, 0, 0, 3, 0, 2, 8,
        0, 0, 9, 3, 0, 0, 0, 7, 4,
        0, 4, 0, 0, 5, 0, 0, 3, 6,
        7, 0, 3, 0, 1, 8, 0, 0, 0 )
      val expOutput = Vector(
        4, 3, 5, 2, 6, 9, 7, 8, 1,
        6, 8, 2, 5, 7, 1, 4, 9, 3,
        1, 9, 7, 8, 3, 4, 5, 6, 2,
        8, 2, 6, 1, 9, 5, 3, 4, 7,
        3, 7, 4, 6, 8, 2, 9, 1, 5,
        9, 5, 1, 7, 4, 3, 6, 2, 8,
        5, 1, 9, 3, 2, 6, 8, 7, 4,
        2, 4, 8, 9, 5, 7, 1, 3, 6,
        7, 6, 3, 4, 1, 8, 2, 5, 9 )
      val output = solveWithZeroAsBlank(input)

      output must not equalTo None
      output.get must contain (allOf(expOutput: _*).inOrder)
    }

    "correctly solves 100 randomly-generated puzzles with 20-50 blank squares" >> {
      val solutions =
        List.fill(100) { generateRandomSolution() }
          .map(generateProblem(_, nBlanks = 20 + nextInt(31)))
          .map(solve)

      Result.foreach(solutions) { solution =>
        // don't check against particular expected solutions,
        // as some problems have more than one
        solution must not equalTo None
        validate(solution.get) must beTrue
      }
    }
  }
} 
开发者ID:fishyfriend,项目名称:sudoku,代码行数:53,代码来源:SolverSpec.scala

示例8: 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

示例9: AkkaStreamTestKitSpecificationLike

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

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.testkit.TestSubscriber.Probe
import akka.testkit.TestKit
import com.typesafe.config.ConfigFactory
import org.specs2.execute.Result
import org.specs2.mutable.SpecificationLike

import scala.reflect.macros.blackbox

abstract class AkkaStreamTestKitSpecificationLike extends
  TestKit(ActorSystem("AkkaStreamTestKitSpecificationLike", ConfigFactory.empty())) with SpecificationLike {
  implicit val materializer = ActorMaterializer()

  implicit def probe2Success[R <: Probe[_]](r: R): Result = success

  //  implicit def probe2MatchResult[R](r: R): MatchResult[Any] = ok
}

object MatcherHelper {
  def matcherhelper(c: blackbox.Context)(r: c.Tree) = {
    c.error(c.enclosingPosition, "test should finish with a Matcher or a Probe[T]")
    c.abort(c.enclosingPosition, "blah")
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:28,代码来源:AkkaStreamTestKitSpecificationLike.scala

示例10: 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

示例11: 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

示例12: beRightXor

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

import org.specs2.matcher.Matcher
import org.specs2.execute.{Failure, Result}
import org.specs2.matcher.MatchersImplicits._
import cats.data.Xor

trait XorMatchers {
  def beRightXor[T](checker: (T => Result)): Matcher[Xor[_, T]] = {
    (x: Xor[_, T]) => x match {
      case Xor.Right(value) =>
        checker(value)
      case _ =>
        new Failure(s"Xor value was instance of Xor.Left: $x")
    }
  }

  def beRightXor: Matcher[Xor[_, _]] = { (x: Xor[_, _]) =>
    (x.isRight, s"Xor value was instance of Xor.Left: $x")
  }

  def beLeftXor[T](checker: (T => Result)): Matcher[Xor[T, _]] = {
    (x: Xor[T, _]) => x match {
      case Xor.Left(value) =>
        checker(value)
      case _ =>
        new Failure(s"Xor value was instance of Xor.Right: $x")
    }
  }

  def beLeftXor: Matcher[Xor[_, _]] = { (x: Xor[_, _]) =>
    (x.isLeft, s"Xor value was instance of Xor.Right: $x")
  }
} 
开发者ID:mediachain,项目名称:oldchain,代码行数:35,代码来源:XorMatchers.scala

示例13: checkResult

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

import com.twitter.util.Duration.fromMilliseconds
import com.twitter.util.{Await, Future}
import org.specs2.execute.Result
import org.specs2.mutable.Specification

trait FutureResultChecks { self: Specification =>
  def checkResult[A](result: Future[A]): Result = {
    try {
      // Note. The `get` here forces the evaluation of the future, which will throw an exception if there is one (and thus fail the spec).
      Await.result(result.liftToTry, fromMilliseconds(10)).get()
      success("ok")
    } catch {
      case e: Throwable => failure(e.getMessage)
    }
  }
} 
开发者ID:redbubble,项目名称:finch-template,代码行数:19,代码来源:FutureResultChecks.scala

示例14: 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

示例15: 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


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