scala test有多种方式,可参见:http://www.scalatest.org

对于我个人而言,比较偏爱FunSuite,参考文章:

http://www.scalatest.org/getting_started_with_fun_suite

http://doc.scalatest.org/3.0.1/#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 downvote up
package utilsimport org.scalatest.FunSuiteclass 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: BigDataMaker   Author: dondrake   File: TestBigDataMaker.scala View Source Project (license) 6 votes vote downvote up
package com.drakeconsulting.big_data_makerimport org.scalatest.FunSuite
import com.holdenkarau.spark.testing.SharedSparkContext
import org.apache.spark.sql.SQLContextclass 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._createDataFramedf.showassert(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 3

Project: scala-dom   Author: rrramiro   File: MappedNamespaceContextTest.scala View Source Project(license) 5 votes vote downvote up
package fr.ramiro.scala.domimport javax.xml.XMLConstantsimport org.scalatest.FunSuiteimport scala.collection.JavaConverters.asScalaIteratorConverterclass 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 4

Project: Functional-Programming-in-Scala   Author: vincenzobaz   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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 5

Project: Earlgrey   Author: PatrickHuang888   File: RepositoryTest.scala View Source Project (license) 5 votes vote downvote up
package com.hxm.earlgrey.jobsimport org.scalatest.{BeforeAndAfter, FunSuite}
import org.mongodb.scala.Documentclass 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 6

Project: hwork   Author: Masebeni   File: PositionPackageTest.scala View Source Project (license) 5 votes vote downvote up
package factories.positionimport domain.position.PositionPackage
import org.joda.time.DateTime
import org.scalatest.FunSuiteclass 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 7

Project: hwork   Author: Masebeni   File: PositionTest.scala View Source Project (license) 5 votes vote downvote up
package factories.positionimport domain.position.Position
import org.joda.time.DateTime
import org.scalatest.FunSuiteclass PositionTest extends FunSuite{test("testCreatePosition")Pval 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 8

Project: sqs-kafka-connect   Author: ConnectedHomes   File: SQSSourceConnectorSuite.scala View Source Project (license) 5 votes vote downvote up
package com.hivehome.kafka.connect.sqsimport 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").asJavatest("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 = 10val taskConfigs = connector.taskConfigs(maxTasks).asScalataskConfigs should have size maxTaskstaskConfigs foreach { taskConfig =>taskConfig shouldEqual props}}
} 

Example 9

Project: sqs-kafka-connect   Author: ConnectedHomes   File: ConfSuite.scala View Source Project(license) 5 votes vote downvote up
package com.hivehome.kafka.connect.sqsimport 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 ++ optionalPropstest("should parse all configurations from a map") {val tryConf = Conf.parse(allProps)val conf = tryConf.success.valueconf.queueName.value shouldEqual "in"conf.topicName.value shouldEqual "out"conf.awsRegion shouldEqual UsEastconf.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.valueconf.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 10

Project: sqs-kafka-connect   Author: ConnectedHomes   File: E2ESpec.scala View Source Project(license) 5 votes vote downvote up
package com.hivehome.kafka.connect.sqsimport java.time.Instantimport org.scalatest.{FunSuite, Matchers}
import org.slf4j.LoggerFactoryimport scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Futureclass 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 SQSqueueUrl = sqs.getQueueUrl(queueName).getQueueUrlprivate 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 servicesignore("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 topicThread.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 11

Project: progfun_assignments   Author: letalvoj   File: HuffmanSuite.scala View Source Project (license) 5 votes vote downvote up
package patmatimport 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.frenchCodedecode(fc, encode(fc)("letsmakeitmorecomplicated".toList)) should be("letsmakeitmorecomplicated".toList)}} 

Example 12

Project: progfun_assignments   Author: letalvoj   File: PascalSuite.scala View Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class PascalSuite extends FunSuite {import Week1.pascaltest("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 13

Project: progfun_assignments   Author: letalvoj   File: BalanceSuite.scala View Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class BalanceSuite extends FunSuite {import Week1.balancetest("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).\n(But he wasn't listening)".toList))}test("balance: ':-)' is unbalanced") {assert(!balance(":-)".toList))}test("balance: counting is not enough") {assert(!balance("())(".toList))}
} 

