org.scalatest.funspec.AnyFunSpec Scala Examples

The following examples show how to use org.scalatest.funspec.AnyFunSpec. 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: PartitionedOrcSinkSpec.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.pipeline

import be.dataminded.lighthouse.testing.SharedSparkSession
import better.files._
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class PartitionedOrcSinkSpec extends AnyFunSpec with SharedSparkSession with Matchers {

  import spark.implicits._

  describe("PartitionedOrcSink") {
    it("should write the DataFrame partitioned by a sequence of columns") {
      val data = Seq(("Boy", 15), ("Girl", 22), ("Dog", 3)).toDF("name", "age")

      SparkFunction.of(data).write(PartitionedOrcSink("./target/output/orc", Seq("age"))).run(spark)

      ("target" / "output" / "orc").list.filter(_.isDirectory).map(_.name).toList should contain theSameElementsAs Seq(
        "age=22",
        "age=15",
        "age=3"
      )
    }
  }
} 
Example 2
Source File: ContravariantSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package contravariant

import scalaz.Contravariant
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class ContravariantSpec
  extends AnyFunSpec
    with Matchers {

  case class Predicate[A](fun: A => Boolean)

  describe("Contravariant") {

    it("split complex Predicate into simpler + function - csutom contramap") {
      val lenAbove5 = Predicate[String](_.length > 5)
      lenAbove5.fun("123456") mustBe true

      // predicate
      val above5 = Predicate[Int](_ > 5)
      above5.fun(42) mustBe true

      // function
      val len: String => Int = _.length

      // way to combine them
      def contramap(pred: Predicate[Int], f: String => Int): Predicate[String] =
        Predicate[String](f andThen pred.fun)

      // yeach !
      val pr = contramap(above5, len)
      pr.fun("123456") mustBe true
    }

    it("custom contramap for Predicate on Person and Balance") {
      case class Person(name: String)
      case class Balance(amount: Int)

      val balanceOverdrawnPred = Predicate[Balance](_.amount > 0)

      val getAccountBalance: Person => Balance = p => // that hows Banks works :)
        if(p.name.startsWith("A")) Balance(-1)
        else Balance(42)

      def contramap[A, B](pred: Predicate[A])(f: B => A): Predicate[B] =
        Predicate[B](f andThen pred.fun)

      val hasOverdrawnBalance = contramap(balanceOverdrawnPred)(getAccountBalance)

      hasOverdrawnBalance.fun(Person("Alice")) mustBe false
      hasOverdrawnBalance.fun(Person("Bob")) mustBe true
    }

    it("contramap with Contravariant instance") {

      implicit val predicateContravariant: Contravariant[Predicate] =
        new Contravariant[Predicate] {
          def contramap[A, B](pred: Predicate[A])(fba: B => A): Predicate[B] =
            Predicate[B](fba andThen pred.fun)
        }

      case class Person(name: String)
      case class Balance(amount: Int)

      val balanceOverdrawn = Predicate[Balance](_.amount > 0)

      val getAccountBalance: Person => Balance = p =>
        if(p.name.startsWith("A")) Balance(-1)
        else Balance(42)

      val hasOverdrawnBalance = Contravariant[Predicate]
        .contramap(balanceOverdrawn)(getAccountBalance)

      hasOverdrawnBalance.fun(Person("Alice")) mustBe false
      hasOverdrawnBalance.fun(Person("Bob")) mustBe true
    }
  }
} 
Example 3
Source File: TraverseEmptyListPermutationsSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package mtl

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers


class TraverseEmptyListPermutationsSpec
  extends AnyFunSpec
  with Matchers {

  describe("filterA") {
    it("compute all permutations of the lit if given List(true, false)") {
      import cats._
      import cats.implicits._

      val allPermutations = List(
        List(1, 2, 3),
        List(1, 2),
        List(1, 3),
        List(2, 3),
        List(1),
        List(2),
        List(3),
        Nil
      )
      val result: List[List[Int]] = List(1, 2, 3).filterA(_ => List(true, false))
      result contains theSameElementsAs (allPermutations)
    }
  }
} 
Example 4
Source File: ReaderMonadSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package monad

import scala.concurrent.duration.Duration
import scala.concurrent.duration._
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

case class Reader[A, B](run: A => B) { // B is changing and A is constant

  def map[C](f: B => C): Reader[A, C] = Reader(run andThen f)

  def flatMap[C](f: B => Reader[A, C]): Reader[A, C] = {
//    def attempt1: A => Reader[A, C] = a => f(run(a))
//    def attempt2: A => (A => C) = (a:A) => f(run(a)).run
    def attempt3: A => C = (a:A) => {
      val b: B = run(a)
      val reader: Reader[A, C] = f(b)
      reader.run(a)
    }
    Reader(attempt3)
  }

  def flatten(r: Reader[A, Reader[A, B]]): Reader[A, B] = { // pass the context A to outer computation and inner computation
    def newRun: A => B = a => {
      val firstRun: Reader[A, B] = r.run(a)
      firstRun.run(a)
    }
    Reader(newRun)
  }
}

object Reader {

  def ask[A]: Reader[A, A] = Reader(identity)
}

class ReaderMonadSpec
  extends AnyFunSpec
  with Matchers {

  describe("Reader") {
    case class DbConfig(maxTimeout: Duration, jdbc: String, user: String, pass: String)

    val baseConfig = DbConfig(60.seconds, "jdbc://localhost:5432/db", "admin", "1234")
    type FindById = Int => String

    def getAllCustomerIds: DbConfig => List[Int] = _ => List(1, 42) // it pass the tests so who cares
    def getDefaultCustomer: DbConfig => FindById = conf => id => s"Johnny Bravo $id"

    it("produces something from configuration") {
      val reader: Reader[DbConfig, (Int => String)] = Reader(getDefaultCustomer)
      reader.run(baseConfig)(1) mustBe "Johnny Bravo 1"
    }

    it("is like Functor") {
      val reader: Reader[DbConfig, List[Int]] = Reader(getAllCustomerIds)
      reader.map(_.mkString(", ")).run(baseConfig) mustBe "1, 42"
    }
  }
} 
Example 5
Source File: DatasetComparerSpec.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.testing

import org.scalatest.funspec.AnyFunSpec

private case class Person(name: String, age: Int)

class DatasetComparerSpec extends AnyFunSpec with SharedSparkSession with DatasetComparer {

  import spark.implicits._

  describe("assertDatasetEquality") {
    it("does nothing true if the Datasets have the same schemas and content") {
      val actual   = Seq(Person("bob", 1), Person("frank", 5)).toDS
      val expected = Seq(Person("bob", 1), Person("frank", 5)).toDS

      assertDatasetEquality(actual, expected)
    }

    it("can performed unordered Dataset comparisons") {
      val actual   = Seq(Person("bob", 1), Person("frank", 5)).toDS
      val expected = Seq(Person("frank", 5), Person("bob", 1)).toDS

      assertDatasetEquality(actual, expected, orderedComparison = false)
    }

    it("throws an error for unordered Dataset comparisons that don't match") {
      val actual   = Seq(Person("bob", 1), Person("frank", 5)).toDS
      val expected = Seq(Person("frank", 5), Person("bob", 1), Person("sadie", 2)).toDS

      intercept[AssertionError] {
        assertDatasetEquality(actual, expected, orderedComparison = false)
      }
    }

    it("returns false if the Dataset content is different") {
      val actual   = Seq(Person("bob", 1), Person("frank", 5)).toDS
      val expected = Seq(Person("sally", 66), Person("sue", 54)).toDS

      intercept[AssertionError] {
        assertDatasetEquality(actual, expected)
      }
    }
  }

  describe("assertDatasetEquality using DataFrames") {
    it("does nothing if the DataFrames have the same schemas and content") {
      val actual   = Seq(1, 5).toDF("number")
      val expected = Seq(1, 5).toDF("number")

      assertDatasetEquality(actual, expected)
    }

    it("assert fails if the DataFrames have different schemas") {
      val actual   = Seq(1, 5).toDF("number")
      val expected = Seq((1, "hi"), (5, "bye")).toDF("number", "word")

      intercept[AssertionError] {
        assertDatasetEquality(actual, expected)
      }
    }

    it("throws an error if the DataFrames content is different") {
      val actual   = Seq(1, 5).toDF("number")
      val expected = Seq(10, 5).toDF("number")

      intercept[AssertionError] {
        assertDatasetEquality(actual, expected)
      }
    }

    it("can performed unordered DataFrame comparisons") {
      val actual   = Seq(1, 5).toDF("number")
      val expected = Seq(5, 1).toDF("number")

      assertDatasetEquality(actual, expected, orderedComparison = false)
    }

    it("throws an error for unordered DataFrame comparisons that don't match") {
      val actual   = Seq(1, 5).toDF("number")
      val expected = Seq(5, 2).toDF("number")

      intercept[AssertionError] {
        assertDatasetEquality(actual, expected)
      }
    }
  }
} 
Example 6
Source File: ColumnComparerSpec.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.testing

import org.apache.spark.sql.functions._
import org.scalatest.funspec.AnyFunSpec

class ColumnComparerSpec extends AnyFunSpec with SharedSparkSession with ColumnComparer {

  import spark.implicits._

  describe("assertColumnEquality") {

    it("doesn't do anything if all the column values are equal") {
      val source = Seq((1, 1), (5, 5)).toDF("num", "expected")

      assertColumnEquality(source, "num", "expected")
    }

    it("throws an error if the columns aren't equal") {
      val source = Seq((1, 3), (5, 5)).toDF("num", "expected")

      intercept[AssertionError] {
        assertColumnEquality(source, "num", "expected")
      }
    }

    it("throws an error if the columns are different types") {
      val source = Seq((1, "hi"), (5, "bye")).toDF("num", "word")

      intercept[AssertionError] {
        assertColumnEquality(source, "num", "word")
      }
    }

    it("works properly, even when null is compared with a value") {
      val source = Seq((1, 1), (null.asInstanceOf[Int], 5), (null.asInstanceOf[Int], null.asInstanceOf[Int]))
        .toDF("num", "expected")

      intercept[AssertionError] {
        assertColumnEquality(source, "num", "expected")
      }
    }

    it("works for ArrayType columns") {
      val source =
        Seq((Array("a"), Array("a")), (Array("a", "b"), Array("a", "b"))).toDF("left", "right")
      assertColumnEquality(source, "left", "right")
    }

    it("works for computed ArrayType columns") {
      val source = Seq(
        ("i like blue and red", Array("blue", "red")),
        ("you pink and blue", Array("blue", "pink")),
        ("i like fun", Array(""))
      ).toDF("words", "expected_colors")

      val actual = source.withColumn(
        "colors",
        split(
          concat_ws(
            ",",
            when(col("words").contains("blue"), "blue"),
            when(col("words").contains("red"), "red"),
            when(col("words").contains("pink"), "pink"),
            when(col("words").contains("cyan"), "cyan")
          ),
          ","
        )
      )
      assertColumnEquality(actual, "colors", "expected_colors")
    }
  }
} 
Example 7
Source File: DatabaseTest.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.common

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class DatabaseTest extends AnyFunSpec with Matchers {

  describe("An in-memory database") {

    val database = Database.inMemory("test")

    it("can easily be created using the factory method") {
      database.driverClassName should equal("org.h2.Driver")
    }

    it("has a function for using the connection") {
      database.withConnection { connection =>
        connection.createStatement.execute("CREATE TABLE nothing (id varchar, name varchar)")
      }
    }

    it("is by default auto-commited") {
      val isAutoCommit = database.withConnection { connection =>
        connection.getAutoCommit
      }
      isAutoCommit should be(true)
    }

    it("can be configured to not be auto-commited") {
      val isAutoCommit = database.withConnection(autoCommit = false) { connection =>
        connection.getAutoCommit
      }
      isAutoCommit should be(false)
    }
  }
} 
Example 8
Source File: PackageTest.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.datalake

import java.util.Properties

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class PackageTest extends AnyFunSpec with Matchers {

  describe("asProperties") {
    it("should convert a Scala to Java Properties implicitly") {
      val properties: Properties = Map("test1" -> "1", "test2" -> "2")

      properties.getProperty("test1") should equal("1")
      properties.getProperty("test2") should equal("2")
    }

    it("does only convert maps of type Map[String, String]") {
      assertDoesNotCompile("val properties: Properties = Map(\"test1\" -> 1, \"test2\" -> 2)")
    }
  }
} 
Example 9
Source File: TextSinkSpec.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.pipeline

import be.dataminded.lighthouse.testing.SharedSparkSession
import better.files._
import org.scalatest.BeforeAndAfterEach
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class TextSinkSpec extends AnyFunSpec with SharedSparkSession with Matchers with BeforeAndAfterEach {

  import spark.implicits._

  describe("TextSink") {
    it("should write the contents of a DataFrame as text") {
      val data = Seq("datadata", "datadatadata").toDF("single")

      SparkFunction.of(data).write(TextSink("./target/output/text")).run(spark)

      ("target" / "output" / "text").glob("*.txt").map(_.contentAsString).toSeq should contain theSameElementsAs Seq(
        "datadata\n",
        "datadatadata\n"
      )
    }
  }

  override protected def afterEach(): Unit = {
    ("target" / "output" / "text").delete(true)
  }
} 
Example 10
Source File: RichSparkFunctionsSpec.scala    From lighthouse   with Apache License 2.0 5 votes vote down vote up
package be.dataminded.lighthouse.pipeline

import java.io.ByteArrayOutputStream

import be.dataminded.lighthouse.testing.SharedSparkSession
import better.files._
import org.apache.spark.sql.Dataset
import org.apache.spark.storage.StorageLevel
import org.scalatest.BeforeAndAfter
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class RichSparkFunctionsSpec extends AnyFunSpec with Matchers with SharedSparkSession with BeforeAndAfter {

  import spark.implicits._

  describe("SparkFunctions with a DataSet inside should have extra functionality") {

    val function = SparkFunction.of(Seq(1, 2, 3, 4, 5).toDS())

    it("can cache") {
      function.cache().run(spark).storageLevel should equal(StorageLevel.MEMORY_ONLY)
    }

    it("can drop the cache") {
      function.cache().dropCache().run(spark).storageLevel should equal(StorageLevel.NONE)
    }

    it("can be written to a sink") {
      function.write(OrcSink("target/output/orc")).run(spark)

      file"target/output/orc".exists should be(true)
    }

    it("can be written to multiple sinks") {
      function.write(OrcSink("target/output/orc"), OrcSink("target/output/orc2")).run(spark)

      file"target/output/orc".exists should be(true)
      file"target/output/orc2".exists should be(true)
    }

    it("is being cached when writing to multiple sinks for performance") {
      val result = function.write(OrcSink("target/output/orc"), OrcSink("target/output/orc2")).run(spark)

      result.storageLevel should equal(StorageLevel.MEMORY_ONLY)
    }

    it("can easily be counted") {
      function.count().run(spark) should equal(5)
    }

    it("can print the schema") {
      val stream = new ByteArrayOutputStream()
      Console.withOut(stream) {
        function.printSchema().run(spark)
      }
      stream.toString() should include("value: integer (nullable = false)")
    }

    it("can be be used as a Dataset") {
      function.as[Int].run(spark) shouldBe a[Dataset[_]]
    }
  }

  after {
    file"target/output/orc".delete(true)
    file"target/output/orc2".delete(true)
  }
} 
Example 11
Source File: DivideSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package contravariant

