• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala OptionValues类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: Benchmarks

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

import com.vatbox.polyjuice.internal.PolyjuiceMapper
import generators.Generator
import org.json4s.native.Serialization
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.time.{Millis, Minutes, Span}
import org.scalatest.{FreeSpec, Matchers, OptionValues, TryValues}

import scala.concurrent.ExecutionContext.Implicits.global

class Benchmarks extends FreeSpec with TryValues with OptionValues with Matchers with ScalaFutures with GeneratorDrivenPropertyChecks {
  implicit val formats = org.json4s.DefaultFormats
  val amount = 10000
  override implicit val patienceConfig = PatienceConfig(Span(1, Minutes), Span(10, Millis))
  val mapper: PolyjuiceMapper = Polyjuice.createMapper(varName = "model", userCode = s"""if (model.bool) return model.int; else return model.str;""")
  "Map many" in {
    forAll(Generator.modelGen, minSuccessful(amount)) { model =>
      val json = Serialization.write(model)
      if (model.bool) {
        val result = mapper.map[Int](json).futureValue.get
        assert(result === model.int)
      }
      else {
        val result = mapper.map[String](json).futureValue.get
        assert(result === model.str)
      }
    }
  }
} 
开发者ID:VATBox,项目名称:polyjuicelib,代码行数:32,代码来源:Benchmarks.scala


示例2: GithubIssuesTests

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

import com.netaporter.uri.config.UriConfig
import com.netaporter.uri.decoding.{PercentDecoder, UriDecodeException}
import com.netaporter.uri.encoding.NoopEncoder
import org.scalatest.{FlatSpec, Matchers, OptionValues}


class GithubIssuesTests extends FlatSpec with Matchers with OptionValues {

  "Github Issue #1" should "throw UriDecodeException when url contains invalid percent encoding" in {
    Seq("/?x=%3", "/%3", "/?a=%3&b=whatever", "/?%3=okay").foreach { part =>
      an[UriDecodeException] should be thrownBy Uri.parse(part)
    }
  }

  it should "leave invalid percent encoded entities as-is when ignoreInvalidPercentEncoding=true" in {
    implicit val c = UriConfig(
      encoder = NoopEncoder,
      decoder = PercentDecoder(ignoreInvalidPercentEncoding = true)
    )
    Seq("/?x=%3", "/%3", "/?a=%3&b=whatever", "/?%3=okay").foreach { part =>
      Uri.parse(part).toString shouldBe part
    }
  }
} 
开发者ID:lemonlabsuk,项目名称:scala-uri,代码行数:27,代码来源:GithubIssuesTests.scala


示例3: CreateAccessTokenHandlerSpec

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.auth

import org.scalatest.{AsyncWordSpecLike, Matchers, OptionValues}
import uk.gov.bis.levyApiMock.data.CommonTestData._
import uk.gov.bis.levyApiMock.data.oauth2.{AuthRecord, AuthRecordOps}
import uk.gov.bis.levyApiMock.data.stubs.StubAuthRecordOps
import uk.gov.bis.levyApiMock.data.{GatewayUser, TimeSource}

import scala.concurrent.{ExecutionContext, Future}
import scalaoauth2.provider.AuthInfo

class CreateAccessTokenHandlerSpec extends AsyncWordSpecLike with Matchers with OptionValues  {

  "createAccessToken" should {
    "create an AuthToken for a non-privileged user" in {
      val authInfo = AuthInfo[GatewayUser](GatewayUser("", "", None, None, None), Some(nonPriviligedClientId), None, None)
      val mockAuthRecords = new MockAuthRecords
      handler(mockAuthRecords).createAccessToken(authInfo).map { _ =>
        mockAuthRecords.createdRecord.value.clientID shouldBe nonPriviligedClientId
        mockAuthRecords.createdRecord.value.privileged.value shouldBe false
      }
    }

    "create an AuthToken for a privileged user" in {
      val authInfo = AuthInfo[GatewayUser](GatewayUser("", "", None, None, None), Some(priviligedClientId), None, None)
      val mockAuthRecords = new MockAuthRecords
      handler(mockAuthRecords).createAccessToken(authInfo).map { _ =>
        mockAuthRecords.createdRecord.value.clientID shouldBe priviligedClientId
        mockAuthRecords.createdRecord.value.privileged.value shouldBe true
      }
    }
  }

