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


Scala BeforeAndAfter类代码示例

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


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

示例1: HttpJsonTopicFetcherTest

//设置package包名称以及导入依赖的类
package com.groupon.dse.kafka.topic

import org.mockito.Mockito
import org.scalatest.{BeforeAndAfter, FlatSpec}

class HttpJsonTopicFetcherTest extends FlatSpec with BeforeAndAfter {

  "The topic fetcher" should "return the correct list of topics " in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val content = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":true}},{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\"}}],\"extras\":\"test\"}"
    Mockito.doReturn(Some(content)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq(TopicAndMetadata("topic1", Map("m1" -> "v1", "m2" -> true.asInstanceOf[AnyRef])), TopicAndMetadata("topic2", Map("m3" -> "v3"))))
  }

  "The topic fetcher" should "return an empty list if the Json in incorrect " in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val content = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":true}}{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\"}}],\"extras\":\"test\"}"
    Mockito.doReturn(Some(content)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq())
  }

  "The topic fetcher " should "return the filtered list if the name field is missing for any topic" in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val contents = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":\"v2\"}},{\"name1\":\"topic2\",\"enabled\":\"false\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}},{\"name\":\"topic3\",\"enabled\":\"true\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}}],\"extras\":\"test\"}"
    Mockito.doReturn(Some(contents)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq(TopicAndMetadata("topic1", Map("m1" -> "v1", "m2" -> "v2")), TopicAndMetadata("topic3", Map("m3" -> "v3", "m4" -> "v4"))))
  }

  "The topic fetcher" should "return an empty map if no metadata is provided" in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val contents = "{\"topics\":[{\"name\":\"topic1\"},{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\",\"m4\":{\"m5\":\"v5\"},\"bool\":true}}]}"
    Mockito.doReturn(Some(contents)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq(TopicAndMetadata("topic1", Map()), TopicAndMetadata("topic2", Map("m3" -> "v3", "m4" -> Map("m5" -> "v5").asInstanceOf[AnyRef], "bool" -> true.asInstanceOf[AnyRef]))))
  }

  "The topic fetcher" should "return an empty list of topics if there is any problem when fetching the Json" in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    Mockito.doReturn(None).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq.empty)
  }

} 
开发者ID:groupon,项目名称:baryon,代码行数:43,代码来源:HttpJsonTopicFetcherTest.scala

示例2: RedirectionSpec

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

import com.kurz.services.RedisConnectionPool
import com.twitter.finagle.http.Status
import io.finch.Input
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}

class RedirectionSpec extends FunSpec with Matchers with BeforeAndAfter {
  import com.kurz.Server.redirection

  before {
    RedisConnectionPool.instance.getResource().del("mb")
    RedisConnectionPool.instance.getResource().set("mb", "http://marceloboeira.com")
  }

  describe ("redirection") {
    describe("when the slug exists") {
      it("returns with the temporary redirection status") {
        redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.TemporaryRedirect)
      }

      it("returns with the proper header for Location") {
        redirection(Input.get("/mb")).awaitOutputUnsafe().map(_.headers) shouldBe Some(Map("Location" -> "http://marceloboeira.com"))
      }
    }

    describe("when the slug does not exist") {
      it("returns with the not found status") {
        redirection(Input.get("/invalid")).awaitOutputUnsafe().map(_.status) shouldBe Some(Status.NotFound)
      }
    }
  }
} 
开发者ID:marceloboeira,项目名称:kurz,代码行数:34,代码来源:RedirectionSpec.scala

示例3: AX25FrameSpec

//设置package包名称以及导入依赖的类
package com.softwaremill.modemconnector.ax25

import com.softwaremill.modemconnector.FrameUtils
import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers}

class AX25FrameSpec extends FlatSpec with Matchers with BeforeAndAfter {

  "A simple AX25Frame" should "contain decoded data" in {
    val ax25frame: AX25Frame = FrameUtils.ax25frameFromFile("/andrej.bin")
    new String(ax25frame.body) should equal("=4603.63N/01431.26E-Op. Andrej")
  }

  "A simple AX25Frame" should "contain sender callsign" in {
    val ax25frame: AX25Frame = FrameUtils.ax25frameFromFile("/andrej.bin")
    ax25frame.sender.callsign should equal("S57LN")
  }