import scalaz.Divide
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class DivideSpec
  extends AnyFunSpec
  with Matchers {

  describe("Divide") {

    case class Serializer[A](run: A => Array[Byte])
    val strSerial = Serializer[String](_.getBytes)
    val intSerial = Serializer[Int](_.toString.getBytes)

    case class Fragment(name: String, size: Int)

    it("custom implementation of Fragment serializer") {

      val fragmentSerial = Serializer[Fragment] { frag =>
        val a1 = strSerial.run(frag.name)
        val a2 = intSerial.run(frag.size)
        a1 ++ a2
      }

      val serialized = fragmentSerial.run(Fragment("Area", 52))
      new String(serialized ) mustBe "Area52"
    }

    it("Fragment serializer using Divide") {

      implicit val fragmentDivide: Divide[Serializer] = new Divide[Serializer] {
        def divide2[A1, A2, Z](s1: => Serializer[A1], s2: => Serializer[A2])(f: Z => (A1, A2)):
            Serializer[Z] = Serializer{ frag =>
          val (a1,a2) = f(frag)
          val serialized1 = s1.run(a1)
          val serializedB = s2.run(a2)
          serialized1 ++ serializedB
        }

        def contramap[A, B](r: Serializer[A])(f: B => A): Serializer[B] = Serializer(f andThen r.run)
      }

      val fragAsTuple: Fragment => (String, Int) = frag => (frag.name, frag.size)
      val fragmentSerial: Serializer[Fragment] = Divide[Serializer].divide(
        strSerial, intSerial)(fragAsTuple)

      val serialized = fragmentSerial.run(Fragment("Area", 52))
      new String(serialized ) mustBe "Area52"
    }
  }
} 
Example 12
Source File: PluginParserSpec.scala    From sbt-dependency-updates   with Apache License 2.0 5 votes vote down vote up
package org.jmotor.sbt.parser

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers
import sbt.ModuleID

class PluginParserSpec extends AnyFunSpec with Matchers {

  describe("PluginParser") {
    it("reads normal plugin") {
      val lines =
        """
          |addSbtPlugin("org.jmotor.sbt" % "sbt-dependency-updates" % "1.1.0")
        """.stripMargin.split("\n")
      val found = PluginParser.parse(lines).toList
      found shouldBe Seq(ModuleID("org.jmotor.sbt", "sbt-dependency-updates", "1.1.0"))
    }

    it("reads a few plugins with mixed content") {
      val lines =
        """
          | // comments
          |
          |addSbtPlugin("org.jmotor.sbt" % "sbt-dependency-updates" % "1.1.0")
          |
          |  addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
          |
        """.stripMargin.split("\n")

      val found = PluginParser.parse(lines).toList
      found shouldBe Seq(
        ModuleID("org.jmotor.sbt", "sbt-dependency-updates", "1.1.0"),
        ModuleID("org.scalastyle", "scalastyle-sbt-plugin", "1.0.0"))
    }

    it("doesnt crash on the intellij plugin") {
      val lines =
        """
          |// Generated by IntelliJ-IDEA Scala plugin.
          |// Add settings when starting sbt from IDEA.
          |// Manual changes to this file will be lost.
          |if (java.lang.System.getProperty("idea.runid", "false") == "2017.2") scala.collection.Seq(
          |addSbtPlugin("org.jetbrains" % "sbt-structure-extractor" % "2017.2"),
          |addSbtPlugin("org.jetbrains" % "sbt-idea-shell" % "2017.2")
          |) else scala.collection.Seq.empty%
        """.stripMargin.split("\n")

      PluginParser.parse(lines) shouldBe Seq(ModuleID("org.jetbrains", "sbt-idea-shell", "2017.2"))
    }
  }
} 
Example 13
Source File: SchemaForUtf8Test.scala    From avro4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.avro4s.schema

import com.sksamuel.avro4s.{AvroSchema, Encoder, FromRecord, ImmutableRecord, ToRecord}
import org.apache.avro.util.Utf8
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class SchemaForUtf8Test extends AnyFunSpec with Matchers {

  describe("Serialization of objects containing Utf8 fields") {
    it("should serialize objects that contains simple Utf8 attributes") {
      case class Person(name: Utf8, alias: Utf8, age: Int)

      ToRecord[Person].to(Person(new Utf8("Name"), new Utf8("Alias"), 30))
    }

    it("should serialize objects that contains simple Utf8 attributes and one attribute has a default value") {
      case class Person(name: Utf8, alias: Utf8 = new Utf8("Not specified"), age: Int)

      ToRecord[Person].to(Person(name = new Utf8("Name"), age = 30))
    }

    it("should serialize objects that contains Optional Utf8 attributes") {
      case class Person(name: Utf8, alias: Option[Utf8], age: Int)

      ToRecord[Person].to(Person(new Utf8("Name"), Some(new Utf8("Alias")), 30))
      ToRecord[Person].to(Person(new Utf8("Name"), None, 30))
    }

    it("should serialize objects that contains Optional Utf8 attributes and one attribute has a default value") {
      case class Person(name: Utf8, alias: Option[Utf8] = Some(new Utf8("Not specified")), age: Int)

      ToRecord[Person].to(Person(new Utf8("Name"), Some(new Utf8("Alias")), 30))
      ToRecord[Person].to(Person(new Utf8("Name"), None, 30))
    }
  }

  describe("Deserialization of objects containing Utf8 fields") {
    it("should deserialize objects that contains simple Utf8 attributes") {
      case class Person(name: Utf8, alias: Utf8, age: Int)

      val record = ImmutableRecord(AvroSchema[Person], Vector(new Utf8("Name"), new Utf8("Alias"), 30.asInstanceOf[AnyRef]))
      FromRecord[Person].from(record)
    }

    it("should deserialize objects that contains Optional Utf8 attributes") {
      case class Person(name: Utf8, familyName: Option[Utf8], alias: Option[Utf8], age: Int)

      val record = ImmutableRecord(AvroSchema[Person], Vector(new Utf8("Name"), None, Some(new Utf8("Alias")), 30.asInstanceOf[AnyRef]))
      FromRecord[Person].from(record)
    }
  }

} 
Example 14
Source File: GithubIssue180.scala    From avro4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.avro4s.github

import com.sksamuel.avro4s.github.SampleProtocol.SubPart1.InnerEnum
import com.sksamuel.avro4s.{AvroSchema, FromRecord, ToRecord}
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

import scala.language.higherKinds

object TopEnum extends Enumeration {
  type TopEnumVal = Value
  val v1, v2 = Value
}

case class WithTopEnum(topEnum: TopEnum.TopEnumVal)

object SampleProtocol {
  object SubPart1 {
    object InnerEnum extends Enumeration {
      type InnerEnum = Value
      val vv1, vv2 = Value
    }
  }
}

case class WithInnerEnum(ie: InnerEnum.InnerEnum)

class Githu4bIssue180 extends AnyFunSpec with Matchers {

  describe("SchemaFor : FromRecord : ToRecord") {
    describe("with top level scala Enumerations") {
      val withTopEnum = WithTopEnum(TopEnum.v1)
      it("should be able to compile `FromRecord`") {
        FromRecord[WithTopEnum] shouldNot be(null)
      }
      it("should be able to compile `ToRecord`") {
        ToRecord[WithTopEnum] shouldNot be(null)
      }
      it("should be able to compile `SchemaFor`") {
        AvroSchema[WithTopEnum] shouldNot be(null)
      }
    }

    describe("with non-top level scala Enumerations") {
      val withInnerEnum = WithInnerEnum(InnerEnum.vv1)
      it("should be able to compile `FromRecord`") {
        FromRecord[WithInnerEnum] shouldNot be(null)
      }
      it("should be able to compile `ToRecord`") {
        ToRecord[WithInnerEnum] shouldNot be(null)
      }
      it("should be able to compile `SchemaFor`") {
        AvroSchema[WithInnerEnum] shouldNot be(null)
      }
    }
  }
} 
Example 15
Source File: Issue145.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import com.twilio.guardrail._
import com.twilio.guardrail.generators.Scala.AkkaHttp
import com.twilio.guardrail.generators.syntax.Scala.companionForStaticDefns
import support.SwaggerSpecRunner

import scala.meta._
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class Issue145 extends AnyFunSpec with Matchers with SwaggerSpecRunner {

  describe("Generate hierarchical classes") {

    val swagger: String = """
      | swagger: '2.0'
      | info:
      |   title: Parsing Error Sample
      |   version: 1.0.0
      | definitions:
      |   Pet:
      |     type: object
      |     properties:
      |       name:
      |         type: string
      |         x-scala-empty-is-null: true
      |         x-scala-type: CustomThing
      |       underscore_name:
      |         type: string
      |         x-scala-empty-is-null: true
      |         x-scala-type: CustomThing
      |       dash-name:
      |         type: string
      |         x-scala-empty-is-null: true
      |         x-scala-type: CustomThing
      |""".stripMargin

    val (
      ProtocolDefinitions(
        ClassDefinition(namePet, tpePet, _, clsPet, staticDefnsPet, catParents) :: Nil,
        _,
        _,
        _
      ),
      _,
      _
    ) = runSwaggerSpec(swagger)(Context.empty, AkkaHttp)

    it("should generate right companion object") {
      val cmp       = companionForStaticDefns(staticDefnsPet)
      val companion = q"""
        object Pet {
          implicit val encodePet: Encoder.AsObject[Pet] = {
            val readOnlyKeys = Set[String]()
            Encoder.AsObject.instance[Pet](a => JsonObject.fromIterable(Vector(("name", a.name.asJson), ("underscore_name", a.underscoreName.asJson), ("dash-name", a.dashName.asJson)))).mapJsonObject(_.filterKeys(key => !(readOnlyKeys contains key)))
          }
          implicit val decodePet: Decoder[Pet] = new Decoder[Pet] { final def apply(c: HCursor): Decoder.Result[Pet] = for (v0 <- c.downField("name").withFocus(j => j.asString.fold(j)(s => if (s.isEmpty) Json.Null else j)).as[Option[CustomThing]]; v1 <- c.downField("underscore_name").withFocus(j => j.asString.fold(j)(s => if (s.isEmpty) Json.Null else j)).as[Option[CustomThing]]; v2 <- c.downField("dash-name").withFocus(j => j.asString.fold(j)(s => if (s.isEmpty) Json.Null else j)).as[Option[CustomThing]]) yield Pet(v0, v1, v2) }
        }
      """

      cmp.structure shouldBe companion.structure
    }

  }
} 
Example 16
Source File: Issue260.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.issues

import com.twilio.guardrail.generators.Scala.Http4s
import com.twilio.guardrail.{ Context, Server, Servers }
import support.SwaggerSpecRunner
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class Issue260 extends AnyFunSpec with Matchers with SwaggerSpecRunner {

  describe("LocalDate path param is generated more than once") {

    val swagger: String = """
      | openapi: "3.0.0"
      | info:
      |   title: Generator Error Sample
      |   version: 1.0.0
      | paths:
      |   /users/{userId}/occasions/{date}:
      |     parameters:
      |       - $ref: '#/components/parameters/UserIdParam'
      |       - $ref: '#/components/parameters/DateParam'
      |     get:
      |       operationId: getOccasionByDate
      |       responses:
      |         200:
      |           description: Requested occasion
      |           content:
      |             application/json:
      |               schema:
      |                 $ref: '#/components/schemas/OccasionResponseJson'
      |         404:
      |           description: Requested user or occasion was not found
      |     delete:
      |       operationId: deleteOccasionByDate
      |       responses:
      |         204:
      |           description: Succesfully deleted occasion
      |         404:
      |           description: Requested user or occasion was not found
      | components:
      |   parameters:
      |     UserIdParam:
      |       name: userId
      |       in: path
      |       description: Id of the specific user
      |       required: true
      |       schema:
      |         type: string
      |     DateParam:
      |       name: date
      |       in: path
      |       description: Date of the specific occasion
      |       required: true
      |       schema:
      |         type: string
      |         format: date
      |   schemas:
      |     OccasionResponseJson:
      |       type: object
      |       properties:
      |         date:
      |           type: string
      |           format: date
      |       required:
      |         - date""".stripMargin

    val (
      _, // ProtocolDefinitions
      _, // clients
      Servers(
        Server(
          _, // pkg
          _, // extraImports
          _, // genHandler
          serverDefinition :: _
        ) :: Nil,
        _ // supportDefinitions
      )
    ) = runSwaggerSpec(swagger)(Context.empty, Http4s)

    it("Ensure LocalDateVar is generated only once") {

      val pattern = "object LocalDateVar".r

      val hits = pattern.findAllIn(serverDefinition.toString()).length

      hits shouldBe 1
    }
  }
} 
Example 17
Source File: ValidationTest.scala    From shaclex   with MIT License 5 votes vote down vote up
package es.weso.slang
import org.scalatest.matchers.should.Matchers 
import org.scalatest.funspec.AnyFunSpec

import es.weso.rdf.jena.RDFAsJenaModel
import es.weso.rdf.nodes.IRI
import es.weso.shex.Schema
import cats.data._ 
import cats.effect._ 
import es.weso.utils.IOUtils._

class ValidationTest extends AnyFunSpec with Matchers with SLang2Clingo with ShEx2SLang {

  describe(s"SLang validation") {
    it(s"Should validate simple example") {
      val node = IRI("http://example.org/a")
      val shape: SLang  = Ref(IRILabel(IRI("http://example.org/User")))
      val r: EitherT[IO,String,ShapesMap] = for {
        rdf <- io2es(RDFAsJenaModel.fromChars(
          """|<a> <name> "a" ;
             | <knows> <a> .
            |
          """.stripMargin, "TURTLE",Some(IRI("http://example.org/"))))
        schema <- io2es(Schema.fromString(
          """|
             |<User> {
             | <name> . ;
             | <knows> .
             |}
          """.stripMargin, "ShEXC",Some(IRI("http://example.org/"))))
        slangSchema <- shex2SLang(schema)
        eitherResult <- io2es(Validation.runValidation(node, shape, rdf, slangSchema))
        result <- either2es(eitherResult)
      } yield result

      run_es(r).unsafeRunSync.fold(e => fail(s"Error: $e"), result => {
        result.isConforming(node, shape) should be(Conforms)
      })
    }
  }
} 
Example 18
Source File: MyListSpec.scala    From scala-quiz   with MIT License 5 votes vote down vote up
package com.chatwork.quiz.collection