  def handler(authRecordOps: AuthRecordOps) = new CreateAccessTokenHandler {
    override def authRecords = authRecordOps

    override def applications = DummyClients

    override def timeSource = new TimeSource {
      override def currentTimeMillis() = 100000L
    }

    override implicit def ec = scala.concurrent.ExecutionContext.Implicits.global
  }

  class MockAuthRecords extends StubAuthRecordOps {
    var createdRecord: Option[AuthRecord] = None

    override def create(record: AuthRecord)(implicit ec: ExecutionContext) = Future.successful {
      createdRecord = Some(record)
    }
  }

} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:55,代码来源:CreateAccessTokenHandlerSpec.scala


示例4: AuthorizedActionBuilderTest

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.actions

import org.scalatest.{AsyncWordSpecLike, Matchers, OptionValues}
import uk.gov.bis.levyApiMock.data.oauth2.AuthRecord
import uk.gov.bis.levyApiMock.data.{GatewayUser, SystemTimeSource}

import scala.concurrent.{ExecutionContext, Future}

class AuthorizedActionBuilderTest extends AsyncWordSpecLike with Matchers with OptionValues {

  private val empref1 = "123/AB12345"
  private val empref2 = "321/XY12345"

  private val testUsername = "user"
  private val testUser = GatewayUser(testUsername, "", Some(empref1), None, None)

  private val nonPrivilegedToken = "12334567890"
  private val nonPrivilegedAuthRecord = AuthRecord(nonPrivilegedToken, None, None, testUsername, None, 3600, System.currentTimeMillis(), "", Some(false))
  private val privilegedToken = "0987654321"
  private val privilegedAuthRecord = AuthRecord(privilegedToken, None, None, testUsername, None, 3600, System.currentTimeMillis(), "", Some(true))

  val records = Map(
    nonPrivilegedToken -> nonPrivilegedAuthRecord,
    privilegedToken -> privilegedAuthRecord
  )
  val users = Map(testUsername -> testUser)


  "non-privileged user with right empref" should {
    "have access" in {
      val sut = new AuthorizedActionBuilder(empref1, new DummyAuthRecords(records), new DummyGatewayUsers(users), new SystemTimeSource)(ExecutionContext.global)
      sut.validateToken(nonPrivilegedToken).map(_.value shouldBe nonPrivilegedAuthRecord)
    }
  }

  "privileged user with other empref" should {
    "have access" in {
      val sut = new AuthorizedActionBuilder(empref2, new DummyAuthRecords(records), new DummyGatewayUsers(users), new SystemTimeSource)(ExecutionContext.global)
      sut.validateToken(privilegedToken).map(_.value shouldBe privilegedAuthRecord)
    }
  }
}

class DummyGatewayUsers(users: Map[String, GatewayUser]) extends StubGatewayUsers {
  override def forGatewayID(gatewayID: String)(implicit ec: ExecutionContext): Future[Option[GatewayUser]] =
    Future.successful(users.get(gatewayID))
}

class DummyAuthRecords(records: Map[String, AuthRecord]) extends StubAuthRecords {
  override def find(accessToken: String)(implicit ec: ExecutionContext): Future[Option[AuthRecord]] =
    Future.successful(records.get(accessToken))
} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:53,代码来源:AuthorizedActionBuilderTest.scala


示例5: RootControllerSpec

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.controllers.api

import org.scalatest.{Matchers, OptionValues, WordSpecLike}
import uk.gov.bis.levyApiMock.actions.AuthenticatedAction
import uk.gov.bis.levyApiMock.data.levy.Href
import uk.gov.bis.levyApiMock.data.stubs.{StubAuthRecordOps, StubGatewayUserOps}
import views.html.helper.urlEncode