  "A simple AX25Frame" should "contain destination callsign" in {
    val ax25frame: AX25Frame = FrameUtils.ax25frameFromFile("/andrej.bin")
    ax25frame.dest.callsign should equal("APRS")
  }

  "A simple AX25Frame" should "encode byte array" in {
    val ax25frame = AX25Frame(FrameUtils.ax25frameFromFile("/andrej.bin").toBytes)
    new String(ax25frame.body) should equal("=4603.63N/01431.26E-Op. Andrej")
    ax25frame.dest.callsign should equal("APRS")
    ax25frame.sender.callsign should equal("S57LN")
  }

  "An AX25Frame with digipiters" should "contain decoded data" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    new String(ax25frame.body) should equal("`'4< \\4>/]\"3k}145.500MHz qrv her=\r")
  }

  "An AX25Frame with digipiters" should "contain sender callsign" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    ax25frame.sender.toString should equal("OZ1IEP-9")
  }

  "An AX25Frame with digipiters" should "contain destination callsign" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    ax25frame.dest.toString should equal("U4TQ33")
  }

  "An AX25Frame with digipiters" should "contain digipiters" in {
    val ax25frame = FrameUtils.ax25frameFromFile("/complexFrame.bin")
    ax25frame.digipeaters.map(_.toString).toSeq should contain theSameElementsInOrderAs List("OZ6DIA-2", "OZ4DIA-2", "OZ4DIE-2")
  }

  "An AX25Frame with digipiters" should "encode byte array" in {
    val ax25frame = AX25Frame(FrameUtils.ax25frameFromFile("/complexFrame.bin").toBytes)
    ax25frame.digipeaters.map(_.toString).toSeq should contain theSameElementsInOrderAs List("OZ6DIA-2", "OZ4DIA-2", "OZ4DIE-2")
    ax25frame.dest.toString should equal("U4TQ33")
    ax25frame.sender.toString should equal("OZ1IEP-9")
    new String(ax25frame.body) should equal("`'4< \\4>/]\"3k}145.500MHz qrv her=\r")
  }

} 
开发者ID:softwaremill,项目名称:modem-connector,代码行数:59,代码来源:AX25FrameSpec.scala

示例4: fillFromEnv

//设置package包名称以及导入依赖的类
package hu.blackbelt.cd.bintray.deploy

import java.io.{File, FileInputStream}
import java.util.Properties

import org.scalatest.{BeforeAndAfter, Suite}

trait Creds extends BeforeAndAfter {
  this: Suite =>

  def fillFromEnv(prop: Properties) = {
    def put(key: String) = sys.env.get(key.replace('.','_')).map(prop.put(key.replace('_','.'), _))
    put(Access.aws_accessKeyId)
    put(Access.aws_secretKey)
    put(Access.bintray_organization)
    put(Access.bintray_user)
    put(Access.bintray_apikey)
  }

  before {
    import scala.collection.JavaConverters._
    val prop = new Properties()
    val propsFile = new File("env.properties")
    if (propsFile.exists()) {
      prop.load(new FileInputStream(propsFile))
    } else {
      fillFromEnv(prop)
    }
    prop.entrySet().asScala.foreach {
      (entry) => {
        sys.props += ((entry.getKey.asInstanceOf[String], entry.getValue.asInstanceOf[String]))
      }
    }
  }


} 
开发者ID:tsechov,项目名称:s3-bintray-deploy,代码行数:38,代码来源:Creds.scala

示例5: CompiledUserDirectorySpec

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

import DataSciencester._

import org.scalatest.FunSpec
import org.scalatest.BeforeAndAfter

class CompiledUserDirectorySpec extends FunSpec with BeforeAndAfter {
  var friendships: List[(Int, Int)] = _

  var users: List[User] = _

  before {
    friendships = List((0, 1))
    users = List(
      Map("id" -> 0, "name" -> "Hero"),
      Map("id" -> 1, "name" -> "Dunn"))
  }

  describe("Relations can be made bidirectional") {
    it("should show graph edge both ways") {
      val result = CompiledUserDirectory(users, friendships).createBiDirectionalRelations(List((1, 2)))

      assert(result == List((1, 2), (2, 1)))
    }
    it("will produce duplicates if 1 way relationships repeat relations") {
      val result = CompiledUserDirectory(users, friendships).createBiDirectionalRelations(List((1, 2), (2, 1)))

      assert(result == List((1, 2), (2, 1), (2, 1), (1, 2)))
    }
  }