import com.chatwork.quiz.{ MyNone, MySome }
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class MyListSpec extends AnyFunSpec with Matchers {

  describe("MyList#apply") {
    it("should return a new MyList instance") {
      MyList(1, 2, 3) shouldEqual MyCons(1, MyCons(2, MyCons(3, MyNil)))
      MyList() shouldEqual MyNil
    }
  }

  describe("MyList#foldLeft") {
    it("should apply an operator a start value and all elements from left to right") {
      MyList("H", "e", "l", "l", "o").foldLeft("Say ") { _ + _ } shouldEqual "Say Hello"
    }
  }

  describe("MyList#foldRight") {
    it("should apply an operator a start value and all elements from right to left") {
      MyList("H", "e", "l", "l", "o").foldRight(" World") { _ + _ } shouldEqual "Hello World"
    }
  }

  describe("MyList#::") {
    it("should return a new MyList added an element at the beginning of this list") {
      "H" :: MyList("e", "l", "l", "o") shouldEqual MyList("H", "e", "l", "l", "o")
    }
  }

  describe("MyList#reverse") {
    it("should return a new MyList with elements in reversed order") {
      MyList(1, 2, 3, 4).reverse shouldEqual MyList(4, 3, 2, 1)
    }
  }

  describe("MyList#++") {
    it("should return a new MyList with elements appended") {
      MyList(1, 2) ++ MyList(3, 4) shouldEqual MyList(1, 2, 3, 4)
    }
  }

  describe("MyList#map") {
    it("should apply an operator to each element in the list") {
      MyList(1, 2, 3, 4).map(_ * 2) shouldEqual MyList(2, 4, 6, 8)
    }
  }

  describe("MyList#flatMap") {
    it("should apply an operator to each element in the list and flatten") {
      MyList(MyList(1, 2), MyList(3, 4), MyList(5, 6), MyList(7, 8))
        .flatMap(_.map(_ * 2)) shouldEqual MyList(2, 4, 6, 8, 10, 12, 14, 16)
    }
  }

  describe("MyList#filter") {
    it("should return a new MyList containing elements filtered by the given predicate") {
      MyList(1, 2, 3, 4, 5).filter(_ > 3) shouldEqual MyList(4, 5)
    }
  }

  describe("MyList#find") {
    it("should return the first element of the sequence satisfying a predicate") {
      MyList(1, 2, 3, 4, 5).find(_ == 1) shouldEqual MySome(1)
      MyList(1, 2, 3, 4, 5).find(_ == 6) shouldEqual MyNone
    }
  }

  describe("for comprehension") {
    it("should provide for comprehension") {
      (for {
        suit   <- MyList("Diamond", "Heart", "Spade", "Club")
        number <- MyList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
        if suit == "Diamond"
      } yield {
        (suit, number)
      }).length shouldBe 13
    }
  }

} 
Example 19
Source File: WordCounterSpec.scala    From scala-quiz   with MIT License 5 votes vote down vote up
package com.chatwork.quiz.misc

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class WordCounterSpec extends AnyFunSpec with Matchers {

  describe("WordCounter#countWord") {
    it("should count words") {
      val words = List("apple banana", "orange apple mango", "kiwi papaya orange", "mango orange muscat apple")
      WordCounter.countWords(words) shouldBe Map(
        "banana" -> 1,
        "muscat" -> 1,
        "orange" -> 3,
        "mango"  -> 2,
        "apple"  -> 3,
        "kiwi"   -> 1,
        "papaya" -> 1
      )
    }
  }

} 
Example 20
Source File: BTreeSpec.scala    From scala-quiz   with MIT License 5 votes vote down vote up
package com.chatwork.quiz.misc

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

import scala.math.Ordering.IntOrdering

class BTreeSpec extends AnyFunSpec with Matchers {

  describe("BTree#size") {
    it("should return the number of elements in the BTree") {
      BTree(Branch(Leaf(1), 2, Leaf(3))).size shouldBe 3
      BTree(Leaf(1)).size shouldBe 1
    }
  }

  describe("BTree#max") {
    it("should return the max value in the BTree") {
      BTree(Branch(Leaf(1), 2, Leaf(3))).max shouldBe 3
    }
  }

  describe("BTree#min") {
    it("should return the min value in the BTree") {
      BTree(Branch(Leaf(1), 2, Leaf(3))).min shouldBe 1
    }
  }

  describe("BTree#sum") {
    it("should return the sum of values in the BTree") {
      BTree(Branch(Leaf(1), 2, Leaf(3))).sum shouldBe 6
    }
  }

  describe("BTree#avg") {
    it("should return the average of values in the BTree") {
      BTree(Branch(Leaf(1), 2, Leaf(3))).avg shouldBe 2.0d
    }
  }

  describe("BTree#find") {
    it("should return a node has the value in the BTree") {
      BTree(Branch(Leaf(1), 2, Leaf(3))).find(1) shouldBe Some(Leaf(1))
    }
  }

  describe("BTree#apply") {
    it("should return a new BTree from List[Int]") {
      BTree(List(1, 2, 3)) shouldEqual BTree(Branch(Leaf(1), 2, Leaf(3)))
    }
  }

} 
Example 21
Source File: ApplicativeExamplesSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package applicative

import educational.category_theory.Applicative
import educational.collections.HeadNel
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class ApplicativeExamplesSpec
  extends AnyFunSpec
  with Matchers {

  describe("derived methods") {
    it("option instance") {
      val optionApplicative: Applicative[Option] = new Applicative[Option] {
        def pure[A](a: A): Option[A] = ???
        def ap[A, B](ff: Option[A => B])(fa: Option[A]): Option[B] = ???
      }

      // TODO
    }

    it("ValidatedNel instance") {
      sealed trait ValidatedNel[A]
      case class SuccessVN[A](value: A) extends ValidatedNel[A]
      case class Errors[A](errors: HeadNel[Throwable]) extends ValidatedNel[A]

      val optionApplicative: Applicative[ValidatedNel] = new Applicative[ValidatedNel] {
        override def pure[A](value: A): ValidatedNel[A] = ???
        override def ap[A, B](ff: ValidatedNel[A => B])(fa: ValidatedNel[A]): ValidatedNel[B] = ???
      }

      // TODO
    }

    it("examples for Option") {
      import cats.Applicative
      import cats.implicits.catsStdInstancesForOption

      val add3: Int => Int = a => a + 3

      Applicative[Option].pure(42) mustBe Some(42)
      Applicative[Option].ap(Some(add3))(Some(39)) mustBe Some(42)
    }

    it("examples for List") {
      import cats.Applicative
      import cats.implicits.catsStdInstancesForList


      val list1 = List(1, 2)
      val listFns: List[Int => Int] = List(a => a + 3, a => a * a)

      Applicative[List].ap(listFns)(list1) mustBe List(4,5,1,4)
      Applicative[List].pure("foo") mustBe List("foo")
    }

    it("map2 on composed Applicative") {
      import cats.Applicative
      import cats.implicits.catsStdInstancesForList
      import cats.implicits.catsStdInstancesForOption

      val listOpt = Applicative[List] compose Applicative[Option]

      val list1 = List(Some(2), None)
      val list2 = List(Some(10), Some(2))
      listOpt.map2(list1, list2)(_ + _) mustBe List(Some(12), Some(4), None, None)
    }
  }
} 
Example 22
Source File: ProbabilityDistributionTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.agents

import java.util.Random
import org.scalatest.funspec.AnyFunSpec

class ProbabilityDistributionTest extends AnyFunSpec {

  describe("Select from a distribution") {

    it("should be low index if distribution skewed low") {
      val dist = createPDist(Array(0.9, 0.8, 0.5, 0.3, 0.2, 0.1, 0.01, 0.001))
      assert(dist.selectRandomIdx() == 2)
      assert(dist.selectRandomIdx() == 1)
      assert(dist.selectRandomIdx() == 0)
    }

    it("should be high index if distribution skewed high") {
      val dist = createPDist(Array(0.001, 0.01, 0.1, 0.3, 0.8, 0.5, 0.8, 0.9))
      assert(dist.selectRandomIdx() == 6)
    }

    it("should be highest index if distribution skewed very high") {
      val dist = createPDist(Array(0.001, 0.01, 0.01, 0.01, 0.01, 0.1, 0.9))
      assert(dist.selectRandomIdx() == 6)
    }

    it("should be near middle if gaussian distribution") {
      val dist = createPDist(Array(0.001, 0.01, 0.1, 0.3, 0.6, 0.8, 0.9, 0.9, 0.8, 0.55, 0.4, 0.2, 0.05, 0.01))
      assert(dist.selectRandomIdx() == 8)
    }

    it("random if uniform distribution") {
      val dist = createPDist(Array(0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2))
      assert(dist.selectRandomIdx() == 5)
    }

    it("should be 0 index if distribution has only 1 0 value") {
      val dist = createPDist(Array(0.0))
      assert(dist.selectRandomIdx() == 0)
    }
  }

  private def createPDist(a: Array[Double]) = ProbabilityDistribution(a, new Random(1))
} 
Example 23
Source File: ZeroAgentTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.agents

import java.io.File

import org.deeplearning4j.nn.graph.ComputationGraph
import org.deeplearning4j.scalphagozero.board.{ BlackPlayer, GameState, GoBoard }
import org.deeplearning4j.scalphagozero.board.Move.Play
import org.deeplearning4j.scalphagozero.encoders.ZeroEncoder
//import org.nd4j.linalg.api.ndarray.INDArray
import org.scalatest.funspec.AnyFunSpec
import org.deeplearning4j.scalphagozero.PATH_PREFIX
//import scala.collection.mutable.ListBuffer
import scala.util.Random



  // 1 .O.O.
  // 2 OOOO.
  // 3 .XX.X
  // 4 .X.X.
  // 5 .XOX.
  //   12345
  private def createSimple5x5GameState(): GameState = {
    var state = GameState(GoBoard(5), BlackPlayer)
    state = state.applyMove(Play(3, 3))
    state = state.applyMove(Play(2, 3)) // white
    state = state.applyMove(Play(3, 2))
    state = state.applyMove(Play(2, 2)) // white
    state = state.applyMove(Play(4, 2))
    state = state.applyMove(Play(2, 1)) // white
    state = state.applyMove(Play(4, 4))
    state = state.applyMove(Play(5, 3)) // white
    state = state.applyMove(Play(5, 2))
    state = state.applyMove(Play(2, 4)) // white
    state = state.applyMove(Play(3, 5))
    state = state.applyMove(Play(1, 4)) // white
    state = state.applyMove(Play(5, 4))
    state = state.applyMove(Play(1, 2)) // white
    //println(state.board)
    state
  }
} 
Example 24
Source File: ZeroTreeNodeCreatorTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.agents

import java.io.File
import org.deeplearning4j.nn.graph.ComputationGraph
import org.deeplearning4j.scalphagozero.PATH_PREFIX
import org.deeplearning4j.scalphagozero.board.Move.Play
import org.deeplearning4j.scalphagozero.board.{ BlackPlayer, GameState, GoBoard, Move }
import org.deeplearning4j.scalphagozero.encoders.ZeroEncoder
import org.deeplearning4j.scalphagozero.strip
import org.scalatest.funspec.AnyFunSpec

class ZeroTreeNodeCreatorTest extends AnyFunSpec {

  describe("zeroTreeNode creation") {

    val model: ComputationGraph =
      ComputationGraph.load(new File(PATH_PREFIX + "model_size_5_layers_2_test.model"), true)
    val encoder = new ZeroEncoder(5)
    val creator = new ZeroTreeNodeCreator(model, encoder)

    val gameState = createSimple5x5GameState()

    val zeroTreeNode = creator.createNode(gameState: GameState)
    it("should create expected zero tree node given gameState") {
      assert(zeroTreeNode.lastMove.isEmpty)
      assert(
        zeroTreeNode.gameState.board.toString ==
          strip("""--------
            | 5 .O.O.
            | 4 OOOO.
            | 3 .XX.X
            | 2 .X.X.
            | 1 .XOX.
            |   ABCDE
            |--------""")
      )
      assert(zeroTreeNode.totalVisitCount == 1)

      val validNextMoves = List(
        Play(5, 1),
        Play(3, 1),
        Play(5, 5),
        Play(4, 1),
        Play(4, 5),
        Play(4, 3),
        Play(1, 5),
        Move.Pass,
        Play(2, 5),
        Play(3, 4)
      )
      assert(zeroTreeNode.moves == validNextMoves)
    }

    it("should not have a child move that is not a valid next move") {
      assert(!zeroTreeNode.branches.keySet.contains(Play(2, 3)))
    }

    it("should have expected values after move(3, 4)") {
      val move = Move.Play(3, 4)
      assert(zeroTreeNode.branches.keySet.contains(move))
      assert(zeroTreeNode.expectedValue(move) == 0)
      assert(zeroTreeNode.visitCount(move) == 0)
      assert(Math.abs(zeroTreeNode.prior(move) - 0.0465302057564) < 0.000001)
    }

    it("should have expected values after move(2, 5)") {
      val move = Move.Play(2, 5)
      assert(zeroTreeNode.branches.keySet.contains(move))
      assert(zeroTreeNode.expectedValue(move) == 0)
      assert(zeroTreeNode.visitCount(move) == 0)
      assert(Math.abs(zeroTreeNode.prior(move) - 0.04731213673949) < 0.000001)
    }
  }

  // 1 .O.O.
  // 2 OOOO.
  // 3 .XX.X
  // 4 .X.X.
  // 5 .XOX.
  //   12345
  private def createSimple5x5GameState(): GameState = {
    var state = GameState(GoBoard(5), BlackPlayer)
    state = state.applyMove(Play(3, 3))
    state = state.applyMove(Play(2, 3)) // white
    state = state.applyMove(Play(3, 2))
    state = state.applyMove(Play(2, 2)) // white
    state = state.applyMove(Play(4, 2))
    state = state.applyMove(Play(2, 1)) // white
    state = state.applyMove(Play(4, 4))
    state = state.applyMove(Play(5, 3)) // white
    state = state.applyMove(Play(5, 2))
    state = state.applyMove(Play(2, 4)) // white
    state = state.applyMove(Play(3, 5))
    state = state.applyMove(Play(1, 4)) // white
    state = state.applyMove(Play(5, 4))
    state = state.applyMove(Play(1, 2)) // white
    //println(state.board)
    state
  }
} 
Example 25
Source File: ValidatorTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.input

import org.deeplearning4j.scalphagozero.board.Move.Play
import org.scalatest.funspec.AnyFunSpec

class ValidatorTest extends AnyFunSpec {

  val validator = new Validator()

  describe("Input 4,C") {

    val expectedResult = Some(Play(2, 3))
    it("should have input = 4C") {
      assertResult(expectedResult) { validator.getValidMove("4,C", 5) }
      assertResult(expectedResult) { validator.getValidMove("4,c", 5) }
      assertResult(expectedResult) { validator.getValidMove("4;C", 5) }
      assertResult(expectedResult) { validator.getValidMove("4C", 5) }
      assertResult(expectedResult) { validator.getValidMove("4c", 5) }
    }
  }