class RootControllerSpec extends WordSpecLike with Matchers with OptionValues {
  implicit val ec = scala.concurrent.ExecutionContext.Implicits.global
  val controller = new RootController(StubGatewayUserOps, new AuthenticatedAction(StubAuthRecordOps))
  "buildLinks" should {
    "build a map without an empref entry if empref is None" in {
      controller.buildLinks(None) shouldBe Map("self" -> Href("/"))
    }

    "build a map with an empref entry if empre is Some" in {
      val empref = "123/AB12345"
      controller.buildLinks(Some(empref)) shouldBe Map(
        "self" -> Href("/"),
        empref -> Href(s"/epaye/${urlEncode(empref)}")
      )
    }
  }

} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:27,代码来源:RootControllerSpec.scala


示例6: AuthRecordTest

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.data.oauth2

import org.scalatest.{Matchers, OptionValues, WordSpecLike}

class AuthRecordTest extends WordSpecLike with Matchers with OptionValues {
  val now = 300000L
  val arWithoutRefreshedAt = AuthRecord("at", Some("rt"), None, "", None, 3600, now, "", None)
  val arWithRefreshedAt = arWithoutRefreshedAt.copy(refreshedAt = Some(now))

  "AuthRecord" should {
    "say the refresh token is expired when there is no refreshedAt time" in {
      arWithoutRefreshedAt.refreshTokenExpired(now + arWithoutRefreshedAt.eighteenMonths + 1) shouldBe true
    }

    "say the refresh token is expired when there is a refreshedAt time" in {
      arWithRefreshedAt.refreshTokenExpired(now + arWithoutRefreshedAt.eighteenMonths + 1) shouldBe true
    }

    "say the refresh token is not expired when there is no refreshedAt time" in {
      arWithoutRefreshedAt.refreshTokenExpired(now) shouldBe false
    }

    "say the refresh token is not expired when there is a refreshedAt time" in {
      arWithRefreshedAt.refreshTokenExpired(now) shouldBe false
    }
  }

} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:29,代码来源:AuthRecordTest.scala


示例7: ClientOpsSpec

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.data

import org.apache.commons.codec.binary.Base32
import org.scalatest.{AsyncWordSpecLike, Matchers, OptionValues}
import uk.gov.bis.levyApiMock.auth.TOTP

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}

class ClientOpsSpec extends AsyncWordSpecLike with Matchers with OptionValues {
  val testTime = 9999L
  val timeSource = new TimeSource {
    override def currentTimeMillis() = testTime
  }

  val testClientOps = new TestClientOps(timeSource)

  "validate" should {
    "handle privileged access client" in {
      val token = TOTP.generateCodeAtTime(testClientOps.paSecret, 0L)
      testClientOps.validate(testClientOps.paClientID, Some(token.value), "").map(_ shouldBe true)
    }

    "handle non-privileged access client" in {
      testClientOps.validate(testClientOps.nonPaClientID, Some(testClientOps.nonPaSecret), "").map(_ shouldBe true)
    }
  }
}

class TestClientOps(val timeSource: TimeSource) extends ClientOps {
  val paClientID = "client-pa"
  val paSecret = new Base32().encodeToString("45122452-1da8-4b69-8f3d-651f42c698c6".getBytes)

  val nonPaClientID = "client-non-pa"
  val nonPaSecret = "45122452-1da8-4b69-8f3d-651f42c698c6"

  val applications = List(
    Application("app-pa", "app-id-1", paClientID, paSecret, "server-token-1", privilegedAccess = true),
    Application("app-non-pa", "app-id-2", nonPaClientID, nonPaSecret, "server-token-2", privilegedAccess = false)
  )

  override def forId(clientID: String)(implicit ec: ExecutionContext): Future[Option[Application]] = Future.successful {
    applications.find(_.clientID == clientID)
  }
} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:46,代码来源:ClientOpsSpec.scala


