[转] org.scalatest.FunSuite Scala Examples

[From]  https://www.programcreek.com/scala/org.scalatest.FunSuite

org.scalatest.FunSuite Scala Examples

The following code examples show how to use org.scalatest.FunSuite. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples. 

 
Example 1
Project: train-stamp-rally   Author: ponkotuy   File: MissionTimeSuite.scala View Source Project (license) 7 votes vote down
package utils

import org.scalatest.FunSuite

class MissionTimeSuite extends FunSuite {
  test("MissionTime.addMinutes") {
    assert(MissionTime(1, 6, 1).addMinutes(15) === MissionTime(1, 6, 16))
    assert(MissionTime(1, 6, 23).addMinutes(-10) === MissionTime(1, 6, 13))
  }

  test("MissionTime.addMinutes if carry") {
    assert(MissionTime(1, 6, 59).addMinutes(3) === MissionTime(1, 7, 2))
    assert(MissionTime(1, 7, 3).addMinutes(-5) === MissionTime(1, 6, 58))
  }

  test("MissionTime.addMinutes if over hour") {
    assert(MissionTime(1, 23, 44).addMinutes(25) === MissionTime(2, 0, 9))
    assert(MissionTime(2, 0, 15).addMinutes(-18) === MissionTime(1, 23, 57))
  }

  test("MissionTime.fromString") {
    assert(MissionTime.fromString("1-06:15") === Some(MissionTime(1, 6, 15)))
  }
}
Example 2
Project: scala-dom   Author: rrramiro   File: MappedNamespaceContextTest.scala View Source Project(license) 5 votes vote downvote up
package fr.ramiro.scala.dom

import javax.xml.XMLConstants

import org.scalatest.FunSuite

import scala.collection.JavaConverters.asScalaIteratorConverter

class MappedNamespaceContextTest extends FunSuite {
  test("get prefix and get namespaceURI") {
    val customUri = "www.ramiro.fr"
    val customPrefix = "ramiro"
    val namespaceContext = new MappedNamespaceContext(Map(customPrefix -> customUri))

    assert(namespaceContext.getNamespaceURI(customPrefix) === customUri)
    assert(namespaceContext.getNamespaceURI(XMLConstants.XML_NS_PREFIX) === XMLConstants.XML_NS_URI)
    assert(namespaceContext.getNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE) === XMLConstants.XMLNS_ATTRIBUTE_NS_URI)

    assert(namespaceContext.getPrefix(customUri) === customPrefix)
    assert(namespaceContext.getPrefix(XMLConstants.XML_NS_URI) === XMLConstants.XML_NS_PREFIX)
    assert(namespaceContext.getPrefix(XMLConstants.XMLNS_ATTRIBUTE_NS_URI) === XMLConstants.XMLNS_ATTRIBUTE)

    assert(namespaceContext.getPrefixes(customUri).asScala.toList === List(customPrefix))
    assert(namespaceContext.getPrefixes(XMLConstants.XML_NS_URI).asScala.toList === List(XMLConstants.XML_NS_PREFIX))
    assert(namespaceContext.getPrefixes(XMLConstants.XMLNS_ATTRIBUTE_NS_URI).asScala.toList === List(XMLConstants.XMLNS_ATTRIBUTE))
  }

  test("getNamespaceURI with null") {
    intercept[IllegalArgumentException] {
      new MappedNamespaceContext(Map.empty).getNamespaceURI(null)
    }
  }

  test("getPrefix with null") {
    intercept[IllegalArgumentException] {
      new MappedNamespaceContext(Map.empty).getPrefix(null)
    }
  }

  test("getPrefixes with null") {
    intercept[IllegalArgumentException] {
      new MappedNamespaceContext(Map.empty).getPrefixes(null)
    }
  }

}
Example 3
Project: Functional-Programming-in-Scala   Author: vincenzobaz   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }
}
Example 4
Project: Earlgrey   Author: PatrickHuang888   File: RepositoryTest.scala View Source Project (license) 5 votes vote downvote up
package com.hxm.earlgrey.jobs

import org.scalatest.{BeforeAndAfter, FunSuite}
import org.mongodb.scala.Document


class RepositoryTest extends FunSuite with BeforeAndAfter {
  val repository = Repository()
  val jobId = "scalaTestId"

  before {
    repository.deleteJob(jobId)
  }

  test("job insert and query") {
    val doc = Document("_id" -> jobId, "type" -> Job.Type.FlowQuery, "name" -> "scalatest", "status" -> Job.Status.Created)
    val job = new Job(doc)
    repository.insertJob(job)
    val j = repository.findJob(jobId)
    assert(j.isDefined)
    assert(j.get.doc.getString("_id") == jobId)
  }

}
Example 5
Project: hwork   Author: Masebeni   File: PositionPackageTest.scala View Source Project (license) 5 votes vote downvote up
package factories.position

import domain.position.PositionPackage
import org.joda.time.DateTime
import org.scalatest.FunSuite


class PositionPackageTest extends FunSuite {

  test("testCreatePositionFunding") {
    val des = new PositionPackageFactory;

    val date = new DateTime(2016, 4, 2, 1, 20, 2, 0);

    val values = Map("positionId" -> "1",
      "positionPackageId" -> "1",
      "gradeId" -> "1",
      "notchId" -> "1",
      "state" -> "testState"
    );

    val posdes = des.createPositionPackageFactory(values, date);

    assert(posdes == PositionPackage(positionId = "1",
      positionPackageId = "1",
      gradeId = "1",
      notchId = "1",
      state = "testState",
      date = new DateTime(2016, 4, 2, 1, 20, 2, 0)));
  }
}
Example 6
Project: hwork   Author: Masebeni   File: PositionTest.scala View Source Project (license) 5 votes vote downvote up
package factories.position

import domain.position.Position
import org.joda.time.DateTime
import org.scalatest.FunSuite


class PositionTest extends FunSuite{

  test("testCreatePosition")P
  val des = new PositionFactory;

  val date = new DateTime(2016, 10, 11, 5, 20, 0, 0);

  val values = Map("positionId" -> "1",
  "organisationId" -> "1",
  "code" -> "123",
  "title" -> "testPosition",
  "jobId" -> "1",
  "positionTypeId" -> "1",
  "description" -> "test Position",
  "supervisorId" -> "2",
  "state" -> "testState");

  val posdes = des.createPosition(values, date);

  assert(posdes == Position(positionId = "1",
    positionTypeId = "1",
    organisationId = "1",
    code = "123",
    title = "testPosition",
    jobId = "1",
    description = "test Position",
    supervisorId = "2",
    state = "testState",
    date = new DateTime(2016, 10, 11, 5, 20, 0, 0));


}
Example 7
Project: sqs-kafka-connect   Author: ConnectedHomes   File: SQSSourceConnectorSuite.scala View Source Project (license) 5 votes vote downvote up
package com.hivehome.kafka.connect.sqs

import org.scalatest.{FunSuite, Matchers}

import scala.collection.JavaConverters._

class SQSSourceConnectorSuite extends FunSuite with Matchers {

  val connector = new SQSSourceConnector()

  val props = Map[String, String](
    Conf.SourceSqsQueue -> "in",
    Conf.DestinationKafkaTopic -> "out"
  ).asJava

  test("should return task class") {
    connector.taskClass shouldEqual classOf[SQSSourceTask]
  }

  test("should return config def") {
    connector.config shouldEqual Conf.ConfigDef
  }

  test("should return successfully from start") {
    connector.start(props)
  }

  test("should create task configs") {
    connector.start(props)
    val maxTasks = 10
    val taskConfigs = connector.taskConfigs(maxTasks).asScala

    taskConfigs should have size maxTasks
    taskConfigs foreach { taskConfig =>
      taskConfig shouldEqual props
    }
  }
}
Example 8
Project: sqs-kafka-connect   Author: ConnectedHomes   File: ConfSuite.scala View Source Project(license) 5 votes vote downvote up
package com.hivehome.kafka.connect.sqs

import org.apache.kafka.connect.errors.ConnectException
import org.scalatest.OptionValues._
import org.scalatest.TryValues._
import org.scalatest.{FunSuite, Matchers}

class ConfSuite extends FunSuite with Matchers {

  private val UsEast = "us-east-1"
  private val EuWest = "eu-west-1"

  val mandatoryProps = Map[String, String](
    Conf.SourceSqsQueue -> "in",
    Conf.DestinationKafkaTopic -> "out"
  )

  val optionalProps = Map[String, String](
    Conf.AwsKey -> "key",
    Conf.AwsSecret -> "secret",
    Conf.AwsRegion -> UsEast
  )

  val allProps = mandatoryProps ++ optionalProps

  test("should parse all configurations from a map") {
    val tryConf = Conf.parse(allProps)

    val conf = tryConf.success.value
    conf.queueName.value shouldEqual "in"
    conf.topicName.value shouldEqual "out"
    conf.awsRegion shouldEqual UsEast
    conf.awsKey.value shouldEqual "key"
    conf.awsSecret.value shouldEqual "secret"
  }

  test("should parse mandatory configurations from a map") {
    val tryConf = Conf.parse(mandatoryProps)

    val conf = tryConf.success.value
    conf.queueName.value shouldEqual "in"
    conf.topicName.value shouldEqual "out"
    conf.awsRegion shouldEqual EuWest
  }

  test("should fail when mandatory config is missing") {
    val tryConf = Conf.parse(Map())

    tryConf.failure.exception.getClass shouldBe classOf[ConnectException]
  }
}
Example 9
Project: sqs-kafka-connect   Author: ConnectedHomes   File: E2ESpec.scala View Source Project(license) 5 votes vote downvote up
package com.hivehome.kafka.connect.sqs

import java.time.Instant

import org.scalatest.{FunSuite, Matchers}
import org.slf4j.LoggerFactory

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


class E2ESpec extends FunSuite with Matchers with SQSSupport {
  val logger = LoggerFactory.getLogger(getClass.getName)
  private val KafkaTopic: String = "connect-test"
  override val queueName = "test-sqs" // kafka connect should be setup with this SQS
  queueUrl = sqs.getQueueUrl(queueName).getQueueUrl

  private val props = Map(
    "bootstrap.servers" -> sys.env.getOrElse("KAFKA", "localhost:9092"),
    "schema.registry.url" -> sys.env.getOrElse("SCHEMA_REGISTRY", "http://localhost:8081"))

  val consumer = KafkaAvroConsumer[String, String](props, topicName = KafkaTopic)

  // Test is ignored because it does not run without dependent services
  ignore("should route message SQS -> Kafka") {
    Future {
      // sleep is required so that the message to SQS
      // is sent after the consumer is listening on the kafka topic
      Thread.sleep(500)
      logger.debug("sending message..")
      sendMessage(Instant.now().toString)
      logger.debug("sent message..")
    }

    val msgs = consumer.poll(1, accept = _ => true)

    msgs should have size 1
  }
}
Example 10
Project: progfun_assignments   Author: letalvoj   File: HuffmanSuite.scala View Source Project (license) 5 votes vote downvote up
package patmat

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{FunSuite, ShouldMatchers}
import patmat.Huffman._

@RunWith(classOf[JUnitRunner])
class HuffmanSuite extends FunSuite with ShouldMatchers {
	trait TestTrees {
		val t1 = Fork(Leaf('a',2), Leaf('b',3), List('a','b'), 5)
		val t2 = Fork(Fork(Leaf('a',2), Leaf('b',3), List('a','b'), 5), Leaf('d',4), List('a','b','d'), 9)
	}


  test("weight of a larger tree") {
    new TestTrees {
      weight(t1) should be(5)
    }
  }


  test("chars of a larger tree") {
    new TestTrees {
      chars(t2) should be(List('a', 'b', 'd'))
    }
  }


  test("string2chars("hello, world")") {
    string2Chars("hello, world") should be(List('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'))
  }


  test("makeOrderedLeafList for some frequency table") {
    makeOrderedLeafList(List(('t', 2), ('e', 1), ('x', 3))) should be(List(Leaf('e', 1), Leaf('t', 2), Leaf('x', 3)))
  }


  test("combine of some leaf list") {
    val leaflist = List(Leaf('e', 1), Leaf('t', 2), Leaf('x', 4))
    combine(leaflist) should be(List(Fork(Leaf('e', 1), Leaf('t', 2), List('e', 't'), 3), Leaf('x', 4)))
  }


  test("decode and encode a very short text should be identity") {
    val fc = Huffman.frenchCode
    decode(fc, encode(fc)("letsmakeitmorecomplicated".toList)) should be("letsmakeitmorecomplicated".toList)
  }

}
Example 11
Project: progfun_assignments   Author: letalvoj   File: PascalSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class PascalSuite extends FunSuite {
  import Week1.pascal
  test("pascal: col=0,row=2") {
    assert(pascal(0,2) === 1)
  }

  test("pascal: col=1,row=2") {
    assert(pascal(1,2) === 2)
  }

  test("pascal: col=1,row=3") {
    assert(pascal(1,3) === 3)
  }
}
Example 12
Project: progfun_assignments   Author: letalvoj   File: BalanceSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class BalanceSuite extends FunSuite {
  import Week1.balance

  test("balance: '(if (zero? x) max (/ 1 x))' is balanced") {
    assert(balance("(if (zero? x) max (/ 1 x))".toList))
  }

  test("balance: 'I told him ...' is balanced") {
    assert(balance("I told him (that it's not (yet) done).
(But he wasn't listening)".toList))
  }

  test("balance: ':-)' is unbalanced") {
    assert(!balance(":-)".toList))
  }

  test("balance: counting is not enough") {
    assert(!balance("())(".toList))
  }
}
Example 13
Project: progfun_assignments   Author: letalvoj   File: CountChangeSuite.scala View Source Project(license) 5 votes vote downvote up
package recfun

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{FunSuite, ShouldMatchers}

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite with ShouldMatchers {

  import Week1.countChange

  test("countChange: example given in instructions") {
    countChange(4, List(1, 2)) should be(3)
  }

  test("countChange: sorted CHF") {
    countChange(300, List(5, 10, 20, 50, 100, 200, 500)) should be(1022)
  }

  test("countChange: no pennies") {
    countChange(301, List(5, 10, 20, 50, 100, 200, 500)) should be(0)
  }

  test("countChange: unsorted CHF") {
    countChange(300, List(500, 5, 50, 100, 20, 200, 10)) should be(1022)
  }
}
Example 14
Project: scala-course-one   Author: mumukiller   File: PascalSuite.scala View Source Project (license) 5 votes vote downvote up
package functions

import org.scalatest.FunSuite

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class PascalSuite extends FunSuite {
  import Main.pascal
  test("pascal: col=0,row=2") {
    assert(pascal(0,2) === 1)
  }

  test("pascal: col=1,row=2") {
    assert(pascal(1,2) === 2)
  }

  test("pascal: col=1,row=3") {
    assert(pascal(1,3) === 3)
  }
}
Example 15
Project: scalajs-frogger   Author: wjsrobertson   File: TiledLayerTest.scala View Source Project (license) 5 votes vote downvote up
package net.xylophones.frogger

import org.junit.runner.RunWith
import org.scalajs.dom.raw.HTMLImageElement
import org.scalatest.junit.JUnitRunner
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}
import org.mockito.Mockito._

@RunWith(classOf[JUnitRunner])
class TiledLayerTest extends FunSuite with Matchers with MockitoSugar with BeforeAndAfterEach {

  val htmlImage = mock[HTMLImageElement]
  val image = new Image(htmlImage)
  when(htmlImage.width).thenReturn(20)
  when(htmlImage.height).thenReturn(10)
  val tiledImage = new TiledImage(image, 10, 10)
  val tiles = Array(Array(Tile(0, 0, CellType.Deadly), Tile(1, 0, CellType.Deadly)))
  val underTest = new TiledLayer(tiledImage, 1, 2, tiles)

  test("TiledLayer contains Rectangles with correct local offset") {
    val rects = underTest.rectangles

    rects.size shouldBe 2
    rects.head.x shouldBe 0
    rects.head.y shouldBe 0
    rects.last.x shouldBe 10
    rects.last.y shouldBe 0
  }
}
Example 16
Project: markovMovieCritic   Author: tammosminia   File: TokensTest.scala View Source Project(license) 5 votes vote downvote up
package markov

import org.scalatest.FunSuite
import Tokens._

class TokensTest extends FunSuite {
  val helloTokens = List(StartToken, WordToken("hello"), EndSentence, EndToken)
  val helloWorldTokens = List(StartToken, WordToken("hello"), WordToken("world"), EndSentence, EndToken)
  val endWithDot = List(StartToken, WordToken("end"), WordToken("with"), WordToken("dot"), EndSentence, EndToken)
  val twoLinesTokens = List(StartToken, WordToken("first"), WordToken("line"), EndSentence,
    WordToken("second"), WordToken("line"), EndSentence, EndToken)

  test("tokenize") {
    assert(tokenize("hello") === helloTokens)
    assert(tokenize("Hello world!") === helloWorldTokens)
    assert(tokenize("End with dot.") === endWithDot)
    assert(tokenize("First line. Second line.") === twoLinesTokens)
    assert(tokenize("First line.
 Second line.
") === twoLinesTokens)
  }

  test("tokensToString") {
    assert(tokensToString(helloTokens) === "Hello.")
    assert(tokensToString(helloWorldTokens) === "Hello world.")
    assert(tokensToString(endWithDot) === "End with dot.")
    assert(tokensToString(twoLinesTokens) === "First line. Second line.")
  }

  test("multiple dots") {
    assert(tokenize("first line .. second line") === twoLinesTokens)
    assert(tokenize("first line ..... second line......") === twoLinesTokens)
  }

  test("weird spacing") {
    assert(tokenize("hello ") === helloTokens)
    assert(tokenize("hello  ") === helloTokens)
    assert(tokenize(" hello") === helloTokens)
    assert(tokenize("  hello") === helloTokens)
    assert(tokenize("  hello  ") === helloTokens)
    assert(tokenize(" ") === List(StartToken, EndSentence, EndToken))
    assert(tokenize("  ") === List(StartToken, EndSentence, EndToken))
    assert(tokenize(" . ") === List(StartToken, EndSentence, EndToken))
    assert(tokenize("first line   .  .   second line") === twoLinesTokens)
  }

}
Example 17
Project: ToSidewalk   Author: kotarohara   File: StreetNodeTableTest.scala View Source Project(license) 5 votes vote downvote up
package tosidewalk.model

import org.scalatest.FunSuite
import tosidewalk.model.connection.H2DBComponent
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Millis, Seconds, Span}
import geotrellis.vector.Point
import slick.lifted.TableQuery

class StreetNodeTableTest extends FunSuite with StreetNodeRepository with H2DBComponent with ScalaFutures {

  implicit val defaultPatience = PatienceConfig(timeout = Span(5, Seconds), interval = Span(500, Millis))

  test("Add new street node") {
    val node = StreetNode(1, Point(1.0, 1.0).jtsGeom)
    var response = insertStreetNode(node)

    whenReady(response) { nodeId =>
      assert(nodeId === 2)
    }
  }
}
Example 18
Project: scalatour   Author: bobxwang   File: ConfigTest.scala View Source Project (license) 5 votes vote downvote up
package com.bob.scalatour.configs

import com.typesafe.config._
import org.scalatest.FunSuite

class ConfigTest extends FunSuite {
  test("load config") {
    val config = ConfigFactory.load("config.conf")
    assert(config.getString("app.name") == "scalatour")
    assert(config.getString("app.db.url") == "jdbc:h2:mem:test;INIT=bbtest FROM 'classpath:ddl.sql")
    assert(config.getString("app.db.driver") == "org.h2.Driver")
    assert(config.getString("app.http.host") == "0.0.0.0")
    assert(config.getInt("app.http.port") == 9999)
  }
}
Example 19
Project: scalatour   Author: bobxwang   File: AsyncTest.scala View Source Project (license) 5 votes vote downvote up
package com.bob.scalatour.futures

import org.scalatest.FunSuite

import scala.async.Async._

import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}

class AsyncTest extends FunSuite {

  implicit val ec = ExecutionContext.global

  test("sequential") {
    val future = async {
      val futureOne = async {
        1
      }
      val futureTwo = async {
        2
      }
      await(futureOne) + await(futureTwo)
    }
    future onComplete {
      case Success(result) => assert(result == 3)
      case Failure(failure) => throw failure
    }
  }

  test("parallel") {
    val futureOne = async {
      1
    }
    val futureTwo = async {
      2
    }
    val futureThree = async {
      await(futureOne) + await(futureTwo)
    }
    futureThree onComplete {
      case Success(result) => assert(result == 3)
      case Failure(failure) => throw failure
    }
  }
}
Example 20
Project: graphic-calculator   Author: typeness   File: LexerTest.scala View Source Project (license) 5 votes vote downvote up
package io.github.typeness.graphiccalculator

import org.scalatest.FunSuite

class LexerTest extends FunSuite {
  test("Tokenize 2x") {
    val f = "2x"
    val lexer = new Lexer(f)
    assert(lexer.tokenize == List(NumberToken(2.0), LiteralToken('x'), EOFToken))
  }
  test("Tokenize x + x") {
    val f = "x + x"
    val lexer = new Lexer(f)
    assert(lexer.tokenize == List(LiteralToken('x'), PlusToken, LiteralToken('x'), EOFToken))
  }
  test("Tokenize x*x*x") {
    val f = "x*x*x"
    val lexer = new Lexer(f)
    assert(lexer.tokenize == List(
      LiteralToken('x'), MultiplicationToken,  LiteralToken('x'), MultiplicationToken,  LiteralToken('x'), EOFToken)
    )
  }
  test("Tokenize x ^ 2+2x+ 1") {
    val f = "x ^ 2+2x+ 1"
    val lexer = new Lexer(f)
    assert(lexer.tokenize == List(
      LiteralToken('x'), PowerToken, NumberToken(2.0), PlusToken, NumberToken(2.0),
      LiteralToken('x'), PlusToken, NumberToken(1.0), EOFToken
    ))
  }
}
Example 21
Project: coursera   Author: syhan   File: VisualizationTest.scala View Source Project (license) 5 votes vote downvote up
package observatory


import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.prop.Checkers
import observatory.Visualization._
import observatory.Extraction._

@RunWith(classOf[JUnitRunner])
class VisualizationTest extends FunSuite with Checkers {

  test("should interpolate color correctly") {
    val c = interpolateColor(List((0.0, Color(255, 0, 0)), (2.147483647E9, Color(0, 0, 255))), 5.3687091175E8)

    assert(c.red === 191)
    assert(c.green === 0)
    assert(c.blue === 64)
  }

  test("exceeding the greatest value of a color scale should return the color associated with the greatest value") {
    val c = interpolateColor(List((-1.0,Color(255, 0, 0)), (15.39640384017234, Color(0,0,255))), 25.39640384017234)

    assert(c.red === 0)
    assert(c.green === 0)
    assert(c.blue === 255)
  }

  test("should predicate temperature correctly") {
    val t1 = predictTemperature(List((Location(0, 0), 10), (Location(-45, 90), 40)), Location(0, 0.001))
    val t2 = predictTemperature(List((Location(0, 0), 10), (Location(-45, 90), 40)), Location(-45, 90.001))
    val t3 = predictTemperature(List((Location(0, 0), 10), (Location(-45, 90), 40)), Location(-45, 90))

    println(t1)
    println(t2)

    assert(t3 === 40)
  }

  test("should output a image by given year correctly") {
    val colors: List[(Double, Color)] = List((60.0, Color(255, 255, 255)), (32.0, Color(255, 0, 0)), (12.0, Color(255, 255, 0)),
                                             (0, Color(0, 255, 255)), (-15.0, Color(0, 0, 255)), (-27.0, Color(255, 0, 255)),
                                             (-50.0, Color(33, 0, 107)), (-60.0, Color(0, 0, 0)))
    val locations = locationYearlyAverageRecords(locateTemperatures(1986, "/stations.csv", "/1986.csv"))
    //val locations = List((Location(0, 0), 10d), (Location(-45, 90), 40d))
    val img = visualize(locations, colors)
    img.output(new java.io.File("output.png"))}}
Example 22
Project: coursera   Author: syhan   File: ExtractionTest.scala View Source Project (license) 5 votes vote downvote up
package observatory

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class ExtractionTest extends FunSuite {

  test("locateTemperature should work with given year") {
    val temp = Extraction.locateTemperatures(1986, "/stations.csv", "/1986.csv")
    assert(temp.size == 2429828)
  }

  test("locationYearlyAverageRecords should work with given year") {
    val temp = Extraction.locateTemperatures(1986, "/stations.csv", "/1986.csv")
    val avg = Extraction.locationYearlyAverageRecords(temp)

    assert(avg.size == 8755)
  }
  
}
Example 23
Project: coursera   Author: syhan   File: StackOverflowSuite.scala View Source Project (license) 5 votes vote downvote up
package stackoverflow

import org.scalatest.{FunSuite, BeforeAndAfterAll}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.RDD
import java.io.File

@RunWith(classOf[JUnitRunner])
class StackOverflowSuite extends FunSuite with BeforeAndAfterAll {


  lazy val testObject = new StackOverflow {
    override val langs =
      List(
        "JavaScript", "Java", "PHP", "Python", "C#", "C++", "Ruby", "CSS",
        "Objective-C", "Perl", "Scala", "Haskell", "MATLAB", "Clojure", "Groovy")
    override def langSpread = 50000
    override def kmeansKernels = 45
    override def kmeansEta: Double = 20.0D
    override def kmeansMaxIterations = 120
  }

  test("testObject can be instantiated") {
    val instantiatable = try {
      testObject
      true
    } catch {
      case _: Throwable => false
    }
    assert(instantiatable, "Can't instantiate a StackOverflow object")
  }


}
Example 24
Project: EnterpriseStreamingBenchmark   Author: BenReissaus   File: Statistics$Test.scala View Source Project (license) 5 votes vote downvote up
package org.hpi.esb.flink.utils

import org.scalatest.{BeforeAndAfter, FunSuite}

class Statistics$Test extends FunSuite with BeforeAndAfter {

  test("testFold - Happy List") {
    val elements: Seq[Long] = Seq(1,2,3,8,9)
    val results = elements.foldLeft(new Statistics())(Statistics.fold)
    assert(results.min === 1)
    assert(results.max === 9)
    assert(results.avg === 4.6)
    assert(results.sum === 23)
    assert(results.count === 5)
  }

  test("testFold - Empty List") {
    val elements: Seq[Long] = Seq()
    val results = elements.foldLeft(new Statistics())(Statistics.fold)
    assert(results.min === Long.MaxValue)
    assert(results.max === Long.MinValue)
    assert(results.avg === 0)
    assert(results.sum === 0)
    assert(results.count === 0)
  }

  test("testFold - One element list") {
    val elements: Seq[Long] = Seq(0, 0, 0, 0)
    val results = elements.foldLeft(new Statistics())(Statistics.fold)
    assert(results.min === 0)
    assert(results.max === 0)
    assert(results.avg === 0)
    assert(results.sum === 0)
    assert(results.count === 4)
  }
}
Example 25
Project: EnterpriseStreamingBenchmark   Author: BenReissaus   File: TopicManagementTest.scalaView Source Project (license) 5 votes vote downvote up
package org.hpi.esb.util

import org.scalatest.FunSuite
import org.scalatest.mockito.MockitoSugar

import scala.collection.mutable

class TopicManagementTest extends FunSuite with MockitoSugar {

  test("testGetMatchingTopics") {

    val topicsToDelete = mutable.Buffer("ESB_IN_0", "ESB_OUT_O", "ESB_STATISTICS_0")
    val topicsToKeep = mutable.Buffer("esb_new_IN_0", "esb_new_OUT_0", "esb_new_STATISTICS_0", "topic1", "topic2")
    val allTopics = topicsToDelete ++ topicsToKeep
    val prefix =  "ESB_"

    assert(allTopics.containsSlice(topicsToDelete))
    assert(allTopics.containsSlice(topicsToKeep))
    assert(allTopics.size == topicsToDelete.size + topicsToKeep.size)
    assert(TopicManagement.getMatchingTopics(allTopics, prefix) == topicsToDelete)
  }
}
Example 26
Project: ScalaJSWithXML   Author: sonumehrotra   File: ApplicationTest.scala View Source Project(license) 5 votes vote downvote up
import controllers.Application
import org.scalatest.FunSuite

class ApplicationTest extends FunSuite {

  val testObject = new Application

  test("correct number of warnings") {
    val result = testObject.findScalastyleWarnings("/home/knoldus/WebPage")
    assert(result === "20")
  }

  test("File not found") {
    val result = testObject.findScalastyleWarnings("/home/knoldus/WebPag")
    assert("N/A" === result)
  }

  test("Paths exist in app.conf") {
    val result = testObject.findProjectPathsFromConfig
    assert(result === Array("/home/knoldus/WebPage", "/home/knoldus/Desktop/PlayScalaJsShowcase/play-scalajs-showcase",
      "/home/knoldus/Desktop/PlayScalaJsShowcase/play-scalajs-showcas", "/home/knoldus/RahulSonuPlayTest"))
  }

  test("Code analysis details") {
    val result = testObject.findScapegoatWarnings("/home/knoldus/WebPage")
    assert(List("warns = 12", "errors = 3", "infos = 23") === result)
  }

  test("Test coverage details") {
    val result = testObject.findScoverageReport("/home/knoldus/WebPage")
    assert("Statement Coverage = 73.08, Branch Coverage = 41.46" === result)
  }

  test("Copy Paste Detector details") {
    val result = testObject.findCopyPasteDetectorReport("/home/knoldus/WebPage")
    assert("17 Files" === result)
  }

}
Example 27
Project: SANSA-OWL   Author: SANSA-Stack   File: FunctionalSyntaxOWLExpressionsRDDBuilderTest.scala View Source Project (license) 5 votes vote downvote up
package net.sansa_stack.owl.spark.rdd

import com.holdenkarau.spark.testing.SharedSparkContext
import org.scalatest.FunSuite


class FunctionalSyntaxOWLExpressionsRDDBuilderTest extends FunSuite with SharedSparkContext {
  var _rdd: OWLExpressionsRDD = null

  def rdd = {
    if (_rdd == null) {
      _rdd = FunctionalSyntaxOWLExpressionsRDDBuilder.build(
        sc, "src/test/resources/ont_functional.owl")
      _rdd.cache()
    }

    _rdd
  }

  test("There should be three annotation lines with full URIs") {
    val res = rdd.filter(line => line.startsWith("Annotation(")).collect()
    val expected = List(
      "Annotation(<http://ex.com/foo#hasName> "Name")",
      "Annotation(<http://ex.com/bar#hasTitle> "Title")",
      """Annotation(<http://ex.com/default#description> "A longer
description running over
several lines")""")

    assert(res.length == 3)
    for (e <- expected) {
      assert(res.contains(e))
    }
  }

  
//  test("There should be an import statement") {
//    val res = rdd.filter(line => line.startsWith("Import")).collect()
//    assert(res.length == 1)
//    assert(res(0) == "Import(<http://www.example.com/my/2.0>)")
//  }

  test("There should not be any empty lines") {
    val res = rdd.filter(line => line.trim.isEmpty).collect()
    assert(res.length == 0)
  }

  test("There should not be any comment lines") {
    val res = rdd.filter(line => line.trim.startsWith("#")).collect()
    assert(res.length == 0)
  }

  test("There should be a DisjointObjectProperties axiom") {
    val res = rdd.filter(line => line.trim.startsWith("DisjointObjectProperties")).collect()
    assert(res.length == 1)
  }

  test("The total number of axioms should be correct") {
    val total = 70 // = 71 - uncommented Import(...)
    assert(rdd.count() == total)
  }
}
Example 28
Project: openhub-source-search-engine   Author: mendozagabe1618   File: ParseTest.scala View Source Project (license) 5 votes vote downvote up
package cloud.hw.util

import org.scalatest.FunSuite

class ParseTest extends FunSuite {
  test("A parser must extract a download URL") {
    val correctMeta = Map(
      "downloadUrl" -> "http://github.com/vslavik/xmlwrapp/downloads",
      "projectName" -> "xmlwrapp",
      "tags" -> "c++,xslt,xml")
    assertResult(correctMeta) {
      OpenHubMetadataFetcher.forUrl("file:src/test/resources/response.xml")
    }
  }
}
Example 29
Project: coursera-parprog1   Author: federicobozzini   File: ParallelParenthesesBalancingSuite.scalaView Source Project (license) 5 votes vote downvote up
package reductions

import java.util.concurrent._
import scala.collection._
import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import common._

import ParallelParenthesesBalancing._

@RunWith(classOf[JUnitRunner])
class ParallelParenthesesBalancingSuite extends FunSuite {

  test("balance should work for empty string") {
    def check(input: String, expected: Boolean) =
      assert(balance(input.toArray) == expected,
        s"balance($input) should be $expected")

    check("", true)
  }

  test("balance should work for string of length 1") {
    def check(input: String, expected: Boolean) =
      assert(balance(input.toArray) == expected,
        s"balance($input) should be $expected")

    check("(", false)
    check(")", false)
    check(".", true)
  }

  test("balance should work for string of length 2") {
    def check(input: String, expected: Boolean) =
      assert(balance(input.toArray) == expected,
        s"balance($input) should be $expected")

    check("()", true)
    check(")(", false)
    check("((", false)
    check("))", false)
    check(".)", false)
    check(".(", false)
    check("(.", false)
    check(").", false)
    check("(((()()())).", false)
    check("(())))(()()())).", false)
    check("(())(()()()).", true)
    check("(((())()()()())).", true)
    check("(((((()()()())))()())).", true)
  }


}
Example 30
Project: high-performance-spark   Author: gourimahapatra   File: DStreamSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.streaming

import org.apache.spark.streaming._

import java.lang.Thread
import com.holdenkarau.spark.testing._

import org.scalatest.FunSuite

class DStreamExamplesSuite extends FunSuite with SharedSparkContext {
  test("simple set up") {
    val ssc = DStreamExamples.makeStreamingContext(sc)
    val inputStream = DStreamExamples.fileAPIExample(ssc, "./")
    val repartitioned = DStreamExamples.repartition(inputStream)
    repartitioned.foreachRDD(rdd =>
      assert(rdd.partitioner.get.numPartitions == 20)
    )
    ssc.start()
    // This is bad don't do this - but we don't have the full test tools here
    Thread.sleep(100)
    ssc.stop()
  }
}
Example 31
Project: high-performance-spark   Author: gourimahapatra   File: NativeExample.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.ffi

import com.holdenkarau.spark.testing._
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Prop.forAll
import org.scalatest.FunSuite
import org.scalatest.prop.Checkers
import org.scalatest.Matchers._

class NativeExampleSuite extends FunSuite
    with SharedSparkContext with Checkers with RDDComparisons {

  test("local sum") {
    val input = Array(1, 2, 3)
    val sumMagic = new SumJNI()
    val result = sumMagic.sum(input)
    val expected = 6
    assert(result === expected)
  }

  test("super simple test") {
    val input = sc.parallelize(List(("hi", Array(1, 2, 3))))
    val result = NativeExample.jniSum(input).collect()
    val expected = List(("hi", 6))
    assert(result === expected)
  }

  test("native call should find sum correctly") {
    val property = forAll(
      RDDGenerator.genRDD[(String, Array[Int])](sc)(
        Arbitrary.arbitrary[(String, Array[Int])])) {
      rdd =>
        val expected = rdd.mapValues(_.sum)
        val result = NativeExample.jniSum(rdd)
        compareRDDWithOrder(expected, result).isEmpty
    }
    check(property)
  }

  test("JNA support") {
    val input = Array(1, 2, 3)
    assert(6 === SumJNA.sum(input, input.size))
  }

  test("JNA Fortran support") {
    val input = Array(1, 2, 3)
    assert(6 === SumFJNA.easySum(input.size, input))
  }
}
Example 32
Project: high-performance-spark   Author: gourimahapatra   File: FilterInvalidPandasSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.tools

import com.highperformancespark.examples.dataframe.RawPanda

import com.holdenkarau.spark.testing._

import org.scalatest.FunSuite

class FilterInvalidPandasSuite extends FunSuite with SharedSparkContext {
  test("simple filter") {
    val invalidPandas = List(1L, 2L)
    val inputPandas = List(
      RawPanda(1L, "94110", "giant", true, Array(0.0)),
      RawPanda(3L, "94110", "giant", true, Array(0.0)))
    val input = sc.parallelize(inputPandas)
    val result1 =
      FilterInvalidPandas.filterInvalidPandas(sc, invalidPandas, input)
    val result2 =
      FilterInvalidPandas.filterInvalidPandasWithLogs(sc, invalidPandas, input)
    assert(result1.collect() === result2.collect())
    assert(result1.count() === 1)
  }
}
Example 33
Project: high-performance-spark   Author: gourimahapatra   File: GenerateScalingDataSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.tools

import com.highperformancespark.examples.dataframe.RawPanda

import com.holdenkarau.spark.testing._

import org.scalatest.FunSuite

class GeneratescalaingDataSuite extends FunSuite with SharedSparkContext {
  // The number of entries depends somewhat on the partition split because we
  // zip multiple separate RDDs so its more of a "request"
  test("expected num entries") {
    val result = GenerateScalingData.generateFullGoldilocks(sc, 10L, 20)
    assert(result.count() <= 10)
    assert(result.count() > 5)
    assert(result.map(_.id).distinct().count() > 1)
  }

  test("expected num entries same id") {
    val result = GenerateScalingData.generateGoldilocks(sc, 5L, 20)
    assert(result.count() <= 5)
    assert(result.count() >= 2)
    assert(result.map(_.id).distinct().count() == 1)
  }

  test("mini scale data") {
    val result = GenerateScalingData.generateMiniScale(sc, 20L, 1)
    assert(result.count() <= 20)
    assert(result.count() > 5)
    assert(result.map(_._1).distinct().count() > 1)
  }

  test("mini scale rows") {
    val result = GenerateScalingData.generateMiniScaleRows(sc, 20L, 1)
    assert(result.count() <= 20)
    assert(result.count() > 5)
    assert(result.map(_(0)).distinct().count() > 1)
  }
}
Example 34
Project: high-performance-spark   Author: gourimahapatra   File: GoldilocksMLlibSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.mllib

import com.highperformancespark.examples.dataframe.RawPanda

import com.holdenkarau.spark.testing._

import org.scalatest.FunSuite


import org.apache.spark.mllib.linalg.{Vector => SparkVector}

class GoldilocksMLlibSuite extends FunSuite with SharedSparkContext {
  val rps = List(
    RawPanda(1L, "94110", "giant", true, Array(0.0, 0.0)),
    RawPanda(2L, "94110", "giant", false, Array(0.0, 3.0)),
    RawPanda(3L, "94110", "giant", true, Array(0.0, 2.0)))

  test("boolean to double") {
    assert(1.0 === GoldilocksMLlib.booleanToDouble(true))
    assert(0.0 === GoldilocksMLlib.booleanToDouble(false))
  }

  test("encoding") {
    val input = sc.parallelize(rps)
    val points = GoldilocksMLlib.toLabeledPointDense(input)
    assert(points.count() == 3)
    assert(points.filter(_.label != 0.0).count() == 2)
  }

  test("lookup table") {
    val input = sc.parallelize(List("hi", "bye", "coffee", "hi"))
    val table = GoldilocksMLlib.createLabelLookup(input)
    assert(table.size == 3)
  }

}
Example 35
Project: parprog   Author: TraitRDS   File: ParallelParenthesesBalancingSuite.scala View Source Project(license) 5 votes vote downvote up
package reductions

import java.util.concurrent._
import scala.collection._
import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import common._

import ParallelParenthesesBalancing._

@RunWith(classOf[JUnitRunner])
class ParallelParenthesesBalancingSuite extends FunSuite {

  test("balance should work for empty string") {
    def check(input: String, expected: Boolean) =
      assert(balance(input.toArray) == expected,
        s"balance($input) should be $expected")

    check("", true)
  }

  test("balance should work for string of length 1") {
    def check(input: String, expected: Boolean) =
      assert(balance(input.toArray) == expected,
        s"balance($input) should be $expected")

    check("(", false)
    check(")", false)
    check(".", true)
  }

  test("balance should work for string of length 2") {
    def check(input: String, expected: Boolean) =
      assert(balance(input.toArray) == expected,
        s"balance($input) should be $expected")

    check("()", true)
    check(")(", false)
    check("((", false)
    check("))", false)
    check(".)", false)
    check(".(", false)
    check("(.", false)
    check(").", false)
  }


}
Example 36
Project: my-scala-playground   Author: rysh   File: MyS3ObjectTest.scala View Source Project (license) 5 votes vote downvote up
package example

import better.files.File
import org.scalatest.{BeforeAndAfterAll, FunSuite}


class MyS3ObjectTest extends FunSuite with BeforeAndAfterAll {

  val s3 = MyS3.create()
  val bucketName = s"rysh-${localName()}-my-s3-object-test"
  val file = File("my-s3-object-test").createIfNotExists()

  override def beforeAll() {
    val bucket = s3.createBucket(bucketName)
  }

  override def afterAll() {
    file.delete()
    s3.deleteBucket(bucketName)
  }

  test("Upload an Object") {
    s3.upload(bucketName, "my-s3-object-test", file)
  }

  ignore("List Objects") {
    ???
  }

  ignore("Download an Object") {
    ???
  }

  ignore("Copy, Move, or Rename Objects") {
    ???
  }

  ignore("Delete an Object") {
    ???
  }

  ignore("Delete Multiple Objects at Once") {
    ???
  }
}
Example 37
Project: coursera-scala   Author: tklo   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 38
Project: newts   Author: julien-truffaut   File: NewtsSuite.scala View Source Project (license) 5 votes vote downvote up
package newts

import cats.instances.AllInstances
import newts.syntax.AllSyntax
import org.scalacheck.{Arbitrary, Cogen}
import org.scalacheck.Arbitrary.arbitrary
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FunSuite, Matchers}
import org.typelevel.discipline.scalatest.Discipline

trait NewtsSuite extends FunSuite
  with Matchers
  with GeneratorDrivenPropertyChecks
  with Discipline
  with AllSyntax
  with AllInstances
  with cats.syntax.AllSyntax
  with ArbitraryInstances

trait ArbitraryInstances {
  def arbNewtype[S, A: Arbitrary](implicit newtype: Newtype.Aux[S, A]): Arbitrary[S] =
    Arbitrary(arbitrary[A].map(newtype.wrap))

  def cogenNewtype[S, A: Cogen](implicit newtype: Newtype.Aux[S, A]): Cogen[S] =
    Cogen[A].contramap(newtype.unwrap)

  implicit val allArbitrary: Arbitrary[All] = arbNewtype[All, Boolean]
  implicit val anyArbitrary: Arbitrary[Any] = arbNewtype[Any, Boolean]
  implicit def multArbitrary[A:Arbitrary]: Arbitrary[Mult[A]] = arbNewtype[Mult[A], A]
  implicit def dualArbitrary[A: Arbitrary]: Arbitrary[Dual[A]] = arbNewtype[Dual[A], A]
  implicit def firstArbitrary[A: Arbitrary]: Arbitrary[First[A]] = arbNewtype[First[A], A]
  implicit def lastArbitrary[A: Arbitrary]: Arbitrary[Last[A]] = arbNewtype[Last[A], A]
  implicit def firstOptionArbitrary[A: Arbitrary]: Arbitrary[FirstOption[A]] = arbNewtype[FirstOption[A], Option[A]]
  implicit def lastOptionArbitrary[A: Arbitrary]: Arbitrary[LastOption[A]]  = arbNewtype[LastOption[A], Option[A]]
  implicit def minArbitrary[A: Arbitrary]: Arbitrary[Min[A]]  = arbNewtype[Min[A], A]
  implicit def maxArbitrary[A: Arbitrary]: Arbitrary[Max[A]]  = arbNewtype[Max[A], A]
  implicit def zipListArbitrary[A: Arbitrary]: Arbitrary[ZipList[A]] = arbNewtype[ZipList[A], List[A]]

  implicit val allCogen: Cogen[All] = cogenNewtype[All, Boolean]implicit val anyCogen:Cogen[Any]= cogenNewtype[Any,Boolean]implicitdef multCogen[A:Cogen]:Cogen[Mult[A]]= cogenNewtype[Mult[A], A]implicitdef dualCogen[A:Cogen]:Cogen[Dual[A]]= cogenNewtype[Dual[A], A]implicitdef firstCogen[A:Cogen]:Cogen[First[A]]= cogenNewtype[First[A], A]implicitdef lastCogen[A:Cogen]:Cogen[Last[A]]= cogenNewtype[Last[A], A]implicitdef firstOptionCogen[A:Cogen]:Cogen[FirstOption[A]]= cogenNewtype[FirstOption[A],Option[A]]implicitdef lastOptionCogen[A:Cogen]:Cogen[LastOption[A]]= cogenNewtype[LastOption[A],Option[A]]implicitdef minOptionCogen[A:Cogen]:Cogen[Min[A]]= cogenNewtype[Min[A], A]implicitdef maxOptionCogen[A:Cogen]:Cogen[Max[A]]= cogenNewtype[Max[A], A]implicitdef zipListCogen[A:Cogen]:Cogen[ZipList[A]]= cogenNewtype[ZipList[A],List[A]]}
Example 39
Project: bittorrent   Author: zpooky   File: TorrentFileManager_LargeFile.scala View Source Project(license) 5 votes vote downvote up
package com.spooky.bittorrent.l.file

import org.scalatest.FunSuite
import java.io.File
import com.spooky.bittorrent.metainfo.Torrents
import java.nio.file.Paths

class TorrentFileManagerTest_LargeFile extends FunSuite {
  val file = new File("O:\tmp\file.dump.torrent")
  val torrent = Torrents(file)
  val root = Paths.get("O:\tmp")
  lazy val stat = new FileInitiator2(torrent, root).state()

  test("xx") {
    val fm = TorrentFileManager(torrent, root, stat)
  }

}
object TorrentFileManagerTest_LargeFilex {
  val file = new File("O:\tmp\file.dump.torrent")
  val torrent = Torrents(file)
  val root = Paths.get("O:\tmp")
  lazy val stat = new FileInitiator2(torrent, root).state()
  def main(args: Array[String]) {
    val fm = TorrentFileManager(torrent, root, stat)
    assert(fm.complete)
  }
}
Example 40
Project: bittorrent   Author: zpooky   File: QueueTest.scala View Source Project (license) 5 votes vote downvote up
package com.spooky.bittorrent

import org.scalatest.FunSuite
import scala.collection.mutable.Queue

class QueueTest extends FunSuite {
  test("t") {
    val q = Queue[Int]()
    q += 1
    q += 2
    q += 3
    q += 4
    q += 5
    Range(0, q.length).foreach { _ =>
      q.dequeue()
    }
    println("size:" + q.size)
  }
}
Example 41
Project: bittorrent   Author: zpooky   File: MonadTest.scala View Source Project (license) 5 votes vote downvote up
package com.spooky.bittorrent

import org.scalatest.FunSuite

class MonadTest extends FunSuite {
  implicit def toOption[T](any: T): Option[T] = Option(any)
  var c = 0
  def func: Option[String] = c match {
    case 0 => {
      c = c + 1
      "0"
    }
    case 1 => {
      c = c + 1
      "1"
    }
    case 2 => {
      c = c + 1
      "2"
    }
    case _ => None
  }
  test("") {
    val xsss = for {
      x <- func
    } yield x
    println(xsss)
  }

}
Example 42
Project: bittorrent   Author: zpooky   File: BencodeMarshallTest.scala View Source Project (license) 5 votes vote downvote up
package com.spooky.bencode

import org.scalatest.FunSuite

class BencodeMarshallTest extends FunSuite {
  case class Tttt(s: String, i: Int)
  val m = new BencodeMarshall
  test("dd"){
    val t = Tttt("ss",112)
    println(m.marshall(t))
    
  }
  test("null"){
//    println(m.marshall(null))
  }
}
Example 43
Project: bittorrent   Author: zpooky   File: RequestTest.scala View Source Project (license) 5 votes vote downvote up
package com.spooky

import org.scalatest.FunSuite
import com.spooky.DHT.PingQuery
import com.spooky.bittorrent.InfoHash
import com.spooky.bencode.BencodeMarshall

class RequestTest extends FunSuite {
    //{"t":"aa", "y":"q", "q":"ping", "a":{"id":"abcdefghij0123456789"}}
  val m = new BencodeMarshall
  test("PingQuery") {
    val pingQuery = PingQuery(InfoHash.hex("abcdef0123456789"),"aa")
    val pq = m.marshall(pingQuery)
    println(pq)
    println(pq.toBencode)
    println(pingQuery.nodeId)
  }
  //{"t":"aa", "y":"r", "r": {"id":"mnopqrstuvwxyz123456"}}
  test("PingResponse") {
	  
  }
  test("FindNodeQuery") {
	  
  }
  test("FindNodeResponse") {
	  
  }
  test("") {
	  
  }
  test("GetPeersQuery") {
	  
  }
  test("GetPeersResponse") {
	  
  }
  test("AnnouncePeersQuery") {
	  
  }
  test("AnnoucePeersResponse") {
	  
  }
  test("ErrorResponse") {
	  
  }
}
Example 44
Project: coursera-funprog-scala-recursion-assignment   Author: jdehlinger   File: CountChangeSuite.scalaView Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 45
Project: scala-ing   Author: vr1090   File: ComplexProperties.scala View Source Project (license) 5 votes vote downvote up
// src/main/scala/progscala2/toolslibs/toolslibs/ComplexProperties.scala
package progscala2.toolslibs
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class ComplexProperties extends FunSuite with PropertyChecks {

  def additionTest(a: Complex, b: Complex) = {
    assert( (a + b).real === (a.real + b.real) )
    assert( (a + b).imaginary === (a.imaginary + b.imaginary) )
  }

  def subtractionTest(a: Complex, b: Complex) = {
    assert( (a - b).real === (a.real - b.real) )
    assert( (a - b).imaginary === (a.imaginary - b.imaginary) )
  }

  val zero = Complex(0.0, 0.0)

  test ("Complex addition with the identity element (zero)") {
    forAll { (real: Double, imag: Double) =>
      val c = Complex(real, imag)
      additionTest(zero, c)
      additionTest(c, zero)
    }
  }

  test ("Complex subtraction with the identity element (zero)") {
    forAll { (real: Double, imag: Double) =>
      val c = Complex(real, imag)
      subtractionTest(zero, c)
      subtractionTest(c, zero)
    }
  }

  test ("Complex addition with two values") {
    forAll { (real1: Double, imag1: Double, real2: Double, imag2: Double) =>
      val c1 = Complex(real1, imag1)
      val c2 = Complex(real2, imag2)
      additionTest(c1, c2)
    }
  }

  test ("Complex subtraction with two values") {
    forAll { (real1: Double, imag1: Double, real2: Double, imag2: Double) =>
      val c1 = Complex(real1, imag1)
      val c2 = Complex(real2, imag2)
      subtractionTest(c1, c2)
    }
  }
}
Example 46
Project: sourceCode   Author: RominYue   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 47
Project: CodeJam   Author: javathought   File: PancakeTest.scala View Source Project (license) 5 votes vote downvote up
package puzzle2016.q

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import Pancake._


@RunWith(classOf[JUnitRunner])
class PancakeTest extends FunSuite {

  test("Count Pankcake Jam is ok") {
    assert( ln(("-"    toList) reverse)    === 1, "solution for '-' is KO")
    assert( ln(("-+"   toList) reverse)    === 1, "solution for '-+' is KO")
    assert( ln(("+-"   toList) reverse)    === 2, "solution for '+-' is KO")
    assert( ln(("+++"  toList) reverse)    === 0, "solution for '+++' is KO")
    assert( ln(("--+-" toList) reverse)    === 3, "solution for '--+-' is KO")
  }

}
Example 48
Project: Parallelism-and-Concurrency-Assignments   Author: vincenzobaz   File: BoundedBufferSuite.scala View Source Project (license) 5 votes vote downvote up
package pubsub

import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.collection.mutable.HashMap

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

import instrumentation._
import instrumentation.Stats._

import pubsub.collection._

@RunWith(classOf[JUnitRunner])
class BoundedBufferSuite extends FunSuite {

  import TestHelper._
  import TestUtils._

  test("Should work in a sequential setting") {
    val buffer = new BoundedBuffer[Int](4);
    buffer.put(1)
    buffer.put(2)
    buffer.put(3)
    buffer.put(4)
    assert(buffer.take() == 1)
    assert(buffer.take() == 2)
    assert(buffer.take() == 3)
    assert(buffer.take() == 4)
  }
  
  test("Should work when Thread 1: `put(1)`, Thread 2: `take` and a buffer of size 1") {
    testManySchedules(2, sched => {
      val prodCons = new SchedulableBoundedBuffer[Int](1, sched)
      List(() => prodCons.put(1), () => prodCons.take())
    }, args =>  (args(1) == 1, s"expected 1 your `take` implementation returned ${args(1)}"))    
  }
}

object TestUtils {
  def failsOrTimesOut[T](action: => T): Boolean = {
    val asyncAction = future {
      action
    }
    try {
      Await.result(asyncAction, 2000.millisecond)
    }
    catch {
      case _: Throwable => return true
    }
    return false
  }
}
Example 49
Project: Parallelism-and-Concurrency-Assignments   Author: vincenzobaz   File: StackOverflowSuite.scala View Source Project (license) 5 votes vote downvote up
package stackoverflow

import org.scalatest.{FunSuite, BeforeAndAfterAll}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.RDD
import java.net.URL
import java.nio.channels.Channels
import java.io.File
import java.io.FileOutputStream

@RunWith(classOf[JUnitRunner])
class StackOverflowSuite extends FunSuite with BeforeAndAfterAll {

  lazy val testObject = new StackOverflow {
    override val langs =
      List(
        "JavaScript", "Java", "PHP", "Python", "C#", "C++", "Ruby", "CSS",
        "Objective-C", "Perl", "Scala", "Haskell", "MATLAB", "Clojure", "Groovy")
    override def langSpread = 50000
    override def kmeansKernels = 45
    override def kmeansEta: Double = 20.0D
    override def kmeansMaxIterations = 120
  }

  test("testObject can be instantiated") {

    val instantiatable = try {
      testObject
      true
    } catch {
      case _: Throwable => false
    }
    assert(instantiatable, "Can't instantiate a StackOverflow object")
  }

}
Example 50
Project: CakePatternPractise   Author: johnnyqian   File: UserServiceSuite.scala View Source Project(license) 5 votes vote downvote up
package CakePattern

import org.scalatest.FunSuite
import org.specs2.mock.Mockito


class UserServiceSuite extends FunSuite
with Mockito
with UserServiceComponent
with UserRepositoryComponent {
  lazy val userRepository = mock[UserRepository]
  lazy val userService = mock[UserService]

  val user = new User("test", "test")
  userRepository.authenticate(any[User]) returns user

  test("testAuthenticate") {
    assert(userRepository.authenticate(user) == user)
  }
}
Example 51
Project: vo-ss-extractor   Author: oginskis   File: FlatRepoTest.scala View Source Project (license) 5 votes vote downvote up
package org.oginskis.ss.repo

import org.bson.Document
import org.junit.runner.RunWith
import org.oginskis.ss.model.Flat
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner


@RunWith(classOf[JUnitRunner])
class FlatRepoTest extends FunSuite{

  test("flat find filter test: All fields are set") {
    val flat = new Flat(Option("Caka 95"),Option("4"),Option(55),
      Option("1/5"),Option(30000),Option("link"))
    val doc: Document = FlatRepo.findFilter(flat)
    assert("Caka 95" === doc.get("address"))
    assert("4" === doc.get("rooms"))
    assert("55" === doc.get("size"))
    assert("1/5" === doc.get("floor"))
    assert("30000" === doc.get("price"))
    assert("link" === doc.get("link"))
  }

  test("flat find filter test: price and link are missing") {
    val flat = new Flat(Option("Caka 95"),Option("4"),Option(55),
      Option("1/5"))
    val doc: Document = FlatRepo.findFilter(flat)
    assert("Caka 95" === doc.get("address"))
    assert("4" === doc.get("rooms"))
    assert("55" === doc.get("size"))
    assert("1/5" === doc.get("floor"))
    assert(doc.get("price") === null)
    assert(doc.get("link") === null)
  }

  test("historic flats") {
    val flats : List[Flat] = FlatRepo.findHistoricAdds(new Flat(Option("Artil?rijas 46"),Option("1"),
      Option(29),Option("2/4")))
  }

}
Example 52
Project: pacttests   Author: PawelWlodarski   File: FirstPactExample.scala View Source Project (license) 5 votes vote downvote up
package com.wlodar.pactexample.first

import com.wlodar.jug.pacttest.client.ServiceClient
import org.scalatest.{FunSpec, FunSuite, Matchers}

import scalaj.http.HttpResponse

class FirstPactExample extends FunSuite with Matchers {

  import com.itv.scalapact.ScalaPactForger._

  test("Pierwszy przyk?ad na demo") {
    forgePact
      .between("tenTutajKonsument")
      .and("uslugaZewnetrzna")
      .addInteraction(
        interaction
          .description("Prosty get bez parametrów")
          .uponReceiving("/apiUslugi")
          .willRespondWith(200, "Pact dzia?a!!!")
      ).runConsumerTest{config=>

      //pokaza? kod
      val result: HttpResponse[String] =ServiceClient.call(config.baseUrl,"apiUslugi")

      result.code shouldBe 200
      result.body shouldBe "Pact dzia?a!!!"
//      result.body shouldBe "B??d"

    }
  }

}
Example 53
Project: scala_specialization_coursera   Author: alvsanand   File: LineOfSightSuite.scala View Source Project (license) 5 votes vote downvote up
package reductions

import java.util.concurrent._
import scala.collection._
import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import common._
import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory

@RunWith(classOf[JUnitRunner]) 
class LineOfSightSuite extends FunSuite {
  import LineOfSight._
  test("lineOfSight should correctly handle an array of size 4") {
    val output = new Array[Float](4)
    lineOfSight(Array[Float](0f, 1f, 8f, 9f), output)
    assert(output.toList == List(0f, 1f, 4f, 4f))
  }


  test("upsweepSequential should correctly handle the chunk 1 until 4 of an array of 4 elements") {
    val res = upsweepSequential(Array[Float](0f, 1f, 8f, 9f), 1, 4)
    assert(res == 4f)
  }


  test("downsweepSequential should correctly handle a 4 element array when the starting angle is zero") {
    val output = new Array[Float](4)
    downsweepSequential(Array[Float](0f, 1f, 8f, 9f), output, 0f, 1, 4)
    assert(output.toList == List(0f, 1f, 4f, 4f))
  }

  test("parLineOfSight should correctly handle an array of size 4") {
    val output = new Array[Float](4)
    parLineOfSight(Array[Float](0f, 1f, 8f, 9f), output, 1)
    assert(output.toList == List(0f, 1f, 4f, 4f))
  }

}
Example 54
Project: scala_specialization_coursera   Author: alvsanand   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 55
Project: BigDataMaker   Author: dondrake   File: TestColumns.scala View Source Project (license) 5 votes vote downvote up
package com.drakeconsulting.big_data_maker

import org.scalatest.FunSuite
import com.holdenkarau.spark.testing.SharedSparkContext
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.types.{StructField, StringType, LongType, DoubleType}

class ColumnsTest extends FunSuite with SharedSparkContext {
  val numLoops = 100

  test("test StringConstant") {
    val s1 = new StringConstant("f1", "abc")
    assert("abc" === s1.getValue(1))
    assert(StructField("f1", StringType, false) == s1.getStructField)
  }

  test("test RandomLong") {
    val s1 = new RandomLong("f1", 666666L)
    for (x <- 1 to numLoops) {
      assert(s1.getValue(1) >= 0)
      assert(s1.getValue(1) <= 666666L)
    }
    assert(StructField("f1", LongType, false) == s1.getStructField)
  }

  test("test RandomDouble") {
    val s1 = new RandomDouble("f1", 666666.00)
    for (x <- 1 to numLoops) {
      assert(s1.getValue(1) >= 0)
      assert(s1.getValue(1) <= 666666.00)
    }
    assert(StructField("f1", DoubleType, false) == s1.getStructField)
  }

  test("test Categorical") {
    val list = List("a", "b", "c", "d")
    val s1 = new Categorical("f1", list)
    for (x <- 1 to numLoops) {
      val v = s1.getValue(1)
      assert(list.exists(key => v.contains(key)))
    }
    assert(StructField("f1", StringType, false) == s1.getStructField)
  }
}
Example 56
Project: BigDataMaker   Author: dondrake   File: TestBigDataMaker.scala View Source Project (license) 5 votes vote downvote up
package com.drakeconsulting.big_data_maker

import org.scalatest.FunSuite
import com.holdenkarau.spark.testing.SharedSparkContext
import org.apache.spark.sql.SQLContext

class BigDataMakerTest extends FunSuite with SharedSparkContext {
  test("first") {
    val sqlContext = new SQLContext(sc)
    val bd = new BigData(sqlContext, "/tmp/b", 5, 100)
    bd.addColumn(new StringConstant("f1", "abc"))
    bd.addColumn(new StringConstant("f2", "def"))

    val df = bd._createDataFrame
    df.show
    assert(500 === df.count)
    assert(2 === df.columns.length)
  }

  test("col names") {
    val sqlContext = new SQLContext(sc)
    val bd = new BigData(sqlContext, "/tmp/b", 5, 100)
    bd.addColumn(new StringConstant("f1", "abc"))
    bd.addColumn(new StringConstant("", "def"))

    assert("f1" === bd.cols(0).name)
    assert("f_1" === bd.cols(1).name)
  }
}
Example 57
Project: Courses   Author: zearom32   File: SimulationSuite.scala View Source Project (license) 5 votes vote downvote up
package practice

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.exceptions.{TestCanceledException, TestFailedDueToTimeoutException}
import org.scalatest.junit.JUnitRunner
import org.scalatest.time.{Millis, Span, Seconds}
import org.scalatest.concurrent.Timeouts._




@RunWith(classOf[JUnitRunner])
class SimulationSuite extends FunSuite{
  object sim extends Circuits with Parameters
  import sim._

  test("a simple test"){
    val in1, in2, sum, carry = new Wire
    probe("sum", sum)
    probe("carry", carry)
    halfAdder(in1, in2, sum, carry)
    in1.setSignal(true)
    sim.run()
    in2.setSignal(true)
    sim.run()
    assert(carry.getSignal == true)
    assert(sum.getSignal == false)
  }

  test("will not terminate") {
    try {
      cancelAfter(Span(10, Seconds)) {
        val in3 = new Wire
        probe("in3", in3)
        inverter(in3, in3)
        sim.run()
      }
    }
    catch {
      case x:TestCanceledException =>
    }
  }

}
Example 58
Project: computation-strategies   Author: socrata-platform   File: GeocodingComputationStrategyTest.scala View Source Project (license) 5 votes vote downvote up
package com.socrata.computation_strategies

import com.socrata.computation_strategies.GeocodingComputationStrategy.GeocodingSourcesDoNotMatchSourceColumns
import org.scalatest.{ShouldMatchers, FunSuite}

class GeocodingComputationStrategyTest extends FunSuite with ShouldMatchers {
  import TestData._
  import TestData.GeocodingData._

  def testValidate(definition: StrategyDefinition[String], expected: Option[ValidationError] = None): Unit = {
    GeocodingComputationStrategy.validate(definition) should be (expected)
  }

  def testTransform(definition: StrategyDefinition[String],
                    columns: Map[String, Int],
                    expected: Either[ValidationError, StrategyDefinition[Int]]): Unit = {
    GeocodingComputationStrategy.transform(definition, columns) should be (expected)
  }

  test("Definition with full sources and parameters should be invalid") {
    testValidate(fullDefinition)
  }

  test("Definition with no sources should be invalid") {
    val expected = Some(GeocodingSourcesDoNotMatchSourceColumns(List(), Some(GeocodingSources(Some(address),Some(city),
      Some(county),Some(state),Some(zip),Some(country)))))
    testValidate(noSourcesDefinition, expected)
  }

  test("Definition with no parameters should be invalid") {
    testValidate(noParamsDefinition, Some(MissingParameters(GeocodingParameterSchema)))
  }

  test("Definition with an unknown source column should fail to transform") {
    testTransform(fullDefinition, columnIds - address, Left(UnknownSourceColumn(address)))
  }

}
Example 59
Project: ProgFun1   Author: albertoadami   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 60
Project: spark-wilcoxon   Author: robert-dodier   File: wilcoxonSuite.scala View Source Project (license) 5 votes vote downvote up
package org.robertdodier

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

class wilcoxonSuite extends FunSuite with BeforeAndAfterAll {

  @transient var sc: SparkContext = _

  override def beforeAll() {
    val conf = new SparkConf()
      .setMaster("local")
      .setAppName("test")
    sc = new SparkContext(conf)
    super.beforeAll()
  }

  override def afterAll() {
    if (sc != null) {
      sc.stop()
    }
    super.afterAll()
  }

  test("compute scaled rank sum with made-up data") {
    val scoresAndLabels = Seq((0.6, 1), (0.9, 1), (0.3, 1), (0.2, 0), (0.1, 0), (0.5, 0))
    val U = wilcoxon.U (sc.parallelize (scoresAndLabels))
    val expected_U = 8.0/9.0
    assert (Math.abs (U - expected_U) <= 1e-12)
  }
}
Example 61
Project: sclib   Author: j-keck   File: EitherOpsSuite.scala View Source Project (license) 5 votes vote downvote up
package sclib.ops

import org.scalatest.{FunSuite, Matchers}

class EitherOpsSuite extends FunSuite with Matchers {
  import sclib.ops.either._

  test("sequence with Right values"){
    val l: List[Either[String, Int]] = List.range(1, 10).map(_.right[String])
    val e: Either[String, List[Int]] = l.sequence
    e should be(Right(List.range(1, 10)))
  }

  test("sequence with one Left"){
    val l: List[Either[String, Int]] = List.range(1, 10).map(Right.apply).updated(6, Left("BOOM"))
    val e: Either[String, Seq[Int]] = l.sequence
    e should be(Left("BOOM"))
  }


  test("right biased map / flatMap"){
    val res1 = for {
      a <- 1.right
      b <- "BOOM".left[Int]
    } yield a + b
    res1 should be(Left("BOOM"))

    val res2 = for{
      a <- 1.right
      b <- 2.right
    } yield a + b
    res2 should be(Right(3))
  }

}
Example 62
Project: sclib   Author: j-keck   File: ListOpsSuite.scala View Source Project (license) 5 votes vote downvote up
package sclib.ops

import org.scalatest.{FunSuite, Matchers}
import sclib.ops.list._

class ListOpsSuite extends FunSuite with Matchers {

  test("unfoldRight") {
    ListOps.unfoldRight(0) { i =>
      if (i > 5) None else Some((i, i + 1))
    } should be(List(0, 1, 2, 3, 4, 5))
  }

  test("unfoldLeft") {
    ListOps.unfoldLeft(0) { i =>
      if (i > 5) None else Some((i + 1, i))
    } should be(List(5, 4, 3, 2, 1, 0))
  }
}
Example 63
Project: sclib   Author: j-keck   File: FSPermSuite.scala View Source Project (license) 5 votes vote downvote up
package sclib.io.fs

import java.nio.file.attribute.PosixFilePermission
import java.nio.file.attribute.PosixFilePermission._

import org.scalatest.{FunSuite, Matchers}
import sclib.ops.all._

class FSPermSuite extends FunSuite with Matchers {
  import FSPerm._

  test("calc: valid") {
    calc(731) should be(
        Seq(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_WRITE, GROUP_EXECUTE, OTHERS_EXECUTE).success)
  }

  test("calc: invalid"){
    calc(738).fold(_.getMessage)(_ => "Failure expected!") should be("Invalid file mode: 738")
  }


  test("mod: valid"){
    def check(s1: Seq[PosixFilePermission], mode: String, s2: Seq[PosixFilePermission]) = {
      mod(s1, mode).map(_.sorted) should be(s2.sorted.success)
    }

    check(Seq(OWNER_READ), "a+x", Seq(OWNER_READ, OWNER_EXECUTE, GROUP_EXECUTE, OTHERS_EXECUTE))
    check(Seq(OWNER_READ), "a+r", Seq(OWNER_READ, GROUP_READ, OTHERS_READ))

    check(Seq(OWNER_READ, GROUP_READ), "u+wx", Seq(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ))

    check(Seq(OWNER_EXECUTE, GROUP_EXECUTE), "u=rw", Seq(OWNER_READ, OWNER_WRITE, GROUP_EXECUTE))

    check(Seq(), "u+r,g+w,o+x", Seq(OWNER_READ, GROUP_WRITE, OTHERS_EXECUTE))

  }

  test("mod: invalid"){
    def check(mode: String, expected: String) = {
      mod(Seq(), mode).fold(_.getMessage)(x => s"Failure expected for mode: ${mode} - received: ${x}") should be(expected)
    }

    check("arwx", "operator [+|-|=] not found")
    check("a/rwx", "operator [+|-|=] not found")
    check("+rwx", "who ([a|u|g|o]+) not found")
    check("a+", "perm ([r|w|x]+) not found")
  }
}
Example 64
Project: wartremover-contrib   Author: wartremover   File: UnsafeInheritanceTest.scala View Source Project (license) 5 votes vote downvote up
package org.wartremover
package contrib.test

import org.scalatest.FunSuite
import org.wartremover.contrib.warts.UnsafeInheritance
import org.wartremover.test.WartTestTraverser

class UnsafeInheritanceTest extends FunSuite with ResultAssertions {
  test("Method must be final or abstract") {
    val result = WartTestTraverser(UnsafeInheritance) {
      trait T {
        def m() = {}
      }
    }
    assertError(result)("Method must be final or abstract")
  }

  test("Final and abstract, private, object methods are allowed") {
    val result = WartTestTraverser(UnsafeInheritance) {
      trait T {
        final def m2() = {}
        def m1(): Unit
        private def m3() = {}
      }
      final class C1 {
        def m() = {}
      }
      sealed class C2 {
        def m() = {}
      }
      object O {
        def m() = {}
      }
      case class CC(i: Int)
    }
    assertEmpty(result)
  }

  test("UnsafeInheritance wart obeys SuppressWarnings") {
    val result = WartTestTraverser(UnsafeInheritance) {
      trait T {
        @SuppressWarnings(Array("org.wartremover.contrib.warts.UnsafeInheritance"))
        def m() = {}
      }
    }
    assertEmpty(result)
  }
}
Example 65
Project: wartremover-contrib   Author: wartremover   File: SomeApplyTest.scala View Source Project(license) 5 votes vote downvote up
package org.wartremover
package contrib.test

import org.scalatest.FunSuite
import org.wartremover.contrib.warts.SomeApply
import org.wartremover.test.WartTestTraverser

class SomeApplyTest extends FunSuite with ResultAssertions {

  test("can't use Some.apply with null") {
    val result = WartTestTraverser(SomeApply) {
      Some(null)
    }
    assertError(result)("Some.apply is disabled - use Option.apply instead")
  }

  test("can't use Some.apply with a literal") {
    val result = WartTestTraverser(SomeApply) {
      Some(1)
    }
    assertError(result)("Some.apply is disabled - use Option.apply instead")
  }

  test("can't use Some.apply with an identifier") {
    val result = WartTestTraverser(SomeApply) {
      val x = 1
      Some(x)
    }
    assertError(result)("Some.apply is disabled - use Option.apply instead")
  }

  test("can use Some.unapply in pattern matching") {
    val result = WartTestTraverser(SomeApply) {
      Option("test") match {
        case Some(test) => println(test)
        case None => println("not gonna happen")
      }
    }
    assertEmpty(result)
  }

  test("obeys SuppressWarnings") {
    val result = WartTestTraverser(SomeApply) {
      @SuppressWarnings(Array("org.wartremover.contrib.warts.SomeApply"))
      val x = Some(null)
    }
    assertEmpty(result)
  }
}
Example 66
Project: phone-guide   Author: videlalvaro   File: EncoderDecoderTest.scala View Source Project(license) 5 votes vote downvote up
package org.videlalvaro.phoneguide.netty

import io.netty.channel.embedded.EmbeddedChannel
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FunSuite, Matchers}
import org.videlalvaro.phoneguide.PhoneNumber
import org.videlalvaro.phoneguide.generators.Generators._

class EncoderDecoderTest extends FunSuite with GeneratorDrivenPropertyChecks with Matchers {
  test("netty encode/decode message") {
    forAll { (phoneNumber: PhoneNumber) =>
      val channel = new EmbeddedChannel(new MessageEncoder(), new MessageDecoder())

      channel.writeOutbound(phoneNumber)
      channel.writeInbound(channel.readOutbound())

      val readPhoneNumber = channel.readInbound();
      readPhoneNumber should not be (null)
      readPhoneNumber.equals(phoneNumber) should be (true)
      phoneNumber.equals(readPhoneNumber) should be (true)
    }
  }
}
Example 67
Project: marathon   Author: xiaozai512   File: ReadinessCheckSerializerTest.scala View Source Project(license) 5 votes vote downvote up
package mesosphere.marathon.state

import mesosphere.marathon.core.readiness.ReadinessCheckTestHelper
import org.scalatest.{ GivenWhenThen, Matchers, FunSuite }
import mesosphere.marathon.Protos

class ReadinessCheckSerializerTest extends FunSuite with Matchers with GivenWhenThen {
  test("get defaultHttp for empty protobuf") {
    Given("an empty protobuf")
    val proto = Protos.ReadinessCheckDefinition.getDefaultInstance
    When("reading it")
    val check = ReadinessCheckSerializer.fromProto(proto)
    Then("we get the defaults")
    check should equal(ReadinessCheckTestHelper.defaultHttp)
  }

  test("defaultHttp example serialized/deserializes") {
    Given("a defaultHttp readinessCheck")
    val defaultHttp = ReadinessCheckTestHelper.defaultHttp
    When("serializing it to a proto")
    val proto = ReadinessCheckSerializer.toProto(defaultHttp)
    And("deserializing it again")
    val reread = ReadinessCheckSerializer.fromProto(proto)
    Then("we get the original check back")
    reread should equal(defaultHttp)
  }

  test("alternativeHttps example serialized/deserializes") {
    Given("a alternativeHttps readinessCheck")
    val alternativeHttps = ReadinessCheckTestHelper.alternativeHttps
    When("serializing it to a proto")
    val proto = ReadinessCheckSerializer.toProto(alternativeHttps)
    And("deserializing it again")
    val reread = ReadinessCheckSerializer.fromProto(proto)
    Then("we get the original check back")
    reread should equal(alternativeHttps)
  }
}
Example 68
Project: marathon   Author: xiaozai512   File: InstanceIdTest.scala View Source Project (license) 5 votes vote downvote up
package mesosphere.marathon.instance

import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.pod.MesosContainer
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.raml.Resources
import mesosphere.marathon.state.PathId._
import org.scalatest.{ FunSuite, Matchers }

class InstanceIdTest extends FunSuite with Matchers {

  test("AppIds can be converted to InstanceIds and back to AppIds") {
    val appId = "/test/foo/bla/rest".toPath
    val instanceId = Instance.Id.forRunSpec(appId)
    instanceId.runSpecId should equal(appId)
  }

  test("InstanceIds can be converted to TaskIds without container name") {
    val appId = "/test/foo/bla/rest".toPath
    val instanceId = Instance.Id.forRunSpec(appId)
    val taskId = Task.Id.forInstanceId(instanceId, container = None)
    taskId.idString should be(instanceId.idString + ".$anon")
  }

  test("InstanceIds can be converted to TaskIds with container name") {
    val appId = "/test/foo/bla/rest".toPath
    val instanceId = Instance.Id.forRunSpec(appId)
    val container = MesosContainer("firstOne", resources = Resources())
    val taskId = Task.Id.forInstanceId(instanceId, Some(container))
    taskId.idString should be(instanceId.idString + ".firstOne")
  }

  test("InstanceIds can be converted from TaskIds with container name") {
    val appId = "/test/foo/bla/rest".toPath
    val parsedTaskId = Task.Id("test_foo_bla_rest.instance-myinstance.someContainerName")
    parsedTaskId.runSpecId should be(appId)
    parsedTaskId.instanceId should be(Instance.Id("test_foo_bla_rest.instance-myinstance"))
    parsedTaskId.containerName should be('nonEmpty)
    parsedTaskId.containerName should be(Some("someContainerName"))
  }

  test("InstanceIds can be converted from TaskIds without a container name") {
    val appId = "/test/foo/bla/rest".toPath
    val parsedTaskId = Task.Id("test_foo_bla_rest.instance-myinstance.$anon")
    parsedTaskId.runSpecId should be(appId)
    parsedTaskId.instanceId should be(Instance.Id("test_foo_bla_rest.instance-myinstance"))
    parsedTaskId.containerName should be('empty)
  }

  test("InstanceIds should be created by static string") {
    val idString = "app.marathon-task"
    val instanceId = Instance.Id(idString)
    instanceId.idString should be(idString)
    instanceId.runSpecId.safePath should be("app")
    val taskId = Task.Id(idString + ".app")
    taskId.instanceId should be(instanceId)
  }

}
Example 69
Project: marathon   Author: xiaozai512   File: TaskIdTest.scala View Source Project (license) 5 votes vote downvote up
package mesosphere.marathon.tasks

import mesosphere.marathon.core.task.Task
import org.apache.mesos.Protos.TaskID
import org.scalatest.{ FunSuite, Matchers }
import mesosphere.marathon.state.PathId._

class TaskIdTest extends FunSuite with Matchers {

  test("AppIds can be converted to TaskIds and back to AppIds") {
    val appId = "/test/foo/bla/rest".toPath
    val taskId = Task.Id.forRunSpec(appId)
    taskId.runSpecId should equal(appId)
  }

  test("Old TaskIds can be converted") {
    val taskId = Task.Id(TaskID.newBuilder().setValue("app_682ebe64-0771-11e4-b05d-e0f84720c54e").build)
    taskId.runSpecId should equal("app".toRootPath)
  }

  test("Old TaskIds can be converted even if they have dots in them") {
    val taskId = Task.Id(TaskID.newBuilder().setValue("app.foo.bar_682ebe64-0771-11e4-b05d-e0f84720c54e").build)
    taskId.runSpecId should equal("app.foo.bar".toRootPath)
  }

  test("Old TaskIds can be converted even if they have underscores in them") {
    val taskId = Task.Id(TaskID.newBuilder().setValue("app_foo_bar_0-12345678").build)
    taskId.runSpecId should equal("/app/foo/bar".toRootPath)
  }

  test("TaskIds with encoded InstanceIds could be encoded") {
    val taskId = Task.Id(TaskID.newBuilder().setValue("test_foo_bla_rest.instance-instance1.62d0f03f-79aa-11e6-a1a0-660c139c5e15").build)
    taskId.runSpecId should equal("/test/foo/bla/rest".toRootPath)
    taskId.instanceId.idString should equal("test_foo_bla_rest.instance-instance1")
  }

  test("TaskIds with encoded InstanceIds could be encoded even with crucial path ids") {
    val taskId = Task.Id(TaskID.newBuilder().setValue("test_foo.instance-_bla_rest.instance-instance1.62d0f03f-79aa-11e6-a1a0-660c139c5e15").build)
    taskId.runSpecId should equal("/test/foo.instance-/bla/rest".toRootPath)
    taskId.instanceId.idString should equal("test_foo.instance-_bla_rest.instance-instance1")
  }

  test("TaskIds without specific instanceId should use taskId as instanceId") {
    val taskId = Task.Id(TaskID.newBuilder().setValue("test_foo_bla_rest.62d0f03f-79aa-11e6-a1a0-660c139c5e15").build)
    taskId.runSpecId should equal("/test/foo/bla/rest".toRootPath)
    taskId.instanceId.idString should equal("test_foo_bla_rest.marathon-62d0f03f-79aa-11e6-a1a0-660c139c5e15")
  }
}
Example 70
Project: marathon   Author: xiaozai512   File: ResourceMatchTest.scala View Source Project (license) 5 votes vote downvote up
package mesosphere.mesos

import mesosphere.marathon.tasks.{ PortsMatch, PortsMatcher }
import mesosphere.marathon.test.MarathonTestHelper
import org.scalatest.{ FunSuite, GivenWhenThen, Matchers }

import scala.collection.immutable.Seq

class ResourceMatchTest
    extends FunSuite with GivenWhenThen with Matchers {
  test("resources include all matched reservations") {
    Given("a resource match with reservations")
    val memReservation = MarathonTestHelper.reservation(principal = "memPrincipal", labels = Map("resource" -> "mem"))
    val portReservation = MarathonTestHelper.reservation(principal = "portPrincipal", labels = Map("resource" -> "ports"))

    val resourceMatch = ResourceMatcher.ResourceMatch(
      scalarMatches = Seq(
        GeneralScalarMatch(
          "mem", 128.0,
          consumed = Seq(GeneralScalarMatch.Consumption(128.0, "role1", reservation = Some(memReservation))),
          scope = ScalarMatchResult.Scope.NoneDisk
        )
      ),
      portsMatch = PortsMatch(Seq(Some(PortsMatcher.PortWithRole("role2", 80, reservation = Some(portReservation)))))
    )

    When("converting it to resources")
    val resources = resourceMatch.resources

    Then("the resources should refer to the reservations")
    resources should equal(
      Seq(
        MarathonTestHelper.scalarResource("mem", 128, "role1", reservation = Some(memReservation)),
        MarathonTestHelper.portsResource(80, 80, "role2", reservation = Some(portReservation))
      )
    )
  }
}
Example 71
Project: functional-structures-refactoring-kata   Author: matteobaglini   File: AppTests.scala View Source Project (license) 5 votes vote downvote up
import App._
import Models._
import org.scalatest.FunSuite

class AppTests extends FunSuite {

  test("happy path") {
    val cartId = CartId("some-gold-cart")
    val storage = new SpyStorage

    applyDiscount(cartId, storage)

    assert(storage.saved.get == Cart(CartId("some-gold-cart"),CustomerId("gold-customer"),50.0) )
  }

  test("no discount") {
    val cartId = CartId("some-normal-cart")
    val storage = new SpyStorage

    applyDiscount(cartId, storage)

    assert(storage.saved.isEmpty)
  }

  test("missing cart") {
    val cartId = CartId("missing-cart")
    val storage = new SpyStorage

    applyDiscount(cartId, storage)

    assert(storage.saved.isEmpty)
  }

  class SpyStorage extends Storage[Cart] {
    var saved: Option[Cart] = None
    override def flush(value: Cart): Unit = saved = Some(value)
  }
}
Example 72
Project: data.ncbitaxonomy   Author: bio4j   File: parseNodes.scala View Source Project (license) 5 votes vote downvote up
package com.bio4j.data.ncbitaxonomy.test

import org.scalatest.FunSuite
import com.bio4j.data.ncbitaxonomy._, dmp._

class ParseNodes extends FunSuite {

  val nodeLines: Seq[String] =
    Seq(
      """318     |       29438   |       no rank |               |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |""",
      """319     |       29438   |       no rank |               |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |""",
      """321     |       317     |       no rank |               |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |""",
      """322     |       47877   |       no rank |               |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |""",
      """323     |       251701  |       no rank |               |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |""",
      """329     |       48736   |       species |       RP      |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |""",
      """330     |       1232139 |       species |       PP      |       0       |       1       |       11      |       1       |       0       |       1       |       1       |       0       |               |"""
    )

  test("parse several nodes") {

    val nodes =
      dmp.nodes.fromLines(nodeLines.toIterator).toSeq

    val firstNode = nodes.head
    val lastNode  = nodes.last

    assert {
      (firstNode.ID === "318"         ) &&
      (firstNode.parentID === "29438" ) &&
      (firstNode.rank === "no rank"   )
    }

    assert {
      (lastNode.ID === "330"           ) &&
      (lastNode.parentID === "1232139" ) &&
      (lastNode.rank === "species"     )
    }
  }
}
Example 73
Project: func-programming-scala-coursera   Author: andrei-l   File: PascalSuite.scala View Source Project (license) 5 votes vote downvote up
package org.coursera.progfun.recfun

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class PascalSuite extends FunSuite {
  import Main.pascal
  test("pascal: col=0,row=2") {
    assert(pascal(0,2) === 1)
  }

  test("pascal: col=1,row=2") {
    assert(pascal(1,2) === 2)
  }

  test("pascal: col=1,row=3") {
    assert(pascal(1,3) === 3)
  }
}
Example 74
Project: functional-programming-principles-scala   Author: filslo   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 75
Project: oanda-scala-api   Author: cnnickolay   File: ApiModelGeneratorUnitTest.scala View Source Project (license) 5 votes vote downvote up
package org.nikosoft.oanda.generator

import org.nikosoft.oanda.generator.ApiModelGeneratorParsers.ParameterTable
import org.scalatest.{FunSuite, Matchers}

class ApiModelGeneratorUnitTest extends FunSuite with Matchers {

  test("generate enumeration") {
    val inputTitle = "TradeState"
    val inputDefinition = "The current state of the Trade."
    val inputParameters = ParameterTable("Value", "Description", Map(
      "OPEN" -> "The Trade is currently open",
      "CLOSED" -> "The Trade has been fully closed",
      "CLOSE_WHEN_TRADEABLE" -> "The Trade will be closed as soon as the trade’s instrument becomes tradeable"
    ))
    val expectedOutput =
      """
         |case class TradeSpecifier(value: String) extends AnyVal""".stripMargin

    val actualOutput = ApiModelGenerator.generateCaseClass(inputTitle, inputDefinition, inputParameters)
    actualOutput shouldBe expectedOutput
  }

}
Example 76
Project: oanda-scala-api   Author: cnnickolay   File: ApiImplUnitTest.scala View Source Project (license) 5 votes vote downvote up
package org.nikosoft.oanda.api.remove

import org.json4s.Formats
import org.json4s.jackson.JsonMethods._
import org.nikosoft.oanda.api.JsonSerializers
import org.nikosoft.oanda.api.`def`.AccountsApi.AccountsResponse
import org.scalatest.FunSuite

class ApiImplUnitTest extends FunSuite {

  implicit val formats: Formats = JsonSerializers.formats

  test("parse account json") {

    val json =
      """{"account":{"id":"001-004-XXXXXXX-003","createdTime":"2017-05-30T07:11:30.656911765Z","currency":"EUR","createdByUserID":1442547,"alias":"MT4","marginRate":"0.02","hedgingEnabled":false,"lastTransactionID":"87","balance":"77.0033","openTradeCount":1,"openPositionCount":1,"pendingOrderCount":2,"pl":"-0.9954","resettablePL":"-0.9954","financing":"-0.0013","commission":"0.0000",
        |"orders":[
        |   {"id":"85","createTime":"2017-06-15T09:08:02.732786641Z","type":"STOP_LOSS","tradeID":"82","clientTradeID":"72179822","price":"1.11000","timeInForce":"GTC","triggerCondition":"DEFAULT","state":"PENDING"},
        |   {"id":"87","createTime":"2017-06-15T09:13:56.368495444Z","replacesOrderID":"84","type":"TAKE_PROFIT","tradeID":"82","clientTradeID":"72179822","price":"1.11850","timeInForce":"GTC","triggerCondition":"DEFAULT","state":"PENDING"}
        |],
        |"positions":[
        |  {"instrument":"EUR_USD",
        |  "long":{"units":"5000","averagePrice":"1.11810","pl":"0.3444","resettablePL":"0.3444","financing":"-0.0024","tradeIDs":["82"],"unrealizedPL":"-2.4386"},
        |  "short":{"units":"0","pl":"-1.3398","resettablePL":"-1.3398","financing":"0.0011","unrealizedPL":"0.0000"},
        |  "pl":"-0.9954","resettablePL":"-0.9954","financing":"-0.0013","commission":"0.0000","unrealizedPL":"-2.4386"}],
        |"trades":[{"id":"82","instrument":"EUR_USD","price":"1.11810","openTime":"2017-06-15T09:07:28.287005040Z","initialUnits":"1000","state":"OPEN","currentUnits":"1000","realizedPL":"0.0000","financing":"0.0000",
        |  "clientExtensions":{"id":"72179822","tag":"0"},"takeProfitOrderID":"87","stopLossOrderID":"85","unrealizedPL":"-2.4386"}],
        |"unrealizedPL":"-2.4386","NAV":"74.5647","marginUsed":"20.0022","marginAvailable":"54.5625","positionValue":"1000.1076","marginCloseoutUnrealizedPL":"-2.3847","marginCloseoutNAV":"74.6186","marginCloseoutMarginUsed":"20.0000","marginCloseoutPositionValue":"1000.0000","marginCloseoutPercent":"0.13401","withdrawalLimit":"54.5625","marginCallMarginUsed":"20.0000","marginCallPercent":"0.26803"},
        |"lastTransactionID":"87"}""".stripMargin

    println(parse(json).children.head.extract[AccountsResponse])
  }

}
Example 77
Project: scalasom   Author: dyamah   File: CellTest.scala View Source Project (license) 5 votes vote downvote up
package com.github.dyamah.scalasom

import org.scalatest.FunSuite


class CellTest extends FunSuite {

  val cell1 = Cell(1, 1, new VectorImpl(List(1, 1, 1)))
  val cell2 = Cell(1, 1, new VectorImpl(List(1, 1, 1)))
  val cell3 = Cell(1, 1, new VectorImpl(List(2, 2, 2)))
  val cell4 = Cell(1, 2, new VectorImpl(List(1, 1, 1)))
  val cell5 = Cell(2, 1, new VectorImpl(List(1, 1, 1)))
  val cell6 = Cell(2, 2, new VectorImpl(List(1, 1, 1)))

  test("testEquals") {
    assert(cell1 == cell2)
    assert(cell1 != cell3)
    assert(cell1 != cell4)
    assert(cell1 != cell5)
    assert(cell1 != cell6)
  }

  test("testDistance") {
    assert(cell1.distance(cell1) == 0)
    assert(cell1.distance(cell2) == 0)
    assert(cell1.distance(cell3) == 0)
    assert(cell1.distance(cell4) == 1)
    assert(cell1.distance(cell5) == 1)
    assert(cell1.distance(cell6) == math.pow(2, 0.5))
  }

}
Example 78
Project: Scala-Machine-Learning   Author: Wei-1   File: DBSCANTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - DBSCAN Test
// 2016-11-10

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.DBSCAN

class DBSCANSuite extends FunSuite {

    val dbscan = new DBSCAN()
    test("DBSCAN Test : Clustering Tiny Data") {
        val result = dbscan.cluster(UNLABELED_TINY_DATA, 2)
        assert(arrayequal(result, LABEL_TINY_DATA))
    }

    test("DBSCAN Test : Clustering Small Data") {
        val result = dbscan.cluster(UNLABELED_SMALL_DATA, 2)
        assert(arrayequal(result, LABEL_SMALL_DATA))
    }

    test("DBSCAN Test : Clustering Large Data") {
        val result = dbscan.cluster(UNLABELED_LARGE_DATA, 3)
        assert(arrayequal(result, LABEL_LARGE_DATA))
    }
}
Example 79
Project: Scala-Machine-Learning   Author: Wei-1   File: LinearSVMTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Linear SVM Test
// 2016-06-03

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.LinearSVM

class LinearSVMSuite extends FunSuite {

    val linearsvm = new LinearSVM()
    test("LinearSVM Test : Initialization") {
        assert(linearsvm.projector.isEmpty)
    }

    test("LinearSVM Test : Linear Train") {
        val cost = Map(-1 -> 1.0, 1 -> 1.0)
        val limit = 1000
        val err = 1e-1
        linearsvm.train(LABELED_LINEAR_DATA, cost, limit, err)
        assert(!linearsvm.projector.isEmpty)
    }

    test("LinearSVM Test : Linear Predict") {
        val result = linearsvm.predict(UNLABELED_LINEAR_DATA)
        assert(arrayequal(result, LABEL_LINEAR_DATA))
    }
    
    test("LinearSVM Test : Clear") {
        linearsvm.clear()
        assert(linearsvm.projector.isEmpty)
    }

    test("LinearSVM Test : Nonlinear Train") {
        val cost = Map(1 -> 1.0, 2 -> 1.0)
        val limit = 1000
        val err = 1e-1
        linearsvm.train(LABELED_NONLINEAR_DATA, cost, limit, err)
        assert(!linearsvm.projector.isEmpty)
    }

    test("LinearSVM Test : Nonlinear Predict - WRONG") {
        val result = linearsvm.predict(UNLABELED_NONLINEAR_DATA)
        assert(!arrayequal(result, LABEL_NONLINEAR_DATA))
    }
}
Example 80
Project: Scala-Machine-Learning   Author: Wei-1   File: GaussianProcessTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Gaussian Process Test
// 2016-11-24

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.GaussianProcess

class GaussianProcessSuite extends FunSuite {

    val gp = new GaussianProcess()
    test("GaussianProcess Test : Initialization") {
        assert(gp.pointGroups.isEmpty)
    }

    test("GaussianProcess Test : Linear Train") {
        gp.train(LABELED_LINEAR_DATA)
        assert(gp.pointGroups.size == 2)
    }
    
    test("GaussianProcess Test : Linear Predict") {
        val result = gp.predict(UNLABELED_LINEAR_DATA, 3)
        assert(arrayequal(result, LABEL_LINEAR_DATA))
    }

    test("GaussianProcess Test : Nonlinear Train") {
        gp.train(LABELED_NONLINEAR_DATA)
        assert(gp.pointGroups.size == 2)
    }
    
    test("GaussianProcess Test : Nonlinear Predict") {
        val result = gp.predict(UNLABELED_NONLINEAR_DATA, 3)
        assert(arrayequal(result, LABEL_NONLINEAR_DATA))
    }
    
    test("GaussianProcess Test : Clear") {
        gp.clear()
        assert(gp.pointGroups.isEmpty)
    }
}
Example 81
Project: Scala-Machine-Learning   Author: Wei-1   File: RandomForestTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Random Forest Test
// 2016-11-29

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.RandomForest

class RandomForestSuite extends FunSuite {

    val rf = new RandomForest()
    test("RandomForest Test : Initialization") {
        assert(rf.trees.isEmpty)
    }

    test("RandomForest Test : Linear Train") {
        rf.train(LABELED_LINEAR_DATA, 5, 4)
        assert(!rf.trees.isEmpty)
    }

    test("RandomForest Test : Linear Predict") {
        val result = rf.predict(UNLABELED_LINEAR_DATA)
        assert(arrayequal(result, LABEL_LINEAR_DATA))
    }

    test("RandomForest Test : Nonlinear Train") {
        rf.train(LABELED_NONLINEAR_DATA, 5, 4)
        assert(!rf.trees.isEmpty)
    }

    test("RandomForest Test : Nonlinear Predict - WRONG") {
        val result = rf.predict(UNLABELED_NONLINEAR_DATA)
        assert(!arrayequal(result, LABEL_NONLINEAR_DATA))
    }
    
    test("RandomForest Test : Clear") {
        rf.clear()
        assert(rf.trees.isEmpty)
    }
}
Example 82
Project: Scala-Machine-Learning   Author: Wei-1   File: LinearRegressionTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Linear Regression Test
// 2016-06-04

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.LinearRegression

class LinearRegressionSuite extends FunSuite {

    val linearregression = new LinearRegression()
    test("LinearRegression Test : Initialization") {
        assert(linearregression.projector.isEmpty)
    }

    test("LinearRegression Test : Linear Train") {
        linearregression.train(LABELED_LINEAR_DATA)
        assert(linearregression.projector(0)._1 == -1)
        assert(linearregression.projector(0)._2 == 1)
    }
    
    test("LinearRegression Test : Linear Predict") {
        val result = linearregression.predict(UNLABELED_LINEAR_DATA)
        assert(arrayequal(result, LABEL_LINEAR_DATA))
    }
    
    test("LinearRegression Test : Clear") {
        linearregression.clear()
        assert(linearregression.projector.isEmpty)
    }

    test("LinearRegression Test : Nonlinear Train") {
        linearregression.train(LABELED_NONLINEAR_DATA)
        assert(linearregression.projector(0)._1 == 1)
        assert(linearregression.projector(0)._2 == 2)
    }
    
    test("LinearRegression Test : Nonlinear Predict - WRONG") {
        val result = linearregression.predict(UNLABELED_NONLINEAR_DATA)
        assert(!arrayequal(result, LABEL_NONLINEAR_DATA))
    }
}
Example 83
Project: Scala-Machine-Learning   Author: Wei-1   File: GeneAlgorithmTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Gene Algorithm Test
// 2017-07-22

import org.scalatest.FunSuite
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.GeneAlgorithm

class GeneAlgorithmSuite extends FunSuite {

    val ga = new GeneAlgorithm()

    val initseeds = Array(Array(0.0), Array(1.0))


    def evaluation(arr: Array[Double]): Double = - (arr.head - 0.7).abs

    def breeding(pa: Array[Double], pb: Array[Double]): Array[Double] =
        pa.zip(pb).map { case (a, b) =>
            if (scala.util.Random.nextDouble > 0.1) (a + b) / 2
            else scala.util.Random.nextDouble
        }

    val generationsize: Int = 100
    val elitesize: Int = 3

    test("GeneAlgorithm Test : Initial") {
        assert(ga.seeds == null)
        ga.setSeeds(initseeds)
        assert(matrixequal(ga.seeds, initseeds))
    }

    test("GeneAlgorithm Test : Evolve") {
        for (i <- 0 until 10)
            ga.evolve(evaluation, breeding, generationsize, elitesize)
        assert(ga.seeds.size == generationsize)

        val best = ga.evolve(evaluation, breeding, generationsize, elitesize)
        assert((best.head - 0.7).abs < 0.05)
    }

}
Example 84
Project: Scala-Machine-Learning   Author: Wei-1   File: QLearningTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Q-Learning Test
// 2017-07-28

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.algorithm.QLearning

class QLearningSuite extends FunSuite {

    val learning_rate = 0.1
    val scale = 1
    val limit = 10000
    val epoch = 100

    val statenumber = 5
    val scores = Map(2 -> 10.0, 3 -> 0.0, 4 -> 100.0)
    val links = Map(0 -> Array(1, 2),
        1 -> Array(3, 4))

    val ql = new QLearning(statenumber)
    ql.addScores(scores)
    ql.addLinks(links)

    test("QLearning Test : Iterate") {
        ql.iterate(limit, learning_rate, scale, epoch)
        assert(true)
    }

    test("QLearning Test : Result") {
        val result = ql.result(epoch)
        assert(result.size == 3)
        assert(result.last.id == 4)
    }
}
Example 85
Project: Scala-Machine-Learning   Author: Wei-1   File: NeuralNetworkTest.scala View Source Project(license) 5 votes vote downvote up
// Wei Chen - Neural Network Test
// 2016-11-06

import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.NeuralNetwork

class NeuralNetworkSuite extends FunSuite {

    val layer_neurons = Array(5, 4)
    val input_column = UNLABELED_LARGE_HIGH_DIM_DATA.head.size
    val output_column = TARGET_LARGE_HIGH_DIM_DATA.head.size
    val limit = 1000

    val nn = new NeuralNetwork(layer_neurons, input_column, output_column)
    test("NeuralNetwork Test : Initialization") {
        assert(nn.syns(0).size == input_column)
        assert(nn.syns(layer_neurons.size).head.size == output_column)
    }

    test("NeuralNetwork Test : Train") {
        nn.train(UNLABELED_LARGE_HIGH_DIM_DATA, TARGET_LARGE_HIGH_DIM_DATA, limit)
        assert(!nn.syns.isEmpty)
    }

    test("NeuralNetwork Test : Predict") {
        val result = nn.predict(UNLABELED_SMALL_HIGH_DIM_DATA)
        assert(matrixsimilar(result, TARGET_SMALL_HIGH_DIM_DATA, 0.2))
    }
}
Example 86
Project: reactiveinflux   Author: pygmalios   File: ExampleApplication.scala View Source Project(license) 5 votes vote downvote up
package com.example

import java.net.URI

import com.pygmalios.reactiveinflux.ReactiveInfluxDbName
import com.pygmalios.reactiveinflux.command.query.BaseQueryCommand
import com.pygmalios.reactiveinflux.itest.ITestConfig
import com.pygmalios.reactiveinflux.response.EmptyJsonResponse
import com.pygmalios.reactiveinflux.{ReactiveInflux, ReactiveInfluxCore}
import org.scalatest.FunSuite
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import play.api.libs.ws.{WSClient, WSResponse}

class ExampleApplication extends FunSuite with ScalaFutures with IntegrationPatience {
  test("Execute custom command") {
    val reactiveInflux = ReactiveInflux(config = Some(ITestConfig.config))
    try {
      implicit val dbName = ReactiveInfluxDbName("ExampleApplicatixon")
      val db = reactiveInflux.database
      try {
        val core = reactiveInflux.asInstanceOf[ReactiveInfluxCore]
        whenReady(core.execute(new CustomQueryCommand(core.config.url)).failed) { ex =>
        }
      }
      finally {
        db.drop()
      }
    }
    finally {
      reactiveInflux.close()
    }
  }
}

class CustomQueryCommand(baseUri: URI) extends BaseQueryCommand(baseUri) {
  override type TResult = Unit
  override protected def responseFactory(wsResponse: WSResponse) =  new CustomQueryCommandResponse(wsResponse)
  override def httpRequest(ws: WSClient) = ws.url(qUri("WHATEVER").toString)
}

class CustomQueryCommandResponse(wsResponse: WSResponse) extends EmptyJsonResponse(wsResponse)
Example 87
Project: functional-programming-scala   Author: borgees   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfun

import org.scalatest.FunSuite


import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {
  import Main.countChange
  test("countChange: example given in instructions") {
    assert(countChange(4,List(1,2)) === 3)
  }

  test("countChange: sorted CHF") {
    assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022)
  }

  test("countChange: no pennies") {
    assert(countChange(301,List(5,10,20,50,100,200,500)) === 0)
  }

  test("countChange: unsorted CHF") {
    assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022)
  }

}
Example 88
Project: backprop   Author: andrisak   File: NetworkTest.scala View Source Project (license) 5 votes vote downvote up
package se.andrisak.backprop.algo

import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}

import scala.util.Random


class NetworkTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val RANDOM_VALUE = 0.2
  val INPUT_LAYER_NEURON_COUNT = 1
  val HIDDEN_LAYER_NEURON_COUNT = 1
  val INPUT = 0.528593

  val random = mock[Random]
  when(random.nextDouble()).thenReturn(RANDOM_VALUE)

  test("test that clearInput clears all node input") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
    network.getInputLayer.neurons.head.addInput(0.534543)
    network.getHiddenLayer.neurons.head.addInput(0.6854543)
    network.clearInputs()

    network.getInputLayer.neurons.head.getInput should equal(0.0)
    network.getHiddenLayer.neurons.head.getInput should equal(0.0)
  }

  test("init of input layer should add the input to input neurons") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
    network.initInputLayer(List(INPUT))

    network.getInputLayer.neurons.head.getInput should equal(INPUT)
  }

  test("adding more input values than input neurons should throw an exception") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)

    intercept[IllegalArgumentException] {
      network.initInputLayer(List(INPUT, INPUT))
    }
  }
}
Example 89
Project: backprop   Author: andrisak   File: NeuronTest.scala View Source Project (license) 5 votes vote downvote up
package se.andrisak.backprop.algo

import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}

import scala.util.Random


class NeuronTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val NEURON_NAME = "neuron"
  val NEURON_NAME2 = "neuron2"
  val RANDOM_VALUE = 0.53
  val random = mock[Random]
  when(random.nextDouble()).thenReturn(RANDOM_VALUE)
  val neuron = new Neuron(NEURON_NAME, random)

  test("input should be stored and be cleared") {
    val input = 0.543
    neuron.addInput(input)

    neuron.getInput should equal (input)
    neuron.clearInput()
    neuron.getInput should equal (0)
  }

  test("neurons should be connected with a ForwardLink") {
    val neuron2 = new Neuron(NEURON_NAME2, random)

    neuron.connectToNeuronsInLayer(List(neuron2))

    val link = neuron.getLinkTo(neuron2)
    link.to should equal(neuron2)
    link.weight should equal(RANDOM_VALUE)
    link should equal(neuron.getNextLayerLinks.head)
  }

  test("neurons should be connected with a ReverseLink") {
    val neuron2 = new Neuron(NEURON_NAME2, random)

    neuron.connectToNeuronsInPreviousLayer(List(neuron2))

    neuron.getPreviousLayerNeurons.head should equal(neuron2)
  }

  test("test the sigmoid computation") {
    neuron.output should equal(0.5)
  }

}
Example 90
Project: backprop   Author: andrisak   File: BackPropagationAlgoTest.scala View Source Project(license) 5 votes vote downvote up
package se.andrisak.backprop.algo

import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}
import se.andrisak.backprop.rest.model.ClassificationRequest.TrainingDataItem

import scala.util.Random


class BackPropagationAlgoTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val ITERATIONS = 1
  val TRAINING_DATA_FIRST_INPUT: Double = 1.0
  val TRAINING_DATA_SECOND_INPUT: Double = 1.0
  val TARGET: Double = 1.0
  val RANDOM = 0.5
  val EXPECTED_OUTPUT = 0.9439400108508628
  var trainingData: TrainingDataItem = null

  override protected def beforeEach(): Unit = {
    trainingData = TrainingDataItem(TRAINING_DATA_FIRST_INPUT, TRAINING_DATA_SECOND_INPUT, TARGET)
  }

  test("test classify") {
    val random = mock[Random]
    when(random.nextDouble()).thenReturn(RANDOM)
    val bp = new BackPropagationAlgo(random)

    val output = bp.classify(ITERATIONS, Seq(trainingData), List(1.0, 1.0))

    output should equal(EXPECTED_OUTPUT)
  }

}
Example 91
Project: train-stamp-rally   Author: ponkotuy   File: TrainTimeSuite.scala View Source Project (license) 5 votes vote downvote up
package utils

import org.scalatest.FunSuite

class TrainTimeSuite extends FunSuite {
  test("TrainTime.addMinutes") {
    assert(TrainTime(6, 1).addMinutes(15) === TrainTime(6, 16))
    assert(TrainTime(6, 23).addMinutes(-10) === TrainTime(6, 13))
  }

  test("TrainTime.addMinutes if carry") {
    assert(TrainTime(6, 59).addMinutes(3) === TrainTime(7, 2))
    assert(TrainTime(7, 3).addMinutes(-5) === TrainTime(6, 58))
  }

  test("TrainTime.addMinutes if over hour") {
    assert(TrainTime(23, 44).addMinutes(25) === TrainTime(0, 9))
    assert(TrainTime(0, 15).addMinutes(-18) === TrainTime(23, 57))
  }
}
Example 92
Project: scala_test   Author: oops   File: ComplexProperties.scala View Source Project (license) 5 votes vote downvote up
// src/main/scala/progscala2/toolslibs/toolslibs/ComplexProperties.scala
package progscala2.toolslibs
import org.scalatest.FunSuite
import org.scalatest.prop.PropertyChecks

class ComplexProperties extends FunSuite with PropertyChecks {

  def additionTest(a: Complex, b: Complex) = {
    assert( (a + b).real === (a.real + b.real) )
    assert( (a + b).imaginary === (a.imaginary + b.imaginary) )
  }

  def subtractionTest(a: Complex, b: Complex) = {
    assert( (a - b).real === (a.real - b.real) )
    assert( (a - b).imaginary === (a.imaginary - b.imaginary) )
  }

  val zero = Complex(0.0, 0.0)

  test ("Complex addition with the identity element (zero)") {
    forAll { (real: Double, imag: Double) =>
      val c = Complex(real, imag)
      additionTest(zero, c)
      additionTest(c, zero)
    }
  }

  test ("Complex subtraction with the identity element (zero)") {
    forAll { (real: Double, imag: Double) =>
      val c = Complex(real, imag)
      subtractionTest(zero, c)
      subtractionTest(c, zero)
    }
  }

  test ("Complex addition with two values") {
    forAll { (real1: Double, imag1: Double, real2: Double, imag2: Double) =>
      val c1 = Complex(real1, imag1)
      val c2 = Complex(real2, imag2)
      additionTest(c1, c2)
    }
  }

  test ("Complex subtraction with two values") {
    forAll { (real1: Double, imag1: Double, real2: Double, imag2: Double) =>
      val c1 = Complex(real1, imag1)
      val c2 = Complex(real2, imag2)
      subtractionTest(c1, c2)
    }
  }
}
Example 93
Project: scala_test   Author: oops   File: ComplexSuite.scala View Source Project (license) 5 votes vote downvote up
// src/test/scala/progscala2/toolslibs/ComplexSuite.scala
package progscala2.toolslibs
import org.scalatest.FunSuite

class ComplexSuite extends FunSuite {

  val c1 = Complex(1.2, 3.4)
  val c2 = Complex(5.6, 7.8)

  test("addition with (0, 0)") {
    assert(c1 + Complex(0.0, 0.0) === c1)
  }

  test("subtraction with (0, 0)") {
    assert(c1 - Complex(0.0, 0.0) === c1)
  }

  test("addition") {
    assert((c1 + c2).real === (c1.real + c2.real))
    assert((c1 + c2).imaginary === (c1.imaginary + c2.imaginary))
  }

  test("subtraction") {
    assert((c1 - c2).real === (c1.real - c2.real))
    assert((c1 - c2).imaginary ===  (c1.imaginary - c2.imaginary))
  }
}
Example 94
Project: Scala-and-Spark-for-Big-Data-Analytics   Author: PacktPublishing   File: TransformationTestWithSparkTestingBase.scala View Source Project (license) 5 votes vote downvote up
package com.chapter16.SparkTesting

import org.scalatest.Assertions._
import org.apache.spark.rdd.RDD
import com.holdenkarau.spark.testing.SharedSparkContext
import org.scalatest.FunSuite

class TransformationTestWithSparkTestingBase extends FunSuite with SharedSparkContext {
  def tokenize(line: RDD[String]) = {
    line.map(x => x.split(' ')).collect()
  }

  test("works, obviously!") {
    assert(1 == 1)
  }

  test("Words counting") {
    assert(sc.parallelize("Hello world My name is Reza".split("\W")).map(_ + 1).count == 6)
  }

  test("Testing RDD transformations using a shared Spark Context") {
    val input = List("Testing", "RDD transformations", "using a shared", "Spark Context")
    val expected = Array(Array("Testing"), Array("RDD", "transformations"), Array("using", "a", "shared"), Array("Spark", "Context"))
    val transformed = tokenize(sc.parallelize(input))
    assert(transformed === expected)
  }
}
Example 95
Project: practical-logic-handbook   Author: inpefess   File: TokenTypeTest.scala View Source Project(license) 5 votes vote downvote up
package chapter1

import org.scalatest.FunSuite

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

class TokenTypeTest extends FunSuite {
  test("testCharType") {
    assert(TokenType.charType('+') == TokenType.Symbolic)
    assert(TokenType.charType('1') == TokenType.Numeric)
    assert(TokenType.charType('A') == TokenType.Alphanumeric)
    assert(TokenType.charType(' ') == TokenType.Space)
    assert(TokenType.charType(',') == TokenType.Punctuation)
    // this character is Cyrillic
    Try(TokenType.charType('?')) match {
      case Success(_) => fail()
      case Failure(e) => assert(e.getMessage == "Unknown character: ?")
    }
  }
}
Example 96
Project: practical-logic-handbook   Author: inpefess   File: LexerTest.scala View Source Project (license) 5 votes vote downvote up
package chapter1

import org.scalatest.{BeforeAndAfter, FunSuite}

class LexerTest extends FunSuite with BeforeAndAfter {
  test("tokenize simple math") {
    assert(
      Lexer.toTokens("2*((var_1 + x’) + 11) ") ==
      Vector("2", "*", "(", "(", "var_1", "+", "x’", ")", "+", "11", ")")
    )
  }
  test("tokenize C++ like code") {
    assert(
      Lexer.toTokens("if (*p1-- == *p2++) then f() else g()") ==
        Vector("if", "(", "*", "p1", "--", "==", "*", "p2", "++", ")", "then", "f", "(", ")", "else", "g", "(", ")")
    )
  }
  test("empty line - no terms") {
    assert(Lexer.toTokens("") == Vector())
  }
}
Example 97
Project: practical-logic-handbook   Author: inpefess   File: PropositionalFormulaTest.scala View Source Project (license) 5 votes vote downvote up
package chapter2

import org.scalatest.FunSuite

class PropositionalFormulaTest extends FunSuite {
  test("someImportantTautologies") {
    val p = Atom("p")
    val q = Atom("q")
    val r = Atom("r")
    assert(Iff(Not(True), False).isTautology)
    assert(Iff(Not(False), True).isTautology)
    assert(Iff(Not(Not(p)), p).isTautology)
    assert(Iff(And(p, False), False).isTautology)
    assert(Iff(And(p, True), p).isTautology)
    assert(Iff(And(p, p), p).isTautology)
    assert(Iff(And(p, Not(p)), False).isTautology)
    assert(Iff(And(p, q), And(q, p)).isTautology)
    assert(Iff(And(And(p, q), r), And(p, And(q, r))).isTautology)
    assert(Iff(Or(p, False), p).isTautology)
    assert(Iff(Or(p, True), True).isTautology)
    assert(Iff(Or(p, p), p).isTautology)
    assert(Iff(Or(p, Not(p)), True).isTautology)
    assert(Iff(Or(p, q), Or(q, p)).isTautology)
    assert(Iff(Or(Or(p, q), r), Or(p, Or(q, r))).isTautology)
    assert(Iff(And(p, Or(q, r)), Or(And(p, q), And(p, r))).isTautology)
    assert(Iff(Or(p, And(q, r)), And(Or(p, q), Or(p, r))).isTautology)
    assert(Iff(Imp(False, p), True).isTautology)
    assert(Iff(Imp(p, True), True).isTautology)
    assert(Iff(Imp(p, False), Not(p)).isTautology)
    assert(Iff(Imp(p, p), True).isTautology)
    assert(Iff(Imp(p, q), Imp(Not(q), Not(p))).isTautology)
    assert(Iff(Imp(p, q), Iff(p, And(p, q))).isTautology)assert(Iff(Imp(p, q),Iff(q,Or(q, p))).isTautology)assert(Iff(Iff(p, q),Iff(q, p)).isTautology)assert(Iff(Iff(Iff(p, q), r),Iff(p,Iff(q, r))).isTautology)}}
Example 98
Project: reactive.queue.router   Author: objektwerks   File: QueueRouterTest.scala View Source Project(license) 5 votes vote downvote up
package reactive.queue.router

import com.typesafe.config.ConfigFactory
import io.scalac.amqp.Connection
import org.scalatest.{BeforeAndAfterAll, FunSuite}

import scala.concurrent.Await
import scala.concurrent.duration._

class QueueRouterTest extends FunSuite with BeforeAndAfterAll with QueueRouterSubscriber {
  implicit val ec = system.dispatcher

  override protected def beforeAll(): Unit = {
    server map { binding =>
      val connection = Connection(ConfigFactory.load("test.reactive.queue.conf"))
      val subscription = QueueSubscription("test.reactive.queue", s"http://127.0.0.1:${binding.localAddress.getPort}/message")
      val prefetch = 10
      system.actorOf(QueueRouter.props(connection, subscription, prefetch), name = "queue-router")
    }
  }

  override protected def afterAll(): Unit = {
    server map { binding =>
      binding.unbind.onComplete { _ =>
        Await.result(system.terminate(), 1 second)
      }
    }
  }

  test("router conf") {
    import net.ceedubs.ficus.Ficus._
    import net.ceedubs.ficus.readers.ArbitraryTypeReader._

    val conf = ConfigFactory.load("test.queue.router.conf").as[QueueRouterConf]("router")
    assert(conf.queueSubscriptions.nonEmpty)
  }

  test("router") {
    val count = 10
    QueueLoader.load(source = "/test.json", total = count)
    while (counter.intValue != count) {
      Thread.sleep(500)
    }
    assert(counter.intValue == count)
  }
}
Example 99
Project: typelevel   Author: objektwerks   File: ShowTest.scala View Source Project (license) 5 votes vote downvote up
package objektwerks.cats

import org.scalatest.{FunSuite, Matchers}

case class Actor(name: String)

object Actor {
  import cats.Show
  implicit val actorShow: Show[Actor] = Show.show[Actor](_.name)
}

class ShowTest extends FunSuite with Matchers {
  test("instances") {
    import cats.Show
    import cats.instances.int._
    
    val showInt = Show[Int]
    showInt.show(1) shouldEqual "1"
  }
  
  test("syntax") {
    import cats.instances.int._
    import cats.syntax.show._
    
    1.show shouldEqual "1"
  }
  
  test("custom") {
    import cats.syntax.show._
    
    val actor = Actor("Fred Flintstone")
    actor.show shouldEqual "Fred Flintstone"
  }
}
Example 100
Project: spark-netsuite   Author: springml   File: TestCSVUtil.scala View Source Project (license) 4 votes vote downvote up
package com.springml.spark.netsuite.util

import org.scalatest.{BeforeAndAfterEach, FunSuite}
import org.scalatest.mock.MockitoSugar


class TestCSVUtil extends FunSuite with MockitoSugar with BeforeAndAfterEach {
  test("Successfully reading CSV file") {
    val csvURL= getClass.getResource("/xpath.csv")
    val csvContent = CSVUtil.readCSV(csvURL.getPath)
    assert(csvContent.size == 6)
    assert(csvContent("Id").equals("string(/platformCore:record/@internalId)"))
    assert(csvContent("Entity").equals("/platformCore:record/listRel:entityId/text()"))
    assert(csvContent("Status").equals("/platformCore:record/listRel:entityStatus[@internalId="13"]/platformCore:name/text()"))
  }
}

https://www.programcreek.com/scala/org.scalatest.FunSuite

原文地址:https://www.cnblogs.com/pekkle/p/10150400.html