  describe("Invalid input") {

    it("should give None for invalid input") {
      assertResult(None) { validator.getValidMove("XX", 5) }
      assertResult(None) { validator.getValidMove("X", 5) }
      assertResult(None) { validator.getValidMove("", 5) }
      assertResult(None) { validator.getValidMove(",,", 5) }
      assertResult(None) { validator.getValidMove("sdf;sd", 5) }
      assertResult(None) { validator.getValidMove("$a", 5) }
    }

  }
} 
Example 26
Source File: ScalphaGoEngineTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.gtp

import org.deeplearning4j.scalphagozero.board.GoBoardSerializer
import org.deeplearning4j.scalphagozero.strip
import org.lisoft.gonector.{ Move, Player }
import org.scalatest.funspec.AnyFunSpec
import scala.util.Random

class ScalphaGoEngineTest extends AnyFunSpec {

  val serializer = new GoBoardSerializer()
  val numLayers = 2

  describe("For Engine genmove black") {
    val engine = createGoEngine
    engine.resizeBoard(5)

    it("has valid next black move") {
      assert(engine.nextMove(Player.BLACK) == new Move(2, 2))
    }
  }

  describe("For Engine genmove white") {
    val engine = createGoEngine
    engine.resizeBoard(5)

    engine.addMove(new Move(2, 3), Player.BLACK)
    engine.addMove(new Move(3, 2), Player.WHITE)
    engine.addMove(new Move(3, 3), Player.BLACK)

    println(serializer.serialize(engine.getGameState.board))

    it("has valid next white move") {
      assert(engine.nextMove(Player.WHITE) == new Move(1, 1))
    }
  }

  describe("For Engine genmove black after many stones placed") {
    val engine = createGoEngine
    engine.resizeBoard(5)

    engine.addMove(new Move(2, 3), Player.BLACK)
    engine.addMove(new Move(3, 2), Player.WHITE)
    engine.addMove(new Move(3, 3), Player.BLACK)
    engine.addMove(new Move(4, 4), Player.WHITE)

    println(serializer.serialize(engine.getGameState.board))

    it("has valid next black move") {
      assert(engine.nextMove(Player.BLACK) == new Move(2, 2))
    }
  }

  describe("Play game with genmoves") {
    val engine = createGoEngine
    engine.resizeBoard(5)

    engine.nextMove(Player.BLACK)
    engine.nextMove(Player.WHITE)
    engine.nextMove(Player.BLACK)
    engine.nextMove(Player.WHITE)
    engine.nextMove(Player.BLACK)
    engine.nextMove(Player.WHITE)

    // println(serializer.serialize(engine.getGameState.board))

    it("has expected board state") {
      assert(
        engine.getGameState.board.toString ==
          strip("""--------
           | 5 .....
           | 4 .....
           | 3 .OXX.
           | 2 .XOO.
           | 1 .....
           |   ABCDE
           |--------""")
      )
    }
  }

  private def createGoEngine = ScalphaGoEngine(numLayers, new Random(1))
} 
Example 27
Source File: GameStateTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.board

import org.deeplearning4j.scalphagozero.board.Move.Play
import org.scalatest.funspec.AnyFunSpec

class GameStateTest extends AnyFunSpec {

  describe("Starting a new 19x19 game") {
    val start = GameState.newGame(19)
    it("should apply moves") {
      val nextState = start.applyMove(Move.Play(Point(16, 16)))

      assert(start == nextState.previousState.get)
      assert(nextState.board.getPlayer(Point(16, 16)).get == BlackPlayer)
      assert(nextState.nextPlayer == WhitePlayer)
    }
  }

  describe("Detect ko in a 5x5 game") {
    var game = GameState.newGame(5)

    it("Apply moves, until ko rule is take the first time") {
      game = game.applyMove(Play(3, 3))
      game = game.applyMove(Play(3, 4))
      game = game.applyMove(Play(4, 4))
      game = game.applyMove(Play(4, 5))
      game = game.applyMove(Play(2, 4))
      game = game.applyMove(Play(2, 5))
      val previous = game
      game = game.applyMove(Play(Point(3, 5))) // initial ko capture
      println("After initial ko: " + game.board)

      assert(previous == game.previousState.get)
      assert(game.board.getPlayer(Point(3, 5)).get == BlackPlayer)
      assert(game.board.getPlayer(Point(3, 4)).isEmpty)
    }

    it("Ko is not allowed to be immediately retaken") {
      println("After initial ko2: " + game.board)
      assert(game.doesMoveViolateKo(WhitePlayer, Play(3, 4)))
    }
  }

  describe("No winner at start of the game") {
    var game = GameState.newGame(5)
    it("should have no winner yet") {
      assert(game.gameResult().isEmpty)
    }

    game = game.applyMove(Play(3, 3))
    game = game.applyMove(Play(3, 4))
    game = game.applyMove(Play(4, 4))
    game = game.applyMove(Play(4, 5))
    it("should have no winner after a few moves played") {
      assert(game.gameResult().isEmpty)
    }
  }

  describe("Won after black player resigns") {
    var game = GameState.newGame(5)
    game = game.applyMove(Play(3, 3)) // black play
    game = game.applyMove(Play(2, 3)) // white play

    it("should be a white win by resignation") {
      game = game.applyMove(Move.Resign)
      val result = game.gameResult().get
      assert(result.winner == WhitePlayer)
      assert(result.toString == "White won by resignation")
    }
  }

  describe("Won after white player resigns") {
    var game = GameState.newGame(5)
    game = game.applyMove(Play(3, 3))
    it("should be a black win") {
      game = game.applyMove(Move.Resign)
      val result = game.gameResult().get
      assert(result.winner == BlackPlayer)
      assert(result.toString == "Black won by resignation")
    }
  }

  describe("Won only after both players pass") {
    var game = GameState.newGame(5)
    game = game.applyMove(Play(3, 3))
    game = game.applyMove(Move.Pass)
    it("should have no winner yet") {
      assert(game.gameResult().isEmpty)
    }

    it("should have winner after the second consecutive pass") {
      game = game.applyMove(Move.Pass)
      // black wins because they have one more stone on the board.
      val result = game.gameResult().get
      assert(result.winner == BlackPlayer)
      assert(result.toString == "Black +24.5")
    }
  }
} 
Example 28
Source File: GoStringTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.board

import org.scalatest.funspec.AnyFunSpec

class GoStringTest extends AnyFunSpec {

  describe("Create an empty string") {
    it("should create empty string") {
      val goString = GoString(BlackPlayer, Set(), Set())

      assertResult(0) { goString.numLiberties }
      assertResult("GoString(BlackPlayer,Set(),Set())") {
        goString.toString
      }
    }
  }

  describe("Create a simple string") {

    val stones = Set(Point(2, 2))
    val liberties = Set((1, 2), (3, 2), (2, 1), (2, 3)).map(p => new Point(p))

    it("should create simple string with one stone") {
      val goString = GoString(BlackPlayer, stones, liberties)

      assertResult(4) { goString.numLiberties }
      assertResult("GoString(BlackPlayer,Set(Point(2,2)),Set(Point(1,2), Point(3,2), Point(2,1), Point(2,3)))") {
        goString.toString
      }
    }
  }

  // OOO
  // O O
  // OO    assume surrounded by black
  describe("Create a string with one eye") {

    val stones = Set((2, 2), (2, 3), (2, 4), (3, 2), (3, 4), (4, 2), (4, 3)).map(new Point(_))
    val liberties = Set(Point(3, 3))

    it("should create simple string with one eye and one liberty") {
      val goString = GoString(BlackPlayer, stones, liberties)

      assertResult(1) { goString.numLiberties }
    }
  }

  describe("Add liberty to string") {

    val stones = Set(Point(2, 2))
    val liberties = Set((1, 2), (3, 2)).map(p => new Point(p))
    it("should have one more liberty") {
      val goString = GoString(BlackPlayer, stones, liberties)
      assert(goString.numLiberties === 2)
      assertResult(3) { goString.withLiberty(Point(2, 1)).numLiberties }
    }
  }

  describe("Remove liberty from string") {

    val stones = Set(Point(2, 2))
    val liberties = Set((1, 2), (3, 2), (2, 1), (2, 3)).map(p => new Point(p))

    it("should have one fewer liberties") {
      val goString = GoString(BlackPlayer, stones, liberties)
      assert(goString.numLiberties === 4)
      var gs = goString.withoutLiberty(Point(2, 1))
      assertResult(3) { gs.numLiberties }
      gs = gs.withoutLiberty(Point(2, 3))
      assertResult(2) { gs.numLiberties }
    }
  }

  describe("Merge strings") {

    it("should have 6 liberties when merged") {
      val stones1 = Set(Point(2, 2))
      val liberties1 = Set((1, 2), (2, 1), (3, 2), (2, 3)).map(p => new Point(p))
      val goString1 = GoString(BlackPlayer, stones1, liberties1)

      val stones2 = Set(Point(2, 3))
      val liberties2 = Set((2, 2), (2, 4), (1, 3), (3, 3)).map(p => new Point(p))
      val goString2 = GoString(BlackPlayer, stones2, liberties2)

      assertResult(4) { goString1.numLiberties }
      assertResult(4) { goString2.numLiberties }
      val mergedString = goString1.mergedWith(goString2)
      assertResult(6) { mergedString.numLiberties }
      assertResult(
        "GoString(BlackPlayer,Set(Point(2,2), Point(2,3)),Set(Point(3,2), Point(1,3), Point(2,4), Point(3,3), Point(1,2), Point(2,1)))"
      ) {
        mergedString.toString
      }
    }
  }

} 
Example 29
Source File: GoBoardBoundsCheckerTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.board

import org.scalatest.funspec.AnyFunSpec

class GoBoardBoundsCheckerTest extends AnyFunSpec {

  describe("Verify piece played on the board") {
    val boundsChecker = GoBoardBoundsChecker.get(9)

    it("is within the board boundary") {
      assert(boundsChecker.inBounds(Point(2, 2)))
      assert(boundsChecker.inBounds(Point(1, 1)))
      assert(boundsChecker.inBounds(Point(9, 9)))
      assert(boundsChecker.inBounds(Point(1, 9)))
    }
  }

  describe("Verify piece played outside the board") {
    val boundsChecker = GoBoardBoundsChecker.get(9)

    it("is not within the board boundary") {
      assert(!boundsChecker.inBounds(Point(0, 2)))
      assert(!boundsChecker.inBounds(Point(1, 0)))
      assert(!boundsChecker.inBounds(Point(10, 9)))
      assert(!boundsChecker.inBounds(Point(8, 10)))
      assert(!boundsChecker.inBounds(Point(0, 0)))
      assert(!boundsChecker.inBounds(Point(-3, 10)))
      assert(!boundsChecker.inBounds(Point(102, 140)))
    }
  }

  describe("Verify piece played not on the edge") {
    val boundsChecker = GoBoardBoundsChecker.get(9)

    it("is not on the edge") {
      assert(!boundsChecker.isEdge(Point(2, 2)))
      assert(!boundsChecker.isEdge(Point(5, 5)))
      assert(!boundsChecker.isEdge(Point(8, 7)))
      assert(!boundsChecker.isEdge(Point(-3, 10)))
      assert(!boundsChecker.isEdge(Point(102, 140)))
    }
  }

  describe("Verify piece played on the edge") {
    val boundsChecker = GoBoardBoundsChecker.get(9)

    it("is on the edge") {
      assert(boundsChecker.isEdge(Point(1, 7)))
      assert(boundsChecker.isEdge(Point(7, 1)))
      assert(boundsChecker.isEdge(Point(9, 5)))
      assert(boundsChecker.isEdge(Point(4, 9)))
      assert(boundsChecker.isEdge(Point(9, 9)))
      assert(boundsChecker.isEdge(Point(1, 1)))
    }
  }

  describe("Verify piece played not in a corner") {
    val boundsChecker = GoBoardBoundsChecker.get(9)

    it("is not in a corner") {
      assert(!boundsChecker.isCorner(Point(2, 2)))
      assert(!boundsChecker.isCorner(Point(5, 5)))
      assert(!boundsChecker.isCorner(Point(8, 7)))
      assert(!boundsChecker.isCorner(Point(-3, 10)))
      assert(!boundsChecker.isCorner(Point(102, 140)))
    }
  }

  describe("Verify piece played in a corner") {
    val boundsChecker = GoBoardBoundsChecker.get(9)

    it("is in a corner") {
      assert(boundsChecker.isCorner(Point(1, 1)))
      assert(boundsChecker.isCorner(Point(9, 9)))
      assert(boundsChecker.isCorner(Point(9, 1)))
      assert(boundsChecker.isCorner(Point(1, 9)))
    }
  }
} 
Example 30
Source File: GoBoardSerializerTest.scala    From ScalphaGoZero   with Apache License 2.0 5 votes vote down vote up
package org.deeplearning4j.scalphagozero.board

import org.deeplearning4j.scalphagozero.strip
import org.scalatest.funspec.AnyFunSpec

class GoBoardSerializerTest extends AnyFunSpec {

  describe("Serialize a board") {
    var board = GoBoard(9)
    it("should have this format") {
      board = board.placeStone(BlackPlayer, Point(2, 2))
      board = board.placeStone(WhitePlayer, Point(3, 3))
      board = board.placeStone(BlackPlayer, Point(2, 3))
      board = board.placeStone(WhitePlayer, Point(5, 4))

      assertResult(strip("""------------
                     | 9 .........
                     | 8 .XX......
                     | 7 ..O......
                     | 6 .........
                     | 5 ...O.....
                     | 4 .........
                     | 3 .........
                     | 2 .........
                     | 1 .........
                     |   ABCDEFGHI
                     |------------""")) { board.toString }
    }
  }

  describe("Serialize another board") {
    var board = GoBoard(9)
    it("should have this format") {
      board = board.placeStone(BlackPlayer, Point(1, 1))
      board = board.placeStone(WhitePlayer, Point(3, 3))
      board = board.placeStone(BlackPlayer, Point(2, 3))
      board = board.placeStone(WhitePlayer, Point(5, 4))

      assertResult(strip("""------------
                           | 9 X........
                           | 8 ..X......
                           | 7 ..O......
                           | 6 .........
                           | 5 ...O.....
                           | 4 .........
                           | 3 .........
                           | 2 .........
                           | 1 .........
                           |   ABCDEFGHI
                           |------------""")) { board.toString }
    }

  }
} 
Example 31
Source File: OrderInstancesSpec.scala    From fs2-rabbit   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.fs2rabbit.laws

import java.time.Instant

import cats._
import cats.implicits._
import cats.kernel.laws.discipline._
import dev.profunktor.fs2rabbit.model.AmqpFieldValue._
import dev.profunktor.fs2rabbit.model._
import dev.profunktor.fs2rabbit.testkit._
import org.scalacheck.Arbitrary._
import org.scalatest.funspec.AnyFunSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.typelevel.discipline.scalatest.FunSpecDiscipline