示例8: EmploymentsGenTest

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.services

import org.joda.time.LocalDate
import org.scalatest.{Matchers, OptionValues, WordSpecLike}
import uk.gov.bis.levyApiMock.controllers.ClosedDateRange
import uk.gov.bis.levyApiMock.data.levy.EmploymentCheckRecord

class EmploymentsGenTest extends WordSpecLike with Matchers with OptionValues {

  import EmploymentStatusGenTestSupport._

  val sut = new EmploymentsGen[TestF](repo)

  "employed" should {
    "return no records" in {
      sut.employed("foo", "bar", ClosedDateRange(new LocalDate(), new LocalDate()))(TestData(Seq.empty))._2 shouldBe None
    }

    val empStart = new LocalDate(2017, 1, 1)
    val empEnd = new LocalDate(2017, 2, 28)
    val data = TestData(Seq(EmploymentCheckRecord("foo", "bar", empStart, empEnd)))

    "return 'employed' if the request specifies a range that overlaps with the employment in any way" in {
      sut.employed("foo", "bar", ClosedDateRange(empStart.minusDays(1), empEnd.plusDays(1)))(data)._2.value.employed shouldBe true
      sut.employed("foo", "bar", ClosedDateRange(empStart, empEnd))(data)._2.value.employed shouldBe true
      sut.employed("foo", "bar", ClosedDateRange(empStart, empEnd.minusDays(1)))(data)._2.value.employed shouldBe true
    }
  }
} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:30,代码来源:EmploymentsGenTest.scala


示例9: InMemoryServiceTest

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

import com.danielasfregola.randomdatagenerator.RandomDataGenerator
import model.domain.{Category, StoreProduct}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers, OptionValues}
import service.InMemoryStoreService

import scala.concurrent.ExecutionContext.Implicits.global

class InMemoryServiceTest extends FlatSpec with ScalaFutures with Matchers with OptionValues with RandomDataGenerator {
  val service = new InMemoryStoreService()


  it should "add a product to the store and retrieve it" in {
    val product = random[StoreProduct]

    val chain = for {
      _ <- service.addProduct(product)
      byTitle <- service.getProduct(product.title)
    } yield byTitle

    whenReady(chain) { res =>
      res shouldBe defined
      res.value shouldEqual product
    }
  }

  it should "associate a product with a category" in {
    val product = random[StoreProduct]
    val cat = random[Category]

    val chain = for {
      _ <- service.addProduct(product)
      byTitle <- service.getProduct(product.title)
      addCategory <- service.addProductToCategory(product.title, cat)
      byTitle2 <- service.getProduct(product.title)
      byCategory <- service.productTitlesForCategory(cat.value)
    } yield (byTitle, byTitle2, byCategory)

    whenReady(chain) { case (beforeUpdate, afterUpdate, productTitles) =>
      beforeUpdate shouldBe defined
      beforeUpdate.value shouldEqual product

      afterUpdate shouldBe defined
      info("The updated product should have one more category")
      afterUpdate.value.categories.values should contain theSameElementsAs (product.categories.values + cat)

      productTitles should contain (product.title)
    }
  }
} 
开发者ID:alexflav23,项目名称:exercises,代码行数:53,代码来源:InMemoryServiceTest.scala


示例10: SurgeSpec

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

import org.scalatest.{FlatSpec, Matchers, OptionValues}

class SurgeSpec extends FlatSpec with Matchers with OptionValues {

  "bucket" should "put page views per minute into a range of bucket values" in {
    Surge.bucket(Some(500)) shouldBe Seq(1, 2, 3, 4, 5)
    Surge.bucket(Some(401)) shouldBe Seq(1, 2, 3, 4, 5)
    Surge.bucket(Some(301)) shouldBe Seq(2, 3, 4, 5)
    Surge.bucket(Some(201)) shouldBe Seq(3, 4, 5)
    Surge.bucket(Some(101)) shouldBe Seq(4, 5)
    Surge.bucket(Some(99)) shouldBe Seq(5)
    Surge.bucket(Some(49)) shouldBe Seq(0)
    Surge.bucket(None) shouldBe Seq(0)
  }
} 
开发者ID:guardian,项目名称:commercial-shared,代码行数:18,代码来源:SurgeSpec.scala


