org.junit.Assert.assertEquals Scala Examples

The following examples show how to use org.junit.Assert.assertEquals. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ChronoPeriodTest.scala    From scala-js-java-time   with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
package org.scalajs.testsuite.javalib.time.chrono

import java.time.LocalDate
import java.time.chrono.ChronoPeriod

import org.junit.Test
import org.junit.Assert.assertEquals

class ChronoPeriodTest {
  @Test def test_between(): Unit = {
    val ds = Seq(LocalDate.MIN, LocalDate.of(2011, 2, 28), LocalDate.MAX)
    for {
      d1 <- ds
      d2 <- ds
    } {
      assertEquals(d1.until(d2), ChronoPeriod.between(d1, d2))
    }
  }
} 
Example 2
Source File: ModelTypesTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.cli

import com.eharmony.aloha.factory.ModelFactory
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner



@RunWith(classOf[BlockJUnit4ClassRunner])
class ModelTypesTest {
  @Test def testKnownModels(): Unit = {
    val expected = Seq(
      "BootstrapExploration",
      "CategoricalDistribution",
      "CloserTester",              // A test model.
      "Constant",
      "DecisionTree",
      "DoubleToLong",
      "EpsilonGreedyExploration",
      "Error",
      "ErrorSwallowingModel",
      "H2o",
      "ModelDecisionTree",
      "Regression",
      "Segmentation",
      "SparseMultilabel",
      "VwJNI"
    )

    val actual = ModelFactory.defaultFactory(null, null).parsers.map(_.modelType).sorted
    assertEquals(expected, actual)
  }
} 
Example 3
Source File: HeaderTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.dataset.csv

import com.eharmony.aloha.dataset.RowCreatorBuilder
import com.eharmony.aloha.semantics.compiled.CompiledSemantics
import com.eharmony.aloha.semantics.compiled.compiler.TwitterEvalCompiler
import com.eharmony.aloha.semantics.compiled.plugin.csv._
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner
import org.junit.Assert.assertEquals

import scala.concurrent.ExecutionContext.Implicits.global


  private def dsJson(encoding: String) =
    s"""
       |{
       |  "imports": [],
       |  "separator": ",",
       |  "nullValue": "null",
       |  "encoding": "$encoding",
       |  "features": [
       |    { "spec": "1 to 3", "type": "int", "size": 3, "name": "vec" },
       |    { "spec": "\\"some_string_value\\"", "type": "string", "name": "str" },
       |    { "spec": "4", "type": "double", "name": "doub" },
       |    { "spec": "true", "type": "boolean", "name": "bool" },
       |    { "spec": "com.eharmony.matching.notaloha.AnEnum.VALUE_2",
       |      "type": "enum",
       |      "enumClass": "com.eharmony.matching.notaloha.AnEnum",
       |      "name": "enum"
       |    }
       |  ]
       |}
     """.stripMargin

  private def csvRowCreator(encoding: String) = {
    val json = dsJson(encoding)
    val plugin = CompiledSemanticsCsvPlugin()
    val semantics = CompiledSemantics(TwitterEvalCompiler(classCacheDir = None), plugin, Nil)
    val sb = RowCreatorBuilder(semantics, List(CsvRowCreator.Producer[CsvLine]()))
    sb.fromString(json).get
  }

  // Since dsJson doesn't rely on any input data, this can be anything, including null.
  private val EmptyLine: CsvLineImpl = null
} 
Example 4
Source File: StdAvroModelFactoryTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.factory.avro

import com.eharmony.aloha.audit.impl.avro.Score
import com.eharmony.aloha.factory.ModelFactory
import com.eharmony.aloha.io.vfs.Vfs1
import com.eharmony.aloha.models.Model
import org.apache.avro.Schema
import org.apache.avro.generic.{GenericData, GenericRecord}
import org.apache.commons.io.IOUtils
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner

import scala.util.Try


  private[this] def record = {
    val r = new GenericData.Record(TheSchema)
    r.put("req_str_1", "smart handsome stubborn")
    r
  }
}

object StdAvroModelFactoryTest {
  private lazy val TheSchema = {
    val is = getClass.getClassLoader.getResourceAsStream(SchemaUrlResource)
    try new Schema.Parser().parse(is) finally IOUtils.closeQuietly(is)
  }

  private val ExpectedResult = 7d

  private val SchemaUrlResource = "avro/class7.avpr"

  private val SchemaUrl = s"res:$SchemaUrlResource"

  private val SchemaFile = new java.io.File(getClass.getClassLoader.getResource(SchemaUrlResource).getFile)

  private val SchemaVfs1FileObject = org.apache.commons.vfs.VFS.getManager.resolveFile(SchemaUrl)

  private val SchemaVfs2FileObject = org.apache.commons.vfs2.VFS.getManager.resolveFile(SchemaUrl)

  private val Imports = Seq("com.eharmony.aloha.feature.BasicFunctions._", "scala.math._")

  private val ReturnType = "Double"

  private val ModelJson =
    """
      |{
      |  "modelType": "Regression",
      |  "modelId": { "id": 0, "name": "" },
      |  "features" : {
      |    "my_attributes": "${req_str_1}.split(\"\\\\W+\").map(v => (s\"=$v\", 1.0))"
      |  },
      |  "weights": {
      |    "my_attributes=handsome": 1,
      |    "my_attributes=smart": 2,
      |    "my_attributes=stubborn": 4
      |  }
      |}
    """.stripMargin
} 
Example 5
Source File: FlatScoreTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.audit.impl.avro

import com.google.common.collect.Lists
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner
import com.eharmony.aloha.audit.impl.avro.AvroScoreAuditorTest.serializeRoundTrip
import scala.collection.JavaConverters.seqAsJavaListConverter
import java.{util => ju}


@RunWith(classOf[BlockJUnit4ClassRunner])
class FlatScoreTest {
  import FlatScoreTest.flatScore

  @Test def testSerializability(): Unit = {
    val serDeserFS =
      serializeRoundTrip(FlatScore.getClassSchema, flatScore).head

    // When comparing the records instead of the JSON strings, equality doesn't
    // hold because they are different types. flatScoreList is a SpecificRecord
    // and SpecificRecord checks if the other values is a SpecificRecord.
    assertEquals(flatScore.toString, serDeserFS.toString)
  }
}

object FlatScoreTest {
  private[this] def empty[A]: ju.List[A] = ju.Collections.emptyList[A]

  private[this] implicit def toArrayList[A, B](as: Seq[A])(implicit ev: A => B): ju.ArrayList[B] =
    Lists.newArrayList(as.map(ev).asJava)

  private[this] def fsd(value: Any, id: Long, children: Int*): FlatScoreDescendant = {
    new FlatScoreDescendant(
      new ModelId(id, ""),
      value,
      children,
      empty[CharSequence],
      empty[CharSequence],
      null
    )
  }

  private[avro] lazy val flatScore: FlatScore = {
    new FlatScore(new ModelId(1L, ""), 1, Vector(0, 1), empty[CharSequence], empty[CharSequence], null,
      Seq(
        fsd(2L, 2, 2, 3),  // 0
        fsd(3d, 3, 4, 5),  // 1
        fsd(4f, 4),        // 2
        fsd(5,  5),        // 3
        fsd(6d, 6),        // 4
        fsd(7L, 7)         // 5
      )
    )
  }
} 
Example 6
Source File: ImplicitsTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.audit.impl.avro

import com.google.common.collect.Lists
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner

import scala.collection.JavaConverters.seqAsJavaListConverter
import com.eharmony.aloha.audit.impl.avro.Implicits.{RichFlatScore, RichScore}
import java.{lang => jl, util => ju}

import org.apache.avro.generic.GenericRecord


  @Test def testAllFieldsAppear(): Unit = {
    val s = filledInScore
    assertEquals(s, s.toFlatScore.toScore)
  }

  @Test def testSameFieldsInGenericRecord(): Unit = {
    val s = filledInScore
    val s1 = s.asInstanceOf[GenericRecord]
    val s2 = s.toFlatScore.asInstanceOf[GenericRecord]

    testStuff(s1, s2, Map(
      "model" -> modelId,
      "value" -> value,
      "errorMsgs" -> errors,
      "missingVarNames" -> missing,
      "prob" -> prob
    ))
  }

  private[this] def testStuff(r1: GenericRecord, r2: GenericRecord, data: Map[String, Any]): Unit = {
    data.foreach { case (k, v) =>
      val v1 = r1.get(k)
      val v2 = r2.get(k)
      assertEquals(s"for r1('$k') = $v1.  Expected $v", v, r1.get(k))
      assertEquals(s"for r2('$k') = $v2.  Expected $v", v, r2.get(k))
    }
  }
}


object ImplicitsTest {
  private def filledInScore = new Score(modelId, value, subvalues, errors, missing, prob)
  private def modelId = new ModelId(5L, "five")
  private def value: jl.Double = 13d
  private def subvalues = Lists.newArrayList(scr(12L, 8))
  private def errors: ju.List[CharSequence] = Lists.newArrayList("one error", "two errors")
  private def missing: ju.List[CharSequence] =
    Lists.newArrayList("some feature", "another feature", "yet another feature")
  private def prob: jl.Float = 1f

  private lazy val score: Score =
    scr(1, 1,
      scr(2L, 2,
        scr(4f, 4),
        scr(5,  5)
      ),
      scr(3d, 3,
        scr(6d, 6),
        scr(7L, 7)
      )
    )

  private lazy val irregularTree: Score =
    scr(1, 1,
      scr(2L, 2),
      scr(3d, 3,
        scr(5d, 5),
        scr(6L, 6)
      ),
      scr(4d, 4,
        scr(7L, 7)
      )
    )

  private[this] def scr(value: Any, id: Long, children: Score*): Score = {
    new Score(
      new ModelId(id, ""),
      value,
      Lists.newArrayList(children.asJava),
      java.util.Collections.emptyList(),
      java.util.Collections.emptyList(),
      null
    )
  }
} 
Example 7
Source File: FriendServiceTest.scala    From activator-lagom-scala-chirper   with Apache License 2.0 5 votes vote down vote up
package sample.chirper.friend.impl

import java.util.concurrent.TimeUnit.SECONDS

import scala.collection.immutable.Seq
import scala.concurrent.duration.FiniteDuration

import org.junit.Assert.assertEquals
import org.junit.Test

import com.lightbend.lagom.javadsl.testkit.ServiceTest.defaultSetup
import com.lightbend.lagom.javadsl.testkit.ServiceTest.eventually
import com.lightbend.lagom.javadsl.testkit.ServiceTest.withServer

import akka.NotUsed
import sample.chirper.friend.api.FriendId
import sample.chirper.friend.api.FriendService
import sample.chirper.friend.api.User

class FriendServiceTest {


  @throws(classOf[Exception])
  @Test
  def shouldBeAbleToCreateUsersAndConnectFriends() {
    withServer(defaultSetup, server => {
      val friendService = server.client(classOf[FriendService])
      val usr1 = new User("usr1", "User 1");
      friendService.createUser().invoke(usr1).toCompletableFuture().get(10, SECONDS)
      val usr2 = new User("usr2", "User 2");
      friendService.createUser().invoke(usr2).toCompletableFuture().get(3, SECONDS)
      val usr3 = new User("usr3", "User 3");
      friendService.createUser().invoke(usr3).toCompletableFuture().get(3, SECONDS)

      friendService.addFriend("usr1").invoke(FriendId(usr2.userId)).toCompletableFuture().get(3, SECONDS)
      friendService.addFriend("usr1").invoke(FriendId(usr3.userId)).toCompletableFuture().get(3, SECONDS)

      val fetchedUsr1 = friendService.getUser("usr1").invoke(NotUsed).toCompletableFuture().get(3,
          SECONDS)
      assertEquals(usr1.userId, fetchedUsr1.userId)
      assertEquals(usr1.name, fetchedUsr1.name)
      assertEquals(Seq("usr2", "usr3"), fetchedUsr1.friends)

      eventually(FiniteDuration(10, SECONDS), () => {
        val followers = friendService.getFollowers("usr2").invoke()
            .toCompletableFuture().get(3, SECONDS)
        assertEquals(Seq("usr1"), followers)
      })

    })
  }

} 
Example 8
Source File: TestArgumentOrder.scala    From lift   with MIT License 5 votes vote down vote up
package opencl.generator

import ir.ArrayTypeWSWC
import ir.ast.{Split, UserFun, fun}
import lift.arithmetic.SizeVar
import opencl.ir.Int
import opencl.ir.pattern.{MapAtomWrg, MapLcl}
import org.junit.Assert.assertEquals
import org.junit.Test
import utils.{OutputKernelJSON, TestOutputKernelJSON}

class TestArgumentOrder {

  
  @Test def ARGUMENT_ORDER_MAP_ATOMIC_WG(): Unit = {
    // Taken from opencl.generator.TestDynMap.ATOM_WRG_MAP
    val splitSize = Math.pow(2, 5).toInt
    val idIterate = UserFun("idIterate", "x", """
                                              int y = x;
                                              for(int i = 0;i<x;i++){
                                                y = y + 1;
                                              }
                                              return y;
                                              """.stripMargin, Int, Int)

    val lambda = fun(ArrayTypeWSWC(Int, SizeVar("N")),
      (array) => MapAtomWrg(MapLcl(idIterate)) o Split(splitSize) $ array
    )

    val json = OutputKernelJSON.getJsonString(lambda)
    val goldJSON = "{\"parameters\" : {\"int* v__8\" : \"(4*v_N_0)\"}, \"outputs\" : {\"int* v__10\" : \"(4*v_N_0)\"}, \"temporary buffers\" : {\"int* v__9\" : \"4\"}, \"sizes\" : {\"int v_N_0\" : \"4\"}}"

    assertEquals(
      TestOutputKernelJSON.sanitiseData(goldJSON).mkString,
      TestOutputKernelJSON.sanitiseData(json).mkString)
  }

} 
Example 9
Source File: TestDbSelect.scala    From lift   with MIT License 5 votes vote down vote up
package opencl.generator

import benchmarks.DbSelect
import opencl.executor.{Execute, TestWithExecutor}
import org.junit.Assert.assertEquals
import org.junit.Test

object TestDbSelect extends TestWithExecutor

class TestDbSelect {
  private def gold(colA: Array[Int], colB: Array[Int], colC: Array[Int]): Vector[(Int, Int, Int)] = {
    val newC = colC.map(n => if(n == 1) 1 else 0)
    (newC, colA, colB).zipped.toVector
  }

  @Test def testNaive(): Unit = {
    val inputSize = 1024
    val colA = Array.fill(inputSize)(util.Random.nextInt(5))
    val colB = Array.fill(inputSize)(util.Random.nextInt(5))
    val colC = Array.fill(inputSize)(util.Random.nextInt(5))

    val (output, runtime) = Execute(inputSize)[Vector[(Int, Int, Int)]](DbSelect.naive, colA, colB, colC)
   
    println(s"Runtime: $runtime")
    
    assertEquals(gold(colA, colB, colC), output)
  }
  
  @Test def testDivideNConquer(): Unit = {
    val inputSize = 128*128
    val colA = Array.fill(inputSize)(util.Random.nextInt(5))
    val colB = Array.fill(inputSize)(util.Random.nextInt(5))
    val colC = Array.fill(inputSize)(util.Random.nextInt(5))
  
    val (output, runtime) = Execute(inputSize)[Vector[(Int, Int, Int)]](DbSelect.divideNConquer, colA, colB, colC)
  
    println(s"Runtime: $runtime")
  
    assertEquals(gold(colA, colB, colC), output)
  }
} 
Example 10
Source File: TestCipherUtil.scala    From spark-highcharts   with Apache License 2.0 5 votes vote down vote up
package com.knockdata.spark.utils

import org.junit.Test
import org.junit.Assert.assertEquals

class TestCipherUtil{
  @Test
  def testEncrypt(): Unit = {
    val encrypted = CipherUtil.encrypt("rockie", "password")
    println(encrypted)

    assertEquals("encrypted a sample password shall be ", "v/nMLHnQCeqDobO01j3syw==", encrypted)
  }

  @Test
  def testDecrypt(): Unit = {
    val decrypted = CipherUtil.decrypt("rockie", "v/nMLHnQCeqDobO01j3syw==")
    println(decrypted)

    assertEquals("encrypted a sample password shall be ", "password", decrypted)
  }

  @Test
  def testEncrypt2(): Unit = {
    val encrypted = CipherUtil.encrypt("yang", "password")
    println(encrypted)

    assertEquals("encrypted a sample password shall be ", "VUhy/KQ2nf7DO0NBBRWW8g==", encrypted)
  }

  @Test
  def testDecrypt2(): Unit = {
    val decrypted = CipherUtil.decrypt("yang", "VUhy/KQ2nf7DO0NBBRWW8g==")
    println(decrypted)

    assertEquals("encrypted a sample password shall be ", "password", decrypted)
  }

  @Test
  def testSymmetric(): Unit = {
    val encrypted = CipherUtil.encrypt("yang", "rockie")
    println(encrypted)

    val decrypted = CipherUtil.decrypt("yang", encrypted)
    assertEquals("encrypted a sample password shall be ", "rockie", decrypted)
  }
} 
Example 11
Source File: RandomUtilTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.common.ml.util