class OrderInstancesSpec
    extends AnyFunSpec
    with FunSpecDiscipline
    with ScalaCheckPropertyChecks
    with InstantArbitraries {
  implicit val orderInstant: Order[Instant] = Order.by(_.getEpochSecond)

  checkAll("ExchangeName.OrderLaws", OrderTests[ExchangeName].order)
  checkAll("QueueName.OrderLaws", OrderTests[QueueName].order)
  checkAll("RoutingKey.OrderLaws", OrderTests[RoutingKey].order)
  checkAll("DeliveryTag.OrderLaws", OrderTests[DeliveryTag].order)
  checkAll("ConsumerTag.OrderLaws", OrderTests[ConsumerTag].order)
  checkAll("Instant.OrderLaws", OrderTests[Instant](instantOrderWithSecondPrecision).order)
  checkAll("DeliveryMode.OrderLaws", OrderTests[DeliveryMode].order)
  checkAll("ShortString.OrderLaws", OrderTests[ShortString].order)
  checkAll("TimestampVal.OrderLaws", OrderTests[TimestampVal].order)
  checkAll("DecimalVal.OrderLaws", OrderTests[DecimalVal].order)
  checkAll("ByteVal.OrderLaws", OrderTests[ByteVal].order)
  checkAll("DoubleVal.OrderLaws", OrderTests[DoubleVal].order)
  checkAll("FloatVal.OrderLaws", OrderTests[FloatVal].order)
  checkAll("ShortVal.OrderLaws", OrderTests[ShortVal].order)
  checkAll("BooleanVal.OrderLaws", OrderTests[BooleanVal].order)
  checkAll("IntVal.OrderLaws", OrderTests[IntVal].order)
  checkAll("LongVal.OrderLaws", OrderTests[LongVal].order)
  checkAll("StringVal.OrderLaws", OrderTests[StringVal].order)
  checkAll("NullVal.OrderLaws", OrderTests[NullVal.type].order)
} 
Example 32
Source File: TreeFunctorSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package functor

import educational.collections.{Branch, Leaf}
import educational.collections.TreeInstances.treeFunctor.map
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class TreeFunctorSpec
  extends AnyFunSpec
    with Matchers {

  describe("map over Tree") {
    it("execute function for value stored inside Left") {
      map(Leaf("foo"))(stringLength) mustBe Leaf(3)
      map(Leaf("foo"))(toUpperCase) mustBe Leaf("FOO")
    }

    it("called with Branch execute function for every subtree") {
      map(Branch(Leaf("foo"), Leaf("bar")))(stringLength) mustBe Branch(Leaf(3), Leaf(3))

      map(Branch(Leaf("foo"), Branch(Leaf("quux"), Leaf("foobar"))))(toUpperCase) mustBe
        Branch(Leaf("FOO"), Branch(Leaf("QUUX"), Leaf("FOOBAR")))
    }

    it("called with complicated Tree execute function for every subtree") {
      val tree = Branch(
        Leaf("a"),
        Branch(
          Leaf("b"),
          Leaf("c")))

      val expected = Branch(
        Leaf("A"),
        Branch(
          Leaf("B"),
          Leaf("C")))

      map(tree)(toUpperCase) mustBe expected
    }
  }

  private def stringLength(s: String) = s.length
  private def toUpperCase(s: String) = s.toUpperCase
} 
Example 33
Source File: FunctorExamplesSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package functor

import cats.Id
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class FunctorExamplesSpec
  extends AnyFunSpec
  with Matchers {

  private def isOdd(i: Int): Boolean = i % 2 == 1

  describe("Functor") {
    describe("map") {
      it("apply given function for each element of List") {
        import cats.Functor
        import cats.implicits._

        Functor[List].map(List(2, 3, 4))(isOdd) mustBe List(false, true, false)
        Functor[Option].map(Option(42))(isOdd) mustBe Option(false)

        val myId: Id[Int] = 42
        Functor[Id].map(myId)(isOdd) mustBe false
      }
    }

    describe("derived methods") {
      it("can be called directly when Functor syntax is imported") {
        import cats.syntax.functor._
        import cats.implicits.catsStdInstancesForList

        List(2, 3, 4).void mustBe List((), (), ())
        List(2, 3, 4).as("foo") mustBe List("foo", "foo", "foo")
        List(2, 3, 4).fproduct(isOdd) mustBe List((2, false), (3, true), (4, false))
      }

      it("for Vector") {
        import cats.syntax.functor._
        import cats.implicits.catsStdInstancesForVector

        Vector(2, 3, 4).void mustBe Vector((), (), ())
        Vector(2, 3, 4).as("foo") mustBe Vector("foo", "foo", "foo")
        Vector(2, 3, 4).fproduct(isOdd) mustBe Vector((2, false), (3, true), (4, false))
      }

      it("for Option") {
        import cats.syntax.functor._
        import cats.implicits.catsStdInstancesForOption

        Option(42).void mustBe Option(())
        Option(42).as("foo") mustBe Option("foo")
        Option(42).fproduct(isOdd) mustBe Option((42, false))
      }
    }

    describe("compose") {
      it("can chain multiple map") {
        import cats.Functor
        import cats.implicits.catsStdInstancesForList
        import cats.implicits.catsStdInstancesForOption

        val functor = Functor[List] compose Functor[Option]
        functor.map(List(Some(42), Some(15), None))(isOdd) mustBe List(Some(false), Some(true), None)
      }

      it("can chain multiple map 2") {
        import cats.Functor
        import cats.implicits.catsStdInstancesForList
        import cats.implicits.catsStdInstancesForOption

        val listOption = Functor[List] compose Functor[Option]
        import listOption.map
        map(List(Some(42), Some(15), None))(isOdd) mustBe List(Some(false), Some(true), None)
      }
    }
  }
} 
Example 34
Source File: StrongSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package educational.category_theory.two.profunctor

import educational.category_theory.two.profunctor.strong.Strong
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

case class DoubleFun[X,Y](fun: (X,X) => (Y,Y))

trait DoubleFunPro extends Profunctor[DoubleFun] {
  override def dimap[S, T, A, B](pab: DoubleFun[A, B])(f: S => A, g: B => T): DoubleFun[S, T] =
    DoubleFun[S, T] { (c1, c2) => pab.fun(f(c1), f(c2)) match {case (z1, z2) => (g(z1), g(z2)) } }
}

class StrongSpec
  extends AnyFunSpec
  with Matchers {

  it("Functions from A to B are Strong Profunctors") {
    trait Function1Profunctor extends Profunctor[Function1] {
      override def dimap[S,T,A,B](pab: A => B)(ab: S => A, cd: B => T): S => T = ab andThen pab andThen cd
    }

    val functionPro: Profunctor[Function1] = new Function1Profunctor {}

    val functionStrong: Strong[Function1] = new Strong[Function1] with Function1Profunctor {
      def first[X, Y, Z](pab: X => Y): Function1[(X, Z), (Y, Z)] = (xz: (X, Z)) => (pab(xz._1), xz._2)
    }

    def len: String => Int = _.length

    functionStrong.first(len)(("foo", 42)) mustBe (3,42)
  }

  it("You can define multiple Strong Profunctors for P[_,_]") {
    val doubleFunProStrength: Strong[DoubleFun] with DoubleFunPro = new Strong[DoubleFun] with DoubleFunPro {
      override def first[A, B, C](fa: DoubleFun[A, B]): DoubleFun[(A, C), (B, C)] = DoubleFun {
        (a1: (A, C), a2: (A, C)) =>
          val bb = fa.fun(a1._1, a2._1)
          ((bb._1, a1._2), (bb._2, a2._2))
      }
    }

    val doubleFunProStrength2: Strong[DoubleFun] with DoubleFunPro = new Strong[DoubleFun] with DoubleFunPro {
      override def first[A, B, C](fa: DoubleFun[A, B]): DoubleFun[(A, C), (B, C)] = DoubleFun {
        (a1: (A, C), a2: (A, C)) =>
          val bb = fa.fun(a1._1, a2._1)
          ((bb._1, a1._2), (bb._1, a2._2))
      }
    }

    def bothLength(a: String, b: String): (Int, Int) = (a.length, b.length)

    doubleFunProStrength.first(DoubleFun(bothLength)) must not be doubleFunProStrength2.first(DoubleFun(bothLength))
  }
} 
Example 35
Source File: ProfunctorSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package educational.category_theory.two.profunctor

import scalaz._
import Scalaz._
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class ProfunctorSpec
  extends AnyFunSpec
    with Matchers {

  describe("Profunctor") {
    it("Profunctor for Function1 is Functor + Contravariant") {
      case class Person(name: String, age: Int)

      val len: String => Int = _.length // String => Int
      val getPersonName: Person => String = _.name // Person => String
      val above5: Int => Boolean = _ > 5 // Int => Boolean

      val personNameAbove5 = Profunctor[Function1].dimap(len)(getPersonName)(above5) // AA => BB
      personNameAbove5(Person("Foo", 100)) mustBe false
    }
  }
} 
Example 36
Source File: AlternativeMonoidInstancesSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package monoid

import cats.Monoid
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class AlternativeMonoidInstancesSpec
  extends AnyFunSpec
  with Matchers {

  
  implicit def createMonoidTuple[L, R](left: Monoid[L], right: Monoid[R]): Monoid[(L, R)] = new Monoid[(L, R)] {
    def empty: (L, R) = (left.empty, right.empty)
    def combine(x: (L, R), y: (L, R)): (L, R) =
      ( left.combine(x._1, y._1), right.combine(x._2, y._2) )
  }

  describe("custom Monoid for multiply Int") {
    it("can use |+| syntax and combineAll method") {
      import cats.Monoid
      import cats.syntax.semigroup._
      import monoid.AlternativeMonoidInstances.multiplyIntMonoid

      Monoid[Int].combineAll(Nil) mustBe 1
      Monoid[Int].combineAll(List(1, 2, 3, 4)) mustBe 24

      2 |+| 3 mustBe 6
    }
  }

  describe("custom Monoid instance for first non empty Option") {
    it("get first non empty option") {
      import cats.Monoid
      import cats.syntax.semigroup._
      import cats.syntax.option._
      import monoid.AlternativeMonoidInstances.optionFirstNonEmpty

      case class Foo(v: Int)

      Monoid[Option[Foo]].combineAll(List(None, Foo(2).some, Foo(3).some)) mustBe Some(Foo(2))
      Foo(2).some |+| Foo(3).some mustBe Foo(2).some
    }
  }
}

object AlternativeMonoidInstances {
  def createMonoid[A](mempty: A, mapply: (A, A) => A): Monoid[A] = new Monoid[A] {
    def empty: A = mempty
    def combine(x: A, y: A) = mapply(x, y)
  }

  implicit val multiplyIntMonoid: Monoid[Int] = createMonoid(1, _ * _)

  implicit def optionFirstNonEmpty[A]: Monoid[Option[A]] = createMonoid(None, _ orElse _)
} 
Example 37
Source File: MonoidExamplesSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package monoid

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class MonoidExamplesSpec
  extends AnyFunSpec
  with Matchers {

  describe("combineAll") {
    it("invoke operation for all elements") {
      import cats.implicits._

      List(1, 2, 3).combineAll mustBe 6
      List[Int]().combineAll mustBe 0
    }
  }
} 
Example 38
Source File: RanCustomImpl.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package kan

import cats.{Functor, Monad}

import scala.language.higherKinds
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class RanCustomImpl
  extends AnyFunSpec
    with Matchers {

  describe("Right Kan extension implemented from Haskell definition") {
    
      def ranMonad[G[_]]: Monad[Ran3[G, G, ?]] =
        new Monad[Ran3[G, G, ?]] {
          override def map[A, B](fa: Ran3[G, G, A])(f: A => B): Ran3[G, G, B] = fa.map(f)

          override def flatMap[A, B](fa: Ran3[G, G, A])(f: A => Ran3[G, G, B]): Ran3[G, G, B] = flatten(map(fa)(f))

          override def tailRecM[A, B](a: A)(f: A => Ran3[G, G, Either[A, B]]): Ran3[G, G, B] = ???

          override def pure[A](x: A): Ran3[G, G, A] =
            new Ran3[G, G, A] {
              def runRan[C](f2: A => G[C]): G[C] = f2(x)
            }
        }
    }
  }
} 
Example 39
Source File: TraverseExamplesSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package traverse

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class TraverseExamplesSpec
  extends AnyFunSpec
  with Matchers {

  describe("Traversing List ") {
    it("traverse") {
      import cats.implicits._

      val xs1: Vector[Int] = Vector(1, 2, 3)
      xs1.traverse(a => Option(a)) mustBe Some(Vector(1, 2, 3))
    }

    it("sequence") {
      import cats.implicits._
      val xs1: List[Option[Int]] = List(Some(1), Some(2), None)
      xs1.sequence mustBe None

      val xs2: List[Option[Int]] = List(Some(1), Some(2), Some(42))
      xs2.sequence mustBe Some(List(1,2,42))
    }
  }
} 
Example 40
Source File: BifunctorExamplesSpec.scala    From scala_typeclassopedia   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package bifunctor

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.must.Matchers