示例11: BrandingSpec

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

import org.scalatest.{FlatSpec, Matchers, OptionValues}

class BrandingSpec extends FlatSpec with Matchers with OptionValues {

  private def mkBranding(brandingType: BrandingType) = Branding(
    brandingType = brandingType,
    sponsorName = "sponsor",
    logo = Logo(
      src = "src",
      dimensions = None,
      link = "link",
      label = "label"
    ),
    logoForDarkBackground = None,
    aboutThisLink = Branding.defaultAboutThisLink,
    hostedCampaignColour = None
  )

  "isPaid" should "be true for paid content" in {
    mkBranding(PaidContent) shouldBe 'paid
  }

  it should "be false for non-paid content" in {
    mkBranding(Sponsored) should not be 'paid
  }

  "isSponsored" should "be true for sponsored content" in {
    mkBranding(Sponsored) shouldBe 'sponsored
  }

  it should "be false for non-sponsored content" in {
    mkBranding(PaidContent) should not be 'sponsored
  }

  "isFoundationFunded" should "be true for foundation-funded content" in {
    mkBranding(Foundation) shouldBe 'foundationFunded
  }

  it should "be false for non-foundation-funded content" in {
    mkBranding(PaidContent) should not be 'foundationFunded
  }
} 
开发者ID:guardian,项目名称:commercial-shared,代码行数:45,代码来源:BrandingSpec.scala


示例12: LogoSpec

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

import com.gu.contentapi.client.model.v1.SponsorshipType
import org.scalatest.{FlatSpec, Matchers, OptionValues}

class LogoSpec extends FlatSpec with Matchers with OptionValues {

  private def mkLogo(sponsorshipType: SponsorshipType, webTitle: String = "") = Logo.make(
    title = webTitle,
    sponsorshipType = sponsorshipType,
    src = "src",
    dimensions = None,
    link = "link"
  )

  "make" should "generate the correct label for sponsored content" in {
    val logo = mkLogo(SponsorshipType.Sponsored)
    logo.label shouldBe "Supported by"
  }

  it should "generate the correct label for paid content" in {
    val logo = mkLogo(SponsorshipType.PaidContent)
    logo.label shouldBe "Paid for by"
  }

  it should "generate the correct label for foundation-funded content" in {
    val logo = mkLogo(SponsorshipType.Foundation, webTitle = "Some title")
    logo.label shouldBe "Some title is supported by"
  }

  it should "generate the correct label for the special inequality foundation-funded section" in {
    val logo = mkLogo(SponsorshipType.Foundation, webTitle = "Inequality")
    logo.label shouldBe "The Inequality Project is supported by"
  }

  it should "generate the correct label for the special America's unequal future foundation-funded section" in {
    val logo = mkLogo(SponsorshipType.Foundation, webTitle = "Inequality and Opportunity in America")
    logo.label shouldBe "This series is supported by"
  }
} 
开发者ID:guardian,项目名称:commercial-shared,代码行数:41,代码来源:LogoSpec.scala


示例13: ZipCodeSpec

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

import org.scalatest.{FlatSpec, Matchers, OptionValues}

// scalastyle:off null
class ZipCodeSpec extends FlatSpec with Matchers with OptionValues {
  behavior of "apply"

  it should "return None if value is null" in {
    ZipCode(null) should be (None)
  }

  it should "return None if value is empty string" in {
    ZipCode("") should be (None)
  }

  it should "return None if value is only white space" in {
    ZipCode("    ") should be (None)
  }

  it should "return None if value is invalid zip code" in {
    ZipCode("3") should be (None)
  }