import org.junit.Assert.assertEquals
import org.junit.Test


class RandomUtilTest {

  @Test
  def evalSlice(): Unit = {
    val list = Seq.range(1, 101)
    val ratios = Seq(0.85, 0.1, 0.05)

    val r = RandomUtil.slice(list, ratios)

    assertEquals(85, r.head.last)
    assertEquals(86, r(1).head)
    assertEquals(96, r(2).head)
    assertEquals(100, r(2).last)
  }
} 
Example 12
Source File: SortTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.common.ml.util

import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test


class SortTest {

  @Test
  def testQuickSelect(): Unit = {
    val v = Array(9, 8, 7, 6, 5, 0, 1, 2, 3, 4)
    val r = v.indices.map(Sort.quickSelect(v, _)).toArray
    assertTrue(Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).deep == r.deep)

    val v2 = Array(Array(9), Array(8), Array(7), Array(6), Array(5), Array(0), Array(1), Array(2)
      , Array(3), Array(4))

    val r2 = v2.indices.map(Sort.quickSelectAxis[Int](v2, _, 0)).toArray
    assertTrue(Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).deep == r2.deep)

    assertEquals(1, Sort.quickSelect(Array(1, 1, 1, 1, 1), 0))
    assertEquals(1, Sort.quickSelect(Array(1, 1, 1, 1, 1), 1))
    assertEquals(1, Sort.quickSelect(Array(1, 1, 1, 2, 2, 2), 2))
    assertEquals(2, Sort.quickSelect(Array(1, 1, 1, 2, 2, 2), 3))
    assertEquals(1, Sort.quickSelect(Array(0, 1, 2, 1), 2))
    assertEquals(0, Sort.quickSelect(Array(0, 0, 0, 0, 1, 2, 1), 3))
  }
} 
Example 13
Source File: TrainingOptionsTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.common.ml.strategy.config

import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test


class TrainingOptionsTest {

  @Test
  def testToArray(): Unit = {
    val opt1 = TrainingOptionsTest.getOption
    val array = opt1.toArray

    val opt2 = TrainingOptions.fromArray(array, "2016-08-31", "learning")
    assertEquals(opt1.trueLowerBound, opt2.trueLowerBound, 0.0001)
    assertEquals(opt1.falseUpperBound, opt2.falseUpperBound, 0.0001)
    assertEquals(opt1.falseLowerBound, opt2.falseLowerBound, 0.0001)
    assertEquals(opt1.trueUpperBound, opt2.trueUpperBound, 0.0001)
    assertEquals(opt1.r1, opt2.r1, 0.0001)
    assertEquals(opt1.r0, opt2.r0, 0.0001)
    assertEquals(opt1.numEpochs, opt2.numEpochs)
    assertEquals(opt1.miniBatchSize, opt2.miniBatchSize)
    assertEquals(opt1.rateDecay, opt2.rateDecay, 0.0001)
    assertEquals(opt1.evalRatio, opt2.evalRatio, 0.0001)
    assertEquals(opt1.maxAvgLossRatio, opt2.maxAvgLossRatio, 0.0001)
    assertEquals(opt1.minTrueLabelCount, opt2.minTrueLabelCount)

    assertTrue(s" ${opt1.min} ${opt2.min} ", opt1.min == opt2.min)
    assertTrue(opt1.max == opt2.max)
    assertTrue(opt1.default == opt2.default)
  }

  @Test
  def testDefaultOrNewValue(): Unit = {
    val pn = List("lowerBound", "upperBound")
    val pv = List(1.03, 3.0)
    val t = TrainingOptions.defaultOrNewValue(
      100.0, pn, pv, "lowerBound")
    assertEquals(t, 1.03, 0.01)

    val t1 = TrainingOptions.defaultOrNewValue(
      100.0, pn, pv, "lower_bound")
    assertEquals(t1, 100, 0.01)
  }
}

object TrainingOptionsTest {
  val getOption: TrainingOptions = {
    TrainingOptions(
      // trueLowerBound, falseUpperBound,
      0.98, 1.0,
      // falseLowerBound trueUpperBound
      0.65, 1.03,
      // r0
      0.1, 0.2, 0.95,
      //numEpochs: Int, miniBatchSize: Int,
      100, 50,
      0.5,
      2, 0.1,
      //min: Array[Double], max: Array[Double],
      List(0.1, 0.0), List(3.0, 3.0),
      List(2.0, 3.0),
      //dsEval: String, learningRateType: String
      "2016-08-31", "learning")
  }

} 
Example 14
Source File: SearchParamsTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.common.ml.strategy.config

import com.typesafe.config.{Config, ConfigFactory}
import org.junit.Assert.assertEquals
import org.junit.Test

import com.airbnb.common.ml.util.ScalaLogging


class SearchParamsTest extends ScalaLogging {


  def makeSingleConfig: Config = {
    val config = """
                   |param_search {
                   |  params: ["lower_bound"]
                   |  lower_bound: [0.65, 0.7, 0.75]
                   |  upper_bound: [1.03, 1.05, 1.08]
                   |  list_params: ["min", "max"]
                   |  min: [{list:[0.0, 1, -4]}, {list:[0.1, 2, -5]}]
                   |  max: [{list:[2.0, 18, 4]}, {list:[3, 20, 4]}]
                   |}
                 """.stripMargin
    ConfigFactory.parseString(config)
  }

  @Test
  def testParseDouble(): Unit = {
    val p1 = SearchParamsTest.getDoubleParams

    assertEquals(9, p1.paramCombinations.length)
    p1.paramCombinations.map(p => {
      val str = SearchParams.prettyPrint(p1.paramNames, p)
      logger.info(s"p: $str")
    }
    )
    assertEquals(2, p1.paramNames.length)
    logger.info(s"p: ${p1.paramNames.mkString(",")}")
  }

  @Test
  def testParseSingle(): Unit = {
    val config = makeSingleConfig
    val p1 = SearchParams.loadDoubleFromConfig(config.getConfig("param_search"))

    assertEquals(3, p1.paramCombinations.length)
    p1.paramCombinations.map(p => {
      val str = SearchParams.prettyPrint(p1.paramNames, p)
      logger.info(s"p: $str")
    }
    )
  }

  @Test
  def testParseSingleCombination(): Unit = {
    val config = makeSingleConfig
    val p1 = SearchParams.loadDoubleFromConfig(config.getConfig("param_search"))

    assertEquals(3, p1.paramCombinations.length)
    p1.paramCombinations.map(p => {
      val str = SearchParams.prettyPrint(p1.paramNames, p)
      logger.info(s"p: $str")
    }
    )
  }

  @Test
  def testParseList(): Unit = {
    val config = SearchParamsTest.makeDoubleConfig
    val p1 = SearchParams.loadListDoubleFromConfig(config.getConfig("param_search"))

    assertEquals(4, p1.paramCombinations.length)
    p1.paramCombinations.map(p => {
      val str = SearchParams.prettyPrint(p1.paramNames, p)
      logger.info(s"p: $str")
    }
    )
  }
}

object SearchParamsTest {
  def makeDoubleConfig: Config = {
    val config = """
                   |param_search {
                   |  params: ["lower_bound", "upper_bound"]
                   |  lower_bound: [0.65, 0.7, 0.75]
                   |  upper_bound: [1.03, 1.05, 1.08]
                   |  list_params: ["min", "max"]
                   |  min: [{list:[0.0, 1, -4]}, {list:[0.1, 2, -5]}]
                   |  max: [{list:[2.0, 18, 4]}, {list:[3, 20, 4]}]
                   |}
                 """.stripMargin
    ConfigFactory.parseString(config)
  }

  def getDoubleParams: SearchParams[Double] = {
    val config = SearchParamsTest.makeDoubleConfig
    SearchParams.loadDoubleFromConfig(config.getConfig("param_search"))
  }

} 
Example 15
Source File: StrategyModelSearchConfigTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.common.ml.strategy.config

import com.typesafe.config.{Config, ConfigFactory}
import org.junit.Assert.assertEquals
import org.junit.Test


class StrategyModelSearchConfigTest {

  @Test
  def testTrainingOptions(): Unit = {
    val paramNames = List("min","max")
    val paramValues = List(1,2)
    assertEquals(1, TrainingOptions.defaultOrNewValue(2, paramNames, paramValues, "min"))

    assertEquals(3, TrainingOptions.defaultOrNewValue(3, paramNames, paramValues, "xxx"))

    assertEquals(2, TrainingOptions.defaultOrNewValue(5, paramNames, paramValues, "max"))
  }

  def makeDoubleConfig: Config = {
    val config = """
                   |param_search {
                   |  params: ["r1"]
                   |  r1: [0.65, 0.7, 0.75]
                   |  upper_bound: [1.03, 1.05, 1.08]
                   |}
                 """.stripMargin
    ConfigFactory.parseString(config)
  }
} 
Example 16
Source File: CyclicCoordinateDescentTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.aerosolve.training

import com.airbnb.aerosolve.training.CyclicCoordinateDescent.Params
import com.airbnb.aerosolve.core.util.Util
import com.airbnb.aerosolve.core.{Example, FeatureVector}
import com.typesafe.config.{ConfigFactory, Config}
import org.apache.spark.SparkContext
import org.junit.Test
import org.slf4j.LoggerFactory
import org.junit.Assert.assertEquals

import scala.collection.mutable.ArrayBuffer

class CyclicCoordinateDescentTest {
  val log = LoggerFactory.getLogger("CyclicCoordinateDescentTest")

  @Test def quadraticTest: Unit = {
    val iterations = 5
    val initial = Array(0.0, 0.0)
    val initialStep = Array(1.0, 1.0)
    val bounds : Array[(Double, Double)] = Array((-10.0, 10.0), (-10.0, 10.0))
    val params = Params(0.1, iterations, initial, initialStep, bounds)
    def f(x : Array[Double]) = {
      (x(0) + 5.0) * (x(0) - 3.0) +
      (x(1) + 2.0) * (x(1) - 7.0)
    }
    val best = CyclicCoordinateDescent.optimize(f, params)
    assertEquals(-1.0, best(0), 0.1)
    assertEquals(2.5, best(1), 0.1)
  }
} 
Example 17
Source File: KDTreeTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.aerosolve.training

import com.airbnb.aerosolve.core.KDTreeNode
import com.airbnb.aerosolve.core.KDTreeNodeType
import com.airbnb.aerosolve.training.KDTree.KDTreeBuildOptions
import org.junit.Test
import org.slf4j.LoggerFactory
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import scala.collection.mutable.ArrayBuffer

class KDTreeTest {
  val log = LoggerFactory.getLogger("KDTreeTest")

  @Test def buildTreeTest: Unit = {
    val pts = ArrayBuffer[(Double, Double)]()
    for (x <- -20 to 20) {
      for (y <- 1 to 5) {
        pts.append((x.toDouble, y.toDouble))
      }
    }
    val options = KDTreeBuildOptions(maxTreeDepth = 16, minLeafCount = 1)
    val tree = KDTree(options, pts.toArray)
    val nodes = tree.nodes
    log.info("Num nodes = %d".format(nodes.size))
    // Since the x dimension is largest we expect the first node to be an xsplit
    assertEquals(KDTreeNodeType.X_SPLIT, nodes(0).nodeType)
    assertEquals(-1.81, nodes(0).splitValue, 0.1)
    assertEquals(1, nodes(0).leftChild)
    assertEquals(2, nodes(0).rightChild)    // Ensure every point is bounded in the box of the kdtree
    for (pt <- pts) {
      val res = tree.query(pt)
      for (idx <- res) {
        assert(pt._1 >= nodes(idx).minX)
        assert(pt._1 <= nodes(idx).maxX)
        assert(pt._2 >= nodes(idx).minY)
        assert(pt._2 <= nodes(idx).maxY)
      }
    }
    // Ensure all nodes are sensible
    for (node <- nodes) {
      assert(node.count > 0)
      assert(node.minX <= node.maxX)
      assert(node.minY <= node.maxY)
      if (node.nodeType != KDTreeNodeType.LEAF) {
        assert(node.leftChild >= 0 && node.leftChild < nodes.size)
        assert(node.rightChild >= 0 && node.rightChild < nodes.size)
      }
    }
  }

} 
Example 18
Source File: HistogramCalibratorTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.aerosolve.training

import org.apache.spark.SparkContext
import org.junit.Test
import org.slf4j.LoggerFactory
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue

class HistogramCalibratorTest {
  val log = LoggerFactory.getLogger("HistogramCalibratorTest")

  @Test
  def testCalibrate = {
    var sc = new SparkContext("local", "HistogramCalibratorTest")
    val src = sc.parallelize(6 to 99)
    val square = src.map(x => 1.0 * x * x)
    val calibrator = HistogramCalibrator(square, 16)
    calibrator.cumulativeDistributionFunction.foreach(
      x => log.info("%f,%f".format(x._1, x._2))
    )
    // Check the extrema
    assertEquals(0.0, calibrator.cumulativeDistributionFunction.head._2, 1e-2)
    assertEquals(1.0, calibrator.cumulativeDistributionFunction.last._2, 1e-2)
    assertEquals(0.0, calibrator.calibrateScore(5 * 5), 1e-2)
    assertEquals(0.0, calibrator.calibrateScore(6 * 6), 1e-2)
    assertEquals(1.0, calibrator.calibrateScore(99 * 99), 1e-2)
    assertEquals(1.0, calibrator.calibrateScore(100 * 100), 1e-2)
    // Check the quartiles
    val median = (6 + 99) / 2.0
    assertEquals(0.5, calibrator.calibrateScore(median * median), 1e-2)
    val lowerQuartile = 6.0 + (99 - 6) * 0.25
    assertEquals(0.25, calibrator.calibrateScore(lowerQuartile * lowerQuartile), 1e-2)
    val upperQuartile = 6.0 + (99 - 6) * 0.75
    assertEquals(0.75, calibrator.calibrateScore(upperQuartile * upperQuartile), 1e-2)
    // Check the thirds
    val lowerThird = 6.0 + (99 - 6) / 3.0
    assertEquals(0.33, calibrator.calibrateScore(lowerThird * lowerThird), 1e-2)
    val secondThird = 6.0 + 2.0 * (99 - 6) / 3.0
    assertEquals(0.66, calibrator.calibrateScore(secondThird * secondThird), 1e-2)
    // Check linear interpolation
    for (i <- 7 until 98) {
      val score = i * i * 1.0
      assertTrue(calibrator.calibrateScore(score) < calibrator.calibrateScore(score + 1.0))
    }

    try {
   } finally {
      sc.stop
      sc = null
      // To avoid Akka rebinding to the same port, since it doesn't unbind immediately on shutdown
      System.clearProperty("spark.master.port")
    }
  }
} 
Example 19
Source File: ErrorModelTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.models

import com.eharmony.aloha.ModelSerializationTestHelper
import com.eharmony.aloha.audit.impl.OptionAuditor
import com.eharmony.aloha.audit.impl.tree.RootedTreeAuditor
import com.eharmony.aloha.factory.ModelFactory
import com.eharmony.aloha.id.ModelId
import com.eharmony.aloha.semantics.NoSemantics
import org.junit.Assert.{assertEquals, assertNotNull, assertTrue}
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner

@RunWith(classOf[BlockJUnit4ClassRunner])
class ErrorModelTest extends ModelSerializationTestHelper {

  private val factory = ModelFactory.defaultFactory(NoSemantics[Unit](), OptionAuditor[Byte]())

  @Test def test1() {
    val em = ErrorModel(ModelId(), Seq("There should be a valid user ID.  Couldn't find one...", "blah blah"), RootedTreeAuditor.noUpperBound[Byte]())
    val s = em(null)
    assertNotNull(s)
    assertTrue(s.value.isEmpty)
  }

  @Test def testEmptyErrors() {

    val json =
      """
        |{
        |  "modelType": "Error",
        |  "modelId": { "id": 0, "name": "" }
        |}
      """.stripMargin

    val m1 = factory.fromString(json)
    assertTrue(m1.isSuccess)

    val json2 =
      """
        |{
        |  "modelType": "Error",
        |  "modelId": { "id": 0, "name": "" },
        |  "errors": []
        |}
      """.stripMargin


    val m2 = factory.fromString(json2)
    assertTrue(m2.isSuccess)
  }

  @Test def testSerialization(): Unit = {
    val m = ErrorModel(ModelId(2, "abc"), Seq("def", "ghi"), OptionAuditor[Byte]())
    val m1 = serializeDeserializeRoundTrip(m)
    assertEquals(m, m1)
  }
} 
Example 20
Source File: RegressionModelTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.models.reg

import com.eharmony.aloha.ModelSerializationTestHelper
import com.eharmony.aloha.audit.impl.OptionAuditor
import com.eharmony.aloha.id.ModelId
import com.eharmony.aloha.semantics.func.GenFunc
import org.junit.Assert.assertEquals
import org.junit.Test


class RegressionModelTest extends ModelSerializationTestHelper {
  import com.eharmony.aloha.models.reg.RegressionModelTest._