class BifunctorExamplesSpec
  extends AnyFunSpec
  with Matchers {

  describe("Bifunctor") {
    describe("bimap") {
      it("apply given functions for first and second element of tuple") {
        import cats.implicits._
        (List("foo", "bar"), 42).bimap(_.headOption, _ - 1) mustBe(Some("foo"), 41)
      }
    }

    describe("leftmap") {
      it("apply given functions for first and second element of tuple") {
        import cats.implicits._
        (List("foo", "bar"), 42).leftMap(_.headOption) mustBe (Some("foo"), 42)
      }
    }
  }
} 
Example 41
Source File: P33Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P33.RichInt
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P33Spec extends AnyFunSpec with Diagrams {
  describe("P33") {
    it("for coprime numbers, x.isCoprime(y) returns true") {
      assert(3.isCoPrime(8))
      assert(12.isCoPrime(25))
      assert(64.isCoPrime(35))
      assert(98.isCoPrime(27))
    }
    it("for non-coprime numbers, x.isCoprime(y) returns false") {
      assert(!4.isCoPrime(16))
      assert(!13.isCoPrime(39))
      assert(!48.isCoPrime(4))
      assert(!56.isCoPrime(42))
    }
  }
} 
Example 42
Source File: P19Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P19Spec extends AnyFunSpec with Diagrams {
  describe("P19") {
    it("for empty list, rotate(n, s) throws Exception") {
      intercept[Throwable] {
        P19.rotate(-2, List.empty[Int])
      }
      intercept[Throwable] {
        P19.rotate(-1, List.empty[Int])
      }
      intercept[Throwable] {
        P19.rotate(0, List.empty[Int])
      }
      intercept[Throwable] {
        P19.rotate(1, List.empty[Int])
      }
      intercept[Throwable] {
        P19.rotate(2, List.empty[Int])
      }
    }
    it("for list one element, rotate(n, s) returns s itself") {
      assert(P19.rotate(-2, List(1)) == List(1))
      assert(P19.rotate(-1, List(1)) == List(1))
      assert(P19.rotate(-0, List(1)) == List(1))
      assert(P19.rotate(-1, List(1)) == List(1))
      assert(P19.rotate(-2, List(1)) == List(1))
    }
    it("otherwise") {
      assert(P19.rotate(-3, List(1, 2)) == List(2, 1))
      assert(P19.rotate(-2, List(1, 2)) == List(1, 2))
      assert(P19.rotate(-1, List(1, 2)) == List(2, 1))
      assert(P19.rotate(0, List(1, 2)) == List(1, 2))
      assert(P19.rotate(1, List(1, 2)) == List(2, 1))
      assert(P19.rotate(2, List(1, 2)) == List(1, 2))
      assert(P19.rotate(3, List(1, 2)) == List(2, 1))
    }
  }
} 
Example 43
Source File: P31Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P31._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P31Spec extends AnyFunSpec with Diagrams {
  describe("P31") {
    it("for prime number") {
      assert(2.isPrime)
      assert(5.isPrime)
      assert(19.isPrime)
      assert(937.isPrime)
    }
    it("for not prime number(even)") {
      assert(!4.isPrime)
      assert(!28.isPrime)
      assert(!1024.isPrime)
      assert(!4800.isPrime)
    }
    it("for not prime number(odd)") {
      assert(!9.isPrime)
      assert(!49.isPrime)
      assert(!(13 * 17).isPrime)
      assert(!(23 * 27).isPrime)
    }
  }
} 
Example 44
Source File: P10Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P10Spec extends AnyFunSpec with Diagrams {
  describe("P10") {
    it("for empty list, encode(s) is s") {
      assert(P10.encode(List.empty[Int]) == List.empty[(Int, Int)])
    }
    it("for list has one element, encode(s) is List((1, s))") {
      assert(P10.encode(List(2)) == List((1, 2)))
    }
    it("otherwise") {
      assert(P10.encode(List(1, 1)) == List((2, 1)))
      assert(P10.encode(List(1, 1, 2)) == List((2, 1), (1, 2)))
      assert(P10.encode(List(1, 1, 2, 3)) == List((2, 1), (1, 2), (1, 3)))
      assert(P10.encode(List(1, 1, 2, 2, 3)) == List((2, 1), (2, 2), (1, 3)))
    }
  }
} 
Example 45
Source File: P12Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P12Spec extends AnyFunSpec with Diagrams {
  describe("P12") {
    it("for empty list, decode(s) is s") {
      assert(P12.decode(List.empty[(Int, Int)]) == List.empty[(Int, Int)])
    }
    it("for list has one element") {
      assert(P12.decode(List((1, 1))) == List(1))
      assert(P12.decode(List((2, 1))) == List(1, 1))
      assert(P12.decode(List((3, 1))) == List(1, 1, 1))
    }
    it("otherwise") {
      assert(P12.decode(List((1, 1), (1, 2))) == List(1, 2))
      assert(P12.decode(List((2, 1), (1, 2), (1, 3))) == List(1, 1, 2, 3))
      assert(P12.decode(List((2, 1), (2, 2), (1, 3))) == List(1, 1, 2, 2, 3))
    }
  }
} 
Example 46
Source File: P08Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P08Spec extends AnyFunSpec with Diagrams {
  describe("P08") {
    it("for empty list, compress(s) is s") {
      assert(P08.compress(List.empty[Int]) == List.empty[Int])
    }
    it("for list has one element, compress(s) is s") {
      assert(P08.compress(List(1)) == List(1))
    }
    it("otherwise") {
      assert(P08.compress(List(1, 1)) == List(1))
      assert(P08.compress(List(1, 2, 1)) == List(1, 2, 1))
      assert(P08.compress(List(1, 2, 2)) == List(1, 2))
    }
  }
} 
Example 47
Source File: P09Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P09Spec extends AnyFunSpec with Diagrams {
  describe("P09") {
    it("for empty list, pack(s) is s") {
      assert(P09.pack(List.empty[Int]) == List.empty[List[Int]])
    }
    it("for list has one element, pack(s) is List(s)") {
      assert(P09.pack(List(1)) == List(List(1)))
    }
    it("otherwise") {
      assert(P09.pack(List(1, 1)) == List(List(1, 1)))
      assert(P09.pack(List(1, 1, 2)) == List(List(1, 1), List(2)))
      assert(P09.pack(List(1, 1, 2, 3)) == List(List(1, 1), List(2), List(3)))
      assert(
        P09.pack(List(1, 1, 2, 2, 3)) == List(List(1, 1), List(2, 2), List(3))
      )
    }
  }
} 
Example 48
Source File: P61Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import binary_trees._
import P61._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P61Spec extends AnyFunSpec with Diagrams {
  describe("P61") {
    it("count leaves correctly") {
      assert(Node("a", Node("a"), End).leafCount == 1)
      assert(
        Node(
          'a',
          Node('b', Node('d'), Node('e')),
          Node('c', End, Node('f', Node('g'), End))
        ).leafCount == 3
      )
    }
  }
} 
Example 49
Source File: P03Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P03Spec extends AnyFunSpec with Diagrams {
  describe("P03") {
    it("any index with empty list should fail") {
      val emptyList = List.empty[Int]
      intercept[Throwable] {
        P03.nth(0, emptyList)
      }
      intercept[Throwable] {
        P03.nth(1, emptyList)
      }
      intercept[Throwable] {
        P03.nth(-1, emptyList)
      }
    }
    it("0 index with a list") {
      intercept[Throwable] {
        P03.nth(0, List.empty[Int])
      }
      assert(P03.nth(0, List(2)) == 2)
      assert(P03.nth(0, List(2, 3)) == 2)
    }
    it("negative index with a list should fail") {
      intercept[Throwable] {
        P03.nth(-1, List.empty[Int])
      }
      intercept[Throwable] {
        P03.nth(-1, List(2))
      }
      intercept[Throwable] {
        P03.nth(-1, List(2, 3))
      }
    }
    it("otherwise") {
      intercept[Throwable] {
        P03.nth(1, List(2))
      }
      assert(P03.nth(1, List(2, 3)) == 3)
    }
  }
} 
Example 50
Source File: P06Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P06Spec extends AnyFunSpec with Diagrams {
  describe("P06") {
    it("for empty list, isPalindrome(s) should be true") {
      assert(P06.isPalindrome(List.empty[Int]))
    }
    it("for list has one element, isPalindrome(s) should be true") {
      assert(P06.isPalindrome(List(1)))
    }
    it("otherwise") {
      assert(P06.isPalindrome(List(1, 2, 1)))
    }
  }
} 
Example 51
Source File: P02Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P02Spec extends AnyFunSpec with Diagrams {
  describe("P02") {
    it("for empty list(should fail)") {
      intercept[Throwable] {
        P02.penultimate(List[Int]())
      }
    }
    it("for list has one element(also should fail)") {
      intercept[Throwable] {
        P02.penultimate(List(1))
      }
    }
    it("for list has more than one element") {
      assert(P02.penultimate(List(1, 2)) == 1)
    }
    it("for list has more than two element") {
      assert(P02.penultimate(List(1, 2, 3)) == 2)
    }
  }
} 
Example 52
Source File: P67Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P67._
import binary_trees._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P67Spec extends AnyFunSpec with Diagrams {
  describe("P67") {
    it("represents another string representation") {
      assert(
        Node(
          'a',
          Node('b', Node('d'), Node('e')),
          Node('c', End, Node('f', Node('g'), End))
        ).toString2 == "a(b(d,e),c(,f(g,)))"
      )
    }
    it("build Node from string") {
      assert(
        Tree.fromString("a(b(d,e),c(,f(g,)))") == Node(
          'a',
          Node('b', Node('d'), Node('e')),
          Node('c', End, Node('f', Node('g'), End))
        )
      )
    }
  }
} 
Example 53
Source File: P49Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P49.gray
import P49.gray2
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P49Spec extends AnyFunSpec with Diagrams {
  describe("P49") {
    it("gray(1)") {
      assert(gray(1) == List("0", "1"))
    }
    it("gray(2)") {
      assert(gray(2) == List("00", "01", "11", "10"))
    }
    it("gray(3)") {
      assert(
        gray(3) == List("000", "001", "011", "010", "110", "111", "101", "100")
      )
    }
    it("gray2(1)") {
      assert(gray2(1) == List("0", "1"))
    }
    it("gray2(2)") {
      assert(gray2(2) == List("00", "01", "11", "10"))
    }
    it("gray2(3)") {
      assert(
        gray2(3) == List("000", "001", "011", "010", "110", "111", "101", "100")
      )
    }
  }
} 
Example 54
Source File: P13Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P13Spec extends AnyFunSpec with Diagrams {
  describe("P13") {
    it("for empty list, encodeDirect(s) is s") {
      assert(P13.encodeDirect(List.empty[Int]) == List.empty[(Int, Int)])
    }
    it("for list has one element, encodeDirect(s) is List((1, s))") {
      assert(P13.encodeDirect(List(2)) == List((1, 2)))
    }
    it("otherwise") {
      assert(P13.encodeDirect(List(1, 1)) == List((2, 1)))
      assert(P13.encodeDirect(List(1, 1, 2)) == List((2, 1), (1, 2)))
      assert(P13.encodeDirect(List(1, 1, 2, 3)) == List((2, 1), (1, 2), (1, 3)))
      assert(
        P13.encodeDirect(List(1, 1, 2, 2, 3)) == List((2, 1), (2, 2), (1, 3))
      )
    }
  }
} 
Example 55
Source File: P05Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P05Spec extends AnyFunSpec with Diagrams {
  describe("P05") {
    it("for empty list, reverse(s) should be itself") {
      assert(P05.reverse(List.empty[Int]) == List.empty[Int])
    }
    it("for list has one element, reverse(s) should be itself") {
      assert(P05.reverse(List(1)) == List(1))
    }
    it("otherwise") {
      assert(P05.reverse(List(1, 2)) == List(2, 1))
    }
  }
} 
Example 56
Source File: P90Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P90._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P90Spec extends AnyFunSpec with Diagrams {
  describe("P90") {
    it("solve n queens problem") {
      assert(getPatterns(4)() == List(List(1, 3, 0, 2), List(2, 0, 3, 1)))
      assert(getPatterns(5)().size == 10)
      assert(getPatterns(6)().size == 4)
      assert(getPatterns(7)().size == 40)
      assert(getPatterns(8)().size == 92)
      assert(solve.size == 92)
    }
  }
} 
Example 57
Source File: P14Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P14Spec extends AnyFunSpec with Diagrams {
  describe("P14") {
    it("for empty list, duplicate(s) is s") {
      assert(P14.duplicate(List.empty[Int]) == List.empty[Int])
    }
    it("for list has one element") {
      assert(P14.duplicate(List(1)) == List(1, 1))
      assert(P14.duplicate(List(2)) == List(2, 2))
      assert(P14.duplicate(List(3)) == List(3, 3))
      assert(P14.duplicate(List(4)) == List(4, 4))
    }
    it("otherwise") {
      assert(P14.duplicate(List(1, 2, 3)) == List(1, 1, 2, 2, 3, 3))
      assert(P14.duplicate(List(1, 1, 2, 3)) == List(1, 1, 1, 1, 2, 2, 3, 3))
      assert(P14.duplicate(List(1, 2, 3, 3)) == List(1, 1, 2, 2, 3, 3, 3, 3))
      assert(
        P14.duplicate(List(1, 1, 2, 3, 3)) == List(1, 1, 1, 1, 2, 2, 3, 3, 3, 3)
      )
      assert(P14.duplicate(List(1, 2, 2, 3)) == List(1, 1, 2, 2, 2, 2, 3, 3))
    }
  }
} 
Example 58
Source File: ProtoMacroTest.scala    From scalapb-circe   with MIT License 5 votes vote down vote up
package scalapb_circe

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers
import scalapb_circe.ProtoMacrosCirce._
import com.google.protobuf.struct._
import jsontest.test.MyTest

import scala.util.Success