  it should "return Some(ZipCode) if value is valid zip code" in {
    ZipCode("20500").value.value should be ("20500")
  }
} 
开发者ID:csunwold,项目名称:repwatch,代码行数:29,代码来源:ZipCodeSpec.scala


示例14: StateSpec

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

import org.scalatest.{FlatSpec, Matchers, OptionValues}

// scalastyle:off null
class StateSpec extends FlatSpec with Matchers with OptionValues {
  behavior of "apply"

  it should "return None if code is null" in {
    State(null) should be (None)
  }

  it should "return None if code is not a state" in {
    State("VC") should be (None)
  }

  it should "return Some(state) when code is 'WA'" in {
    val state = State("WA")

    state.value.code should be ("WA")
  }
} 
开发者ID:csunwold,项目名称:repwatch,代码行数:23,代码来源:StateSpec.scala


示例15: OrderEntitySpec

//设置package包名称以及导入依赖的类
package be.yannickdeturck.lagomshopscala.order.impl

import java.util.UUID

import akka.actor.ActorSystem
import akka.testkit.TestKit
import be.yannickdeturck.lagomshopscala.order.impl._
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.lightbend.lagom.scaladsl.testkit.PersistentEntityTestDriver
import org.scalatest.{BeforeAndAfterAll, Matchers, OptionValues, WordSpec}


class OrderEntitySpec extends WordSpec with Matchers with BeforeAndAfterAll with OptionValues {
  private val system = ActorSystem("OrderEntitySpec",
    JsonSerializerRegistry.actorSystemSetupFor(OrderSerializerRegistry))

  override protected def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }

  private val id = UUID.randomUUID
  private val itemId = UUID.randomUUID
  private val order = Order(id, itemId, 3, "Yannick")

  private def withTestDriver[T](block: PersistentEntityTestDriver[OrderCommand, OrderEvent, Option[Order]] => T): T = {
    val driver = new PersistentEntityTestDriver(system, new OrderEntity, id.toString)
    try {
      block(driver)
    } finally {
      driver.getAllIssues shouldBe empty
    }
  }

  "order entity" should {
    "allow creating an order" in withTestDriver { driver =>
      val outcome = driver.run(CreateOrder(order))
      outcome.events should contain only OrderCreated(order)
      outcome.state should ===(Some(order))
    }

    "allow looking up an order" in withTestDriver { driver =>
      driver.run(CreateOrder(order))
      val outcome = driver.run(GetOrder)
      outcome.events shouldBe empty
      outcome.replies should contain only Some(order)
      outcome.state should ===(Some(order))
    }
  }
} 
开发者ID:yannickdeturck,项目名称:lagom-shop-scala,代码行数:50,代码来源:OrderEntitySpec.scala


示例16: ItemEntitySpec

//设置package包名称以及导入依赖的类
package be.yannickdeturck.lagomshopscala.item.impl

import java.util.UUID

import akka.actor.ActorSystem
import akka.testkit.TestKit
import com.lightbend.lagom.scaladsl.playjson.JsonSerializerRegistry
import com.lightbend.lagom.scaladsl.testkit.PersistentEntityTestDriver
import org.scalatest.{BeforeAndAfterAll, Matchers, OptionValues, WordSpec}


class ItemEntitySpec extends WordSpec with Matchers with BeforeAndAfterAll with OptionValues {
  private val system = ActorSystem("ItemEntitySpec",
    JsonSerializerRegistry.actorSystemSetupFor(ItemSerializerRegistry))