  @Test def testSerialization(): Unit = {
    val m = RegressionModel(modelId = ModelId(2, "2"),
                            featureNames = Vector("empty"),
                            featureFunctions = Vector(GenFunc.f0("", Empty)),
                            beta = PolynomialEvaluator.builder.result(),
                            invLinkFunction = Identity(),
                            Option(ConstantDeltaSpline(0, 1, Vector(0, 1))),
                            Option(1),
                            OptionAuditor[Double]())

    val m1 = serializeDeserializeRoundTrip(m)
    assertEquals(m, m1)
  }
}

object RegressionModelTest {
  case class Identity[A]() extends (A => A) {
    def apply(a: A) = a
  }

  case object Empty extends (Any => Iterable[(String, Double)]) {
    def apply(a: Any) = Iterable.empty
  }
} 
Example 21
Source File: DumThroAwayTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.semantics.compiled.plugin.csv

import com.eharmony.aloha.audit.impl.OptionAuditor
import com.eharmony.aloha.factory.ModelFactory
import com.eharmony.aloha.semantics.compiled.CompiledSemantics
import com.eharmony.aloha.semantics.compiled.compiler.TwitterEvalCompiler
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner

import scala.concurrent.ExecutionContext.Implicits.global

@RunWith(classOf[BlockJUnit4ClassRunner])
class DumThroAwayTest {
    @Test def test1() {
        val compiler = TwitterEvalCompiler()
        val plugin = CompiledSemanticsCsvPlugin(Map("profile.user_id" -> CsvTypes.withNameExtended("oi")))
        val imports = Seq("com.eharmony.aloha.feature.BasicFunctions._", "scala.math._")
        val semantics = CompiledSemantics(compiler, plugin, imports)
        val factory = ModelFactory.defaultFactory(semantics, OptionAuditor[Double]())

        val model = factory.fromResource("fizzbuzz.json").get

        val lineProducer = CsvLines(Map("profile.user_id" -> 0))
        val examples = "" :: (-16 to 16 map { _.toString }).toList
        val lines = lineProducer(examples)

        val expected = Seq(
            (None, -1.0),
            (Some(-16), 16.0),
            (Some(-15), -6.0),
            (Some(-14), 14.0),
            (Some(-13), 13.0),
            (Some(-12), -2.0),
            (Some(-11), 11.0),
            (Some(-10), -4.0),
            (Some(-9), -2.0),
            (Some(-8), 8.0),
            (Some(-7), 7.0),
            (Some(-6), -2.0),
            (Some(-5), -4.0),
            (Some(-4), 4.0),
            (Some(-3), -2.0),
            (Some(-2), 2.0),
            (Some(-1), 1.0),
            (Some(0), -6.0),

            (Some(1), 1.0),
            (Some(2), 2.0),
            (Some(3), -2.0),
            (Some(4), 4.0),
            (Some(5), -4.0),
            (Some(6), -2.0),
            (Some(7), 7.0),
            (Some(8), 8.0),
            (Some(9), -2.0),
            (Some(10), -4.0),
            (Some(11), 11.0),
            (Some(12), -2.0),
            (Some(13), 13.0),
            (Some(14), 14.0),
            (Some(15), -6.0),
            (Some(16), 16.0)
        )

        val results = lines.map { l => (l.oi("profile.user_id"), model(l)) }.
                            map { case (optId, s) => (optId, s.get) }

        assertEquals(expected, results)
    }
} 
Example 22
Source File: CommandsTests.scala    From activemq-cli   with Apache License 2.0 5 votes vote down vote up
package activemq.cli.command

import java.io.File

import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertNotNull
import org.junit.BeforeClass
import org.junit.AfterClass
import org.springframework.shell.Bootstrap
import org.springframework.shell.core.CommandResult
import org.springframework.shell.core.JLineShellComponent

object CommandsTests {

  System.setProperty("config.file", "./src/test/resources/activemq-cli-test.config")

  def createShell(): JLineShellComponent = {
    new Bootstrap().getJLineShellComponent()
  }

  def startAndConnectToEmbeddedBroker(shell: JLineShellComponent): Unit = {
    assertTrue(shell.executeCommand("start-embedded-broker").isSuccess)
    assertTrue(shell.executeCommand("connect --broker test").isSuccess)
  }

  def stopEmbeddedBroker(shell: JLineShellComponent): Unit = {
    assertTrue(shell.executeCommand("stop-embedded-broker").isSuccess)
  }

  def createTempFilePath(prefix: String): String = {
    val file = File.createTempFile(prefix, ".xml")
    file.delete
    file.getAbsolutePath
  }

  def assertCommandFailed(commandResult: CommandResult) {
    assertFalse(commandResult.isSuccess)
    assertNull(commandResult.getResult)
    assertNull(commandResult.getException)
  }
} 
Example 23
Source File: BrokerCommandsTests.scala    From activemq-cli   with Apache License 2.0 5 votes vote down vote up
package activemq.cli.command

import activemq.cli.ActiveMQCLI
import activemq.cli.command.CommandsTests._
import activemq.cli.command.MessageCommandsTests._
import activemq.cli.util.Console._
import java.io.File
import org.junit.After
import org.junit.AfterClass
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import org.junit.Test
import org.springframework.shell.Bootstrap
import org.springframework.shell.core.CommandResult
import org.springframework.shell.core.JLineShellComponent
import scala.xml.XML

class BrokerCommandsTests {

  @Before
  def before = {
    assertTrue(shell.executeCommand("remove-all-queues --force").isSuccess)
    assertTrue(shell.executeCommand("remove-all-topics --force").isSuccess)
  }

  @Test
  def testExportBrokerFileAlreadyExists = {
    val testExportBrokerFileAlreadyExists = File.createTempFile("MessageCommandsTests_testExportBrokerFileAlreadyExists", ".xml")
    try assertEquals(warn(s"File '${testExportBrokerFileAlreadyExists.getCanonicalPath}' already exists"), shell.executeCommand(s"export-broker --file ${testExportBrokerFileAlreadyExists.getAbsolutePath}").getResult)
    finally testExportBrokerFileAlreadyExists.delete
  }

  @Test
  def testAvailabilityIndicators: Unit = {
    assertTrue(shell.executeCommand("disconnect").isSuccess)
    try {
      List("info", "disconnect", "export-broker").map(command ⇒ {
        assertCommandFailed(shell.executeCommand(command))
      })
    } finally {
      assertTrue(shell.executeCommand("connect --broker test").isSuccess)
    }
  }
}

object BrokerCommandsTests {

  val shell = createShell

  @BeforeClass
  def beforeClass() = startAndConnectToEmbeddedBroker(shell)

  @AfterClass
  def afterClass() = stopEmbeddedBroker(shell)
} 
Example 24
Source File: FunctionsAndMethodsUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala.functionsandmethods

import org.junit.Assert.assertEquals
import org.junit.{Before, Test}

import scala.util.Random

class FunctionsAndMethodsUnitTest {
  @Test
  def givenAnonymousFunction_whenPassItToAMethodCall_thenAnonymousFunctionUsage (): Unit = {
    val result1 = FunctionsAndMethods.anonymousFunctionUsage((number: Int) => number + 1)
    val result2 = FunctionsAndMethods.anonymousFunctionUsageWithApply((number: Int) => number + 1)

    assertEquals(result1, result2)
  }

  @Test
  def givenFunction_whenCheckingItsType_thenItIsAFunctionN(): Unit = {
    val functionWithoutParameters = () => Random.nextInt()
    val functionWithOneParameter = (number: Int) => number + 1
    val functionWithTwoParameters = (x: Int, y: Int) => (x + 1, y + 1)

    assert(functionWithoutParameters.isInstanceOf[Function0[Int]])
    assert(functionWithOneParameter.isInstanceOf[Function1[Int, Int]])
    assert(functionWithTwoParameters.isInstanceOf[Function2[Int, Int, (Int, Int)]])
  }

  @Test
  def givenByValueFunction_whenCallIt_thenValuesAreEquals(): Unit = {
    val (firstAccess, secondAccess) = FunctionsAndMethods.byValue(Random.nextInt)
    assert(firstAccess == secondAccess)
  }

  @Test
  def givenByNameFunction_whenCallIt_thenValuesAreDifferent(): Unit = {
    val (firstAccess, secondAccess) = FunctionsAndMethods.byName(Random.nextInt)
    assert(firstAccess != secondAccess)
  }

  @Test
  def givenExtensionMethod_whenImportInContext_thenWeCanUseIt(): Unit = {
    import FunctionsAndMethods._
    assertEquals(true, 10.isOdd)
    assertEquals(false, 11.isOdd)
  }

  @Test
  def givenLine45_whenUseItInAPlot_thenCorrectResults(): Unit = {
    val a45DegreeLine = FunctionsAndMethods.line(1,0)
    val results = FunctionsAndMethods.plot(a45DegreeLine)
    val expected = List(-10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0,
                        0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
    assertEquals(expected, results)
  }

  @Test
  def givenNestedMethod_whenUseIt_thenCorrectResults(): Unit = {
    val factorialResult = FunctionsAndMethods.factorial(10)
    val expected = 3628800;
    assertEquals(expected, factorialResult)
  }

  @Test
  def givenParameterizedMethod_whenUseIt_thenCorrectResults(): Unit = {
    val strings = Seq("a", "b", "c")
    val first = FunctionsAndMethods.pop(strings)
    assertEquals("a", first)

    val ints = Seq(10, 3, 11, 22, 10)
    val second = FunctionsAndMethods.pop(ints)
    assertEquals(10, second)


  }
} 
Example 25
Source File: CaseClasses.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala


import org.junit.Assert.assertEquals
import org.junit.Test

case class CovidCountryStats(countryCode: String, deaths: Int, confirmedCases: Int)

class CaseClassesUnitTest {
  @Test
  def givenCaseClass_whenPatternMatched_thenReturnsProperValue() = {
    val covidPL = CovidCountryStats("PL", 776, 15366)

    val text = covidPL match {
      case CovidCountryStats("PL", x, y) => "Death rate for Poland is " + x.toFloat / y.toFloat
      case _ => "Unknown country"
    }

    assertEquals("Death rate for Poland is 0.05050111", text)
  }

  @Test
  def givenTwoEqualsCaseClasses_whenCheckingEquality_thenReturnsTrue(): Unit = {
    assert(CovidCountryStats("PL", 776, 15366) == CovidCountryStats("PL", 776, 15366))
  }

  @Test
  def givenCaseClass_whenCallingCopy_thenParametersAreCopied(): Unit = {
    val covidPL = CovidCountryStats("PL", 776, 15366)
    val covidUA = covidPL.copy(countryCode = "UA")

    assertEquals("UA", covidUA.countryCode)
    assertEquals(776, covidUA.deaths)
    assertEquals(15366, covidUA.confirmedCases)
  }

  @Test
  def givenTuple_whenCallingApply_thenCreatesNewInstance() = {
    val tuple = ("PL", 776, 15366)
    val covidPL = (CovidCountryStats.apply _).tupled(tuple)

    assertEquals(CovidCountryStats("PL", 776, 15366), covidPL)
  }
} 
Example 26
Source File: UtilsUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala

import com.baeldung.scala.Utils.{average, fibonacci, power, randomLessThan}
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test

class UtilsUnitTest {

  @Test
  def whenAverageCalled_thenCorrectValueReturned(): Unit = {
    assertEquals(15.0, average(10, 20), 1e-5)
  }

  @Test
  def whenRandomLessThanInvokedWithANumber_thenARandomLessThanItReturned: Unit = {
    val d = 0.1
    assertTrue(randomLessThan(d) < d)
  }

  @Test
  def whenPowerInvokedWith2And3_then8Returned: Unit = {
    assertEquals(8, power(2, 3))
  }

  @Test
  def whenFibonacciCalled_thenCorrectValueReturned: Unit = {
    assertEquals(1, fibonacci(0))
    assertEquals(1, fibonacci(1))
    assertEquals(fibonacci(6),
      fibonacci(4) + fibonacci(5))
  }
} 
Example 27
Source File: ScoreUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala.traits

import org.junit.Assert.assertEquals
import org.junit.Test

class ScoreUnitTest {

  @Test
  def givenScore_whenComposeCalled_thenCompositionIsReturned() = {

    val composer = "Hans Zimmer"
    val engineer = "Matt Dunkley"
    val orchestra = "Berlin Philharmonic"
    val mixer = "Dave Stewart"
    val studio = "Abbey Studios"
    val score = new Score(composer, engineer, orchestra, mixer, 10, studio)

    assertEquals(score.compose(),
      s"""The score is composed by $composer,
         |Orchestration by $orchestra,
         |Mixed by $mixer""".stripMargin)
  }

  @Test
  def givenScore_whenProduceCalled_thenSoundProductionIsReturned() = {

    val composer = "Hans Zimmer"
    val engineer = "Matt Dunkley"
    val orchestra = "Berlin Philharmonic"
    val mixer = "Dave Stewart"
    val studio = "Abbey Studios"
    val score = new Score(composer, engineer, orchestra, mixer, 3, studio)

    assertEquals(score.produce(), s"The score is produced by $engineer")
  }

  @Test
  def givenScore_whenLowQualityRatioSet_thenCorrectAlgorithmIsReturned() = {

    val composer = "Hans Zimmer"
    val engineer = "Matt Dunkley"
    val orchestra = "Berlin Philharmonic"
    val mixer = "Dave Stewart"
    val studio = "Abbey Studios"
    val score = new Score(composer, engineer, orchestra, mixer, 1, studio)

    assertEquals(score.algorithm().toString, "Low instrumental quality")
  }

  @Test
  def givenScore_whenHighQualityRatioSet_thenCorrectAlgorithmIsReturned() = {

    val composer = "Hans Zimmer"
    val engineer = "Matt Dunkley"
    val orchestra = "Berlin Philharmonic"
    val mixer = "Dave Stewart"
    val studio = "Abbey Studios"
    val score = new Score(composer, engineer, orchestra, mixer, 10, studio)

    assertEquals(score.algorithm().toString, "High instrumental quality")
  }

  @Test
  def givenScore_whenVocalsMixinAttached_thenSingCanBeCalled() = {

    val composer = "Hans Zimmer"
    val engineer = "Matt Dunkley"
    val orchestra = "Berlin Philharmonic"
    val mixer = "Dave Stewart"
    val studio = "Abbey Studios"
    val score = new Score(composer, engineer, orchestra, mixer, 10, studio) with Vocals

    assertEquals(score.sing, "Vocals mixin")
  }

  @Test
  def givenScore_whenGetStudioCalled_thenStudiosAreReturned() = {

    val composer = "Hans Zimmer"
    val engineer = "Matt Dunkley"
    val orchestra = "Berlin Philharmonic"
    val mixer = "Dave Stewart"
    val studio = "Abbey Studios"
    val score = new Score(composer, engineer, orchestra, mixer, 10, studio)

    assertEquals(
      score.getStudio(),
      s"Composed at studio $studio, Produced at studio $studio"
    )
  }
} 
Example 28
Source File: RegexUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala.regex

import org.junit.Test
import org.junit.Assert.assertEquals

class RegexUnitTest {
  private val polishPostalCode = "([0-9]{2})\\-([0-9]{3})".r
  private val timestamp = "([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{3})".r
  private val timestampUnanchored = timestamp.unanchored

  @Test
  def givenRegularExpression_whenCallingFindFirstIn_thenShouldFindCorrectMatches(): Unit = {
    val postCode = polishPostalCode.findFirstIn("Warsaw 01-011, Jerusalem Avenue")
    assertEquals(Some("01-011"), postCode)
  }

  @Test
  def givenRegularExpression_whenCallingFindFirstMatchIn_thenShouldFindCorrectMatches(): Unit = {
    val postCodes = polishPostalCode.findFirstMatchIn("Warsaw 01-011, Jerusalem Avenue")
    assertEquals(Some("011"), for (m <- postCodes) yield m.group(2))
  }

  @Test
  def givenRegularExpression_whenCallingFindAllIn_thenShouldFindCorrectMatches(): Unit = {
    val postCodes = polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue")
      .toList
    assertEquals(List("01-011", "30-059"), postCodes)

    polishPostalCode.findAllIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue")
  }

  @Test
  def givenRegularExpression_whenCallingFindAlMatchlIn_thenShouldFindCorrectMatches(): Unit = {
    val postCodes = polishPostalCode.findAllMatchIn("Warsaw 01-011, Jerusalem Avenue, Cracow 30-059, Mickiewicza Avenue")
      .toList
    val postalDistricts = for (m <- postCodes) yield m.group(1)
    assertEquals(List("01", "30"), postalDistricts)
  }

  @Test
  def givenRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = {
    val description = "11:34:01.411" match {
      case timestamp(hour, minutes, _, _) => s"It's $minutes minutes after $hour"
    }

    assertEquals("It's 34 minutes after 11", description)
  }

  @Test
  def givenUnanchoredRegularExpression_whenExtractingValues_thenShouldExtractCorrectValues(): Unit = {
    val description = "Timestamp: 11:34:01.411 error appeared" match {
      case timestampUnanchored(hour, minutes, _, _) => s"It's $minutes minutes after $hour"
    }

    assertEquals("It's 34 minutes after 11", description)
  }

  @Test
  def givenRegularExpression_whenCallingReplaceAllIn_thenShouldReplaceText(): Unit = {
    val minutes = timestamp.replaceAllIn("11:34:01.311", m => m.group(2))

    assertEquals("34", minutes)
  }

  @Test
  def givenRegularExpression_whenCallingReplaceAllInWithMatcher_thenShouldReplaceText(): Unit = {
    val secondsThatDayInTotal = timestamp.replaceAllIn("11:34:01.311", _ match {
      case timestamp(hours, minutes, seconds, _) => s"$hours-$minutes"
    })

    assertEquals("11-34", secondsThatDayInTotal)
  }
} 
Example 29
Source File: EmployeeUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala

import org.junit.Assert.assertEquals
import org.junit.Test

class EmployeeUnitTest {

  @Test
  def whenEmployeeSalaryIncremented_thenCorrectSalary() = {
    val employee = new Employee("John Doe", 1000)
    employee.incrementSalary()
    assertEquals(1020, employee.salary)
  }

  @Test
  def givenEmployee_whenToStringCalled_thenCorrectStringReturned() = {
    val employee = new Employee("John Doe", 1000)
    assertEquals("Employee(name=John Doe, salary=1000)", employee.toString)
  }

  @Test
  def givenEmployeeWithTrait_whenToStringCalled_thenCorrectStringReturned() = {
    val employee =
      new Employee("John Doe", 1000) with UpperCasePrinter
    assertEquals("EMPLOYEE(NAME=JOHN DOE, SALARY=1000)", employee.toString)
  }

} 
Example 30
Source File: HigherOrderFunctionsExamplesUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala

import org.junit.Assert.assertEquals
import org.junit.Test


class HigherOrderFunctionsExamplesUnitTest {

  @Test
  def whenCallingMapWithAnonymousFunction_thenTransformationIsApplied() = {
    val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard")

    val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard")
    val sirNames = names.map(name => "sir " + name)

    assertEquals(expected, sirNames)
  }

  @Test
  def whenCallingMapWithDefined_thenTransformationIsApplied() = {
    val expected = Seq("sir Alex Ferguson", "sir Bobby Charlton", "sir Frank Lampard")

    val names = Seq("Alex Ferguson", "Bobby Charlton", "Frank Lampard")

    def prefixWithSir(name: String) = "sir " + name
    val sirNames = names.map(prefixWithSir)

    assertEquals(expected, sirNames)
  }

  @Test
  def whenCallingFilter_thenUnecessaryElementsAreRemoved() = {
    val expected = Seq("John O'Shea", "John Hartson")

    val names = Seq("John O'Shea", "Aiden McGeady", "John Hartson")
    val johns = names.filter(name => name.matches("^John .*"))

    assertEquals(expected, johns)
  }

  @Test
  def whenCallingReduce_thenProperSumIsCalculated() = {
    val expected = 2750

    val earnings = Seq(1000, 1300, 450)
    val sumEarnings = earnings.reduce((acc, x) => acc + x)

    assertEquals(expected, sumEarnings)
  }

  @Test
  def whenCallingFold_thenNumberOfWordsShouldBeCalculated() = {
    val expected = 6

    val strings = Seq("bunch of words", "just me", "it")
    val sumEarnings = strings.foldLeft(0)((acc, x) => acc + x.split(" ").size)

    assertEquals(expected, sumEarnings)
  }

  @Test
  def whenCallingOwnHigherOrderFunction_thenProperFunctionIsReturned() = {
    def mathOperation(name: String): (Int, Int) => Int = (x: Int, y: Int) => {
      name match {
        case "addition" => x + y
        case "multiplication" => x * y
        case "division" => x/y
        case "subtraction" => x - y
      }
    }

    def add: (Int, Int) => Int = mathOperation("addition")
    def mul: (Int, Int) => Int = mathOperation("multiplication")
    def div: (Int, Int) => Int = mathOperation("division")
    def sub: (Int, Int) => Int = mathOperation("subtraction")

    assertEquals(15, add(10, 5))
    assertEquals(50, mul(10, 5))
    assertEquals(2, div(10, 5))
    assertEquals(5, sub(10, 5))
  }
} 
Example 31
Source File: HigherOrderFunctionsUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala

import com.baeldung.scala.HigherOrderFunctions.mapReduce
import org.junit.Assert.assertEquals
import org.junit.Test

class HigherOrderFunctionsUnitTest {

  @Test
  def whenCalledWithSumAndSquareFunctions_thenCorrectValueReturned() = {
    def square(x : Int) = x * x

    def sum(x : Int, y : Int) = x + y

    def sumSquares(a : Int, b : Int) =
      mapReduce(sum, 0, square, a, b)

    assertEquals(385, sumSquares(1, 10))
  }

  @Test
  def whenComputingSumOfSquaresWithAnonymousFunctions_thenCorrectValueReturned() = {
    def sumSquares(a : Int, b : Int) =
      mapReduce((x, y) => x + y, 0, x => x * x, a, b)

    assertEquals(385, sumSquares(1, 10))
  }

  @Test
  def givenCurriedFunctions_whenInvoked_thenCorrectValueReturned() = {
    // a curried function
    def sum(f : Int => Int)(a : Int,
                            b : Int) : Int =
      if (a > b) 0 else f(a) + sum(f)(a + 1, b)

    // another curried function
    def mod(n : Int)(x : Int) = x % n

    // application of a curried function
    assertEquals(1, mod(5)(6))

    // partial application of curried function
    // trailing underscore is required to make function type explicit
    val sumMod5 = sum(mod(5)) _

    assertEquals(10, sumMod5(6, 10))
  }
} 
Example 32
Source File: ControlStructuresDemoUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala

import com.baeldung.scala.ControlStructuresDemo._
import org.junit.Assert.assertEquals
import org.junit.Test

class ControlStructuresDemoUnitTest {
  @Test
  def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned() = {
    assertEquals(3, gcd(15, 27))
  }

  @Test
  def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned() = {
    assertEquals(3, gcdIter(15, 27))
  }

  @Test
  def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned() = {
    assertEquals(55, rangeSum(1, 10))
  }

  @Test
  def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned() = {
    assertEquals(720, factorial(6))
  }

  @Test
  def whenFactorialOf0Invoked_then1Returned() = {
    assertEquals(1, factorial(0))
  }

} 
Example 33
Source File: FingersOperationUnitTest.scala    From scala-tutorials   with MIT License 5 votes vote down vote up
package com.baeldung.scala.enumerations

import com.baeldung.scala.enumerations.Fingers._
import org.junit.Assert.assertTrue
import org.junit.Assert.assertFalse
import org.junit.Assert.assertEquals
import org.junit.Test

class FingersOperationUnitTest {

  @Test
  def givenAFinger_whenIsShortestCalled_thenCorrectValueReturned() = {
    val operation = new FingersOperation()

    assertTrue(operation.isShortest(Little))
    assertFalse(operation.isShortest(Index))
  }

  @Test
  def givenFingers_whenTwoLongestCalled_thenCorrectValuesReturned() = {
    val operation = new FingersOperation()

    assertEquals(List(Index, Middle), operation.twoLongest())
  }

  @Test
  def givenStringValueOfFinger_whenWithNameCalled_thenCorrectValueReturned() = {
    assertEquals(Middle, Fingers.withName("The Middle Finger"))
  }

  @Test
  def givenAFinger_whenIdAndtoStringCalled_thenCorrectValueReturned() = {
    assertEquals(6, Thumb.id)
    assertEquals("Shorty Finger", Little.toString())
  }

  @Test
  def givenFingers_whenValuesCalled_thenOrderedValuesReturned() = {
    assertEquals(List(Index, Middle, Ring, Little, Thumb), Fingers.values.toList)
  }
} 
Example 34
Source File: TestScalarFunctionGenerator.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.compiler.scala

import com.amazon.milan.program.{ApplyFunction, CreateInstance, FunctionDef, FunctionReference, SelectField, SelectTerm, TypeChecker, Unpack, ValueDef}
import com.amazon.milan.typeutil.{TypeDescriptor, createTypeDescriptor, types}
import org.junit.Assert.assertEquals
import org.junit.Test


object TestScalarFunctionGenerator {

  case class IntRecord(i: Int)

}

import com.amazon.milan.compiler.scala.TestScalarFunctionGenerator._


@Test
class TestScalarFunctionGenerator {
  @Test
  def test_ScalarFunctionGenerator_WithTwoObjectInputs_ReturnsExpectedCode(): Unit = {
    val input1 = TypeDescriptor.of[IntRecord]
    val input2 = TypeDescriptor.of[IntRecord]
    val tree = FunctionDef(
      List(ValueDef("a", input1), ValueDef("b", input2)),
      ApplyFunction(
        FunctionReference("FakeType", "fakeFunction"),
        List(SelectField(SelectTerm("a"), "i"), SelectField(SelectTerm("b"), "i")),
        types.String))

    val code = ScalarFunctionGenerator.default.getScalaAnonymousFunction(tree)
    val expectedCode = "(a: com.amazon.milan.compiler.scala.TestScalarFunctionGenerator.IntRecord, b: com.amazon.milan.compiler.scala.TestScalarFunctionGenerator.IntRecord) => FakeType.fakeFunction(a.i, b.i)"
    assertEquals(expectedCode, code)
  }

  @Test
  def test_ScalarFunctionGenerator_WithCreateInstance_ReturnsExpectedCode(): Unit = {
    val tree = FunctionDef(
      List(ValueDef("r", TypeDescriptor.of[IntRecord])),
      CreateInstance(createTypeDescriptor[IntRecord], List(SelectField(SelectTerm("r"), "i"))))

    val code = ScalarFunctionGenerator.default.getScalaAnonymousFunction(tree)
    val expectedCode = "(r: com.amazon.milan.compiler.scala.TestScalarFunctionGenerator.IntRecord) => new com.amazon.milan.compiler.scala.TestScalarFunctionGenerator.IntRecord(r.i)"
    assertEquals(expectedCode, code)
  }

  @Test
  def test_ScalarFunctionGenerator_WithUnpackOfTuple_ReturnsCodeUsingMatchStatement(): Unit = {
    val inputType = TypeDescriptor.createTuple[(Int, String)](List(types.Int, types.String))
    val tree = FunctionDef(List(ValueDef("t", inputType)), Unpack(SelectTerm("t"), List("i", "s"), SelectTerm("i")))
    TypeChecker.typeCheck(tree)

    val code = ScalarFunctionGenerator.default.getScalaAnonymousFunction(tree)
    val expectedCode = "(t: Tuple2[Int, String]) => t match { case (i, s) => i }"
    assertEquals(expectedCode, code)
  }
} 
Example 35
Source File: KvStreamingTest.scala    From spark-riak-connector   with Apache License 2.0 5 votes vote down vote up
package com.basho.riak.spark.streaming

import java.nio.ByteBuffer
import java.util.concurrent._

import com.basho.riak.spark._
import com.basho.riak.spark.rdd.{AbstractRiakSparkTest, RiakTSTests}
import org.junit.Assert.assertEquals
import org.junit.experimental.categories.Category
import org.junit.{After, Before, Test}

@Category(Array(classOf[RiakTSTests]))
class KvStreamingTest extends AbstractRiakSparkTest with SparkStreamingFixture {

  protected final val VALUES_NUMBER = 5

  protected final val executorService = Executors.newCachedThreadPool()
  private val dataSource = new SocketStreamingDataSource
  private var port = -1

  @Before
  def setUp(): Unit = {
    port = dataSource.start(client => {
      (0 until VALUES_NUMBER).foreach(i => client.write(ByteBuffer.wrap(s"value-$i\n".getBytes)))
      logInfo(s"$VALUES_NUMBER values were send to client")
    })
  }

  @After
  def tearDown(): Unit = {
    dataSource.stop()
  }

  @Test(timeout = 10 * 1000) // 10 seconds timeout
  def saveToRiak(): Unit = {
    executorService.submit(new Runnable {
      override def run(): Unit = {
        ssc.socketTextStream("localhost", port)
          .saveToRiak(DEFAULT_NAMESPACE_4STORE.getBucketNameAsString)

        ssc.start()
        ssc.awaitTerminationOrTimeout(5 * 1000)
      }
    })

    val data: List[(String, Any)] = executorService.submit(new Callable[List[(String, Any)]] {
      override def call(): List[(String, Any)] = {
        var rdd = sc.riakBucket(DEFAULT_NAMESPACE_4STORE).queryAll()
        var count = rdd.count()
        while (count < VALUES_NUMBER) {
          TimeUnit.SECONDS.sleep(2)

          rdd = sc.riakBucket(DEFAULT_NAMESPACE_4STORE).queryAll()
          count = rdd.count()
        }
        rdd.collect().toList
      }
    }).get()

    assertEquals(VALUES_NUMBER, data.length)
    assertEqualsUsingJSONIgnoreOrder(
      """[
        | ['${json-unit.ignore}', 'value-0'],
        | ['${json-unit.ignore}', 'value-1'],
        | ['${json-unit.ignore}', 'value-2'],
        | ['${json-unit.ignore}', 'value-3'],
        | ['${json-unit.ignore}', 'value-4']
        | ]""".stripMargin, data)
  }
} 
Example 36
Source File: RiakCoveragePlanBasedPartitionerTest.scala    From spark-riak-connector   with Apache License 2.0 5 votes vote down vote up
package com.basho.riak.spark.rdd.partitioner

import com.basho.riak.spark.rdd.{ReadConf, RiakRDD}
import org.junit.{Ignore, Test}
import org.junit.Assert.assertEquals

class RiakCoveragePlanBasedPartitionerTest extends AbstractCoveragePlanBasedPartitionerTest {
  val defaultNumberOfSparkExecutors = 3

  @Test
  def smartSplitShouldBeUsedByDefault(): Unit = {
    mockKVCoveragePlan(
      ("h1", 1),
      ("h1", 2),
      ("h2", 3),
      ("h2", 4),
      ("h3", 5),
      ("h3", 6),
      ("h3", 7),
      ("h4", 8),
      ("h4", 9)
    )

    mockSparkExecutorsNumber(defaultNumberOfSparkExecutors)
    val rdd = new RiakRDD(sc, rc, "default", "test").queryAll()
    val partitions = rdd.partitions

    assertEquals(ReadConf.smartSplitMultiplier * defaultNumberOfSparkExecutors, partitions.length)

    assertEqualsUsingJSONIgnoreOrder("""[
        | {index: '${json-unit.ignore}', primaryHost: 'h4:0', queryData: {entries:[
        |     {host: 'h4:0', description: '8'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h3:0', queryData: {entries:[
        |     {host: 'h3:0', description: '6'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h1:0', queryData: {entries:[
        |     {host: 'h1:0', description: '1'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h3:0', queryData: {entries:[
        |     {host: 'h3:0', description: '7'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h2:0', queryData: {entries:[
        |     {host: 'h2:0', description: '4'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h1:0', queryData: {entries:[
        |     {host: 'h1:0', description: '2'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: "h3:0", queryData: {entries:[
        |     {host: 'h3:0', description: '5'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h4:0', queryData: {entries:[
        |     {host: 'h4:0', description: '9'}]}},
        |
        | {index: '${json-unit.ignore}', primaryHost: 'h2:0', queryData:{entries:[
        |     {host: 'h2:0', description: '3'}]}}
        |
      ]""".stripMargin,
      partitions
    )
  }

  @Test
  def explicitlySpecifiedSplitCountShouldOverrideDefaultOne(): Unit = {

    mockKVCoveragePlan(
      ("h1", 1),
      ("h1", 2),
      ("h2", 3),
      ("h2", 4),
      ("h3", 5),
      ("h3", 6),
      ("h3", 7),
      ("h4", 8),
      ("h4", 9)
    )

    mockSparkExecutorsNumber(defaultNumberOfSparkExecutors)
    val requestedSplit = 5
    val rdd = new RiakRDD(sc, rc, "default", "test", None, ReadConf(_splitCount=Some(requestedSplit))).queryAll()
    val partitions = rdd.partitions

    assertEquals(requestedSplit, partitions.length)
    assertEqualsUsingJSONIgnoreOrder("""[
        | {index: '${json-unit.ignore}', primaryHost: 'h2:0', queryData:{entries:[
        |     {host: 'h2:0', description: '3'},
        |     {host: 'h2:0', description: '4'}]}},
        | {index: '${json-unit.ignore}', primaryHost: 'h3:0', queryData:{entries:[
        |     {host: 'h3:0', description: '6'},
        |     {host: 'h3:0', description: '7'}]}},
        | {index: '${json-unit.ignore}', primaryHost: 'h4:0', queryData:{entries:[
        |     {host: 'h4:0', description: '8'},
        |     {host: 'h4:0', description: '9'}]}},
        | {index:'${json-unit.ignore}', primaryHost: 'h3:0', queryData:{entries:[
        |     {host: 'h3:0', description: '5'}]}},
        | {index:'${json-unit.ignore}', primaryHost: 'h1:0', queryData:{entries:[
        |     {host: 'h1:0', description: '1'},
        |     {host: 'h1:0', description: '2'}]}}]
        |]""".stripMargin, partitions)
  }
} 
Example 37
Source File: SeqDecoratorTest.scala    From scala-collection-contrib   with Apache License 2.0 5 votes vote down vote up
package scala.collection
package decorators

import org.junit.Assert.assertEquals
import org.junit.Test
import scala.collection.immutable._

class SeqDecoratorTest {

  @Test def intersperse(): Unit = {
    assertEquals(List(1, 0, 2, 0, 3), List(1, 2, 3).intersperse(0))
    assertEquals(List(-1, 1, 0, 2, 0, 3, -2), List(1, 2, 3).intersperse(-1, 0, -2))
    assertEquals(List.empty[Int], List.empty[Int].intersperse(0))
    assertEquals(List(1, 2), List.empty[Int].intersperse(1, 0, 2))
    assertEquals(List(1), List(1).intersperse(0))
    assertEquals(List(0, 1, 2), List(1).intersperse(0, 5, 2))
  }

  // This test just checks that there is no compilation error
  @Test def genericDecorator(): Unit = {
    val vector = Vector(1, 2, 3)
    val range = Range(0, 10)
    val array = Array(1, 2, 3)
    val string = "foo"
    val list = List(1, 2, 3)
    val result = list.intersperse(0)
    typed[List[Int]](result)
    list.view.intersperse(0)
    val result2 = range.intersperse(0)
    typed[IndexedSeq[Int]](result2)
    vector.intersperse(0)
    vector.view.intersperse(0)
    val result3 = array.intersperse(0)
    typed[Array[Int]](result3)
    array.view.intersperse(0)
    string.intersperse(' ')
    string.view.intersperse(' ')
  }

  def typed[T](t: => T): Unit = ()

  @Test def testReplaced(): Unit = {
    val s = Seq(1, 2, 3, 2, 1)
    assertEquals(s.replaced(2, 4), Seq(1, 4, 3, 4, 1))
    assertEquals(s.replaced(3, 4), Seq(1, 2, 4, 2, 1))
    assertEquals(s.replaced(4, 4), s)
  }
} 
Example 38
Source File: SigProofTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen

import java.io.{BufferedReader, File, FileReader}
import java.util.Optional
import java.{lang, util}

import com.horizen.box.WithdrawalRequestBox
import com.horizen.box.data.WithdrawalRequestBoxData
import com.horizen.cryptolibprovider.{SchnorrFunctionsImplZendoo, ThresholdSignatureCircuitImplZendoo}
import com.horizen.proposition.MCPublicKeyHashProposition
import com.horizen.schnorrnative.SchnorrSecretKey
import com.horizen.utils.BytesUtils
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.{Ignore, Test}

import scala.collection.JavaConverters._
import scala.util.Random

class SigProofTest {
  private val classLoader: ClassLoader = getClass.getClassLoader
  private val sigCircuit: ThresholdSignatureCircuitImplZendoo = new ThresholdSignatureCircuitImplZendoo()
  private val schnorrFunctions: SchnorrFunctionsImplZendoo = new SchnorrFunctionsImplZendoo()

  private def buildSchnorrPrivateKey(index: Int): SchnorrSecretKey = {
    var bytes: Array[Byte] = null
    try {
      val resourceName = "schnorr_sk0"+ index + "_hex"
      val file = new FileReader(classLoader.getResource(resourceName).getFile)
      bytes = BytesUtils.fromHexString(new BufferedReader(file).readLine())
    }
    catch {
      case e: Exception =>
        assertEquals(e.toString(), true, false)
    }

    SchnorrSecretKey.deserialize(bytes)
  }

  //Test will take around 2 minutes, enable for sanity checking of ThresholdSignatureCircuit
  @Ignore
  @Test
  def simpleCheck(): Unit = {
    val keyPairsLen = 7
    val threshold = 5 //hardcoded value

    val keyPairs = (0 until keyPairsLen).view.map(buildSchnorrPrivateKey).map(secret => (secret, secret.getPublicKey))
    val publicKeysBytes: util.List[Array[Byte]] = keyPairs.map(_._2.serializePublicKey()).toList.asJava
    val provingKeyPath = new File(classLoader.getResource("sample_proving_key_7_keys_with_threshold_5").getFile).getAbsolutePath;
    val verificationKeyPath = new File(classLoader.getResource("sample_vk_7_keys_with_threshold_5").getFile).getAbsolutePath;

    val sysConstant = sigCircuit.generateSysDataConstant(publicKeysBytes, threshold)

    val mcBlockHash = Array.fill(32)(Random.nextInt().toByte)
    val previousMcBlockHash = Array.fill(32)(Random.nextInt().toByte)

    val wb: util.List[WithdrawalRequestBox] = Seq(new WithdrawalRequestBox(new WithdrawalRequestBoxData(new MCPublicKeyHashProposition(Array.fill(20)(Random.nextInt().toByte)), 2345), 42)).asJava

    val messageToBeSigned = sigCircuit.generateMessageToBeSigned(wb, mcBlockHash, previousMcBlockHash)

    val emptySigs = List.fill[Optional[Array[Byte]]](keyPairsLen - threshold)(Optional.empty[Array[Byte]]())
    val signatures: util.List[Optional[Array[Byte]]] = (keyPairs
      .map{case (secret, public) => schnorrFunctions.sign(secret.serializeSecretKey(), public.serializePublicKey(), messageToBeSigned)}
      .map(b => Optional.of(b))
      .take(threshold)
      .toList ++ emptySigs)
      .asJava

    val proofAndQuality: utils.Pair[Array[Byte], lang.Long] = sigCircuit.createProof(wb, mcBlockHash, previousMcBlockHash, publicKeysBytes, signatures, threshold, provingKeyPath)

    val result = sigCircuit.verifyProof(wb, mcBlockHash, previousMcBlockHash, proofAndQuality.getValue, proofAndQuality.getKey, sysConstant, verificationKeyPath)

    assertTrue("Proof verification expected to be successfully", result)
  }

} 
Example 39
Source File: VrfFunctionsTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.vrf

import java.util

import com.horizen.cryptolibprovider.VrfFunctions.{KeyType, ProofType}
import com.horizen.cryptolibprovider.{FieldElementUtils, CryptoLibProvider}
import org.junit.Assert.{assertEquals, assertFalse, assertNotEquals, assertTrue}
import org.junit.Test

import scala.util.Random


class VrfFunctionsTest {
  val keys: util.EnumMap[KeyType, Array[Byte]] = CryptoLibProvider.vrfFunctions.generatePublicAndSecretKeys(1.toString.getBytes())
  val secretBytes: Array[Byte] = keys.get(KeyType.SECRET)
  val publicBytes: Array[Byte] = keys.get(KeyType.PUBLIC)
  val message: Array[Byte] = "Very secret message!".getBytes
  val vrfProofBytes: Array[Byte] = CryptoLibProvider.vrfFunctions.createProof(secretBytes, publicBytes, message).get(ProofType.VRF_PROOF)
  val vrfProofCheck: Boolean = CryptoLibProvider.vrfFunctions.verifyProof(message, publicBytes, vrfProofBytes)
  val vrfOutputBytes: Array[Byte] = CryptoLibProvider.vrfFunctions.proofToOutput(publicBytes, message, vrfProofBytes).get()

  @Test
  def sanityCheck(): Unit = {
    assertNotEquals(vrfProofBytes.deep, vrfOutputBytes.deep)
    assertTrue(CryptoLibProvider.vrfFunctions.publicKeyIsValid(publicBytes))
    assertTrue(vrfProofCheck)
    assertTrue(vrfOutputBytes.nonEmpty)
  }


  @Test
  def determinismCheck(): Unit = {
    //@TODO add seed check here as it became supported
    val rnd = new Random()

    for (i <- 1 to 10) {
      val messageLen = rnd.nextInt(128) % FieldElementUtils.maximumFieldElementLength()
      val newMessage = rnd.nextString(rnd.nextInt(128)).getBytes.take(messageLen)
      val firstVrfProofBytes = CryptoLibProvider.vrfFunctions.createProof(secretBytes, publicBytes, newMessage).get(ProofType.VRF_PROOF)
      val secondVrfProofBytes = CryptoLibProvider.vrfFunctions.createProof(secretBytes, publicBytes, newMessage).get(ProofType.VRF_PROOF)
      //@TODO uncomment this ASAP after proof generation became deterministic
      //assertEquals(vrfProofBytes.deep, otherVrfProofBytes.deep)

      val firstVrfOutputBytes = CryptoLibProvider.vrfFunctions.proofToOutput(publicBytes, newMessage, firstVrfProofBytes).get
      val secondVrfOutputBytes = CryptoLibProvider.vrfFunctions.proofToOutput(publicBytes, newMessage, secondVrfProofBytes).get

      assertEquals(firstVrfOutputBytes.deep, secondVrfOutputBytes.deep)
      println(s"Vrf output determinism check: iteration ${i}, for message len ${newMessage.length}")
    }
  }

  @Test()
  def tryToCorruptProof(): Unit= {
    val corruptedMessage: Array[Byte] = "Not very secret message!".getBytes
    val vrfProofCheckCorruptedMessage = CryptoLibProvider.vrfFunctions.verifyProof(corruptedMessage, publicBytes, vrfProofBytes)
    assertFalse(vrfProofCheckCorruptedMessage)

    val corruptedProofBytes: Array[Byte] = util.Arrays.copyOf(vrfProofBytes, vrfProofBytes.length)
    corruptedProofBytes(0) = (~corruptedProofBytes(0)).toByte
    val vrfProofCheckCorruptedVrfProof = CryptoLibProvider.vrfFunctions.verifyProof(message, publicBytes, corruptedProofBytes)
    assertFalse(vrfProofCheckCorruptedVrfProof)

    val corruptedPublicBytes: Array[Byte] = util.Arrays.copyOf(publicBytes, publicBytes.length)
    corruptedPublicBytes(0) = (~corruptedPublicBytes(0)).toByte
    val vrfProofCheckCorruptedPublicBytes = CryptoLibProvider.vrfFunctions.verifyProof(message, corruptedPublicBytes, vrfProofBytes)
    assertFalse(vrfProofCheckCorruptedPublicBytes)
  }

} 
Example 40
Source File: ForgerBoxMerklePathInfoTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.validation

import java.io.{BufferedReader, BufferedWriter, FileReader, FileWriter}
import java.lang.{Byte => JByte}
import java.util
import java.util.{ArrayList => JArrayList}

import com.horizen.box.ForgerBox
import com.horizen.fixtures.BoxFixture
import com.horizen.utils.{BytesUtils, ForgerBoxMerklePathInfo, ForgerBoxMerklePathInfoSerializer, MerklePath, Pair}
import com.horizen.vrf.VrfGeneratedDataProvider
import org.junit.Assert.{assertEquals, assertNotEquals, assertTrue}
import org.junit.Test
import org.scalatest.junit.JUnitSuite

class ForgerBoxMerklePathInfoTest extends JUnitSuite with BoxFixture {
  val vrfGenerationSeed = 907
  val vrfGenerationPrefix = "ForgerBoxMerklePathInfoTest"

  //uncomment if you want update vrf related data
  if (false) {
    VrfGeneratedDataProvider.updateVrfPublicKey(vrfGenerationPrefix, vrfGenerationSeed)
  }

  val forgerBox: ForgerBox = getForgerBox(
    getPrivateKey25519("123".getBytes()).publicImage(),
    1000L,
    100L,
    getPrivateKey25519("456".getBytes()).publicImage(),
    VrfGeneratedDataProvider.getVrfPublicKey(vrfGenerationPrefix, vrfGenerationSeed)
  )
  val emptyMerklePath: MerklePath = new MerklePath(new JArrayList())

  val nonEmptyMerklePath: MerklePath = new MerklePath(util.Arrays.asList(
    new Pair[JByte, Array[Byte]](0.toByte, BytesUtils.fromHexString("29d000eee85f08b6482026be2d92d081d6f9418346e6b2e9fe2e9b985f24ed1e")),
    new Pair[JByte, Array[Byte]](1.toByte, BytesUtils.fromHexString("61bfbdf7038dc7f21e2bcf193faef8e6caa8222af016a6ed86b9e9d860f046df"))
  ))

  @Test
  def comparison(): Unit = {
    assertNotEquals("Box merkle path info expected to be different.", emptyMerklePath, nonEmptyMerklePath)
  }

  @Test
  def serialization(): Unit = {
    // Test 1: empty merkle path (single element in merkle tree)
    val boxWithEmptyPath = ForgerBoxMerklePathInfo(forgerBox, emptyMerklePath)
    var boxBytes = boxWithEmptyPath.bytes
    var deserializedBox = ForgerBoxMerklePathInfoSerializer.parseBytes(boxBytes)
    assertEquals("Deserialized box merkle path info hashCode expected to be equal to the original one.", boxWithEmptyPath.hashCode(), deserializedBox.hashCode())
    assertEquals("Deserialized box merkle path info expected to be equal to the original one.", boxWithEmptyPath, deserializedBox)


    // Test 2: non empty merkle path
    val boxWithNonEmptyPath = ForgerBoxMerklePathInfo(forgerBox, nonEmptyMerklePath)
    boxBytes = boxWithNonEmptyPath.bytes
    deserializedBox = ForgerBoxMerklePathInfoSerializer.parseBytes(boxBytes)
    assertEquals("Deserialized box merkle path info hashCode expected to be equal to the original one.", boxWithNonEmptyPath.hashCode(), deserializedBox.hashCode())
    assertEquals("Deserialized box merkle path info expected to be equal to the original one.", boxWithNonEmptyPath, deserializedBox)

    // Set to true and run if you want to update regression data.
    if (false) {
      val out = new BufferedWriter(new FileWriter("src/test/resources/boxmerklepathinfo_hex"))
      out.write(BytesUtils.toHexString(boxBytes))
      out.close()
    }

    // Test 3: try to deserialize broken bytes.
    assertTrue("ForgerBoxMerklePathInfo expected to be not parsed due to broken data.", ForgerBoxMerklePathInfoSerializer.parseBytesTry("broken bytes".getBytes).isFailure)
  }

  @Test
  def serializationRegression(): Unit = {
    var bytes: Array[Byte] = null
    try {
      val classLoader = getClass.getClassLoader
      val file = new FileReader(classLoader.getResource("boxmerklepathinfo_hex").getFile)
      bytes = BytesUtils.fromHexString(new BufferedReader(file).readLine())
    }
    catch {
      case e: Exception =>
        fail(e.toString)
    }

    val boxMerklePathInfoTry = ForgerBoxMerklePathInfoSerializer.parseBytesTry(bytes)
    assertTrue("ForgerBoxMerklePathInfo expected to by parsed.", boxMerklePathInfoTry.isSuccess)

    val boxWithNonEmptyPath = ForgerBoxMerklePathInfo(forgerBox, nonEmptyMerklePath)
    assertEquals("Parsed info is different to original.", boxWithNonEmptyPath, boxMerklePathInfoTry.get)
  }
} 
Example 41
Source File: ForgingBoxesInfoStorageTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.integration.storage

import com.horizen.SidechainTypes
import com.horizen.consensus.ConsensusEpochNumber
import com.horizen.fixtures.{BoxFixture, IODBStoreFixture}
import com.horizen.storage.{ForgingBoxesInfoStorage, IODBStoreAdapter}
import com.horizen.utils.{BytesUtils, ForgerBoxMerklePathInfo, MerklePath}
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test
import org.scalatest.junit.JUnitSuite
import java.util.{ArrayList => JArrayList}

import com.horizen.box.ForgerBox


class ForgingBoxesInfoStorageTest extends JUnitSuite with IODBStoreFixture with SidechainTypes with BoxFixture {

  @Test
  def mainWorkflow(): Unit = {
    val forgingBoxesMerklePathStorage = new ForgingBoxesInfoStorage(new IODBStoreAdapter(getStore()))

    val updateVersion = getVersion
    val forgerBox = getForgerBox
    val forgerBoxesToAppend: Seq[ForgerBox] = Seq(forgerBox)

    // Test rollback versions of empty storage
    assertTrue("lastVersionId must be empty for empty storage.",
      forgingBoxesMerklePathStorage.lastVersionId.isEmpty)
    assertEquals("Storage must not contain versions.",
      0, forgingBoxesMerklePathStorage.rollbackVersions.size)

    // Test updateForgerBoxes operation (empty storage).
    assertTrue("updateForgerBoxes must be successful.",
      forgingBoxesMerklePathStorage.updateForgerBoxes(updateVersion, forgerBoxesToAppend, Seq()).isSuccess)
    assertEquals("Different ForgerBox seq expected.", forgerBoxesToAppend, forgingBoxesMerklePathStorage.getForgerBoxes.get)

    // Test updateForgerBoxMerklePathInfo operation.
    val epochNumber = ConsensusEpochNumber @@ 2
    val boxMerklePathInfoSeq = Seq(
      ForgerBoxMerklePathInfo(
        forgerBox,
        new MerklePath(new JArrayList())
      )
    )
    assertTrue("updateForgerBoxMerklePathInfo must be successful.", forgingBoxesMerklePathStorage.updateForgerBoxMerklePathInfo(epochNumber, boxMerklePathInfoSeq).isSuccess)

    // Test retrieving of merkle path info seq for EXISTING epoch
    forgingBoxesMerklePathStorage.getForgerBoxMerklePathInfoForEpoch(epochNumber) match {
      case Some(merklePathInfoSeq) => assertEquals("MerklePathInfoSeq expected to be equal to the original one.", boxMerklePathInfoSeq, merklePathInfoSeq)
      case None => fail(s"MerklePathInfoSeq expected to be present in storage for epoch $epochNumber.")
    }

    // Test retrieving of merkle path info seq for MISSED epoch
    val missedEpochNumber = ConsensusEpochNumber @@ 3
    assertTrue(s"MerklePathInfoSeq expected to be NOT present in storage for epoch $missedEpochNumber.",
      forgingBoxesMerklePathStorage.getForgerBoxMerklePathInfoForEpoch(missedEpochNumber).isEmpty)


    // Test rollback operation
    assertTrue("Rollback operation must be successful.", forgingBoxesMerklePathStorage.rollback(updateVersion).isSuccess)
    assertEquals("Version in storage must be - " + updateVersion, updateVersion, forgingBoxesMerklePathStorage.lastVersionId.get)
    assertEquals("Storage must contain 1 version.", 1, forgingBoxesMerklePathStorage.rollbackVersions.size)
    assertTrue(s"MerklePathInfoSeq expected to be NOT present in storage for epoch $epochNumber.",
      forgingBoxesMerklePathStorage.getForgerBoxMerklePathInfoForEpoch(epochNumber).isEmpty)
  }

  @Test
  def updateForgerBoxes(): Unit = {
    val forgingBoxesMerklePathStorage = new ForgingBoxesInfoStorage(new IODBStoreAdapter(getStore()))

    // Test 1: Update empty storage with 3 new forger boxes
    val version1 = getVersion
    val forgerBox1 = getForgerBox
    val forgerBox2 = getForgerBox
    val forgerBox3 = getForgerBox
    val forgerBoxesToAppend: Seq[ForgerBox] = Seq(forgerBox1, forgerBox2, forgerBox3)

    assertTrue("updateForgerBoxes must be successful.",
      forgingBoxesMerklePathStorage.updateForgerBoxes(version1, forgerBoxesToAppend, Seq()).isSuccess)
    assertEquals("Different ForgerBox seq expected.", forgerBoxesToAppend, forgingBoxesMerklePathStorage.getForgerBoxes.get)


    // Test 2: Update non empty storage with 2 new forger boxes and 2 boxes to remove
    val version2 = getVersion
    val forgerBox4 = getForgerBox
    val forgerBox5 = getForgerBox

    assertTrue("updateForgerBoxes must be successful.",
      forgingBoxesMerklePathStorage.updateForgerBoxes(version2, Seq(forgerBox4, forgerBox5), Seq(forgerBox1.id(), forgerBox3.id())).isSuccess)
    assertEquals("Different ForgerBox seq expected.", Seq(forgerBox2, forgerBox4, forgerBox5), forgingBoxesMerklePathStorage.getForgerBoxes.get)
  }
} 
Example 42
Source File: ApplicationApiRouteTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.api.http

import akka.http.scaladsl.model.{ContentTypes, StatusCodes}
import akka.http.scaladsl.server.Route
import org.junit.Assert.{assertEquals, assertTrue}
import scala.collection.JavaConverters._

class ApplicationApiRouteTest extends SidechainApiRouteTest {

  override val basePath = "/simpleApi/"

  "The Api should to" should {

    "reject and reply with http error" in {

      Get(basePath) ~> Route.seal(applicationApiRoute) ~> check {
        status.intValue() shouldBe StatusCodes.NotFound.intValue
        responseEntity.getContentType() shouldEqual ContentTypes.`application/json`
      }
    }

    "reply at /allSecrets" in {

      Post(basePath + "allSecrets") ~> applicationApiRoute ~> check {
        status.intValue() shouldBe StatusCodes.OK.intValue
        responseEntity.getContentType() shouldEqual ContentTypes.`application/json`
        mapper.readTree(entityAs[String]).get("result") match {
          case result =>
            assertEquals(1, result.elements().asScala.length)
            assertTrue(result.get("secrets").isArray)
            assertEquals(2, result.get("secrets").elements().asScala.length)
            result.get("secrets").elements().asScala.toList.foreach(node => {
              assertTrue(node.isObject)
              assertEquals(0, node.elements().asScala.length)
            })
          case _ => fail("Serialization failed for object SidechainApiResponseBody")
        }
      }

      sidechainApiMockConfiguration.setShould_nodeViewHolder_GetDataFromCurrentSidechainNodeView_reply(false)
      Post(basePath + "allSecrets") ~> applicationApiRoute ~> check {
        status.intValue() shouldBe StatusCodes.OK.intValue
        responseEntity.getContentType() shouldEqual ContentTypes.`application/json`
        assertsOnSidechainErrorResponseSchema(entityAs[String], new ErrorAllSecrets("", None).code())
      }
    }
  }
} 
Example 43
Source File: SidechainSyncInfoTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen

import java.io._

import com.horizen.fixtures.SidechainBlockInfoFixture
import com.horizen.utils.BytesUtils
import org.scalatest.junit.JUnitSuite
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test
import scorex.util.ModifierId

class SidechainSyncInfoTest extends JUnitSuite with SidechainBlockInfoFixture {
  val size: Int = 255
  val modifiers: Seq[ModifierId] = getRandomModifiersSeq(size, basicSeed = 444123L)

  @Test
  def creation(): Unit = {
    // Test 1: create empty sync info
    var info: SidechainSyncInfo = SidechainSyncInfo(Seq())
    assertTrue("SidechainSyncInfo expected to be empty", info.knownBlockIds.isEmpty)
    assertTrue("SidechainSyncInfo starting points expected to be empty", info.startingPoints.isEmpty)


    // Test 2: create sync info with data
    info = SidechainSyncInfo(modifiers)
    assertEquals("SidechainSyncInfo size expected to be different", size, info.knownBlockIds.size)
    assertEquals("SidechainSyncInfo starting points size should be different", 1, info.startingPoints.size)
    assertEquals("SidechainSyncInfo starting points expected to be different", modifiers.head, info.startingPoints.head._2)
  }

  @Test
  def serialization(): Unit = {
    val info: SidechainSyncInfo = SidechainSyncInfo(modifiers)
    val bytes = info.bytes

    // Test 1: try to deserializer valid bytes
    val serializedInfoTry = SidechainSyncInfoSerializer.parseBytesTry(bytes)
    assertTrue("SidechainSyncInfo expected to by parsed", serializedInfoTry.isSuccess)
    assertEquals("SidechainSyncInfo known blocks count is different", info.knownBlockIds.size, serializedInfoTry.get.knownBlockIds.size)
    for(i <- info.knownBlockIds.indices)
      assertEquals("SidechainSyncInfo known block %d is different".format(i), info.knownBlockIds(i), serializedInfoTry.get.knownBlockIds(i))



//    Uncomment and run if you want to update regression data.
//    val out = new BufferedWriter(new FileWriter("src/test/resources/sidechainsyncinfo_hex"))
//    out.write(BytesUtils.toHexString(bytes))
//    out.close()



    // Test 2: try to deserialize broken bytes.
    assertTrue("SidechainSyncInfo expected to be not parsed due to broken data.", SidechainSyncInfoSerializer.parseBytesTry("broken bytes".getBytes).isFailure)
  }

  @Test
  def serialization_regression(): Unit = {
    var bytes: Array[Byte] = null
    try {
      val classLoader = getClass.getClassLoader
      val file = new FileReader(classLoader.getResource("sidechainsyncinfo_hex").getFile)
      bytes = BytesUtils.fromHexString(new BufferedReader(file).readLine())
    }
    catch {
      case e: Exception =>
        assertEquals(e.toString(), true, false)
    }

    val serializedInfoTry = SidechainSyncInfoSerializer.parseBytesTry(bytes)
    assertTrue("SidechainSyncInfo expected to by parsed.", serializedInfoTry.isSuccess)
    for(i <- modifiers.indices)
      assertEquals("SidechainSyncInfo known block %d is different".format(i), modifiers(i), serializedInfoTry.get.knownBlockIds(i))
  }
} 
Example 44
package com.horizen.block

import com.horizen.fixtures.MainchainTxCrosschainOutputFixture
import com.horizen.proposition.PublicKey25519Proposition
import com.horizen.secret.PrivateKey25519Creator
import com.horizen.utils.{BytesUtils, Utils}
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test
import org.scalatest.junit.JUnitSuite

import scala.util.Random
import scala.util.Try

class MainchainTxForwardTransferCrosschainOutputTest extends JUnitSuite with MainchainTxCrosschainOutputFixture {

  @Test
  def creation(): Unit = {
    val amount: Long = 100L
    val proposition: PublicKey25519Proposition = PrivateKey25519Creator.getInstance().generateSecret("test1".getBytes()).publicImage()
    var sidechainId: Array[Byte] = new Array[Byte](32)
    Random.nextBytes(sidechainId)

    val bytes: Array[Byte] = generateMainchainTxForwardTransferCrosschainOutputBytes(amount, proposition, sidechainId)
    val hash: String = BytesUtils.toHexString(BytesUtils.reverseBytes(Utils.doubleSHA256Hash(bytes)))


    // Test 1: successful creation
    var output: Try[MainchainTxForwardTransferCrosschainOutput] = MainchainTxForwardTransferCrosschainOutput.create(bytes, 0)

    assertTrue("Forward Transfer crosschain output expected to be parsed.", output.isSuccess)
    assertEquals("Output Hash is different.", hash, BytesUtils.toHexString(output.get.hash))
    assertEquals("Output amount is different.", amount, output.get.amount)
    assertEquals("Output proposition bytes are different.", proposition, new PublicKey25519Proposition(output.get.propositionBytes))
    assertEquals("Output sidechainId is different.", BytesUtils.toHexString(sidechainId), BytesUtils.toHexString(output.get.sidechainId))


    // Test 2: broken bytes: length is too small
    val brokenBytes = bytes.slice(0, bytes.length - 1)

    output = MainchainTxForwardTransferCrosschainOutput.create(brokenBytes, 0)
    assertTrue("Forward Transfer crosschain output expected to be NOT parsed.", output.isFailure)

  }
} 
Example 45
Source File: PublicKey25519PropositionTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.proposition

import com.fasterxml.jackson.databind.JsonNode
import com.horizen.serialization.ApplicationJsonSerializer
import com.horizen.utils.Ed25519
import org.junit.Assert.assertEquals
import org.junit.Test
import org.scalatest.junit.JUnitSuite
import scorex.core.utils.ScorexEncoder

class PublicKey25519PropositionScalaTest
  extends JUnitSuite
{

  @Test
  def testToJson(): Unit = {
    val seed = "12345".getBytes
    val keyPair = Ed25519.createKeyPair(seed)
    val privateKey = keyPair.getKey
    val publicKey = keyPair.getValue

    val prop1 = new PublicKey25519Proposition(publicKey)

    val serializer = ApplicationJsonSerializer.getInstance()
    serializer.setDefaultConfiguration()

    val jsonStr = serializer.serialize(prop1)

    val node : JsonNode = serializer.getObjectMapper().readTree(jsonStr)

    assertEquals("Json must contain only 1 publicKey.",
      1, node.findValues("publicKey").size())
    assertEquals("PublicKey json value must be the same.",
      ScorexEncoder.default.encode(prop1.pubKeyBytes()), node.path("publicKey").asText())
  }
} 
Example 46
Source File: Signature25519ScalaTest.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.proof


import com.fasterxml.jackson.databind.JsonNode
import com.horizen.secret.PrivateKey25519Creator
import com.horizen.serialization.ApplicationJsonSerializer
import org.junit.Assert.assertEquals
import org.junit.Test
import org.scalatest.junit.JUnitSuite
import scorex.core.utils.ScorexEncoder

class Signature25519ScalaTest
  extends JUnitSuite
{

  @Test
  def testToJson(): Unit = {
    val testMessage: Array[Byte] = "Test string message to sign/verify.".getBytes
    val seed = "12345".getBytes
    val key = PrivateKey25519Creator.getInstance.generateSecret(seed)
    val prp = key.publicImage
    val pr = key.sign(testMessage)

    val serializer = ApplicationJsonSerializer.getInstance()
    serializer.setDefaultConfiguration()

    val jsonStr = serializer.serialize(pr)

    val node : JsonNode = serializer.getObjectMapper().readTree(jsonStr)

    assertEquals("Json must contain only 1 signature.",
      1, node.findValues("signature").size())
    assertEquals("",
      ScorexEncoder.default.encode(pr.signatureBytes), node.path("signature").asText())
  }
} 
Example 47
Source File: TestTypeDescriptor.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.typeutil

import com.amazon.milan.serialization.MilanObjectMapper
import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Test


object TestTypeDescriptor {

  case class Record()

  case class GenericRecord[T]()

}

import com.amazon.milan.typeutil.TestTypeDescriptor._


class TestTypeDescriptor {
  @Test
  def test_TypeDescriptor_Of_WithNonGenericRecordType_CreatesExpectedRecordTypeDescriptor(): Unit = {
    val target = TypeDescriptor.of[Record]
    assertTrue(target.genericArguments.isEmpty)
    assertEquals("com.amazon.milan.typeutil.TestTypeDescriptor.Record", target.typeName)
  }

  @Test
  def test_TypeDescriptor_Of_WithGenericRecordType_CreatesExpectedRecordTypeDescriptor(): Unit = {
    val target = TypeDescriptor.of[GenericRecord[Int]]
    assertEquals("com.amazon.milan.typeutil.TestTypeDescriptor.GenericRecord", target.typeName)
    assertEquals(1, target.genericArguments.length)
    assertEquals("Int", target.genericArguments.head.typeName)
  }

  @Test
  def test_TypeDescriptor_Of_WithGenericRecordTypeWithGenericArg_CreatesExpectedRecordTypeDescriptor(): Unit = {
    val target = TypeDescriptor.of[GenericRecord[List[Int]]]
    assertEquals("com.amazon.milan.typeutil.TestTypeDescriptor.GenericRecord", target.typeName)

    assertEquals(1, target.genericArguments.length)

    val genericArg = target.genericArguments.head
    assertEquals("List", genericArg.typeName)

    assertEquals(1, genericArg.genericArguments.length)
    assertEquals("Int", genericArg.genericArguments.head.typeName)
  }

  @Test
  def test_TypeDescriptor_Create_WithTupleType_ReturnsTypeDescriptorWithExpectedGenericArguments(): Unit = {
    val target = TypeDescriptor.forTypeName[Any]("Tuple3[Int, String, Long]")
    assertEquals("Tuple3", target.typeName)
    assertEquals(List(TypeDescriptor.of[Int], TypeDescriptor.of[String], TypeDescriptor.of[Long]), target.genericArguments)
  }

  @Test
  def test_TypeDescriptor_ForTypeName_ThenIsNumeric_WithNumericTypeNames_ReturnsTrue(): Unit = {
    val numericTypeNames = Seq("Double", "Float", "Int", "Long")
    numericTypeNames.foreach(name => assertTrue(TypeDescriptor.forTypeName[Any](name).isNumeric))
  }

  @Test
  def test_TupleTypeDescriptor_JsonSerializerAndDeserialize_ReturnsEquivalentType(): Unit = {
    val original = TypeDescriptor.of[(Int, String)]
    assertTrue(original.isTuple)

    val copy = MilanObjectMapper.copy(original)
    assertTrue(copy.isTuple)
    assertEquals(original, copy)
  }

  @Test
  def test_TypeDescriptor_NamedTupleOf_ReturnsExpectedFields(): Unit = {
    val actual = TypeDescriptor.namedTupleOf[(Int, String, Long)]("a", "b", "c")
    val expectedGenericArgs = List(types.Int, types.String, types.Long)
    val expectedFields = List(
      FieldDescriptor("a", types.Int),
      FieldDescriptor("b", types.String),
      FieldDescriptor("c", types.Long)
    )
    val expected = new TupleTypeDescriptor[(Int, String, Long)]("Tuple3", expectedGenericArgs, expectedFields)
    assertEquals(expected, actual)
  }

  @Test
  def test_TypeDescriptor_OfTuple_DoesntHaveFields(): Unit = {
    val target = TypeDescriptor.of[(Int, String)]
    assertTrue(target.fields.isEmpty)
  }
} 
Example 48
Source File: TestTypeUtil.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.typeutil

import org.junit.Assert.assertEquals
import org.junit.Test


@Test
class TestTypeUtil {
  @Test
  def test_TypeUtil_GetGenericArgumentTypeNames_WithThreeBasicTypes_ReturnsExpectedListOfTypeNames(): Unit = {
    val names = getGenericArgumentTypeNames("(Int, String, Float)")
    assertEquals(List("Int", "String", "Float"), names)
  }

  @Test
  def test_TypeUtil_GetGenericArgumentTypeNames_WithNestedGenericTypes_ReturnsExpectedListOfTypeNames(): Unit = {
    val typeName = "Tuple2[Int, com.amazon.milan.test.Tuple3Record[Int, Int, Int]]"
    val genericArgNames = getGenericArgumentTypeNames(typeName)
    assertEquals(List("Int", "com.amazon.milan.test.Tuple3Record[Int, Int, Int]"), genericArgNames)
  }
} 
Example 49
Source File: TestFlinkGenFilter.scala    From milan   with Apache License 2.0 5 votes vote down vote up
package com.amazon.milan.compiler.flink.generator

import com.amazon.milan.application.ApplicationConfiguration
import com.amazon.milan.compiler.flink.testing.{IntRecord, TestApplicationExecutor, TwoIntRecord}
import com.amazon.milan.lang._
import com.amazon.milan.testing.applications._
import org.junit.Assert.assertEquals
import org.junit.Test


@Test
class TestFlinkGenFilter {
  @Test
  def test_FlinkGenFilter_WithFilterOnObjectStream_OutputsExpectedRecords(): Unit = {
    val stream = Stream.of[IntRecord]
    val filtered = stream.where(r => r.i == 3)

    val graph = new StreamGraph(filtered)

    val config = new ApplicationConfiguration()
    config.setListSource(stream, IntRecord(1), IntRecord(2), IntRecord(3), IntRecord(4))

    val results = TestApplicationExecutor.executeApplication(graph, config, 60, filtered)

    val actualOutput = results.getRecords(filtered)
    assertEquals(List(IntRecord(3)), actualOutput)
  }

  @Test
  def test_FlinkGenFilter_WithFilterOnTupleStream_OutputsExpectedRecords(): Unit = {
    val stream = Stream.of[TwoIntRecord]
    val tupleStream = stream.map(r => fields(field("a", r.a), field("b", r.b)))
    val filtered = tupleStream.where { case (a, b) => a == b }

    val graph = new StreamGraph(filtered)

    val config = new ApplicationConfiguration()
    config.setListSource(stream, TwoIntRecord(1, 2), TwoIntRecord(2, 2))

    val results = TestApplicationExecutor.executeApplication(graph, config, 60, filtered)

    val actualOutput = results.getRecords(filtered)
    assertEquals(List((2, 2)), actualOutput)
  }
} 
Example 50
Source File: SplineQualityMetricsTest.scala    From aerosolve   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.aerosolve.training

import org.junit.Test
import org.slf4j.LoggerFactory
import org.junit.Assert.assertEquals

class SplineQualityMetricsTest {
  val log = LoggerFactory.getLogger("SplineQualityMetricsTest")

  def makeData(monotonic : String, direction: String) : Array[Double] = {
      (monotonic, direction) match {
        case ("monotonic", "increasing") => (1 to 5).map(x => x.toDouble).toArray
        case ("monotonic", "decreasing") => (0 to 4).map(x => 5 - x.toDouble).toArray
        case ("nonmonotonic", "increasing") => Array[Double](1.0, 3.0, 2.0, 4.0, 5.0)
        case ("nonmonotonic", "decreasing") => Array[Double](5.0, 3.0, 4.0, 2.0, 1.0)
      }
  }

  @Test
  def testSplineQualityMetricsSmoothDecreasing : Unit = {
    testSplineQualityMetricsSmoothness("monotonic", "decreasing")
    testSplineQualityMetricsMonotonicity("monotonic", "decreasing")
  }

  @Test
  def testSplineQualityMetricsSmoothIncreasing : Unit = {
    testSplineQualityMetricsSmoothness("monotonic", "increasing")
    testSplineQualityMetricsMonotonicity("monotonic", "increasing")
  }

  @Test
  def testSplineQualityMetricsNonSmoothDecreasing : Unit = {
    testSplineQualityMetricsSmoothness("nonmonotonic", "decreasing")
    testSplineQualityMetricsMonotonicity("nonmonotonic", "decreasing")
  }

  @Test
  def testSplineQualityMetricsNonSmoothIncreasing : Unit = {
    testSplineQualityMetricsSmoothness("nonmonotonic", "increasing")
    testSplineQualityMetricsMonotonicity("nonmonotonic", "increasing")
  }

  def testSplineQualityMetricsMonotonicity(monotonic: String,
                                           direction: String) = {
    val data = makeData(monotonic, direction)

    if (monotonic == "monotonic"){
      assertEquals(1.0, SplineQualityMetrics.getMonotonicity(data), 0.01)
    } else if (monotonic == "nonmonotonic") {
      assertEquals(0.8, SplineQualityMetrics.getMonotonicity(data), 0.01)
    }
  }

  def testSplineQualityMetricsSmoothness(monotonic: String,
                                           direction: String) = {
    val data = makeData(monotonic, direction)

    if (monotonic == "monotonic"){
      assertEquals(1.0, SplineQualityMetrics.getSmoothness(data), 0.01)
    } else if (monotonic == "nonmonotonic") {
      assertEquals(0.4, SplineQualityMetrics.getSmoothness(data), 0.01)
    }
  }



} 
Example 51
Source File: LazyZipTest.scala    From scala-library-compat   with Apache License 2.0 5 votes vote down vote up
package test.scala.collection

import org.junit.Assert.assertEquals
import org.junit.Test

import scala.collection.compat._

class LazyZipTest {

  private val ws      = List(1, 2, 3)
  private val xs      = List(1, 2, 3, 4, 5, 6)
  private val ys      = List("a", "b", "c", "d", "e", "f")
  private val zs      = List(true, false, true, false, true, false)
  private val zipped2 = ws lazyZip xs
  private val zipped3 = ws lazyZip xs lazyZip ys
  private val zipped4 = ws lazyZip xs lazyZip ys lazyZip zs
  private val map     = Map(1 -> "foo", 2 -> "bar")

  @Test
  def lazyZipTest(): Unit = {
    val res: List[(Int, Int)] = zipped2.map((a, b) => (a, b))
    assertEquals(List((1, 1), (2, 2), (3, 3)), res)
  }

  @Test
  def lazyZip3_map(): Unit = {
    val res: List[(Int, Int, String)] = zipped3.map((a: Int, b: Int, c: String) => (a, b, c))
    assertEquals(List((1, 1, "a"), (2, 2, "b"), (3, 3, "c")), res)
  }

  @Test
  def collectionValueIsNotEvaluated(): Unit = {
    val st = Stream.cons(1, throw new AssertionError("should not be evaluated"))
    ws.lazyZip(st)
  }

  @Test
  def zip3collectionValueIsNotEvaluated(): Unit = {
    val st = Stream.cons(1, throw new AssertionError("should not be evaluated"))
    ws.lazyZip(st).lazyZip(st)
  }

} 
Example 52
Source File: TestTDMLUnparseCases.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.tdml

import org.apache.daffodil.xml.XMLUtils
import org.junit.Assert.assertEquals
import org.junit.Test
import org.apache.daffodil.Implicits._

class TestTDMLUnparseCases {

  val tdml = XMLUtils.TDML_NAMESPACE
  val dfdl = XMLUtils.DFDL_NAMESPACE
  val xsi = XMLUtils.XSI_NAMESPACE
  val xsd = XMLUtils.XSD_NAMESPACE
  val example = XMLUtils.EXAMPLE_NAMESPACE
  val tns = example

  @Test def testUnparseSuite1(): Unit = {

    val testSuite = <ts:testSuite xmlns:dfdl={ dfdl } xmlns:xs={ xsd } xmlns:ex={ example } xmlns:ts={ tdml } suiteName="theSuiteName">
                      <ts:defineSchema name="s">
                        <xs:include schemaLocation="org/apache/daffodil/xsd/DFDLGeneralFormat.dfdl.xsd"/>
                        <dfdl:format ref="ex:GeneralFormat"/>
                        <xs:element name="bar" dfdl:lengthKind="explicit" dfdl:length="5" type="xs:string"/>
                      </ts:defineSchema>
                      <ts:unparserTestCase ID="test1" name="test1" root="bar" model="s">
                        <ts:infoset>
                          <ts:dfdlInfoset>
                            <ex:bar>Hello</ex:bar>
                          </ts:dfdlInfoset>
                        </ts:infoset>
                        <ts:document>Hello</ts:document>
                      </ts:unparserTestCase>
                    </ts:testSuite>
    lazy val ts = new DFDLTestSuite(testSuite)
    val tc: UnparserTestCase = ts.unparserTestCases.find { utc => utc.tcName == "test1" }.get
    // println(tc)
    tc.document
    val is = tc.inputInfoset
    // println(is)
    val bar = is.dfdlInfoset.contents
    val scala.xml.Elem(pre, label, _, _, _) = bar
    assertEquals("ex", pre)
    assertEquals("bar", label)
    // ts.trace
    ts.runOneTest("test1")
  }

} 
Example 53
Source File: TestSchemaCache.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.tdml

import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Test
import java.io.FileOutputStream
import org.apache.daffodil.api.URISchemaSource
import org.junit.Before
import scala.Right

class TestSchemaCache {

  object SCache extends SchemaCache[Null, Null]

  var compileCount = 0
  var originalUSS: URISchemaSource = null
  var newUSS: URISchemaSource = null
  var tempFile: File = null

  @Before def setup: Unit = {
    compileCount = 0
    SCache.resetCache
    tempFile = java.io.File.createTempFile("tdml", "tdml")
    tempFile.deleteOnExit()
    touchFile()
    val originalURI = tempFile.toURI
    originalUSS = URISchemaSource(originalURI)
    val newURI = tempFile.toURI
    newUSS = URISchemaSource(newURI)
  }

  
  def touchFile(): Unit = {
    val startingModTime = tempFile.lastModified()
    var iters = 0
    while (tempFile.lastModified() <= startingModTime) {
      iters += 1
      Thread.sleep(100)
      val os = new FileOutputStream(tempFile)
      os.write(0)
      os.flush()
      os.close()
    }
    // println("iters = " + iters)
  }

  def compileTheSchema(uss: URISchemaSource): Unit = {
    SCache.compileAndCache(uss, false, false, null, null) {
      compileCount += 1
      uss.newInputSource().getByteStream().close()
      Right(null)
    }
  }

  @Test def testReset: Unit = {
    compileTheSchema(originalUSS)
    SCache.resetCache
  }

  @Test def testSameFileCompiledOnce: Unit = {
    compileTheSchema(originalUSS)
    assertEquals(1, compileCount)
    compileTheSchema(newUSS) // file has not been touched, so this should hit the cache.
    assertEquals(1, compileCount)
  }

  @Test def testSameFileCompiledTwice: Unit = {
    compileTheSchema(originalUSS)
    assertEquals(1, compileCount)

    touchFile()

    compileTheSchema(newUSS) // file has changed
    assertEquals(2, compileCount)

  }

} 
Example 54
Source File: TestTunables.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.general

import org.junit.Test

import org.apache.daffodil.Implicits.ImplicitsSuppressUnusedImportWarning
import org.apache.daffodil.compiler.Compiler; object INoWarnDSOM1 { ImplicitsSuppressUnusedImportWarning() }

import org.apache.daffodil.util.Fakes
import org.apache.daffodil.util.Logging
import org.apache.daffodil.util.SchemaUtils
import org.apache.daffodil.xml.XMLUtils
import org.junit.Assert.assertEquals
import org.apache.daffodil.api.DaffodilTunables

class TestTunables extends Logging {

  val xsd = XMLUtils.XSD_NAMESPACE
  val dfdl = XMLUtils.dfdlAppinfoSource // XMLUtils.DFDL_NAMESPACE
  val xsi = XMLUtils.XSI_NAMESPACE
  val example = XMLUtils.EXAMPLE_NAMESPACE

  // The below is lazy for a reason.
  // It defers evaluation until used. This is nice because suppose there is a bug
  // in the Fakes stuff. Then you want tests that use that to fail. But lots of
  // these tests don't use this. If you make this an eager val, then if there
  // is any problem in the Fakes, the whole class can't be constructed, and None
  // of the tests will run. Lazy lets this class be constructed no matter what.
  lazy val dummyGroupRef = Fakes.fakeGroupRef

  @Test def testTunableCopy(): Unit = {
    val testSchema = SchemaUtils.dfdlTestSchema(
      <xs:include schemaLocation="org/apache/daffodil/xsd/DFDLGeneralFormat.dfdl.xsd"/>,
      <dfdl:format ref="tns:GeneralFormat"/>,
      <xs:element name="list" type="tns:example1"/>
      <xs:complexType name="example1">
        <xs:sequence>
          <xs:element name="w" type="xs:int" dfdl:length="1" dfdl:lengthKind="explicit"/>
        </xs:sequence>
      </xs:complexType>)

    val c = Compiler()
    val c1 = c.withTunable("maxSkipLengthInBytes", "1026")
    val pf1 = c1.compileNode(testSchema)

    val c2 = c.withTunable("maxSkipLengthInBytes", "2048")
    val pf2 = c2.compileNode(testSchema)

    val dp1 = pf1.onPath("/")
    var dp2 = pf2.onPath("/")

    val t1 = dp1.getTunables()
    val t2 = dp2.getTunables()

    
    dp2 = dp2.withTunable("maxSkipLengthInBytes", "50")

    val t3 = dp2.getTunables() // modified tunables at 'run-time'
    val t4 = dp1.getTunables() // obtain first data processor to see if anything changed

    assertEquals(1026, t1.maxSkipLengthInBytes) // initial compiler-set value
    assertEquals(2048, t2.maxSkipLengthInBytes) // overwrite of compiler-set value
    assertEquals(50, t3.maxSkipLengthInBytes) // data-processor-set value
    //
    //  initial compiler-set value not changed
    //  for first data processor object.
    assertEquals(1026, t4.maxSkipLengthInBytes)
  }

  @Test def testTunableSuppressionListCopying(): Unit = {
    val t1 = DaffodilTunables("suppressSchemaDefinitionWarnings", "escapeSchemeRefUndefined")
    val t2 = DaffodilTunables("suppressSchemaDefinitionWarnings", "all")

    val w1 = t1.suppressSchemaDefinitionWarnings.mkString(",")
    val w2 = t2.suppressSchemaDefinitionWarnings.mkString(",")
    assertEquals(true, w1.contains("escapeSchemeRefUndefined"))
    assertEquals(true, w2.contains("all"))

    val w3 = t1.suppressSchemaDefinitionWarnings.mkString(",")
    val w4 = t1.copy().suppressSchemaDefinitionWarnings.mkString(",")
    assertEquals(true, w3.contains("escapeSchemeRefUndefined"))
    assertEquals(true, w4.contains("escapeSchemeRefUndefined"))
  }

} 
Example 55
Source File: TestDsomCompiler3.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.api

import org.apache.daffodil.xml.XMLUtils
import org.apache.daffodil.util._
import org.apache.daffodil.Implicits._
import org.apache.daffodil.compiler._
import org.apache.daffodil.schema.annotation.props.gen._
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.io.File
import org.junit.Test
import org.apache.daffodil.dsom.DFDLElement

class TestDsomCompiler3 {

  val xsd = XMLUtils.XSD_NAMESPACE
  val dfdl = XMLUtils.dfdlAppinfoSource // XMLUtils.DFDL_NAMESPACE
  val xsi = XMLUtils.XSI_NAMESPACE
  val example = XMLUtils.EXAMPLE_NAMESPACE

  @Test def testTmpDirProvided(): Unit = {
    val sc = SchemaUtils.dfdlTestSchema(
      <xs:include schemaLocation="org/apache/daffodil/xsd/DFDLGeneralFormat.dfdl.xsd"/>,
      <dfdl:format ref="tns:GeneralFormat"/>,

      <xs:element name="list" type="tns:example1">
        <xs:annotation>
          <xs:appinfo source={ dfdl }>
            <dfdl:element encoding="US-ASCII" alignmentUnits="bytes"/>
          </xs:appinfo>
        </xs:annotation>
      </xs:element>
      <xs:complexType name="example1">
        <xs:sequence dfdl:separator="">
          <xs:element name="w" type="xs:int" dfdl:length="1" dfdl:lengthKind="explicit"/>
        </xs:sequence>
      </xs:complexType>)

    val tmpDir = new File("./dfdl_tmp")
    if (tmpDir.exists) {
      tmpDir.listFiles.foreach(_.delete)
      tmpDir.delete
    }
    try {
      tmpDir.mkdirs
      val sset = Compiler().compileNode(sc, Some(tmpDir)).sset

      val list = tmpDir.list()
      assertEquals(1, list.length)

      val fileName = list(0)
      assertTrue(fileName.contains(".dfdl.xsd"))

      // Verify things still work using specified tmpDir
      //
      val Seq(schema) = sset.schemas
      val Seq(schemaDoc, _) = schema.schemaDocuments
      val Seq(decl) = schemaDoc.globalElementDecls.map{ _.asRoot }
      val Seq(ct) = schemaDoc.globalComplexTypeDefs
      assertEquals("example1", ct.name)

      decl.formatAnnotation.asInstanceOf[DFDLElement]
      assertEquals(AlignmentUnits.Bytes, decl.alignmentUnits)
    } finally {
      if (tmpDir.exists) {
        tmpDir.listFiles.foreach(_.delete)
        tmpDir.delete
      }
    }
  }

} 
Example 56
Source File: TestMoreEncodings.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.tdml

import org.junit.Test

import org.junit.Assert.assertEquals

class TestMoreEncodings {

  @Test def testBitsEncoding1(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-BITS-LSBF">1</documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    val expected = List(0x01).map { _.toByte }
    assertEquals(expected, actual)
    assertEquals(1, doc.nBits)
  }

  @Test def testBitsEncoding2(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-BITS-LSBF">10</documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    val expected = List(0x01).map { _.toByte }
    assertEquals(expected, actual)
    assertEquals(2, doc.nBits)
  }

  @Test def testBitsEncoding8(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-BITS-LSBF">00110101</documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    val expected = List(0xAC).map { _.toByte }
    assertEquals(expected, actual)
    assertEquals(8, doc.nBits)
  }

  @Test def testBitsEncoding9(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-BITS-LSBF">001101011</documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    val expected = List(0xAC, 0x01).map { _.toByte }
    assertEquals(expected, actual)
    assertEquals(9, doc.nBits)
  }

  @Test def testSixBitEncoding1(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-6-BIT-DFI-264-DUI-001"><![CDATA[0]]></documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    val expected = List(0x3F).map { _.toByte }
    assertEquals(expected, actual)
    assertEquals(6, doc.nBits)
  }

  @Test def testSixBitEncoding2(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-6-BIT-DFI-264-DUI-001"><![CDATA[00]]></documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    val expected = List(0xFF, 0x0F).map { _.toByte }
    assertEquals(expected, actual)
    assertEquals(12, doc.nBits)
  }

  @Test def testSixBitEncoding40(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-6-BIT-DFI-264-DUI-001"><![CDATA[0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ012]]></documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    assertEquals(30, actual.length)
  }

  @Test def testSixBitEncoding39(): Unit = {
    val xml = <document>
                <documentPart type="text" bitOrder="LSBFirst" encoding="X-DFDL-6-BIT-DFI-264-DUI-001"><![CDATA[0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ00]]></documentPart>
              </document>
    val doc = new Document(xml, null)
    val actual = doc.documentBytes.toList
    assertEquals(30, actual.length)
    val lastByte = actual.last
    assertEquals(0x03, lastByte)
  }
} 
Example 57
Source File: TestBitOrderByteOrder.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil

import org.junit.Assert.assertEquals
import org.apache.daffodil.util._
import org.junit.Test
import org.apache.daffodil.util._

class TestByteOrder {

  @Test def testLittleEndianBitValue = {
    var bsl = 13
    assertEquals(0x80, Bits.littleEndianBitValue(1, bsl))
    assertEquals(0x40, Bits.littleEndianBitValue(2, bsl))
    assertEquals(0x20, Bits.littleEndianBitValue(3, bsl))
    assertEquals(0x10, Bits.littleEndianBitValue(4, bsl))
    assertEquals(0x08, Bits.littleEndianBitValue(5, bsl))
    assertEquals(0x04, Bits.littleEndianBitValue(6, bsl))
    assertEquals(0x02, Bits.littleEndianBitValue(7, bsl))
    assertEquals(0x01, Bits.littleEndianBitValue(8, bsl))
    assertEquals(0x1000, Bits.littleEndianBitValue(9, bsl))
    assertEquals(0x800, Bits.littleEndianBitValue(10, bsl))
    assertEquals(0x400, Bits.littleEndianBitValue(11, bsl))
    assertEquals(0x200, Bits.littleEndianBitValue(12, bsl))
    assertEquals(0x100, Bits.littleEndianBitValue(13, bsl))

    bsl = 3
    assertEquals(0x4, Bits.littleEndianBitValue(1, bsl))
    assertEquals(0x2, Bits.littleEndianBitValue(2, bsl))
    assertEquals(0x1, Bits.littleEndianBitValue(3, bsl))
  }
}

class TestBitOrder {

  @Test def testAsLSBitFirst = {
    assertEquals(0x20, Bits.asLSBitFirst(0x04))
    assertEquals(0x80, Bits.asLSBitFirst(1))
    assertEquals(0xA5, Bits.asLSBitFirst(0xA5))
    assertEquals(0xCC, Bits.asLSBitFirst(0x33))
  }

} 
Example 58
Source File: TestQName.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.xml.test.unit

import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.Assert._
import org.apache.daffodil.xml.QNameRegex
import org.apache.daffodil.xml.QName
import org.apache.daffodil.xml.RefQName
import org.apache.daffodil.xml.NoNamespace
import scala.util.Success
import org.apache.daffodil.xml.UnspecifiedNamespace
import org.apache.daffodil.xml.ExtendedQNameSyntaxException
import scala.util.Failure
import java.net.URISyntaxException

class TestQName {

  @Test def testQNameLongPrefix(): Unit = {
    val bigPrefix = ("a" * 6000)
    val data = <xs:element name="one" type={ bigPrefix + ":b" }/>
    val qntext = (data \ "@type").text

    // println("length of type attribute = " + qntext.length)
    qntext match {
      case QNameRegex.QName(pre, local) => {
        // println(pre)
        // println(local)
        assertEquals(6001, pre.length + local.length)
      }
    }
  }

  @Test def testExtQName1(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("local")
    tryrqn match {
      case Success(RefQName(None, "local", UnspecifiedNamespace)) => // ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName2(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("{}local")
    tryrqn match {
      case Success(RefQName(None, "local", NoNamespace)) => // ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName3(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("{uri}local")
    tryrqn match {
      case Success(RefQName(None, "local", ns)) => assertEquals("uri", ns.uri.toString)
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName4(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("pre:local")
    tryrqn match {
      case Success(RefQName(Some("pre"), "local", UnspecifiedNamespace)) => //ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName5(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("pre:{}local")
    tryrqn match {
      case Failure(exc: ExtendedQNameSyntaxException) => // ok
      case _ => fail(tryrqn.toString)
    }
  }

  @Test def testExtQName6(): Unit = {
    val tryrqn = QName.refQNameFromExtendedSyntax("{http://<<notValidURI>>}local")
    tryrqn match {
      case Failure(exc: ExtendedQNameSyntaxException) => {
        val c = exc.getCause()
        c match {
          case usex: URISyntaxException => // ok
          case _ => fail("Expected a URISyntaxException, but got " + c)
        }
      }
      case Failure(exc) => fail(exc.getMessage())
      case _ => fail(tryrqn.toString)
    }
  }

} 
Example 59
Source File: TestNamespaces.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.xml.test.unit

import org.junit.Assert.assertEquals
import org.junit.Test


  @Test def testNewElementWithNamespaces(): Unit = {
    val xml = <bar xmlns="defaultNS" xmlns:foo="fooNS" xmlns:bar="barNS">
                <quux xmlns:baz="bazNS" attr1="x"/>
              </bar>

    // val scope = (xml \ "quux")(0).scope // will have multiple namespace definitions.
    // println(scope)
    // val newElem = scala.xml.Elem("somePrefix", "someElement", Null, scope, true)
    // println(newElem)
    val quux = (xml \ "quux")(0)
    val barNS = quux.getNamespace("bar")
    assertEquals("barNS", barNS)
    val fooNS = quux.getNamespace("foo")
    assertEquals("fooNS", fooNS)
    val bazNS = quux.getNamespace("baz")
    assertEquals("bazNS", bazNS)
    val defaultNS = quux.getNamespace(null)
    assertEquals("defaultNS", defaultNS)
  }

} 
Example 60
Source File: TestListMap.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.util

import org.junit.Assert.assertEquals
import org.junit.Test
import scala.collection.immutable.ListMap
import scala.util.Random

class TestListMap {

  
  @Test def test_listMap = {
    val orig = Random.shuffle((0 until 1000).toList)
    val mt: ListMap[Int, String] = ListMap.empty
    val listMap: ListMap[Int, String] = orig.foldLeft(mt) {

      (lm, n) => lm + (n -> n.toString)
    }

    // test that removals still maintain order
    val removeKey = Random.nextInt(1000)
    val smallerOrig = orig.filter(_ != removeKey)
    val smallerMap = listMap - removeKey

    val zipped = smallerOrig.zip(smallerMap)
    zipped.foreach { case (o, (k, v)) => assertEquals(o, k) }
  }
} 
Example 61
Source File: TestListUtils.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package org.apache.daffodil.util

import org.junit.Assert.assertEquals
import org.junit.Test

class TestListUtils {

  @Test def testTailAfter1 = {
    val actual = ListUtils.tailAfter(List(1, 2, 3, 4, 5), 3)
    val expected = List(4, 5)
    assertEquals(expected, actual)
  }

  @Test def testTailAfter2 = {
    val actual = ListUtils.tailAfter(Nil, 3)
    val expected = Nil
    assertEquals(expected, actual)
  }

  @Test def testTailAfter3 = {
    val actual = ListUtils.tailAfter(List(1, 2, 3, 4, 5), 5)
    val expected = Nil
    assertEquals(expected, actual)
  }

  @Test def testTailAfter4 = {
    val actual = ListUtils.tailAfter(List(1, 2, 3, 4, 5), 0)
    val expected = Nil // The answer if not found at all is Nil
    assertEquals(expected, actual)
  }

  @Test def testPreceding1 = {
    val actual = ListUtils.preceding(List(1, 2, 3, 4, 5), 3)
    val expected = List(1, 2)
    assertEquals(expected, actual)
  }

  @Test def testPreceding2 = {
    val actual = ListUtils.preceding(Nil, 3)
    val expected = Nil
    assertEquals(expected, actual)
  }

  @Test def testPreceding3 = {
    val actual = ListUtils.preceding(List(1, 2, 3, 4, 5), 1)
    val expected = Nil
    assertEquals(expected, actual)
  }

  @Test def testPreceding4 = {
    val actual = ListUtils.preceding(List(1, 2, 3, 4, 5), 0)
    val expected = Nil // The answer if not found at all is Nil
    assertEquals(expected, actual)
  }

  @Test def testPreceding5 = {
    val actual = ListUtils.preceding(List(1, 2, 3, 4, 5), 5)
    val expected = List(1, 2, 3, 4)
    assertEquals(expected, actual)
  }

} 
Example 62
Source File: TestULong.scala    From incubator-daffodil   with Apache License 2.0 5 votes vote down vote up
package passera.test

import java.math.{ BigInteger => JBigInt }

import org.junit.Assert.assertEquals
import org.junit.Test

import passera.unsigned.ULong

class TestULong {

  @Test def testULongToString1: Unit = {
    val mm1 = ULong(-1L)
    assertEquals("FFFFFFFFFFFFFFFF", mm1.toHexString.toUpperCase)
    assertEquals(ULong.MaxValueAsBigInt, mm1.toBigInt)
    assertEquals(JBigInt.valueOf(Long.MinValue).abs.toString, mm1.toString)
  }

  // DAFFODIL-1714
  @Test def testULongModulus1: Unit = {
    for (i <- 0 to 16 ) {
      val numerator = ULong(i)
      val denominator = ULong(8)
      val remainder = numerator % denominator
      assertEquals(ULong(i%8), remainder)
    }
  }

  @Test def testULongModulus2: Unit = {
    val mm1 = ULong(-1L)
    val remainder = mm1 % ULong(65536)
    assertEquals(ULong(0x0000FFFF), remainder)
  }
  
  @Test def testULongModulus3: Unit = {
    val mm1 = ULong(-1L)
    val mm2 = ULong(-2L)
    val remainder = mm1 % mm2
    assertEquals(ULong(1), remainder)
  }
  
} 
Example 63
Source File: RFFeatureSizerTest.scala    From reforest   with Apache License 2.0 5 votes vote down vote up
package reforest.rf.feature

import org.junit.Assert.assertEquals
import reforest.rf.{RFCategoryInfo, RFCategoryInfoEmpty}
import reforest.rf.split.RFSplitter
import test.RFResourceFactory
import org.junit.{Assert, Test}

class RFFeatureSizerTest {
  private val numberBin = 32
  private val numClasses = 10
  private val splitter = RFResourceFactory.getSplitterRandomDefault(-23.5, 12.7, numberBin)
  private val sizer = splitter.generateRFSizer(numClasses)

  @Test
  def getSize(): Unit = {
    assertEquals((numberBin + 1) * numClasses, sizer.getSize(1))
  }

  @Test
  def shrinker(): Unit = {
    val sizer = new RFFeatureSizerSimpleModelSelection(32, 2, new RFCategoryInfoEmpty, 16)
    assertEquals(0, sizer.getShrinkedValue(1, 0))
    assertEquals(1, sizer.getShrinkedValue(1, -1))
    assertEquals(16, sizer.getShrinkedValue(1, 32))
    assertEquals(16, sizer.getShrinkedValue(1, 33))
    assertEquals(16, sizer.getShrinkedValue(1, 100))
  }

  @Test
  def shrinkerSpecialized(): Unit = {
    val splitNumberMap = Map(0 -> 4, 1 -> 8, 2 -> 7)
    val sizer = new RFFeatureSizerSpecializedModelSelection(splitNumberMap, 2, new RFCategoryInfoEmpty, 8, 32)

    assertEquals(5, sizer.getShrinkedValue(0, 5))
    assertEquals(4, sizer.getShrinkedValue(0, 4))
    assertEquals(1, sizer.getShrinkedValue(0, 1))
    assertEquals(0, sizer.getShrinkedValue(0, 0))
    assertEquals(0, sizer.getShrinkedValue(1, 0))
    assertEquals(1, sizer.getShrinkedValue(1, -1))
    assertEquals(8, sizer.getShrinkedValue(1, 32))
    assertEquals(8, sizer.getShrinkedValue(1, 33))
    assertEquals(8, sizer.getShrinkedValue(1, 100))
    assertEquals(8, sizer.getShrinkedValue(2, 8))
    assertEquals(7, sizer.getShrinkedValue(2, 7))
    assertEquals(6, sizer.getShrinkedValue(2, 6))
    assertEquals(2, sizer.getShrinkedValue(2, 2))
    assertEquals(1, sizer.getShrinkedValue(2, 1))
  }

  @Test
  def deShrinker(): Unit = {
    val sizer = new RFFeatureSizerSimpleModelSelection(32, 2, new RFCategoryInfoEmpty, 16)

    assertEquals(0, sizer.getDeShrinkedValue(0, 0))
    assertEquals(0, sizer.getDeShrinkedValue(1, 0))
    assertEquals(32, sizer.getDeShrinkedValue(1, 32))
    assertEquals(32, sizer.getDeShrinkedValue(1, 33))
    assertEquals(32, sizer.getDeShrinkedValue(1, 100))
  }

  @Test
  def deShrinkerSpecialized(): Unit = {
    val splitNumberMap = Map(0 -> 4, 1 -> 8, 2 -> 7)
    val sizer = new RFFeatureSizerSpecializedModelSelection(splitNumberMap, 2, new RFCategoryInfoEmpty, 8, 32)

    assertEquals(5, sizer.getDeShrinkedValue(0, 5))
    assertEquals(4, sizer.getDeShrinkedValue(0, 4))
    assertEquals(1, sizer.getDeShrinkedValue(0, 1))
    assertEquals(0, sizer.getDeShrinkedValue(0, 0))
    assertEquals(0, sizer.getDeShrinkedValue(1, 0))
    assertEquals(9, sizer.getDeShrinkedValue(1, 32))
    assertEquals(9, sizer.getDeShrinkedValue(1, 33))
    assertEquals(9, sizer.getDeShrinkedValue(1, 100))
    assertEquals(8, sizer.getDeShrinkedValue(2, 8))
    assertEquals(7, sizer.getDeShrinkedValue(2, 7))
    assertEquals(6, sizer.getDeShrinkedValue(2, 6))
    assertEquals(2, sizer.getDeShrinkedValue(2, 2))
    assertEquals(1, sizer.getDeShrinkedValue(2, 1))
  }
} 
Example 64
Source File: Neo4jTest.scala    From morpheus   with Apache License 2.0 5 votes vote down vote up
package org.opencypher.morpheus.impl.io.neo4j.external

import org.junit.Assert.assertEquals
import org.opencypher.morpheus.testing.fixture.SparkSessionFixture
import org.opencypher.okapi.neo4j.io.testing.Neo4jServerFixture
import org.opencypher.okapi.testing.BaseTestSuite

class Neo4jTest extends BaseTestSuite
  with SparkSessionFixture
  with Neo4jServerFixture {

  override def dataFixture: String =
    """
      UNWIND range(1,100) as id
      CREATE (p:Person {id:id}) WITH collect(p) as people
      UNWIND people as p1
      UNWIND range(1,10) as friend
      WITH p1, people[(p1.id + friend) % size(people)] as p2
      CREATE (p1)-[:KNOWS]->(p2)
      """

  lazy private val neo4j = Neo4j(neo4jConfig, sparkSession)

  test("run Cypher Query With Params") {
    val result = neo4j.cypher("MATCH (n:Person) WHERE n.id <= {maxId} RETURN id(n)").param("maxId", 10)
    assertEquals(10, result.loadRowRdd.count())
  }

  test("run Cypher Node Query") {
    val result = neo4j.cypher("MATCH (n:Person) RETURN id(n)")
    assertEquals(100, result.loadRowRdd.count())
  }

  test("run Cypher Rel Query") {
    val result = neo4j.cypher("MATCH ()-[r:KNOWS]->() RETURN id(r)")
    assertEquals(1000, result.loadRowRdd.count())
  }

  test("run Cypher Query With Partition") {
    val result = neo4j.cypher("MATCH (n:Person) RETURN id(n) SKIP {_skip} LIMIT {_limit}").partitions(4).batch(25)
    assertEquals(100, result.loadRowRdd.count())
  }

  test("run Cypher Rel Query WithPartition") {
    val result = neo4j.cypher("MATCH (n:Person)-[r:KNOWS]->(m:Person) RETURN id(n) as src,id(m) as dst,type(r) as value SKIP {_skip} LIMIT {_limit}").partitions(7).batch(200)
    assertEquals(1000, result.loadRowRdd.count())
  }
}