class ProtoMacrosCirceTest extends AnyFunSpec with Matchers {
  describe("ProtoMacrosCirce") {
    it("struct") {
      assert(struct"{}" == Struct.defaultInstance)

      assert(
        struct"""{ "a" : [1, false, null, "x"] }""" == Struct(
          Map(
            "a" -> Value(
              Value.Kind.ListValue(
                ListValue(
                  List(
                    Value(Value.Kind.NumberValue(1.0)),
                    Value(Value.Kind.BoolValue(false)),
                    Value(Value.Kind.NullValue(NullValue.NULL_VALUE)),
                    Value(Value.Kind.StringValue("x"))
                  )
                )
              )
            )
          )
        )
      )

      """ struct" { invalid json " """ shouldNot compile
    }

    it("value") {
      assert(value" 42 " == Value(Value.Kind.NumberValue(42)))
      assert(value" false " == Value(Value.Kind.BoolValue(false)))
      assert(value""" "x" """ == Value(Value.Kind.StringValue("x")))
      assert(value""" [] """ == Value(Value.Kind.ListValue(ListValue())))

      """ value" { invalid json " """ shouldNot compile
    }

    it("fromJson") {
      assert(MyTest.fromJsonConstant("{}") === MyTest())
      assert(
        MyTest.fromJsonConstant(
          """{
            "hello" : "foo",
            "foobar" : 42
          }"""
        ) === MyTest().update(
          _.hello := "foo",
          _.foobar := 42
        )
      )
      """ jsontest.test.MyTest.fromJsonConstant("{") """ shouldNot compile

      assert(MyTest.fromJsonTry("{").isFailure)
      assert(MyTest.fromJsonTry("""{"hello":"foo"}""") === Success(MyTest(hello = Some("foo"))))

      assert(MyTest.fromJsonOpt("{").isEmpty)
      assert(MyTest.fromJsonOpt("""{"hello":"foo"}""") === Some(MyTest(hello = Some("foo"))))

      assert(MyTest.fromJsonEither("{").isLeft)
      assert(MyTest.fromJsonEither("""{"hello":"foo"}""") === Right(MyTest(hello = Some("foo"))))
    }
  }
} 
Example 59
Source File: JsonMatchersSpec.scala    From scalatest-json   with Apache License 2.0 5 votes vote down vote up
package com.stephenn.scalatest.jsonassert

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class JsonMatchersSpec extends AnyFunSpec with Matchers {
  describe("JsonMatchers") {
    it("should pass when json is the same") {
      Seq("{}" -> "{}", "[]" -> "[]", "0" -> "0").foreach {
        case (left, right) =>
          val matchResult = JsonMatchers.matchJson(right).apply(left)
          matchResult.matches shouldBe true
      }
    }

    it("should pass when json is equivalent") {
      val matchResult = JsonMatchers.matchJson("{  }").apply("  {}  ")
      matchResult.matches shouldBe true

      Seq("{}" -> " { }",
          " [ ] " -> "[]",
          "0" -> "0",
          """{"a":0, "b":1}""" -> """{"b":1,"a":0}""").foreach {
        case (left, right) =>
          val matchResult = JsonMatchers.matchJson(right).apply(left)
          matchResult.matches shouldBe true
      }
    }

    it("should fail when left has extra fields") {
      val matchResult = JsonMatchers.matchJson("""{"l":1}""").apply("{}")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe
        """
          |Json did not match "{}" did not match "{"l":1}"
          |
          |Json Diff:
          |"
          |Expected: l
          |     but none found
          |"
        """.stripMargin.trim
    }

    it("should fail when right has extra fields") {
      val matchResult = JsonMatchers.matchJson("{}").apply("""{"r":0}""")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe
        """
          |Json did not match "{"r":0}" did not match "{}"
          |
          |Json Diff:
          |"
          |Unexpected: r
          |"
        """.stripMargin.trim
    }

    it("should fail on invalid json") {
      val matchResult =
        JsonMatchers.matchJson("{}").apply("""{"a": [1  "two"]}""")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe """Could not parse json "{"a": [1  "two"]}" did not equal "{}""""
    }
  }
} 
Example 60
Source File: JsonMatchersSpec.scala    From scalatest-json   with Apache License 2.0 5 votes vote down vote up
package com.stephenn.scalatest.json4s

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class JsonMatchersSpec extends AnyFunSpec with Matchers {

  describe("JsonMatchers") {
    it("should pass when json is the same") {
      Seq("{}" -> "{}", "[]" -> "[]").foreach {
        case (left, right) =>
          val matchResult = JsonMatchers.matchJson(right).apply(left)
          matchResult.matches shouldBe true
      }
    }

    it("should pass when json is equivalent") {
      val matchResult = JsonMatchers.matchJson("{  }").apply("  {}  ")
      matchResult.matches shouldBe true

      Seq("{}" -> " { }",
          " [ ] " -> "[]",
          """{"a":0, "b":1}""" -> """{"b":1,"a":0}""").foreach {
        case (left, right) =>
          val matchResult = JsonMatchers.matchJson(right).apply(left)
          matchResult.matches shouldBe true
      }
    }

    it("should fail when left has extra fields") {
      val matchResult = JsonMatchers.matchJson("""{"l":1}""").apply("{}")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe "Json did not match \"{}\" did not match \"{\"l\":1}\"\n\nJson Diff:\n\"Added:\n{\"l\":1}\""
    }

    it("should fail when right has extra fields") {
      val matchResult = JsonMatchers.matchJson("{}").apply("""{"r":0}""")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe "Json did not match \"{\"r\":0}\" did not match \"{}\"\n\nJson Diff:\n\"Removed:\n{\"r\":0}\""
    }

    it("should fail on invalid json") {
      val matchResult =
        JsonMatchers.matchJson("{}").apply("""{"a": nope]}""")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe "Could not parse json \"{\"a\": nope]}\" did not equal \"{}\""
    }

    it("should match a json object to a json string") {
      import org.json4s.native.JsonMethods._
      val matchResult = JsonMatchers
        .matchJsonString("""{"b":1,"a":0}""")
        .apply(parse("""{"a":0, "b":1}"""))
      matchResult.matches shouldBe true
    }
  }
} 
Example 61
Source File: P15Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P15Spec extends AnyFunSpec with Diagrams {
  describe("P15") {
    it("for empty list, duplicateN(i, s) is always s") {
      assert(P15.duplicateN(0, List.empty[Int]) == List.empty[Int])
      assert(P15.duplicateN(1, List.empty[Int]) == List.empty[Int])
      assert(P15.duplicateN(2, List.empty[Int]) == List.empty[Int])
      assert(P15.duplicateN(3, List.empty[Int]) == List.empty[Int])
    }
    it("for list has one element") {
      assert(P15.duplicateN(0, List(1)) == List.empty[Int])
      assert(P15.duplicateN(1, List(1)) == List(1))
      assert(P15.duplicateN(2, List(1)) == List(1, 1))
      assert(P15.duplicateN(3, List(1)) == List(1, 1, 1))
    }
    it("otherwise") {
      assert(P15.duplicateN(1, List(1, 2, 3)) == List(1, 2, 3))
      assert(P15.duplicateN(2, List(1, 2, 3)) == List(1, 1, 2, 2, 3, 3))
      assert(P15.duplicateN(1, List(1, 1, 2, 3)) == List(1, 1, 2, 3))
      assert(
        P15.duplicateN(2, List(1, 2, 3, 3)) == List(1, 1, 2, 2, 3, 3, 3, 3)
      )
      assert(
        P15.duplicateN(2, List(1, 1, 2, 3, 3)) == List(1, 1, 1, 1, 2, 2, 3, 3,
          3, 3)
      )
      assert(
        P15.duplicateN(2, List(1, 2, 2, 3)) == List(1, 1, 2, 2, 2, 2, 3, 3)
      )
    }
  }
} 
Example 62
Source File: MetricTreeSpec.scala    From spark-knn   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.ml.knn

import org.apache.spark.ml.knn.KNN.{RowWithVector, VectorWithNorm}
import org.apache.spark.ml.linalg.Vectors
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class MetricTreeSpec extends AnyFunSpec with Matchers {

  describe("MetricTree") {
    val origin = Vectors.dense(0, 0)
    describe("can be constructed with empty data") {
      val tree = MetricTree.build(IndexedSeq.empty[RowWithVector])
      it("iterator should be empty") {
        tree.iterator shouldBe empty
      }
      it("should return empty when queried") {
        tree.query(origin) shouldBe empty
      }
      it("should have zero leaf") {
        tree.leafCount shouldBe 0
      }
    }

    describe("without duplicates") {
      val data = (-5 to 5).flatMap(i => (-5 to 5).map(j => new RowWithVector(Vectors.dense(i, j), null)))
      List(1, data.size / 2, data.size, data.size * 2).foreach {
        leafSize =>
          describe(s"with leafSize of $leafSize") {
            val tree = MetricTree.build(data, leafSize)
            it("should have correct size") {
              tree.size shouldBe data.size
            }
            it("should return an iterator that goes through all data points") {
              tree.iterator.toIterable should contain theSameElementsAs data
            }
            it("should return vector itself for those in input set") {
              data.foreach(v => tree.query(v.vector, 1).head._1 shouldBe v)
            }
            it("should return nearest neighbors correctly") {
              tree.query(origin, 5).map(_._1.vector.vector) should contain theSameElementsAs Set(
                Vectors.dense(-1, 0),
                Vectors.dense(1, 0),
                Vectors.dense(0, -1),
                Vectors.dense(0, 1),
                Vectors.dense(0, 0)
              )
              tree.query(origin, 9).map(_._1.vector.vector) should contain theSameElementsAs
                (-1 to 1).flatMap(i => (-1 to 1).map(j => Vectors.dense(i, j)))
            }
            it("should have correct number of leaves") {
              tree.leafCount shouldBe (tree.size / leafSize.toDouble).ceil
            }
            it("all points should fall with radius of pivot") {
              def check(tree: Tree): Unit = {
                tree.iterator.foreach(_.vector.fastDistance(tree.pivot) <= tree.radius)
                tree match {
                  case t: MetricTree =>
                    check(t.leftChild)
                    check(t.rightChild)
                  case _ =>
                }
              }
              check(tree)
            }
          }
      }
    }

    describe("with duplicates") {
      val data = (Vectors.dense(2.0, 0.0) +: Array.fill(5)(Vectors.dense(0.0, 1.0))).map(new RowWithVector(_, null))
      val tree = MetricTree.build(data)
      it("should have 2 leaves") {
        tree.leafCount shouldBe 2
      }
      it("should return all available duplicated candidates") {
        val res = tree.query(origin, 5).map(_._1.vector.vector)
        res.size shouldBe 5
        res.toSet should contain theSameElementsAs Array(Vectors.dense(0.0, 1.0))
      }
    }

    describe("for other corner cases") {
      it("queryCost should work on Empty") {
        Empty.distance(new KNNCandidates(new VectorWithNorm(origin), 1)) shouldBe 0
        Empty.distance(new VectorWithNorm(origin)) shouldBe 0
      }
    }
  }
} 
Example 63
Source File: SpillTreeSpec.scala    From spark-knn   with Apache License 2.0 5 votes vote down vote up
package org.apache.spark.ml.knn

import org.apache.spark.ml.knn.KNN.RowWithVector
import org.apache.spark.ml.linalg.Vectors
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class SpillTreeSpec extends AnyFunSpec with Matchers {
  describe("SpillTree") {
    val origin = Vectors.dense(0, 0)
    describe("can be constructed with empty data") {
      val tree = SpillTree.build(IndexedSeq.empty[RowWithVector], tau = 0.0)
      it("iterator should be empty") {
        tree.iterator shouldBe empty
      }
      it("should return empty when queried") {
        tree.query(origin) shouldBe empty
      }
      it("should have zero leaf") {
        tree.leafCount shouldBe 0
      }
    }

    describe("with equidistant points on a circle") {
      val n = 12
      val points = (1 to n).map {
        i => new RowWithVector(Vectors.dense(math.sin(2 * math.Pi * i / n), math.cos(2 * math.Pi * i / n)), null)
      }
      val leafSize = n / 4
      describe("built with tau = 0.0") {
        val tree = SpillTree.build(points, leafSize = leafSize, tau = 0.0)
        it("should have correct size") {
          tree.size shouldBe points.size
        }
        it("should return an iterator that goes through all data points") {
          tree.iterator.toIterable should contain theSameElementsAs points
        }
        it("can return more than min leaf size") {
          val k = leafSize + 5
          points.foreach(v => tree.query(v.vector, k).size shouldBe k)
        }
      }
      describe("built with tau = 0.5") {
        val tree = SpillTree.build(points, leafSize = leafSize, tau = 0.5)
        it("should have correct size") {
          tree.size shouldBe points.size
        }
        it("should return an iterator that goes through all data points") {
          tree.iterator.toIterable should contain theSameElementsAs points
        }
        it("works for every point to identify itself") {
          points.foreach(v => tree.query(v.vector, 1).head._1 shouldBe v)
        }
        it("has consistent size and iterator") {
          def check(tree: Tree): Unit = {
            tree match {
              case t: SpillTree =>
                t.iterator.size shouldBe t.size

                check(t.leftChild)
                check(t.rightChild)
              case _ =>
            }
          }
          check(tree)
        }
      }
    }
  }

  describe("HybridTree") {
    val origin = Vectors.dense(0, 0)
    describe("can be constructed with empty data") {
      val tree = HybridTree.build(IndexedSeq.empty[RowWithVector], tau = 0.0)
      it("iterator should be empty") {
        tree.iterator shouldBe empty
      }
      it("should return empty when queried") {
        tree.query(origin) shouldBe empty
      }
      it("should have zero leaf") {
        tree.leafCount shouldBe 0
      }
    }

    describe("with equidistant points on a circle") {
      val n = 12
      val points = (1 to n).map {
        i => new RowWithVector(Vectors.dense(math.sin(2 * math.Pi * i / n), math.cos(2 * math.Pi * i / n)), null)
      }
      val leafSize = n / 4
      val tree = HybridTree.build(points, leafSize = leafSize, tau = 0.5)
      it("should have correct size") {
        tree.size shouldBe points.size
      }
      it("should return an iterator that goes through all data points") {
        tree.iterator.toIterable should contain theSameElementsAs points
      }
    }
  }
} 
Example 64
Source File: EncryptedReadSuite.scala    From spark-excel   with Apache License 2.0 5 votes vote down vote up
package com.crealytics.spark.excel

import org.apache.spark.sql._
import org.apache.spark.sql.types._
import scala.collection.JavaConverters._

import com.holdenkarau.spark.testing.DataFrameSuiteBase
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

object EncryptedReadSuite {
  val simpleSchema = StructType(
    List(
      StructField("A", DoubleType, true),
      StructField("B", DoubleType, true),
      StructField("C", DoubleType, true),
      StructField("D", DoubleType, true)
    )
  )

  val expectedData = List(Row(1.0d, 2.0d, 3.0d, 4.0d)).asJava
}

class EncryptedReadSuite extends AnyFunSpec with DataFrameSuiteBase with Matchers {
  import EncryptedReadSuite._

  lazy val expected = spark.createDataFrame(expectedData, simpleSchema)

  def readFromResources(path: String, password: String, maxRowsInMemory: Option[Int] = None): DataFrame = {
    val url = getClass.getResource(path)
    val reader = spark.read
      .excel(
        dataAddress = s"Sheet1!A1",
        treatEmptyValuesAsNulls = true,
        workbookPassword = password,
        inferSchema = true
      )
    val withMaxRows = maxRowsInMemory.fold(reader)(rows => reader.option("maxRowsInMemory", s"$rows"))
    withMaxRows.load(url.getPath)
  }

  describe("spark-excel") {
    it("should read encrypted xslx file") {
      val df = readFromResources("/spreadsheets/simple_encrypted.xlsx", "fooba")

      assertDataFrameEquals(expected, df)
    }

    it("should read encrypted xlsx file with maxRowsInMem=10") {
      val df = readFromResources("/spreadsheets/simple_encrypted.xlsx", "fooba", maxRowsInMemory = Some(10))

      assertDataFrameEquals(expected, df)
    }

    it("should read encrypted xlsx file with maxRowsInMem=1") {
      val df = readFromResources("/spreadsheets/simple_encrypted.xlsx", "fooba", maxRowsInMemory = Some(1))

      assertDataFrameEquals(expected, df)
    }

    it("should read encrypted xls file") {
      val df = readFromResources("/spreadsheets/simple_encrypted.xls", "fooba")

      assertDataFrameEquals(expected, df)
    }
  }
} 
Example 65
Source File: DataLocatorSuite.scala    From spark-excel   with Apache License 2.0 5 votes vote down vote up
package com.crealytics.spark.excel
import com.crealytics.tags.WIP
import com.norbitltd.spoiwo.model.{CellRange, Sheet, Workbook}
import org.apache.poi.ss.SpreadsheetVersion
import org.apache.poi.ss.util.AreaReference
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import com.norbitltd.spoiwo.natures.xlsx.Model2XlsxConversions._
import org.scalacheck.Gen

import scala.collection.JavaConverters._
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class DataLocatorSuite extends AnyFunSpec with ScalaCheckPropertyChecks with Matchers with Generators {
  describe("with a table reference") {
    val dl = DataLocator(Map("dataAddress" -> s"$tableName[#All]"))
    describe("containing #All") {
      it("extracts the entire table data") {
        forAll(sheetWithTableGen) { sheet =>
          val actualData = dl.readFrom(sheet.convertAsXlsx()).map(_.map(_.value)).to[Seq]
          actualData should contain theSameElementsAs sheet.extractTableData(0)
        }
      }

      it("writes into a new table in a new sheet if no corresponding table exists") {
        forAll(sheetGenerator(withHeader = Gen.const(true), numCols = Gen.choose(1, 200))) { dataSheet =>
          val workbook = new XSSFWorkbook()
          val header = dataSheet.rows.head.cells.map(_.value.toString).toSeq
          val generatedSheet = dl.toSheet(
            header = Some(header),
            data = dataSheet.rows.tail.iterator.map(_.cells.map(_.value.toString).toSeq),
            existingWorkbook = workbook
          )
          generatedSheet.convertAsXlsx(workbook)
          val pTable = workbook.getTable(tableName)
          pTable.getSheetName should equal(tableName)
          pTable.getColumns.asScala.map(_.getName) should contain theSameElementsInOrderAs header
          val actualData = dl.readFrom(workbook).map(_.map(_.value)).to[Seq]
          actualData should contain theSameElementsAs dataSheet.rows.map(_.cells.map(_.value))
        }
      }

      it("overwrites an existing table") {
        forAll(sheetWithTableGen) { sheetWithTable =>
          val workbook = sheetWithTable.convertAsXlsx()
          val table = sheetWithTable.tables.head
          val header = table.columns.map(_.name)
          val tableData = dl.readFrom(workbook).map(_.map(c => s"new_$c")).toList
          val generatedSheet =
            dl.toSheet(header = tableData.headOption, data = tableData.iterator.drop(1), existingWorkbook = workbook)
          Workbook(generatedSheet).writeToExisting(workbook)
          val pTable = workbook.getTable(tableName)
          pTable.getSheetName should equal(sheetName)
          pTable.getColumns.asScala.map(_.getName) should contain theSameElementsInOrderAs header
          val actualData = dl.readFrom(workbook).map(_.map(_.value)).to[Seq]
          actualData should contain theSameElementsAs tableData
        }
      }
    }
  }
  describe("without any dataAddress") {
    it("defaults to starting at cell A1 in the first sheet") {
      val dl = DataLocator(Map())
      dl shouldBe a[CellRangeAddressDataLocator]
      val cradl = dl.asInstanceOf[CellRangeAddressDataLocator]
      cradl.dataAddress.getFirstCell.formatAsString() should equal("A1")
      cradl.dataAddress.getFirstCell.getSheetName should equal(null)
    }
  }
} 
Example 66
Source File: P58Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import jp.co.dwango.s99.P58.Tree
import jp.co.dwango.s99.binary_trees.{Node, End}
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P58Spec extends AnyFunSpec with Diagrams {
  describe("P58") {
    it("""Tree.symmetricBalancedTrees(5, "x")""") {
      assert(
        List(
          Node(
            "x",
            Node("x", End, Node("x")),
            Node("x", Node("x", End, End), End)
          ),
          Node("x", Node("x", Node("x"), End), Node("x", End, Node("x")))
        ) ==
          Tree.symmetricBalancedTrees(5, "x")
      )
    }
  }
} 
Example 67
Source File: P16Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P16Spec extends AnyFunSpec with Diagrams {
  describe("P16") {
    it("for index less than equal 0, drop(i, s) throws Exception") {
      intercept[Throwable] {
        P16.drop(0, List.empty[Int])
      }
      intercept[Throwable] {
        P16.drop(-1, List.empty[Int])
      }
      intercept[Throwable] {
        P16.drop(0, List(1))
      }
      intercept[Throwable] {
        P16.drop(-1, List(1))
      }
    }
    it("for positive index and empty list, drop(i, s) is empty list") {
      assert(P16.drop(1, List.empty[Int]) == List.empty[Int])
      assert(P16.drop(2, List.empty[Int]) == List.empty[Int])
      assert(P16.drop(3, List.empty[Int]) == List.empty[Int])
    }
    it("otherwise") {
      assert(P16.drop(1, List(1)) == List.empty[Int])
      assert(P16.drop(1, List(1, 2)) == List.empty[Int])
      assert(P16.drop(1, List(1, 2, 3)) == List.empty[Int])
      assert(P16.drop(2, List(1, 2)) == List(1))
      assert(P16.drop(2, List(1, 2, 3)) == List(1, 3))
      assert(P16.drop(2, List(0, 0)) == List(0))
    }
  }
} 
Example 68
Source File: P04Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P04Spec extends AnyFunSpec with Diagrams {
  describe("P04") {
    it("for empty list") {
      assert(P04.length(List.empty[Int]) == 0)
    }
    it("for list has one element") {
      assert(P04.length(List(1)) == 1)
    }
    it("otherwise") {
      assert(P04.length(List(1, 2)) == 2)
      assert(P04.length(List(1, 2, 3)) == 3)
    }
  }
} 
Example 69
Source File: P57Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import jp.co.dwango.s99.P57.Tree
import jp.co.dwango.s99.P56._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P57Spec extends AnyFunSpec with Diagrams {
  describe("P57") {
    it("Tree.fromList(List(5, 3, 18, 1, 4, 12, 21)") {
      assert(Tree.fromList(List(5, 3, 18, 1, 4, 12, 21)).isSymmetric)
    }
    it("Tree.fromList(List(3, 2, 5, 7, 4))") {
      assert(!Tree.fromList(List(3, 2, 5, 7, 4)).isSymmetric)
    }
  }
} 
Example 70
Source File: P62Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import binary_trees._
import P62._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P62Spec extends AnyFunSpec with Diagrams {
  describe("P62") {
    it("collect value of internal nodes") {
      assert(
        Node(
          'a',
          Node('b'),
          Node('c', Node('d'), Node('e'))
        ).internalList == List(
          'a',
          'c'
        )
      )
    }
  }
} 
Example 71
Source File: JsonMatchersSpec.scala    From scalatest-json   with Apache License 2.0 5 votes vote down vote up
package com.stephenn.scalatest.playjson

import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers

class JsonMatchersSpec extends AnyFunSpec with Matchers {

  describe("JsonMatchers") {
    it("should pass when json is the same") {
      Seq("{}" -> "{}", "[]" -> "[]").foreach {
        case (left, right) =>
          val matchResult = JsonMatchers.matchJson(right).apply(left)
          matchResult.matches shouldBe true
      }
    }

    it("should pass when json is equivalent") {
      val matchResult = JsonMatchers.matchJson("{  }").apply("  {}  ")
      matchResult.matches shouldBe true

      Seq(
        "{}" -> " { }",
        " [ ] " -> "[]",
        """{"a":0, "b":1}""" -> """{"b":1,"a":0}"""
      ).foreach {
        case (left, right) =>
          val matchResult = JsonMatchers.matchJson(right).apply(left)
          matchResult.matches shouldBe true
      }
    }

    it("should fail when left has extra fields") {
      val matchResult = JsonMatchers.matchJson("""{"l":1}""").apply("{}")
      matchResult.matches shouldBe false
      matchResult.failureMessage.trim shouldBe
        """
          |Json did not match "{}" did not match "{"l":1}"
          |
          |Json Diff:
          |"JsonPatch(List(Add(Chain(Left(l)),1)))"
        """.stripMargin.trim
    }

    it("should fail when right has extra fields") {
      val matchResult = JsonMatchers.matchJson("{}").apply("""{"r":0}""")
      matchResult.matches shouldBe false
      matchResult.failureMessage.trim shouldBe
        """
          |Json did not match "{"r":0}" did not match "{}"
          |
          |Json Diff:
          |"JsonPatch(List(Remove(Chain(Left(r)),None)))"
        """.stripMargin.trim
    }

    it("should fail on invalid json") {
      val matchResult =
        JsonMatchers.matchJson("{}").apply("""{"a": nope]}""")
      matchResult.matches shouldBe false
      matchResult.failureMessage shouldBe "Could not parse json \"{\"a\": nope]}\" did not equal \"{}\""
    }

    it("should match a json object to a json string") {
      import play.api.libs.json._
      val matchResult = JsonMatchers
        .matchJsonString("""{"b":1,"a":0}""")
        .apply(Json.parse("""{"a":0, "b":1}"""))
      matchResult.matches shouldBe true
    }
  }
} 
Example 72
Source File: P61aSpec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import binary_trees._
import P61a._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P61aSpec extends AnyFunSpec with Diagrams {
  describe("P61a") {
    it("collect value of leaves") {
      assert(
        Node(
          'a',
          Node('b'),
          Node('c', Node('d'), Node('e'))
        ).leafList.toSet == Set(
          'b',
          'd',
          'e'
        )
      )
      assert(End.leafList == Nil)
      assert(Node('b', Node('a'), End).leafList == List('a'))
    }
  }
} 
Example 73
Source File: P17Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P17Spec extends AnyFunSpec with Diagrams {
  describe("P17") {
    it("for index less than 0, split(n, s) throws Exception") {
      intercept[Throwable] {
        P17.split(-1, List.empty[Int])
      }
      intercept[Throwable] {
        P17.split(-1, List(1))
      }
      intercept[Throwable] {
        P17.split(-1, List(1, 2))
      }
    }
    it("for index which is out of range, split(n, s) throws Exception") {
      intercept[Throwable] {
        P17.split(1, List.empty[Int])
      }
      intercept[Throwable] {
        P17.split(-1, List.empty[Int])
      }
      intercept[Throwable] {
        P17.split(2, List(1))
      }
      intercept[Throwable] {
        P17.split(3, List(1, 2))
      }
    }
    it("for 0 index and empty list, split(n, s) returns (List(), List())") {
      assert(
        P17.split(0, List.empty[Int]) == ((List.empty[Int], List.empty[Int]))
      )
    }
    it("otherwise") {
      assert(P17.split(0, List(1, 2)) == ((List(), List(1, 2))))
      assert(P17.split(1, List(1, 2)) == ((List(1), List(2))))
      assert(P17.split(0, List(1, 2, 3)) == ((List(), List(1, 2, 3))))
      assert(P17.split(1, List(1, 2, 3)) == ((List(1), List(2, 3))))
      assert(P17.split(2, List(1, 2, 3)) == ((List(1, 2), List(3))))
      assert(P17.split(3, List(1, 2, 3)) == ((List(1, 2, 3), List())))
    }
  }
} 
Example 74
Source File: P07Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P07Spec extends AnyFunSpec with Diagrams {
  describe("P07") {
    it("for empty list, flatten(s) is s") {
      assert(P07.flatten(List.empty[Int]) == List.empty[Int])
    }
    it("for list of empty list, flatten(List(List.empty)) is List.empty") {
      assert(P07.flatten(List(List.empty[Int])) == List.empty[Int])
    }
    it("otherwise") {
      assert(P07.flatten(List(List(1))) == List(1))
    }
  }
} 
Example 75
Source File: P96Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P96._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P96Spec extends AnyFunSpec with Diagrams {
  describe("P96") {
    it("for letter parser") {
      assert(letter("a") == Success(""))
      assert(letter("abc") == Success("bc"))
    }
    it("for ~ parser") {
      val ab = letter ~ letter
      assert(ab("abc") == Success("c"))
    }
    it("for ? parser") {
      val p1 = letter.?
      assert(p1("abc") == Success("bc"))
      assert(p1("123") == Success("123"))
      val p2 = letter ~ letter.?
      assert(p2("a12") == Success("12"))
      assert(p2("ab1") == Success("1"))
      assert(p2("abc") == Success("c"))
    }
    it("for | parser") {
      val p1 = letter | digit
      assert(p1("abc") == Success("bc"))
      assert(p1("123") == Success("23"))
    }
    it("for identifier parser") {
      assert(identifier("abc") == Success(""))
      assert(identifier("Time_of_Day") == Success(""))
      assert(identifier("only_1_percent") == Success(""))
      assert(identifier("abc123_xyz") == Success(""))
    }
  }
} 
Example 76
Source File: P62bSpec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import binary_trees._
import P62b._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P62bSpec extends AnyFunSpec with Diagrams {
  describe("P62b") {
    it("collect value of specific levels") {
      assert(
        Node('a', Node('b'), Node('c', Node('d'), Node('e')))
          .atLevel(2) == List('b', 'c')
      )
    }
  }
} 
Example 77
Source File: P11Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P11Spec extends AnyFunSpec with Diagrams {
  describe("P11") {
    it("for empty list, encodeModified(s) is s") {
      assert(P11.encodeModified(List.empty[Int]) == List.empty[Int])
    }
    it("for list has one element, encodeModified(s) is s") {
      assert(P11.encodeModified(List(1)) == List(1))
      assert(P11.encodeModified(List(2)) == List(2))
      assert(P11.encodeModified(List(2)) == List(2))
    }
    it("otherwise") {
      assert(P11.encodeModified(List(1, 1)) == List((2, 1)))
      assert(P11.encodeModified(List(1, 1, 2)) == List((2, 1), 2))
      assert(P11.encodeModified(List(1, 1, 2, 3)) == List((2, 1), 2, 3))
      assert(P11.encodeModified(List(1, 1, 2, 2, 3)) == List((2, 1), (2, 2), 3))
    }
  }
} 
Example 78
Source File: P32Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P32Spec extends AnyFunSpec with Diagrams {
  describe("P32") {
    it("for zero test") {
      assert(P32.gcd(0, 0) == 0)
      assert(P32.gcd(2, 0) == 2)
      assert(P32.gcd(0, 33) == 33)
    }
    it("for positive integer numbers") {
      assert(
        P32.gcd(3 * 5 * 7 * 11, 3 * 5 * 7 * 11 * 17 * 19) == 3 * 5 * 7 * 11
      )
      assert(P32.gcd(3, 3) == 3)
      assert(P32.gcd(2 * 3 * 5 * 7, 2 * 3 * 5 * 17) == 2 * 3 * 5)
      assert(P32.gcd(Int.MaxValue, Int.MaxValue) == Int.MaxValue)
    }
    it("for negative integer numbers") {
      assert(P32.gcd(-5, -5) == 5)
      assert(P32.gcd(-2, -4) == 2)
      assert(P32.gcd(Int.MinValue, Int.MinValue) == Int.MinValue)
    }
  }
} 
Example 79
Source File: P68Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import P68._
import binary_trees._
import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P68Spec extends AnyFunSpec with Diagrams {
  describe("P68") {
    it("do pre-order traversal") {
      assert(
        Tree.string2Tree("a(b(d,e),c(,f(g,)))").preorder ==
          List('a', 'b', 'd', 'e', 'c', 'f', 'g')
      )
    }
    it("do in-order traversal") {
      assert(
        Tree.string2Tree("a(b(d,e),c(,f(g,)))").inorder ==
          List('d', 'b', 'e', 'a', 'c', 'g', 'f')
      )
    }
  }
} 
Example 80
Source File: P01Spec.scala    From S99   with MIT License 5 votes vote down vote up
package jp.co.dwango.s99

import org.scalatest.diagrams.Diagrams
import org.scalatest.funspec.AnyFunSpec

class P01Spec extends AnyFunSpec with Diagrams {
  describe("P01") {
    it("for empty list(should fail)") {
      intercept[Throwable] {
        P01.last(List[Int]())
      }
    }
    it("for list has one element") {
      assert(P01.last(List(1)) == 1)
    }
    it("for list has more than one element") {
      assert(P01.last(List(1, 2)) == 2)
    }
  }
}