  override protected def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }

  private val id = UUID.randomUUID
  private val item = Item(id, "title", "desc", BigDecimal.valueOf(25.95))

  private def withTestDriver[T](block: PersistentEntityTestDriver[ItemCommand, ItemEvent, Option[Item]] => T): T = {
    val driver = new PersistentEntityTestDriver(system, new ItemEntity, id.toString)
    try {
      block(driver)
    } finally {
      driver.getAllIssues shouldBe empty
    }
  }

  "item entity" should {
    "allow creating an item" in withTestDriver { driver =>
      val outcome = driver.run(CreateItem(item))
      outcome.events should contain only ItemCreated(item)
      outcome.state should ===(Some(item))
    }

    "allow looking up an item" in withTestDriver { driver =>
      driver.run(CreateItem(item))
      val outcome = driver.run(GetItem)
      outcome.events shouldBe empty
      outcome.replies should contain only Some(item)
      outcome.state should ===(Some(item))
    }
  }
} 
开发者ID:yannickdeturck,项目名称:lagom-shop-scala,代码行数:48,代码来源:ItemEntitySpec.scala


示例17: UnitSpec

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

import org.mongodb.scala.bson.collection.immutable.Document
import org.scalatest.FunSuite
import org.scalatest.Inside
import org.scalatest.Inspectors
import org.scalatest.Matchers
import org.scalatest.OptionValues

abstract class UnitSpec extends FunSuite
  with Matchers
  with OptionValues
  with Inside
  with Inspectors


class MongoQueryParserTest extends UnitSpec {

  trait Fixture {
    val parser = new MongoQueryParser()
  }

  test("Parse query") {
    new Fixture {

      val query: String =
        """
          |{
          |"name" : "The Lord of The Rings",
          |"author" : "J. R. R. Tolkien",
          |"isHardcover" : true,
          |"pages" : 1178,
          |"price" : 13.60,
          |"currency" : "GBP"
          |}
        """.stripMargin

      val expected: String =
        """{
          |"name" : "The Lord of The Rings",
          |"author" : "J. R. R. Tolkien",
          |"isHardcover" : true,
          |"pages" : 1178,
          |"price" : { "$numberDecimal" : "13.60" },
          |"currency" : "GBP"
          |}
        """.stripMargin

      val document: Document = parser.parse(query)
      assert(normalize(document.toJson()) === normalize(expected))
    }
  }

  private def normalize(s: String): String = s.split('\n').map(_.trim.filter(_ != ' ')).mkString

} 
开发者ID:dougsleite,项目名称:oak,代码行数:57,代码来源:MongoQueryParserTest.scala


示例18: MixedPlaySpecWithNoDefaultApp

//设置package包名称以及导入依赖的类
import org.scalatest.concurrent.{Eventually, IntegrationPatience}
import org.scalatest.{MustMatchers, OptionValues, fixture}
import org.scalatestplus.play.{PortNumber, WsScalaTestClient}
import play.api.libs.ws.{WSClient, WSRequest}
import play.api.mvc.Call

abstract class MixedPlaySpecWithNoDefaultApp extends fixture.WordSpec
  with MustMatchers
  with OptionValues
  with MixedFixturesWithNoDefaultApp
  with Eventually
  with IntegrationPatience
  with WsScalaTestClient
{

  //def wsCall(call: Call)(implicit portNumber: PortNumber, wsClient: WSClient): WSRequest = doCall(call.url, wsClient, portNumber)

  // def wsUrl(url: String)(implicit portNumber: PortNumber, wsClient: WSClient): WSRequest = doCall(url, wsClient, portNumber)

  //private def doCall(url: String, wsClient: WSClient, portNumber: PortNumber) = {
  //  wsClient.url("http://localhost:" + portNumber.value + url)
  //}
} 
开发者ID:wsargent,项目名称:play-cucumber,代码行数:24,代码来源:MixedPlaySpecWithNoDefaultApp.scala


示例19: GroupSpec

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

import org.scalatest.{FunSpec, Matchers, OptionValues, Inside, Inspectors}