Example 14

Project: progfun_assignments   Author: letalvoj   File: CountChangeSuite.scala View Source Project(license) 5 votes vote downvote up
package recfunimport 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.countChangetest("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 15

Project: scala-course-one   Author: mumukiller   File: PascalSuite.scala View Source Project (license) 5 votes vote downvote up
package functionsimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class PascalSuite extends FunSuite {import Main.pascaltest("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 16

Project: scalajs-frogger   Author: wjsrobertson   File: TiledLayerTest.scala View Source Project (license) 5 votes vote downvote up
package net.xylophones.froggerimport 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.rectanglesrects.size shouldBe 2rects.head.x shouldBe 0rects.head.y shouldBe 0rects.last.x shouldBe 10rects.last.y shouldBe 0}
} 

Example 17

Project: markovMovieCritic   Author: tammosminia   File: TokensTest.scala View Source Project(license) 5 votes vote downvote up
package markovimport 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.\n Second line.\n") === 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 18

Project: ToSidewalk   Author: kotarohara   File: StreetNodeTableTest.scala View Source Project (license) 5 votes vote downvote up
package tosidewalk.modelimport 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.TableQueryclass 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 19

Project: scalatour   Author: bobxwang   File: ConfigTest.scala View Source Project (license) 5 votes vote downvote up
package com.bob.scalatour.configsimport com.typesafe.config._
import org.scalatest.FunSuiteclass 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 20

Project: scalatour   Author: bobxwang   File: AsyncTest.scala View Source Project (license) 5 votes vote downvote up
package com.bob.scalatour.futuresimport org.scalatest.FunSuiteimport scala.async.Async._import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}class AsyncTest extends FunSuite {implicit val ec = ExecutionContext.globaltest("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 21

Project: graphic-calculator   Author: typeness   File: LexerTest.scala View Source Project (license) 5 votes vote downvote up
package io.github.typeness.graphiccalculatorimport org.scalatest.FunSuiteclass 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 22

Project: coursera   Author: syhan   File: VisualizationTest.scala View Source Project (license) 5 votes vote downvote up
package observatoryimport 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 23

Project: coursera   Author: syhan   File: ExtractionTest.scala View Source Project (license) 5 votes vote downvote up
package observatoryimport 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 24

Project: coursera   Author: syhan   File: StackOverflowSuite.scala View Source Project (license) 5 votes vote downvote up
package stackoverflowimport 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 = 50000override def kmeansKernels = 45override def kmeansEta: Double = 20.0Doverride def kmeansMaxIterations = 120}test("testObject can be instantiated") {val instantiatable = try {testObjecttrue} catch {case _: Throwable => false}assert(instantiatable, "Can't instantiate a StackOverflow object")}} 

Example 25

Project: EnterpriseStreamingBenchmark   Author: BenReissaus   File: Statistics$Test.scala View Source Project (license) 5 votes vote downvote up
package org.hpi.esb.flink.utilsimport 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 26

Project: EnterpriseStreamingBenchmark   Author: BenReissaus   File: TopicManagementTest.scalaView Source Project (license) 5 votes vote downvote up
package org.hpi.esb.utilimport org.scalatest.FunSuite
import org.scalatest.mockito.MockitoSugarimport scala.collection.mutableclass 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 ++ topicsToKeepval prefix =  "ESB_"assert(allTopics.containsSlice(topicsToDelete))assert(allTopics.containsSlice(topicsToKeep))assert(allTopics.size == topicsToDelete.size + topicsToKeep.size)assert(TopicManagement.getMatchingTopics(allTopics, prefix) == topicsToDelete)}
} 

Example 27

Project: ScalaJSWithXML   Author: sonumehrotra   File: ApplicationTest.scala View Source Project(license) 5 votes vote downvote up
import controllers.Application
import org.scalatest.FunSuiteclass ApplicationTest extends FunSuite {val testObject = new Applicationtest("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.findProjectPathsFromConfigassert(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 28

Project: SANSA-OWL   Author: SANSA-Stack   File: FunctionalSyntaxOWLExpressionsRDDBuilderTest.scala View Source Project (license) 5 votes vote downvote up
package net.sansa_stack.owl.spark.rddimport com.holdenkarau.spark.testing.SharedSparkContext
import org.scalatest.FunSuiteclass FunctionalSyntaxOWLExpressionsRDDBuilderTest extends FunSuite with SharedSparkContext {var _rdd: OWLExpressionsRDD = nulldef 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 29

Project: openhub-source-search-engine   Author: mendozagabe1618   File: ParseTest.scala View Source Project (license) 5 votes vote downvote up
package cloud.hw.utilimport org.scalatest.FunSuiteclass 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 30

Project: coursera-parprog1   Author: federicobozzini   File: ParallelParenthesesBalancingSuite.scalaView Source Project (license) 5 votes vote downvote up
package reductionsimport 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 31

Project: high-performance-spark   Author: gourimahapatra   File: DStreamSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.streamingimport org.apache.spark.streaming._import java.lang.Thread
import com.holdenkarau.spark.testing._import org.scalatest.FunSuiteclass 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 hereThread.sleep(100)ssc.stop()}
} 

Example 32

Project: high-performance-spark   Author: gourimahapatra   File: NativeExample.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.ffiimport 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 FunSuitewith 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 = 6assert(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 33

Project: high-performance-spark   Author: gourimahapatra   File: FilterInvalidPandasSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.toolsimport com.highperformancespark.examples.dataframe.RawPandaimport com.holdenkarau.spark.testing._import org.scalatest.FunSuiteclass 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 34

Project: high-performance-spark   Author: gourimahapatra   File: GenerateScalingDataSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.toolsimport com.highperformancespark.examples.dataframe.RawPandaimport com.holdenkarau.spark.testing._import org.scalatest.FunSuiteclass 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 35

Project: high-performance-spark   Author: gourimahapatra   File: GoldilocksMLlibSuite.scala View Source Project (license) 5 votes vote downvote up
package com.highperformancespark.examples.mllibimport com.highperformancespark.examples.dataframe.RawPandaimport com.holdenkarau.spark.testing._import org.scalatest.FunSuiteimport 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 36

Project: parprog   Author: TraitRDS   File: ParallelParenthesesBalancingSuite.scala View Source Project(license) 5 votes vote downvote up
package reductionsimport 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 37

Project: my-scala-playground   Author: rysh   File: MyS3ObjectTest.scala View Source Project (license) 5 votes vote downvote up
package exampleimport 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 38

Project: coursera-scala   Author: tklo   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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 39

Project: newts   Author: julien-truffaut   File: NewtsSuite.scala View Source Project (license) 5 votes vote downvote up
package newtsimport 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.Disciplinetrait NewtsSuite extends FunSuitewith Matcherswith GeneratorDrivenPropertyCheckswith Disciplinewith AllSyntaxwith AllInstanceswith cats.syntax.AllSyntaxwith ArbitraryInstancestrait 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]implicit def multCogen[A: Cogen]: Cogen[Mult[A]] = cogenNewtype[Mult[A], A]implicit def dualCogen[A: Cogen]: Cogen[Dual[A]] = cogenNewtype[Dual[A], A]implicit def firstCogen[A: Cogen]: Cogen[First[A]] = cogenNewtype[First[A], A]implicit def lastCogen[A: Cogen]: Cogen[Last[A]] = cogenNewtype[Last[A], A]implicit def firstOptionCogen[A: Cogen]: Cogen[FirstOption[A]] = cogenNewtype[FirstOption[A], Option[A]]implicit def lastOptionCogen[A: Cogen] : Cogen[LastOption[A]]  = cogenNewtype[LastOption[A], Option[A]]implicit def minOptionCogen[A: Cogen] : Cogen[Min[A]]  = cogenNewtype[Min[A], A]implicit def maxOptionCogen[A: Cogen] : Cogen[Max[A]]  = cogenNewtype[Max[A], A]implicit def zipListCogen[A: Cogen]: Cogen[ZipList[A]] = cogenNewtype[ZipList[A], List[A]]
} 

Example 40

Project: bittorrent   Author: zpooky   File: TorrentFileManager_LargeFile.scala View Source Project(license) 5 votes vote downvote up
package com.spooky.bittorrent.l.fileimport org.scalatest.FunSuite
import java.io.File
import com.spooky.bittorrent.metainfo.Torrents
import java.nio.file.Pathsclass 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 41

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

Example 42

Project: bittorrent   Author: zpooky   File: MonadTest.scala View Source Project (license) 5 votes vote downvote up
package com.spooky.bittorrentimport org.scalatest.FunSuiteclass MonadTest extends FunSuite {implicit def toOption[T](any: T): Option[T] = Option(any)var c = 0def 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 xprintln(xsss)}} 

Example 43

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

Example 44

Project: bittorrent   Author: zpooky   File: RequestTest.scala View Source Project (license) 5 votes vote downvote up
package com.spookyimport org.scalatest.FunSuite
import com.spooky.DHT.PingQuery
import com.spooky.bittorrent.InfoHash
import com.spooky.bencode.BencodeMarshallclass RequestTest extends FunSuite {//{"t":"aa", "y":"q", "q":"ping", "a":{"id":"abcdefghij0123456789"}}val m = new BencodeMarshalltest("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 45

Project: coursera-funprog-scala-recursion-assignment   Author: jdehlinger   File: CountChangeSuite.scalaView Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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 46

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.PropertyChecksclass 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 47

Project: sourceCode   Author: RominYue   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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 48

Project: CodeJam   Author: javathought   File: PancakeTest.scala View Source Project (license) 5 votes vote downvote up
package puzzle2016.qimport 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 49

Project: Parallelism-and-Concurrency-Assignments   Author: vincenzobaz   File: BoundedBufferSuite.scala View Source Project (license) 5 votes vote downvote up
package pubsubimport scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.collection.mutable.HashMapimport org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunnerimport 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 50

Project: Parallelism-and-Concurrency-Assignments   Author: vincenzobaz   File: StackOverflowSuite.scalaView Source Project (license) 5 votes vote downvote up
package stackoverflowimport 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 = 50000override def kmeansKernels = 45override def kmeansEta: Double = 20.0Doverride def kmeansMaxIterations = 120}test("testObject can be instantiated") {val instantiatable = try {testObjecttrue} catch {case _: Throwable => false}assert(instantiatable, "Can't instantiate a StackOverflow object")}} 

Example 51

Project: CakePatternPractise   Author: johnnyqian   File: UserServiceSuite.scala View Source Project(license) 5 votes vote downvote up
package CakePatternimport org.scalatest.FunSuite
import org.specs2.mock.Mockitoclass 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 usertest("testAuthenticate") {assert(userRepository.authenticate(user) == user)}
} 

Example 52

Project: vo-ss-extractor   Author: oginskis   File: FlatRepoTest.scala View Source Project (license) 5 votes vote downvote up
package org.oginskis.ss.repoimport 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 53

Project: pacttests   Author: PawelWlodarski   File: FirstPactExample.scala View Source Project (license) 5 votes vote downvote up
package com.wlodar.pactexample.firstimport com.wlodar.jug.pacttest.client.ServiceClient
import org.scalatest.{FunSpec, FunSuite, Matchers}import scalaj.http.HttpResponseclass 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? kodval result: HttpResponse[String] =ServiceClient.call(config.baseUrl,"apiUslugi")result.code shouldBe 200result.body shouldBe "Pact dzia?a!!!"
//      result.body shouldBe "B??d"}}} 

Example 54

Project: scala_specialization_coursera   Author: alvsanand   File: LineOfSightSuite.scala View Source Project (license) 5 votes vote downvote up
package reductionsimport 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 55

Project: scala_specialization_coursera   Author: alvsanand   File: CountChangeSuite.scala View Source Project (license) 5 votes vote downvote up
package recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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 56

Project: BigDataMaker   Author: dondrake   File: TestColumns.scala View Source Project (license) 5 votes vote downvote up
package com.drakeconsulting.big_data_makerimport 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 = 100test("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 57

Project: Courses   Author: zearom32   File: SimulationSuite.scala View Source Project (license) 5 votes vote downvote up
package practiceimport 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 Parametersimport sim._test("a simple test"){val in1, in2, sum, carry = new Wireprobe("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 Wireprobe("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_strategiesimport 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 recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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.robertdodierimport 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.0assert (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.opsimport 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.sequencee 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.sequencee should be(Left("BOOM"))}test("right biased map / flatMap"){val res1 = for {a <- 1.rightb <- "BOOM".left[Int]} yield a + bres1 should be(Left("BOOM"))val res2 = for{a <- 1.rightb <- 2.right} yield a + bres2 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.opsimport 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.fsimport 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.testimport org.scalatest.FunSuite
import org.wartremover.contrib.warts.UnsafeInheritance
import org.wartremover.test.WartTestTraverserclass 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(): Unitprivate 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.testimport org.scalatest.FunSuite
import org.wartremover.contrib.warts.SomeApply
import org.wartremover.test.WartTestTraverserclass 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 = 1Some(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.nettyimport 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.stateimport mesosphere.marathon.core.readiness.ReadinessCheckTestHelper
import org.scalatest.{ GivenWhenThen, Matchers, FunSuite }
import mesosphere.marathon.Protosclass ReadinessCheckSerializerTest extends FunSuite with Matchers with GivenWhenThen {test("get defaultHttp for empty protobuf") {Given("an empty protobuf")val proto = Protos.ReadinessCheckDefinition.getDefaultInstanceWhen("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.defaultHttpWhen("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.alternativeHttpsWhen("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.instanceimport 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".toPathval 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".toPathval 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".toPathval 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".toPathval 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".toPathval 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.tasksimport 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".toPathval 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.mesosimport mesosphere.marathon.tasks.{ PortsMatch, PortsMatcher }
import mesosphere.marathon.test.MarathonTestHelper
import org.scalatest.{ FunSuite, GivenWhenThen, Matchers }import scala.collection.immutable.Seqclass ResourceMatchTestextends 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.resourcesThen("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.FunSuiteclass AppTests extends FunSuite {test("happy path") {val cartId = CartId("some-gold-cart")val storage = new SpyStorageapplyDiscount(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 SpyStorageapplyDiscount(cartId, storage)assert(storage.saved.isEmpty)}test("missing cart") {val cartId = CartId("missing-cart")val storage = new SpyStorageapplyDiscount(cartId, storage)assert(storage.saved.isEmpty)}class SpyStorage extends Storage[Cart] {var saved: Option[Cart] = Noneoverride 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.testimport 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).toSeqval firstNode = nodes.headval lastNode  = nodes.lastassert {(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.recfunimport org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class PascalSuite extends FunSuite {import Main.pascaltest("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 recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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.generatorimport 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""".stripMarginval 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.removeimport 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.FunSuiteclass ApiImplUnitTest extends FunSuite {implicit val formats: Formats = JsonSerializers.formatstest("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"}""".stripMarginprintln(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.scalasomimport org.scalatest.FunSuiteclass 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-10import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.DBSCANclass 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-03import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.LinearSVMclass 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 = 1000val err = 1e-1linearsvm.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 = 1000val err = 1e-1linearsvm.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-24import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.GaussianProcessclass 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-29import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.RandomForestclass 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-04import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.LinearRegressionclass 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-22import org.scalatest.FunSuite
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.GeneAlgorithmclass 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).absdef 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) / 2else scala.util.Random.nextDouble}val generationsize: Int = 100val elitesize: Int = 3test("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-28import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.algorithm.QLearningclass QLearningSuite extends FunSuite {val learning_rate = 0.1val scale = 1val limit = 10000val epoch = 100val statenumber = 5val 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-06import org.scalatest.FunSuite
import ght.mi.TestData._
import ght.mi.general.MatrixFunc._
import ght.mi.algorithm.NeuralNetworkclass NeuralNetworkSuite extends FunSuite {val layer_neurons = Array(5, 4)val input_column = UNLABELED_LARGE_HIGH_DIM_DATA.head.sizeval output_column = TARGET_LARGE_HIGH_DIM_DATA.head.sizeval limit = 1000val 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.exampleimport java.net.URIimport 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.databasetry {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 = Unitoverride 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 recfunimport org.scalatest.FunSuiteimport org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner@RunWith(classOf[JUnitRunner])
class CountChangeSuite extends FunSuite {import Main.countChangetest("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.algoimport org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}import scala.util.Randomclass NetworkTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {val RANDOM_VALUE = 0.2val INPUT_LAYER_NEURON_COUNT = 1val HIDDEN_LAYER_NEURON_COUNT = 1val INPUT = 0.528593val 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.algoimport org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}import scala.util.Randomclass NeuronTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {val NEURON_NAME = "neuron"val NEURON_NAME2 = "neuron2"val RANDOM_VALUE = 0.53val 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.543neuron.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.algoimport org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}
import se.andrisak.backprop.rest.model.ClassificationRequest.TrainingDataItemimport scala.util.Randomclass BackPropagationAlgoTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {val ITERATIONS = 1val TRAINING_DATA_FIRST_INPUT: Double = 1.0val TRAINING_DATA_SECOND_INPUT: Double = 1.0val TARGET: Double = 1.0val RANDOM = 0.5val EXPECTED_OUTPUT = 0.9439400108508628var trainingData: TrainingDataItem = nulloverride 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 utilsimport org.scalatest.FunSuiteclass 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.PropertyChecksclass 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.FunSuiteclass 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.SparkTestingimport org.scalatest.Assertions._
import org.apache.spark.rdd.RDD
import com.holdenkarau.spark.testing.SharedSparkContext
import org.scalatest.FunSuiteclass 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 chapter1import org.scalatest.FunSuiteimport 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 CyrillicTry(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 chapter1import 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 chapter2import org.scalatest.FunSuiteclass 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.routerimport 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.dispatcheroverride 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 = 10system.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 = 10QueueLoader.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.catsimport org.scalatest.{FunSuite, Matchers}case class Actor(name: String)object Actor {import cats.Showimplicit val actorShow: Show[Actor] = Show.show[Actor](_.name)
}class ShowTest extends FunSuite with Matchers {test("instances") {import cats.Showimport 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.utilimport org.scalatest.{BeforeAndAfterEach, FunSuite}
import org.scalatest.mock.MockitoSugarclass 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()"))}
} 

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

Scala Test相关推荐

  1. hadoop,spark,scala,flink 大数据分布式系统汇总

    20220314 https://shimo.im/docs/YcPW8YY3T6dT86dV/read 尚硅谷大数据文档资料 iceberg相当于对hive的读写,starrocks相当于对mysq ...

  2. 2021年大数据常用语言Scala(三十八):scala高级用法 隐式转换和隐式参数

    目录 隐式转换和隐式参数 隐式转换 自动导入隐式转换方法 隐式转换的时机 隐式参数 隐式转换和隐式参数 隐式转换和隐式参数是scala非常有特色的功能,也是Java等其他编程语言没有的功能.我们可以很 ...

  3. 2021年大数据常用语言Scala(三十七):scala高级用法 高阶函数用法

    目录 高阶函数用法 作为值的函数 匿名函数 柯里化(多参数列表) 闭包 高阶函数用法 Scala 混合了面向对象和函数式的特性,在函数式编程语言中,函数是"头等公民",它和Int. ...

  4. 2021年大数据常用语言Scala(三十六):scala高级用法 泛型

    目录 泛型 定义一个泛型方法 定义一个泛型类 上下界 协变.逆变.非变 非变 协变 逆变 泛型 scala和Java一样,类和特质.方法都可以支持泛型.我们在学习集合的时候,一般都会涉及到泛型. sc ...

  5. 2021年大数据常用语言Scala(三十五):scala高级用法 提取器(Extractor)

    目录 提取器(Extractor) 定义提取器 提取器(Extractor)  我们之前已经使用过scala中非常强大的模式匹配功能了,通过模式匹配,我们可以快速匹配样例类中的成员变量.例如: // ...

  6. 2021年大数据常用语言Scala(三十四):scala高级用法 异常处理

    目录 异常处理 捕获异常 抛出异常 异常处理 Scala中 无需在方法上声明异常 来看看下面一段代码. def main(args: Array[String]): Unit = {val i = 1 ...

  7. 2021年大数据常用语言Scala(三十一):scala面向对象 特质(trait)

    目录 特质(trait) 作为接口使用 定义具体的方法 定义具体方法和抽象方法 定义具体的字段和抽象的字段 实例对象混入trait trait调用链 trait的构造机制 trait继承class 特 ...

  8. 2021年大数据常用语言Scala(二十九):scala面向对象 单例对象

    目录 单例对象 定义object - 掌握 伴生对象 - 掌握 apply方法 - 掌握 main方法 单例对象 Scala中没有static关键字,但是它支持静态 如果要定义静态的东西,统统定义到o ...

  9. 2021年大数据常用语言Scala(二十八):scala面向对象 MAVEN依赖和类

    目录 scala面向对象 MAVEN依赖 类 - 掌握 创建类和对象 - 掌握 getter/setter - 了解 类的构造器 - 掌握 scala面向对象 MAVEN依赖 <?xml ver ...

  10. 2021年大数据常用语言Scala(二十七):函数式编程 聚合操作

    目录 聚合操作 聚合  reduce 定义 案例 折叠  fold 定义 案例 聚合操作 聚合操作,可以将一个列表中的数据合并为一个.这种操作经常用来统计分析中 聚合  reduce reduce表示 ...

最新文章

  1. 尝试插入cctv视频
  2. java date 格式化_Date类日期格式化
  3. Eclipse添加Spket插件实现ExtJs智能提示
  4. 分析IBASE save 白屏问题
  5. 字体--Ubuntu手记之系统配置
  6. mysql 多数据源访问_通过Spring Boot配置动态数据源访问多个数据库的实现代码
  7. 基础算法 —— 排序算法
  8. BZOJ 1779. [Usaco2010 Hol]Cowwar 奶牛战争
  9. 英特尔再曝安全漏洞:黑客可窃取个人电脑中机密数据
  10. Python 最新版破解滑块验证码自动登录QQ空间
  11. 快速学会普源示波器的调节和使用
  12. 贝叶斯滤波和粒子滤波
  13. 教务管理系统乱码服务器不可,青果教务管理系统Post登录(二)
  14. 计算三角形网格的tangent space
  15. unicode,UTF-8,UTF-16,UTF-32是什么,各有什么关系
  16. 中瀛手机维修管理软件 3gp转换软件
  17. 随机优化中的样本均值近似方法
  18. 【数据结构实训--集合基本运算(附代码)】
  19. 【MATLAB教程案例86】通过matlab实现lorenz混沌系统
  20. 孕妇免疫力低怎么办?就看蛋白粉的功效!

热门文章

  1. 什么时候做都不晚——十大大器晚成的人物
  2. Java - constants
  3. Python Flask学习_使用flask-login实现认证蓝本(一)
  4. 削峰填谷,你只知道消息队列?
  5. 电脑无法获取服务器信息,电脑无法获取IP地址怎么办?原来只需四招就搞定
  6. 密码分析之单表代换原理详解与算法实现
  7. BZOJ5442 [Ceoi2018]Global warming
  8. 弗吉尼亚理工大学计算机科学,美国弗吉尼亚理工大学计算机科学本科.pdf
  9. sumifs函数的使用方法,sumifs函数的多条件运用
  10. 【论文阅读】Conversational Memory Networkfor Emotion Recognition in Dyadic Dialogue Videos