  describe("We should be able to establish friendships immutably and with delayed evaluation") {
    it("should allow following friends from myself and back again") {
      val result = CompiledUserDirectory(users, friendships)

      assert(result.usersWithFriends.size == 2)

      val herosFriends: List[scala.Function0[CompiledUser]] = result.usersWithFriends(0).friends
      assert(herosFriends.size == 1)

      val dunnsFriends: List[scala.Function0[CompiledUser]] = result.usersWithFriends(1).friends
      assert(dunnsFriends.size == 1)
    }
  }

} 
开发者ID:InvisibleTech,项目名称:datasciencefromscratch,代码行数:48,代码来源:CompiledUserDirectorySpec.scala

示例6: EmailParserSpec

//设置package包名称以及导入依赖的类
package uk.pkerrigan.dmarcparser

import org.scalatest.{BeforeAndAfter, FlatSpec}
import uk.pkerrigan.dmarcparser.report._

import scala.io.Source

class EmailParserSpec extends FlatSpec with BeforeAndAfter with ParserTrait {

  val dummyFeedback = Feedback(1.0, ReportMetadata("", "", "", "", DateRange(1,1), List()), PolicyPublished("", AlignmentRelaxed, AlignmentRelaxed, DispositionNone, DispositionNone, 0, ""), List())
  val emailParser = new EmailParser(this)
  var passedToParser: String = ""

  before {
    passedToParser = ""
  }

  "An email with a zip file" should "invoke the DMARC parser with unzipped contents" in {
    val result = emailParser.parseEmail(Source.fromResource("test.zip.eml").mkString)
    assert(passedToParser == "Test zip file")
    assert(result.get == dummyFeedback)
  }

  "An email with a gzip file" should "invoke the DMARC parser with unzipped contents" in {
    val result = emailParser.parseEmail(Source.fromResource("test.gz.eml").mkString)
    assert(passedToParser == "Test gzip file")
    assert(result.get == dummyFeedback)
  }

  "An email with a an unrecognised attachment" should "not invoke the DMARC parser" in {
    val result = emailParser.parseEmail(Source.fromResource("test.txt.eml").mkString)
    assert(passedToParser == "")
    assert(result.isEmpty)
  }

  "An email with no attachment" should "not invoke the DMARC parser" in {
    val result = emailParser.parseEmail(Source.fromResource("test.none.eml").mkString)
    assert(passedToParser == "")
    assert(result.isEmpty)
  }

  override def parse(rawReport: String): Feedback = {
    passedToParser = rawReport.trim
    dummyFeedback
  }
} 
开发者ID:patrickkerrigan,项目名称:dmarc-parser,代码行数:47,代码来源:EmailParserSpec.scala

示例7: GitHubFunctionTest

//设置package包名称以及导入依赖的类
package com.atomist.rug.function.github

import com.atomist.source.ArtifactSourceException
import com.atomist.source.git.GitHubServices
import com.atomist.source.git.domain.Issue
import com.typesafe.scalalogging.LazyLogging
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FlatSpec, Matchers}

import scala.util.{Failure, Success, Try}

abstract class GitHubFunctionTest(val oAuthToken: String, val apiUrl: String = "")
  extends FlatSpec
    with Matchers
    with BeforeAndAfter
    with BeforeAndAfterAll
    with LazyLogging {

  import TestConstants._

  protected val ghs = GitHubServices(oAuthToken, apiUrl)

  override protected def afterAll(): Unit = cleanUp()

  
  private def cleanUp() =
    Try(ghs.searchRepositories(Map("q" -> s"user:$TestOrg in:name $TemporaryRepoPrefix", "per_page" -> "100"))) match {
      case Success(repos) => repos.items.foreach(repo => ghs.deleteRepository(repo.name, repo.ownerName))
      case Failure(e) => throw ArtifactSourceException(e.getMessage, e)
    }

  private def getRepoName = s"$TemporaryRepoPrefix${System.nanoTime}"

  protected def createIssue(repo: String, owner: String): Issue =
    ghs.createIssue(repo, owner, "test issue", "Issue body")
} 
开发者ID:atomist,项目名称:rug-functions-github,代码行数:36,代码来源:GitHubFunctionTest.scala

示例8: RulesSpec

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

import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.ai._
import org.scalatest.prop.PropertyChecks

@RunWith(classOf[JUnitRunner])
class RulesSpec extends FlatSpec with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter
    with PropertyChecks with HanabiDomain {
  import SimpleRules._
  import Cards._

  "simple rules" should "have proper number of cards" in {
    forAll { c: Card =>
      whenever(c.level == 1) {
        count(c) shouldBe 3
      }
    }
    forAll { c: Card =>
      whenever(c.level == 5) {
        count(c) shouldBe 1
      }
    }
    forAll { c: Card =>
      whenever(c.level > 1 && c.level < 5) {
        count(c) shouldBe 2
      }
    }
  }

  implicit override val generatorDrivenConfig = PropertyCheckConfiguration(
    minSuccessful = 100,
    maxDiscardedFactor = 15)
} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:43,代码来源:RulesSpec.scala

示例9: PlayerSpec

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

import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.ai._

@RunWith(classOf[JUnitRunner])
class PlayerSpec extends FlatSpec with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter {
  import SimpleRules._

  val player = new Player {
    def nextMove(s: GameState) = ???
  }

  val onesToThrees = allCards.filter(_.level < 4)
  val foursFives = allCards.filter(_.level >= 4)
  val (fives, allExceptFives) = allCards.partition(_.level == 5)

  "a player" should "guess its possible cards with no clues" in {
    val possible = player.possibleCards(allExceptFives, 5)
    for (p <- 0 to 4)
      possible(p) should contain theSameElementsAs fives
  }

  it should "guess its possible cards with a single clue" in {
    val possible = player.possibleCards(onesToThrees, 5, Seq(LevelClue(level = 5, position = 3)))
    possible(1) should contain theSameElementsAs allCards.filter(_.level == 5)
  }

  val clues = Seq(
    LevelClue(position = 3, level = 5),
    ColorClue(position = 3, color = Blue))

  it should "guess its possible cards with a 2 clues on the same card" in {
    val possible = player.possibleCards(onesToThrees, 5, clues)
    possible(3) should contain theSameElementsAs Seq(Card(5, Blue))
  }

  //  it should "guess its possible cards with a 2 clues on another card" in {
  //    player.possibleCards(4, onesToThrees, clues) should
  //      contain theSameElementsAs (foursFives diff Seq(Card(5, Blue)))
  //  }
} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:51,代码来源:PlayerSpec.scala

示例10: DeckSpec

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

import state._

import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.Card._
import hanabi.ai._
import SimpleRules._

@RunWith(classOf[JUnitRunner])
class DeckSpec extends FlatSpec
    with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter
    with StackedDeck {

  "a Deck" should "distribute cards one by one" in {
    val (h, rest) = Deck(allCards.distinct).deal(hands = 5, cardsPerHand = 5)
    val hnds = h.toVector
    println(hnds)
    def expected(lvl: Int) = allColors.map(c => Card(lvl, c)).toVector
    for {
      h <- 0 until 5
      (c, i) <- hnds(h).cards.zipWithIndex
    } c.level should be(5 - i)
  }

  //  it should "allow to try to draw from an empty deck an return unchanged deck" in {
  //  }

} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:37,代码来源:DeckSpec.scala

示例11: BaseTest

//设置package包名称以及导入依赖的类
package com.unity.analytics.spark.utils.parquet

import org.apache.spark.sql.SQLContext
import org.apache.spark.{SparkConf, SparkContext}
import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuite}


class BaseTest extends FunSuite with BeforeAndAfterAll with BeforeAndAfter {
  private val master = "local[*]"
  private val appName = "example-spark"
  private val conf = new SparkConf()
    .setMaster(master)
    .setAppName(appName)
    .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
    .set("spark.task.maxFailures", "1")


  protected var sc: SparkContext = _
  protected var sqlContext: SQLContext = _

  protected def getSQLContext(): SQLContext = sqlContext


  override def beforeAll() {
    System.clearProperty("spark.driver.port")
    System.clearProperty("spark.hostPort")
    sc = new SparkContext(conf)
    sc.setLogLevel("ERROR")
    sqlContext = new SQLContext(sc)
  }

  override def afterAll() {
    if (sc != null) {
      sc.stop()
      sc = null
      System.clearProperty("spark.driver.port")
      System.clearProperty("spark.hostPort")
    }
  }
} 
开发者ID:UnityTech,项目名称:parquet-s3-backup,代码行数:41,代码来源:BaseTest.scala

示例12: TaskStatusModuleTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.task.bus.impl

import mesosphere.marathon.core.instance.TestInstanceBuilder
import mesosphere.marathon.core.instance.update.InstanceChange
import mesosphere.marathon.core.task.bus.{ TaskBusModule, TaskStatusUpdateTestHelper }
import mesosphere.marathon.state.PathId
import org.scalatest.{ BeforeAndAfter, FunSuite }

class TaskStatusModuleTest extends FunSuite with BeforeAndAfter {
  var module: TaskBusModule = _
  before {
    module = new TaskBusModule
  }

  test("observable forAll includes all app status updates") {
    var received = List.empty[InstanceChange]
    module.taskStatusObservables.forAll.foreach(received :+= _)

    TaskStatusUpdateTestHelper.running()
    val aa: InstanceChange = TaskStatusUpdateTestHelper.running(instance("/a/a")).wrapped
    val ab: InstanceChange = TaskStatusUpdateTestHelper.running(instance("/a/b")).wrapped
    module.taskStatusEmitter.publish(aa)
    module.taskStatusEmitter.publish(ab)
    assert(received == List(aa, ab))
  }

  test("observable forAll unsubscribe works") {
    var received = List.empty[InstanceChange]
    val subscription = module.taskStatusObservables.forAll.subscribe(received :+= _)
    subscription.unsubscribe()
    val aa: InstanceChange = TaskStatusUpdateTestHelper.running(instance("/a/a")).wrapped
    module.taskStatusEmitter.publish(aa)
    assert(received == List.empty)
  }

  test("observable forAppId includes only app status updates") {
    var received = List.empty[InstanceChange]
    module.taskStatusObservables.forRunSpecId(PathId("/a/a")).foreach(received :+= _)
    val aa: InstanceChange = TaskStatusUpdateTestHelper.running(instance("/a/a")).wrapped
    val ab: InstanceChange = TaskStatusUpdateTestHelper.running(instance("/a/b")).wrapped
    module.taskStatusEmitter.publish(aa)
    module.taskStatusEmitter.publish(ab)
    assert(received == List(aa))
  }

  test("observable forAppId unsubscribe works") {
    var received = List.empty[InstanceChange]
    val subscription = module.taskStatusObservables.forRunSpecId(PathId("/a/a")).subscribe(received :+= _)
    subscription.unsubscribe()
    val aa: InstanceChange = TaskStatusUpdateTestHelper.running(instance("/a/a")).wrapped
    module.taskStatusEmitter.publish(aa)
    assert(received == List.empty)
  }

  private[this] def instance(appId: String) = TestInstanceBuilder.newBuilder(PathId(appId)).addTaskStaged().getInstance()

} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:58,代码来源:TaskStatusModuleTest.scala

示例13: ClusterImplTest

//设置package包名称以及导入依赖的类
package com.groupon.dse.kafka.cluster.impl

import com.groupon.dse.configs.KafkaServerConfig
import com.groupon.dse.testutils.{EmbeddedKafka, TestDefaults}
import com.groupon.dse.zookeeper.ZkClientBuilder
import kafka.producer.{Producer, ProducerConfig}
import org.I0Itec.zkclient.ZkClient
import org.scalatest.{BeforeAndAfter, FlatSpec}

class ClusterImplTest extends FlatSpec with BeforeAndAfter {

  val kafkaTopic = TestDefaults.TestTopic
  val zkConnTimeout = 10000
  val zkSessionTimeout = 10000
  var producer: Producer[String, Array[Byte]] = _
  var embeddedKafka: EmbeddedKafka = _
  var cluster: ClusterImpl = _
  var zkConnect: String = _
  var kafkaServerConfigs: KafkaServerConfig = _
  var zkClient: ZkClient = _

  before {
    embeddedKafka = new EmbeddedKafka
    embeddedKafka.startCluster()
    producer = new Producer[String, Array[Byte]](new ProducerConfig(embeddedKafka.kafkaProducerProperties))
    zkConnect = embeddedKafka.zkServer.connectString
    kafkaServerConfigs = TestDefaults.testKafkaServerConfig(zkConnect)
    cluster = new ClusterImpl(kafkaServerConfigs)
    zkClient = ZkClientBuilder(zkConnect, zkConnTimeout, zkSessionTimeout)
  }

  after {
    zkClient.close()
    embeddedKafka.stopCluster()
  }

  "The topic list" must "have size 0 before producing" in {
    assert(cluster.topics(zkClient).size == 0)
  }

  "The topic list" must "have size 1 after producing" in {
    embeddedKafka.sendMessage(4, producer, kafkaTopic)
    assert(cluster.topics(zkClient).size == 1)
  }

  "The number of partitions for a topic" should "be 1 for 1 valid topic" in {
    embeddedKafka.sendMessage(4, producer, kafkaTopic)
    assert(cluster.partitions(List(kafkaTopic), zkClient).size == 1)
  }

  "The number of partitions" should "be 0 for an invalid topic" in {
    embeddedKafka.sendMessage(4, producer, kafkaTopic)
    assert(cluster.partitions(List("invalid_topic"), zkClient).size == 0)
  }

  "The number of partitions" should "be 1 for a valid and invalid topic" in {
    embeddedKafka.sendMessage(4, producer, kafkaTopic)
    assert(cluster.partitions(List(kafkaTopic, "invalid_topic"), zkClient).size == 1)
  }

} 
开发者ID:groupon,项目名称:baryon,代码行数:62,代码来源:ClusterImplTest.scala

示例14: TopicFetcherBuilder

//设置package包名称以及导入依赖的类
package com.groupon.dse.kafka.topic

import java.util.Properties

import com.groupon.dse.configs.AppConfigs
import com.groupon.dse.kafka.topic.TopicFetcherBuilder.InvalidTopicFetcherException
import org.scalatest.{BeforeAndAfter, FlatSpec}

class TopicFetcherBuilder$Test extends FlatSpec with BeforeAndAfter {

  var properties: Properties = _
  before {
    properties = new Properties()
  }

  "The topic Fetcher builder" should "return the appropriate TopicFetcher" in {
    properties.setProperty("topics", "sometopic")
    assert(TopicFetcherBuilder(properties).getClass == classOf[LocalTopicFetcher])
    properties.setProperty("topics.fetcher.type", "HDFS")
    properties.setProperty("topics.fetcher.hdfs.source", "/path/in/hdfs")
    assert(TopicFetcherBuilder(properties).getClass == classOf[HdfsJsonTopicFetcher])
    properties.setProperty("topics.fetcher.type", "LOCAL")
    assert(TopicFetcherBuilder(properties).getClass == classOf[LocalTopicFetcher])
  }

  "the topic fetcher builder" should "throw an exception if invalid type is provided" in {
    intercept[InvalidTopicFetcherException] {
      properties.setProperty("topics.fetcher.type", "INVALID")
      TopicFetcherBuilder(properties)
    }
  }

  "the topic fetcher" should "throw an exception if there are any missing configs" in {
    intercept[AppConfigs.MissingConfigException] {
      TopicFetcherBuilder(properties)
    }

    intercept[AppConfigs.MissingConfigException] {
      properties.setProperty("topics.fetcher.type", "HDFS")
      TopicFetcherBuilder(properties)
    }
  }
} 
开发者ID:groupon,项目名称:baryon,代码行数:44,代码来源:TopicFetcherBuilder$Test.scala

示例15: IntegrationTest

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

import org.scalatest.{BeforeAndAfter, Matchers, FlatSpec}
import CompilerTestMatchers.passIntegrationTest

class IntegrationTest extends FlatSpec with Matchers with BeforeAndAfter {

  val TestDir = "mj-test/run/"
  val testFiles = new java.io.File(TestDir).listFiles.filter(_.getName.endsWith(".mj")).sortBy(_.getName.toLowerCase)

  val weirdFirmTests = Set("prometheus3.mj")

  for (file <- testFiles) {
    if (!weirdFirmTests(file.getName))
      file.getName should "produce correct output with the FIRM backend" in {
        file.getPath should passIntegrationTest(Seq("--compile-firm"))
      }

    file.getName should "produce correct output with our backend" in {
      file.getPath should passIntegrationTest(Seq())
    }
  }
} 
开发者ID:jspam,项目名称:mjis,代码行数:24,代码来源:IntegrationTest.scala


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