class GroupSpec extends FunSpec with Matchers
    with OptionValues with Inside with Inspectors
    with Implicits {
  describe("Constructor method") {
    it("should give a specified name") {
      val g1 = Group("foo", "[a-zA-Z0-9]+")
      g1.name shouldBe "foo"
      g1.pattern shouldBe "[a-zA-Z0-9]+"
      g1.names shouldBe Seq("foo")
      g1.allNames shouldBe Seq("foo")

      val p1 = pattern"$g1:$g1"

      val g2 = NestedGroup("bar", p1)
      g2.name shouldBe "bar"
      g2.pattern shouldBe "([a-zA-Z0-9]+):([a-zA-Z0-9]+)"
      g2.names shouldBe Seq("bar")
      g2.allNames shouldBe Seq("bar", "foo", "foo")

      val p2 = pattern"$g2-$g2"
      val g3 = NestedGroup("baz", p2)
      g3.name shouldBe "baz"
      g3.pattern shouldBe "(([a-zA-Z0-9]+):([a-zA-Z0-9]+))-(([a-zA-Z0-9]+):([a-zA-Z0-9]+))"
      g3.names shouldBe Seq("baz")
      g3.allNames shouldBe Seq("baz", "bar", "foo", "foo", "bar", "foo", "foo")

      val g4 = UnnamedGroup(p1)
      g4.name shouldBe "UnnamedGroup(${foo}:${foo})"
      g4.pattern shouldBe "([a-zA-Z0-9]+):([a-zA-Z0-9]+)"
      g4.names shouldBe Seq("foo", "foo")
      g4.allNames shouldBe Seq("foo", "foo")

      val g5 = UnnamedGroup(p2)
      g5.name shouldBe "UnnamedGroup(${bar}-${bar})"
      g5.pattern shouldBe "(([a-zA-Z0-9]+):([a-zA-Z0-9]+))-(([a-zA-Z0-9]+):([a-zA-Z0-9]+))"
      g5.names shouldBe Seq("bar", "bar")
      g5.allNames shouldBe Seq("bar", "foo", "foo", "bar", "foo", "foo")
    }
  }
} 
开发者ID:tarao,项目名称:namedcap-scala,代码行数:45,代码来源:GroupSpec.scala


示例20: ServiceInvokerTest

//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.definition

import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, Matchers, OptionValues}
import pl.touk.nussknacker.engine.api.process.WithCategories
import pl.touk.nussknacker.engine.api.test.InvocationCollectors.NodeContext
import pl.touk.nussknacker.engine.api.{ParamName, Service}
import pl.touk.nussknacker.engine.definition.DefinitionExtractor.ObjectWithMethodDef

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}

class ServiceInvokerTest extends FlatSpec with ScalaFutures with OptionValues with Matchers {

  it should "invoke service method with declared parameters as scala params" in {
    val mock = new MockService
    val definition = ObjectWithMethodDef[Service](WithCategories(mock), ServiceDefinitionExtractor)
    val invoker = ServiceInvoker(definition)

    whenReady(invoker.invoke(Map("foo" -> "aa", "bar" -> 1), NodeContext("", "", ""))) { _ =>
      mock.invoked.value.shouldEqual(("aa", 1))
    }

  }

  it should "throw excpetion with nice message when parameters do not match" in {
    val mock = new MockService
    val definition = ObjectWithMethodDef[Service](WithCategories(mock), ServiceDefinitionExtractor)
    val invoker = ServiceInvoker(definition)

    intercept[IllegalArgumentException](
      invoker.invoke(Map("foo" -> "aa", "bar" -> "terefere"), NodeContext("", "", ""))).getMessage shouldBe "Parameter bar has invalid class: java.lang.String, should be: int"
  }

}

class MockService extends Service {

  @volatile var invoked: Option[(String, Int)] = None

  def invoke(@ParamName("foo") foo: String, @ParamName("bar") bar: Int)
            (implicit ec: ExecutionContext): Future[Any] = {
    invoked = Some((foo, bar))
    Future.successful(Unit)
  }

} 
开发者ID:TouK,项目名称:nussknacker,代码行数:48,代码来源:ServiceInvokerTest.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala AmazonKinesisClient类代码示例发布时间:2022-05-23
下一篇:
Scala FetchRequestBuilder类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap