org.scalatest.freespec.AnyFreeSpec Scala Examples

The following examples show how to use org.scalatest.freespec.AnyFreeSpec. 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: CaseStringSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.marshalling

import org.scalatest.freespec.AnyFreeSpec

class CaseStringSpec extends AnyFreeSpec {
  val snake: String = "some_snake_case_string"
  val camel: String = "someSnakeCaseString"
  val pascal: String = camel.capitalize

  "snake_case" - {
    "to camelCase" in {
      assert(snake.camelCase == camel)
    }

    "to PascalCase" in {
      assert(snake.pascalCase == pascal)
    }
  }

  "camelCase" - {
    "to snake_case" in {
      assert(camel.snakeCase == snake)
    }

    "to PascalCase" in {
      assert(camel.pascalCase == pascal)
    }
  }

  "PascalCase" - {
    "to snake_case" in {
      assert(pascal.snakeCase == snake)
    }

    "to camelCase" in {
      assert(pascal.camelCase == camel)
    }
  }
} 
Example 2
Source File: ResultSetIteratorSpec.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill

import io.getquill.context.monix.Runner
import io.getquill.util.LoadConfig
import monix.eval.Task
import monix.execution.Scheduler
import org.scalatest.BeforeAndAfterAll
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import org.scalatest.matchers.should.Matchers._

import scala.collection.mutable.ArrayBuffer

class ResultSetIteratorSpec extends AnyFreeSpec with Matchers with BeforeAndAfterAll {

  val ds = JdbcContextConfig(LoadConfig("testPostgresDB")).dataSource
  implicit val scheduler = Scheduler.global

  val ctx = new PostgresMonixJdbcContext(Literal, ds, Runner.default)
  import ctx._

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

  val peopleInsert =
    quote((p: Person) => query[Person].insert(p))

  val peopleEntries = List(
    Person("Alex", 60),
    Person("Bert", 55),
    Person("Cora", 33)
  )

  override def beforeAll = {
    ctx.transaction {
      for {
        _ <- ctx.run(query[Person].delete)
        _ <- ctx.run(liftQuery(peopleEntries).foreach(p => peopleInsert(p)))
      } yield ()
    }.runSyncUnsafe()
  }

  "traverses correctly" in {
    val results =
      Task(ds.getConnection).bracket { conn =>
        Task {
          val stmt = conn.prepareStatement("select * from person")
          val rs = new ResultSetIterator[String](stmt.executeQuery(), extractor = (rs) => { rs.getString(1) })
          val accum = ArrayBuffer[String]()
          while (rs.hasNext) accum += rs.next()
          accum
        }
      } { conn => Task(conn.close()) }.runSyncUnsafe()

    results should contain theSameElementsAs (peopleEntries.map(_.name))
  }

  "can take head element" in {
    val result =
      Task(ds.getConnection).bracket { conn =>
        Task {
          val stmt = conn.prepareStatement("select * from person where name = 'Alex'")
          val rs = new ResultSetIterator(stmt.executeQuery(), extractor = (rs) => { rs.getString(1) })
          rs.head
        }
      } { conn => Task(conn.close()) }.runSyncUnsafe()

    result must equal("Alex")
  }
} 
Example 3
Source File: SchemaMaker.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill.codegen.util

import java.io.Closeable

import io.getquill._
import io.getquill.codegen.integration.DbHelper
import javax.sql.DataSource
import org.scalatest.freespec.AnyFreeSpec

import scala.language.implicitConversions

abstract class CodegenSpec extends AnyFreeSpec with SchemaMaker {
  type Prefix <: ConfigPrefix
  val prefix: Prefix

  implicit def regToOption[T](t: T) = Some(t)
}

object SchemaMaker extends SchemaMaker

case class SchemaMakerCoordinates(dbPrefix: ConfigPrefix, naming: NamingStrategy, schemaConfig: SchemaConfig)

trait SchemaMaker {

  private[getquill] def withDatasource[T](schemaConfig: SchemaConfig, dbPrefix: ConfigPrefix)(testCode: DataSource with Closeable => T): T = {
    val ds = dbPrefix.makeDatasource
    val helper = new DbHelper(schemaConfig, dbPrefix, ds)
    DbHelper.dropTables(ds)
    helper.setup()
    testCode(ds)
  }

  def withContext[T](coords: SchemaMakerCoordinates)(testCode: => T): T = {
    import coords._
    withDatasource(schemaConfig, dbPrefix)(ds => {
      testCode
    })
  }
} 
Example 4
Source File: MongoObservableReactivePublisherTest.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package mongo.async

import com.avsystem.commons.concurrent.RunNowEC
import com.github.ghik.silencer.silent
import com.mongodb.async.{client => mongo}
import monix.execution.{Cancelable, Scheduler}
import org.mockito.ArgumentMatchers.{eq => eqTo, _}
import org.mockito.Mockito
import org.mockito.Mockito._
import org.mongodb.scala.{Completed, Document, FindObservable, MongoCollection, SingleObservable}
import org.scalactic.source.Position
import org.scalatest.freespec.AnyFreeSpec

import scala.concurrent.duration.Duration

@silent("deprecated")
class MongoObservableReactivePublisherTest extends AnyFreeSpec {

  abstract class MockedObservableTests(implicit position: Position) extends MongoObservableExtensions {

    def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit

    "should drop test collection" in {
      val collection = Mockito.mock(classOf[MongoCollection[Document]])
      when(collection.drop()).thenReturn(SingleObservable(Completed()))
      val dropSubscriber = TestSubscriber[Completed]()

      subscribe(collection.drop(), dropSubscriber)

      dropSubscriber.assertNoTerminalEvent()
      dropSubscriber.requestMore(1)
      dropSubscriber.awaitTerminalEvent(Duration(100, "ms"))
      dropSubscriber.assertNoErrors()
      dropSubscriber.assertReceivedOnNext(Seq(Completed()))

      verify(collection).drop()
      verifyNoMoreInteractions(collection)
    }

    "should insert documents" in {
      val collection = Mockito.mock(classOf[MongoCollection[Document]])
      val insertSubscriber = TestSubscriber[Completed]()
      when(collection.insertMany(any())).thenReturn(SingleObservable(Completed()))

      val documents: IndexedSeq[Document] = (1 to 100) map { i: Int => Document("_id" -> i) }
      subscribe(collection.insertMany(documents), insertSubscriber)
      insertSubscriber.requestMore(1)
      insertSubscriber.awaitTerminalEvent(Duration(100, "ms"))
      insertSubscriber.assertNoErrors()
      insertSubscriber.assertReceivedOnNext(Seq(Completed()))

      verify(collection).insertMany(eqTo(documents))
      verifyNoMoreInteractions(collection)
    }

    "should find documents" in {
      val documents: IndexedSeq[Document] = (1 to 100) map { i: Int => Document("_id" -> i) }
      val original = Mockito.mock(classOf[FindObservable[Document]])
      val findSubscriber = TestSubscriber[Document]()
      doNothing().when(original).subscribe(any())

      subscribe(original, findSubscriber)
      findSubscriber.assertNoTerminalEvent()
      findSubscriber.requestMore(101)
      documents.foreach(findSubscriber.onNext)
      findSubscriber.onComplete()
      findSubscriber.awaitTerminalEvent(Duration(100, "ms"))
      findSubscriber.assertNoErrors()
      findSubscriber.assertReceivedOnNext(documents)


      verify(original).subscribe(any(classOf[mongo.Observer[_ >: Document]]))
      verifyNoMoreInteractions(original)
    }
  }

  "A Mongo-Reactive observable" - new MockedObservableTests {
    override def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit =
      obs.asReactive.subscribe(testSubscriber)
  }
  "A Mongo-Monix observable" - new MockedObservableTests {
    override def subscribe[T](obs: mongo.Observable[T], testSubscriber: TestSubscriber[T]): Unit =
      obs.asMonix.subscribe(
        monix.reactive.observers.Subscriber.fromReactiveSubscriber(testSubscriber, Cancelable.empty)(Scheduler(RunNowEC))
      )
  }
} 
Example 5
Source File: WartremoverWarnings.scala    From better-monadic-for   with MIT License 5 votes vote down vote up
package com.olegpy.bm4

import org.scalatest.freespec.AnyFreeSpec


class WartremoverWarnings extends AnyFreeSpec {
  "Wartremover should not complain" in {
    def right[A, B](b: B): Either[A, B] = Right(b)
    case class Foo(a: Long)
    for {
      Foo(a) <- right[String, Foo](Foo(1))
      b <- right(Foo(2))
      Foo(c) = b
    } yield a + c
  }
} 
Example 6
Source File: JsonSchemasOptionalFieldsTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.playjson

import endpoints4s.{Invalid, Valid, Validated, algebra}
import play.api.libs.json.{
  JsArray,
  JsBoolean,
  JsError,
  JsNull,
  JsNumber,
  JsObject,
  JsString,
  JsSuccess,
  JsValue
}
import org.scalatest.freespec.AnyFreeSpec

class JsonSchemasOptionalFieldsTest
    extends AnyFreeSpec
    with algebra.JsonSchemasOptionalFieldsTest
    with JsonSchemas {

  object Json extends Json {
    type Json = JsValue
    def obj(fields: (String, Json)*): Json = JsObject(fields)
    def arr(items: Json*): Json = JsArray(items)
    def num(x: BigDecimal): Json = JsNumber(x)
    def str(s: String): Json = JsString(s)
    def bool(b: Boolean): Json = JsBoolean(b)
    def `null`: Json = JsNull
  }

  def decodeJson[A](schema: JsonSchema[A], json: Json.Json): Validated[A] =
    schema.reads.reads(json) match {
      case JsSuccess(a, _) => Valid(a)
      case JsError(errors) =>
        val stringErrors =
          for {
            (_, pathErrors) <- errors
            error <- pathErrors
            message <- error.messages
          } yield message
        Invalid(stringErrors.toList)
    }

  def encodeJson[A](schema: JsonSchema[A], value: A): Json.Json =
    schema.writes.writes(value)

} 
Example 7
Source File: JsonSchemasOptionalFieldsTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s
package circe

import org.scalatest.freespec.AnyFreeSpec

class JsonSchemasOptionalFieldsTest
    extends AnyFreeSpec
    with algebra.JsonSchemasOptionalFieldsTest
    with JsonSchemas {

  object Json extends Json {
    type Json = io.circe.Json
    def obj(fields: (String, Json)*): Json = io.circe.Json.obj(fields: _*)
    def arr(items: Json*): Json = io.circe.Json.arr(items: _*)
    def num(x: BigDecimal): Json = io.circe.Json.fromBigDecimal(x)
    def str(s: String): Json = io.circe.Json.fromString(s)
    def bool(b: Boolean): Json = io.circe.Json.fromBoolean(b)
    def `null`: Json = io.circe.Json.Null
  }

  def decodeJson[A](schema: JsonSchema[A], json: Json.Json): Validated[A] =
    schema.decoder.decodeAccumulating(json.hcursor) match {
      case cats.data.Validated.Valid(a)   => Valid(a)
      case cats.data.Validated.Invalid(e) => Invalid(e.toList.map(_.message))
    }

  def encodeJson[A](schema: JsonSchema[A], value: A): Json.Json =
    schema.encoder(value)

} 
Example 8
Source File: JsonSchemasOptionalFieldsTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.ujson

import endpoints4s.{Validated, algebra}
import org.scalatest.freespec.AnyFreeSpec

import scala.collection.mutable

class JsonSchemasOptionalFieldsTest
    extends AnyFreeSpec
    with algebra.JsonSchemasOptionalFieldsTest
    with JsonSchemas {

  object Json extends Json {
    type Json = ujson.Value
    def obj(fields: (String, Json)*): Json =
      ujson.Obj(new mutable.LinkedHashMap ++= fields)
    def arr(items: Json*): Json = ujson.Arr(items: _*)
    def num(x: BigDecimal): Json = ujson.Num(x.doubleValue)
    def str(s: String): Json = ujson.Str(s)
    def bool(b: Boolean): Json = ujson.Bool(b)
    def `null`: Json = ujson.Null
  }

  def decodeJson[A](schema: JsonSchema[A], json: Json.Json): Validated[A] =
    schema.decoder.decode(json)

  def encodeJson[A](schema: JsonSchema[A], value: A): Json.Json =
    schema.encoder.encode(value)

} 
Example 9
Source File: EndpointsTest.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.xhr

import org.scalatest.freespec.AnyFreeSpec

// Separation of the Algebra here is important, due to implementation details
// of the underlying representation of header in the xhr algebra.
trait FixturesAlgebra extends endpoints4s.algebra.Endpoints {
  val foo = endpoint(get(path / "foo" / segment[String]()), ok(emptyResponse))
  val bar = endpoint(
    post(path / "bar" /? qs[Int]("quux"), emptyRequest),
    ok(emptyResponse)
  )
  // Currently, the fact that this line compiles is a test, as there's no way
  // to inspect the result of constructing headers at the moment.
  val baz = endpoint(
    post(
      path / "baz",
      emptyRequest,
      headers =
        requestHeader("quuz") ++ requestHeader("corge") ++ optRequestHeader(
          "grault"
        )
    ),
    ok(emptyResponse)
  )
}

object Fixtures extends FixturesAlgebra with thenable.Endpoints

// TODO try to use traits defined in algebra tests.
// It cannot be simply reused because dependency on wiremock which is not available for js
class EndpointsTest extends AnyFreeSpec {

  "href" in {
    assert("/foo/hello%20world" == Fixtures.foo.href("hello world"))
    assert("/bar?quux=42" == Fixtures.bar.href(42))
  }

} 
Example 10
Source File: DiffResultTest.scala    From diffx   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.diffx

import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class DiffResultTest extends AnyFreeSpec with Matchers with DiffxConsoleSupport {
  implicit val colorConfig: ConsoleColorConfig =
    ConsoleColorConfig(default = identity, arrow = identity, right = identity, left = identity)

  "diff set output" - {
    "it should show a simple difference" in {
      val output = DiffResultSet(List(Identical("a"), DiffResultValue("1", "2"))).show
      output shouldBe
        s"""Set(
          |     a,
          |     1 -> 2)""".stripMargin
    }

    "it should show an indented difference" in {
      val output = DiffResultSet(List(Identical("a"), DiffResultValue("1", "2"))).showIndented(5)
      output shouldBe
        s"""Set(
           |     a,
           |     1 -> 2)""".stripMargin
    }

    "it should show a nested list difference" in {
      val output = DiffResultSet(List(Identical("a"), DiffResultSet(List(Identical("b"))))).show
      output shouldBe
        s"""Set(
           |     a,
           |     Set(
           |          b))""".stripMargin
    }

    "it should show null" in {
      val output = DiffResultSet(List(Identical(null), DiffResultValue(null, null))).show
      output shouldBe
        s"""Set(
          |     null,
          |     null -> null)""".stripMargin
    }
  }

  "diff map output" - {
    "it should show a simple diff" in {
      val output =
        DiffResultMap(Map(Identical("a") -> DiffResultValue(1, 2), DiffResultMissing("b") -> DiffResultMissing(3))).show
      output shouldBe
        s"""Map(
           |     a: 1 -> 2,
           |     b: 3)""".stripMargin
    }

    "it should show an indented diff" in {
      val output =
        DiffResultMap(Map(Identical("a") -> DiffResultValue(1, 2), DiffResultMissing("b") -> DiffResultMissing(3)))
          .showIndented(5)
      output shouldBe
        s"""Map(
           |     a: 1 -> 2,
           |     b: 3)""".stripMargin
    }

    "it should show a nested diff" in {
      val output =
        DiffResultMap(Map(Identical("a") -> DiffResultMap(Map(Identical("b") -> DiffResultValue(1, 2))))).show
      output shouldBe
        s"""Map(
           |     a: Map(
           |          b: 1 -> 2))""".stripMargin
    }
  }

  "diff object output" - {
    "it should show an indented diff with plus and minus signs" in {
      val colorConfigWithPlusMinus: ConsoleColorConfig =
        ConsoleColorConfig(default = identity, arrow = identity, right = s => "+" + s, left = s => "-" + s)

      val output = DiffResultObject("List", Map("0" -> DiffResultValue(1234, 123), "1" -> DiffResultMissing(1234)))
        .showIndented(5)(colorConfigWithPlusMinus)
      output shouldBe
        s"""List(
           |     0: -1234 -> +123,
           |     1: +1234)""".stripMargin
    }
  }
} 
Example 11
Source File: CodecsSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.marshalling

import canoe.marshalling.codecs._
import io.circe.generic.semiauto._
import io.circe.{Decoder, Encoder, Json}
import org.scalatest.freespec.AnyFreeSpec

class CodecsSpec extends AnyFreeSpec {
  case class Inner(longName: String)
  case class Outer(longInt: Int, inner: Inner)

  implicit val innerDecoder: Decoder[Inner] = deriveDecoder
  implicit val innerEncoder: Encoder[Inner] = deriveEncoder

  val decoder: Decoder[Outer] = deriveDecoder
  val encoder: Encoder[Outer] = deriveEncoder

  val instance: Outer = Outer(12, Inner("name"))

  "encoder works as expected" in {
    assert(allJsonKeys(encoder(instance)) == List("longInt", "inner", "longName"))
  }

  "snake case encoder encodes keys in snake_case manner" in {
    val encodedKeys = allJsonKeys(encoder.snakeCase(instance))

    assert(encodedKeys.map(_.snakeCase) == encodedKeys)
  }

  "encoded snake_case is decoded in camelCase" in {
    val encodedDecoded = decoder.camelCase.decodeJson(encoder.snakeCase(instance))

    assert(encodedDecoded.contains(instance))
  }

  def allJsonKeys(json: Json): List[String] =
    json.asObject.toList.flatMap(_.toList).flatMap {
      case (k, json) => k :: allJsonKeys(json)
    }
} 
Example 12
Source File: PollingSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.api.sources

import canoe.TestIO._
import canoe.api.TelegramClient
import canoe.methods.Method
import canoe.methods.updates.GetUpdates
import canoe.models.messages.TextMessage
import canoe.models.{MessageReceived, PrivateChat, Update}
import cats.effect.IO
import org.scalatest.freespec.AnyFreeSpec

import scala.concurrent.duration.Duration

class PollingSpec extends AnyFreeSpec {
  implicit val updatesClient: TelegramClient[IO] = new TelegramClient[IO] {
    def execute[Req, Res](request: Req)(implicit M: Method[Req, Res]): IO[Res] =
      if (M.name != GetUpdates.method.name) throw new UnsupportedOperationException
      else {
        val getUpdates: GetUpdates = request.asInstanceOf[GetUpdates]
        val update: Update =
          MessageReceived(getUpdates.offset.get, TextMessage(-1, PrivateChat(-1, None, None, None), -1, ""))
        IO.pure(List(update).asInstanceOf[Res])
      }
  }

  val polling = new Polling(Duration.Zero)
  "polling" - {
    "starts with given offset" in {
      assert(polling.pollUpdates(0).take(1).value().head.updateId == 0)
    }

    "uses last offset increased by 1 for each new call" in {
      val updates = polling
        .pollUpdates(0)
        .zipWithNext
        .collect { case (u1, Some(u2)) => u1.last -> u2.head }
        .take(5)
        .toList()

      assert(updates.forall { case (u1, u2) => u2.updateId == u1.updateId + 1 })
    }
  }
} 
Example 13
Source File: BroadcastSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.api

import canoe.TestIO._
import cats.effect.IO
import fs2.{Pipe, Stream}
import org.scalatest.freespec.AnyFreeSpec
import cats.effect.concurrent.Ref
import scala.concurrent.duration._

class BroadcastSpec extends AnyFreeSpec {
  def broadcast[A]: Stream[IO, Broadcast[IO, A]] = Stream.eval(Broadcast[IO, A])

  def recordPulled[A](b: Broadcast[IO, A], duration: FiniteDuration): Pipe[IO, A, List[A]] =
    input =>
      Stream.eval(Ref[IO].of(List.empty[A])).flatMap { ref =>
        input
          .evalTap(i => ref.update(i :: _))
          .through(b.publish)
          .drain
          .interruptAfter(duration)
          .append(Stream.eval(ref.get))
      }

  "Broadcast" - {
    val input = Stream.range(1, 100)

    "subscriber" - {
      "sees all elements after subscription" in {
        val res = broadcast[Int].flatMap { b =>
          val pop = Stream.sleep_(0.05.second) ++ input.through(b.publish)
          val sub = b.subscribe(1).take(input.size())
          sub.concurrently(pop)
        }

        assert(res.toList() == input.toList)
      }

      "is deregistered after it is done pulling" in {
        val pulled = broadcast[Int].flatMap { b =>
          val pop = Stream.sleep_(0.1.second) ++ input.through(recordPulled(b, 1.second))
          val consumer = b.subscribe(1).metered(0.1.second).take(5)
          pop.concurrently(consumer)
        }

        assert(pulled.value() == input.toList.reverse)
      }
    }

    "pulls from publisher" - {
      "one element before it's blocked by the subscriber" in {
        val pulled = broadcast[Int].flatMap { b =>
          val pop = Stream.sleep_(0.05.second) ++ input.through(recordPulled(b, 0.2.second))
          val consumer = b.subscribe(0).evalMap(_ => IO.never)
          pop.concurrently(consumer)
        }

        assert(pulled.value() == input.head.toList)
      }

      "maxQueued + 2 elements for non-empty blocking consumer" in {
        val maxQueued = 3
        val pulled = broadcast[Int].flatMap { b =>
          val pop = Stream.sleep_(0.05.second) ++ input.through(recordPulled(b, 0.2.second))
          val consumer = b.subscribe(maxQueued).evalMap(_ => IO.never)
          pop.concurrently(consumer)
        }
        assert(pulled.value() == input.take(maxQueued + 2).toList.reverse)
      }

      "all elements" - {
        "for non-blocking consumer" in {
          val pulled = broadcast[Int].flatMap { b =>
            val pop = input.through(recordPulled(b, 0.2.second))
            val consumer = b.subscribe(1)
            pop.concurrently(consumer)
          }
          assert(pulled.value() == input.toList.reverse)
        }

        "for no consumer" in {
          val pulled = broadcast[Int].flatMap { b =>
            input.through(recordPulled(b, 0.2.second))
          }
          assert(pulled.value() == input.toList.reverse)
        }
      }
    }
  }
} 
Example 14
Source File: ExpectTextMessageOpsSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.syntax

import canoe.models.PrivateChat
import canoe.models.messages.{TelegramMessage, TextMessage}
import org.scalatest.freespec.AnyFreeSpec

class ExpectTextMessageOpsSpec extends AnyFreeSpec {
  val anyTextMessage: Expect[TextMessage] = canoe.syntax.textMessage

  def message(text: String): TelegramMessage =
    TextMessage(-1, PrivateChat(-1, None, None, None), -1, text)

  "startingWith" - {
    "is defined only at messages which texts are starting with provided string" in {
      val expect = anyTextMessage.startingWith("start")
      assert(expect.isDefinedAt(message("start dadada")))
      assert(!expect.isDefinedAt(message("ad")))
    }
  }

  "endingWith" - {
    "is defined only at messages which texts are ending with provided string" in {
      val expect = anyTextMessage.endingWith("end")
      assert(expect.isDefinedAt(message("adasdend")))
      assert(!expect.isDefinedAt(message("ad")))
    }
  }

  "containing" - {
    "is defined only at messages which texts contain provided string" in {
      val expect = anyTextMessage.containing("sub")
      assert(expect.isDefinedAt(message("adassubdend")))
      assert(!expect.isDefinedAt(message("ad")))
    }
  }

  "matching" - {
    "is defined only at messages which texts match provided regex" in {
      val expect = anyTextMessage.matching("[a-z]*")
      assert(expect.isDefinedAt(message("adassubdend")))
      assert(!expect.isDefinedAt(message("aTd")))
    }
  }
} 
Example 15
Source File: PartialFunctionOpsSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.syntax

import org.scalatest.freespec.AnyFreeSpec

class PartialFunctionOpsSpec extends AnyFreeSpec {
  val evenInt: PartialFunction[Int, Int] = {
    case i if i % 2 == 0 => i
  }

  "when" - {
    "appends new condition to isDefineAt" in {
      val evenBiggerThanTen = evenInt.when(_ > 10)
      assert(evenBiggerThanTen.isDefinedAt(12))
      assert(!evenBiggerThanTen.isDefinedAt(6))
      assert(!evenBiggerThanTen.isDefinedAt(13))
    }
  }
} 
Example 16
Source File: Http4sClientSpec.scala    From canoe   with MIT License 5 votes vote down vote up
package canoe.api.clients

import canoe.api._
import canoe.methods.Method
import canoe.models.InputFile
import cats.effect.IO
import io.circe.{Decoder, Encoder}
import org.http4s.HttpApp
import org.http4s.client.Client
import org.http4s.dsl.io._
import io.circe.Json
import io.chrisdavenport.log4cats.slf4j.Slf4jLogger
import org.scalatest.freespec.AnyFreeSpec

class Http4sClientSpec extends AnyFreeSpec {
  private case class TestMethod(name: String = "test",
                                encoder: Encoder[String] = Encoder.encodeString,
                                decoder: Decoder[String] = Decoder.decodeString,
                                files: List[InputFile] = Nil)
      extends Method[String, String] {
    def attachments(request: String): List[(String, InputFile)] = files.map("" -> _)
  }

  private implicit val testMethod = TestMethod()

  private def response(s: String) = s"""{"ok" : true, "result" : "$s"}"""

  private implicit val logger = Slf4jLogger.getLogger[IO]

  "Client" - {
    "sends" - {
      "to correct Telegram endpoint" in {
        val client: Client[IO] = Client.fromHttpApp(HttpApp(r => Ok(response(r.uri.toString))))
        val tgClient = new Http4sTelegramClient("token", client)

        assert(tgClient.execute("any").unsafeRunSync() == s"https://api.telegram.org/bottoken/${testMethod.name}")
      }

      val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO] { r =>
        Ok(response(r.headers.get(org.http4s.headers.`Content-Type`).map(_.value.replace("\"", "''")).getOrElse("")))
      }))

      "json POST request if attachments contain file upload" in {
        assert(tgClient.execute("any").unsafeRunSync() == "application/json")
      }

      "multipart POST request if attachments contain file upload" in {
        val resp = tgClient.execute("any")(testMethod.copy(files = List(InputFile.Upload("", Array.emptyByteArray))))
        assert(resp.unsafeRunSync().startsWith("multipart/form-data"))
      }
    }

    "encodes/decodes" - {
      "request entity with method encoder" in {
        val tgClient = new Http4sTelegramClient(
          "",
          Client.fromHttpApp(HttpApp[IO](_.bodyAsText.compile.string.flatMap(s => Ok(response(s.replace("\"", "'"))))))
        )
        val res = tgClient.execute("")(testMethod.copy(encoder = Encoder.instance(_ => Json.fromString("encoded"))))

        assert(res.unsafeRunSync() == "'encoded'")
      }

      "result entity with method decoder" in {
        val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO](_ => Ok(response("")))))
        val res = tgClient.execute("")(testMethod.copy(decoder = Decoder.const("decoded")))

        assert(res.unsafeRunSync() == "decoded")
      }
    }

    "handles" - {
      "decode failure as ResponseDecodingError" in {
        val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO](_ => Ok("{}"))))

        assertThrows[ResponseDecodingError](tgClient.execute("any").unsafeRunSync())
      }

      "unsuccessful result as FailedMethod" in {
        val response = """{"ok" : false, "result" : "any"}"""
        val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO](_ => Ok(response))))

        assertThrows[FailedMethod[String, String]](tgClient.execute("any").unsafeRunSync())
      }
    }
  }
} 
Example 17
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.freespec.AnyFreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends AnyFreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 18
Source File: JsonImplicitsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalacheck.{Arbitrary, Gen, Shrink}
import org.scalacheck.ops._
import org.scalatest.freespec.AnyFreeSpec
import play.api.libs.json.{Format, Json}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks._

case class KeyWrapper(key: String)
object KeyWrapper {
  implicit val arbKeyWrapper: Arbitrary[KeyWrapper] = Arbitrary(Gen.string.map(KeyWrapper(_)))
  implicit val shrinkKeyWrapper: Shrink[KeyWrapper] = Shrink { k =>
    Shrink.shrinkString.shrink(k.key).map(KeyWrapper(_))
  }

  implicit lazy val format: Format[KeyWrapper] = Format.asString(convertFromString, _.key)
  implicit val writeKey: WritesKey[KeyWrapper] = WritesKey(_.key)
  implicit val readKey: ReadsKey[KeyWrapper] = ReadsKey.of[String].map(KeyWrapper(_))
  implicit lazy val convertFromString: String => KeyWrapper = KeyWrapper(_)
}

class JsonImplicitsSpec extends AnyFreeSpec {

  private val exampleJson = Json.obj(
    "A" -> "value",
    "B" -> "other"
  )

  private val exampleMap = Map(
    KeyWrapper("A") -> "value",
    KeyWrapper("B") -> "other"
  )

  private val exampleMapFormat = Format.of[Map[KeyWrapper, String]]

  "explicit call to write should format the Json correctly" in {
    assertResult(exampleJson) {
      exampleMapFormat.writes(exampleMap)
    }
  }

  "explicit call to read should read correctly formatted Json" in {
    assertResult(exampleMap) {
      exampleMapFormat.reads(exampleJson).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](exampleJson, err)
      }
    }
  }

  "formatter should read every value it writes and write it out the same way" in {
    forAll { value: Map[String, String] =>
      val keyWrappedMap = value.map {
        case (k, v) => (KeyWrapper(k), v)
      }
      val json = exampleMapFormat.writes(keyWrappedMap)
      val parsedMap = exampleMapFormat.reads(json).recoverTotal { err =>
        throw InvalidJsonException[Map[KeyWrapper, String]](json, err)
      }
      assertResult(keyWrappedMap)(parsedMap)
    }
  }
} 
Example 19
Source File: DiffxCatsTest.scala    From diffx   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.diffx.cats

import cats.data._
import cats.instances.int._
import com.softwaremill.diffx._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class DiffxCatsTest extends AnyFreeSpec with Matchers {
  "nonEmptyList" in {
    compare(NonEmptyList.of(1), NonEmptyList.of(2)) shouldBe DiffResultObject("List", Map("0" -> DiffResultValue(1, 2)))
  }

  "nonEmptyChain" in {
    compare(NonEmptyChain.one(1), NonEmptyChain.one(2)) shouldBe DiffResultObject(
      "List",
      Map("0" -> DiffResultValue(1, 2))
    )
  }

  "nonEmptySet" in {
    compare(NonEmptySet.of(1), NonEmptySet.of(2)) shouldBe DiffResultSet(
      List(DiffResultAdditional(1), DiffResultMissing(2))
    )
  }

  "nonEmptyVector" in {
    compare(NonEmptyVector.of(1), NonEmptyVector.of(2)) shouldBe DiffResultObject(
      "List",
      Map("0" -> DiffResultValue(1, 2))
    )
  }
} 
Example 20
Source File: JacksonNestedTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Jackson

import java.lang.reflect.Modifier
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import polymorphismNested.client.dropwizard.definitions.{ A, B, C, TestResponse }

class JacksonNestedTest extends AnyFreeSpec with Matchers {
  "Jackson nested schemas" - {
    "Should have the nested objects in the right place" in {
      new TestResponse.Builder()
        .withEnum1(A.Enum1.B)
        .withEnum2(B.Enum2.D)
        .withObj(new C.Obj.Builder().withValue("foo").build())
        .build()
    }

    "Should have nested classes as public static members" in {
      classOf[C.Obj].getModifiers & Modifier.PUBLIC mustBe Modifier.PUBLIC
      classOf[C.Obj].getModifiers & Modifier.STATIC mustBe Modifier.STATIC
    }

    "Should have nested enums as public non-static members that nonetheless reflect as static" in {
      classOf[A.Enum1].getModifiers & Modifier.PUBLIC mustBe Modifier.PUBLIC
      classOf[A.Enum1].getModifiers & Modifier.STATIC mustBe Modifier.STATIC
    }
  }
} 
Example 21
Source File: JavaInvalidCharacterEscapingTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Dropwizard

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import invalidCharacters.client.dropwizard.invalidCharacters.InvalidCharactersClient
import invalidCharacters.server.dropwizard.definitions.{InvalidCharacters, InvalidCharactersEnum}
import io.netty.buffer.Unpooled
import java.net.{SocketAddress, URI, URLDecoder}
import java.util.concurrent.{CompletableFuture, CompletionStage}
import java.util.function
import org.asynchttpclient.Response.ResponseBuilder
import org.asynchttpclient.netty.EagerResponseBodyPart
import org.asynchttpclient.uri.Uri
import org.asynchttpclient.{HttpResponseStatus, Request, Response}
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import scala.collection.JavaConverters._

object JavaInvalidCharacterEscapingTest {
  private implicit class RichString(private val s: String) extends AnyVal {
    def dec: String = URLDecoder.decode(s, "UTF-8")
  }

  private object OkStatus extends HttpResponseStatus(Uri.create("http://localhost:1234/foo?foo^bar=query-param")) {
    override def getStatusCode = 200
    override def getStatusText = "OK"
    override def getProtocolName = "HTTP"
    override def getProtocolMajorVersion = 1
    override def getProtocolMinorVersion = 1
    override def getProtocolText = "HTTP/1.1"
    override def getRemoteAddress: SocketAddress = ???
    override def getLocalAddress: SocketAddress = ???
  }
}

class JavaInvalidCharacterEscapingTest extends AnyFreeSpec with Matchers {
  import JavaInvalidCharacterEscapingTest._

  "Invalid characters in Java enums should be escaped" in {
    InvalidCharactersEnum.NORMAL.getName mustBe "normal"
    InvalidCharactersEnum.BANG_MOO_COLON_COW_SEMICOLON.getName mustBe "!moo:cow;"
    InvalidCharactersEnum.POUND_YEAH.getName mustBe "#yeah"
    InvalidCharactersEnum.WEIRD_AT.getName mustBe "weird@"
  }

  "Invalid characters in Java POJO properties should be escaped" in {
    val invChar = new InvalidCharacters.Builder("stuff", InvalidCharactersEnum.POUND_YEAH).build()
    invChar.getCloseSquareBraceMoo mustBe "stuff"
    invChar.getSomeEnumAsteriskCaret mustBe InvalidCharactersEnum.POUND_YEAH

    classOf[InvalidCharacters].getDeclaredField("closeSquareBraceMoo").getAnnotation(classOf[JsonProperty]).value mustBe "]moo"
    classOf[InvalidCharacters].getDeclaredField("someEnumAsteriskCaret").getAnnotation(classOf[JsonProperty]).value mustBe "some-enum*^"
  }

  "Invalid characters in Java operation param names should be escaped" in {
    val httpClient = new function.Function[Request, CompletionStage[Response]] {
      override def apply(request: Request): CompletionStage[Response] = {
        println(request.getUri)
        println(request.getQueryParams.asScala.map(_.getName))
        val qps = request.getQueryParams.asScala.map(p => (p.getName.dec, p.getValue.dec))
        val fps = request.getFormParams.asScala.map(p => (p.getName.dec, p.getValue.dec))
        qps.find(_._1 == "foo^bar").map(_._2) mustBe Some("firstarg")
        fps.find(_._1 == "a*b").map(_._2) mustBe Some("secondarg")
        fps.find(_._1 == "bc?").map(_._2) mustBe Some("thirdarg")
        fps.find(_._1 == "d/c").map(_._2) mustBe Some("fourtharg")
        val response = new ResponseBuilder()
        response.accumulate(OkStatus)
        response.accumulate(new EagerResponseBodyPart(
          Unpooled.copiedBuffer(new ObjectMapper().writeValueAsBytes(new InvalidCharacters.Builder("foo", InvalidCharactersEnum.WEIRD_AT).build())),
          true
        ))
        CompletableFuture.completedFuture(response.build())
      }
    }

    val client = new InvalidCharactersClient.Builder(new URI("http://localhost:1234")).withHttpClient(httpClient).build()
    val response = client.getFoo("firstarg", "secondarg", "thirdarg", "fourtharg").call().toCompletableFuture.get()
    response.fold(
      { invChar =>
        invChar.getCloseSquareBraceMoo mustBe "foo"
        invChar.getSomeEnumAsteriskCaret mustBe invalidCharacters.client.dropwizard.definitions.InvalidCharactersEnum.WEIRD_AT
      }
    )
  }
} 
Example 22
Source File: DropwizardContentTypesTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package tests.generators.dropwizard.server

import com.github.javaparser.ast.body.MethodDeclaration
import com.twilio.guardrail.generators.Java.Dropwizard
import com.twilio.guardrail.{ Context, Server, Servers }
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import scala.collection.JavaConverters._
import scala.compat.java8.OptionConverters._
import support.SwaggerSpecRunner

class DropwizardContentTypesTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner {
  private val swagger: String =
    s"""
       |openapi: 3.0.1
       |paths:
       |  /foo:
       |    post:
       |      operationId: foo
       |      responses:
       |        204: {}
       |        404:
       |          content:
       |            application/json:
       |              schema:
       |                type: object
       |  /foo-multiple:
       |    post:
       |      operationId: fooMultiple
       |      responses:
       |        204:
       |          content:
       |            application/json:
       |              schema:
       |                type: object
       |        404:
       |          content:
       |            text/plain:
       |              schema:
       |                type: string
       |""".stripMargin

  "Produces annotation should still be added when success response has no body, but errors do" in {
    val (
      _,
      _,
      Servers(Server(_, _, _, genResource :: Nil) :: Nil, _)
    ) = runSwaggerSpec(swagger)(Context.empty, Dropwizard)

    genResource
      .asClassOrInterfaceDeclaration()
      .getMembers
      .asScala
      .collectFirst({
        case method: MethodDeclaration if method.getNameAsString == "foo" => method
      })
      .value
      .getAnnotationByName("Produces")
      .asScala
      .value
      .asSingleMemberAnnotationExpr()
      .getMemberValue
      .toString mustBe "MediaType.APPLICATION_JSON"
  }

  // This doesn't yet work because when the core threads through response info, we lose which content-type
  // is associated with which response.  But I'll leave the test here to re-enable later when we fix that.
  
} 
Example 23
Source File: RequestBodiesTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package tests.core

import com.github.javaparser.ast.`type`.PrimitiveType
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.twilio.guardrail.generators.Java.Dropwizard
import com.twilio.guardrail.generators.syntax.Java._
import com.twilio.guardrail.{ Clients, Context }
import scala.collection.JavaConverters._
import support.SwaggerSpecRunner
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class RequestBodiesTest extends AnyFreeSpec with Matchers with SwaggerSpecRunner {
  val openapi: String =
    """
      |openapi: 3.0.2
      |info:
      |  version: 1.0.0
      |paths:
      |  /foo:
      |    post:
      |      x-jvm-package: requestBodies
      |      operationId: foo
      |      requestBody:
      |        $ref: "#/components/requestBodies/SomeRequestBodyForm"
      |      responses:
      |        200: {}
      |  /bar:
      |    post:
      |      x-jvm-package: requestBodies
      |      operationId: bar
      |      requestBody:
      |        $ref: "#/components/requestBodies/SomeRequestBodyWithRef"
      |      responses:
      |        200: {}
      |components:
      |  schemas:
      |    SomeSchema:
      |      type: object
      |      required:
      |        - a
      |      properties:
      |        a:
      |          type: string
      |        b:
      |          type: boolean
      |  requestBodies:
      |    SomeRequestBodyForm:
      |      required: true
      |      content:
      |        application/x-www-form-urlencoded:
      |          schema:
      |            required:
      |              - d
      |            properties:
      |              c:
      |                type: integer
      |                format: int64
      |              d:
      |                type: number
      |                format: double
      |    SomeRequestBodyWithRef:
      |      required: true
      |      content:
      |        application/json:
      |          schema:
      |            $ref: "#/components/schemas/SomeSchema"
    """.stripMargin

  "References to requestBodies should resolve and generate the proper args/methods" in {
    val (_, Clients(client :: _, _), _) =
      runSwaggerSpec(openapi)(Context.empty, Dropwizard)

    val cls = client.client.head.getOrElse(fail("Client does not contain a ClassDefinition"))

    val fooMethod = cls.getMethodsByName("foo").get(0)
    fooMethod.getParameter(0).getType shouldBe PrimitiveType.doubleType

    val fooCallBuilder = cls.getMembers.toList
      .collectFirst({
        case cbClass: ClassOrInterfaceDeclaration if cbClass.getNameAsString == "FooCallBuilder" => cbClass
      })
      .get
    val withCMethods = fooCallBuilder.getMethodsByName("withC").asScala
    withCMethods.length shouldBe 2
    withCMethods.foreach({
      case md if md.getParameter(0).getType.isPrimitiveType =>
        md.getParameter(0).getType shouldBe PrimitiveType.longType
      case md =>
        val paramType = md.getParameter(0).getType.asClassOrInterfaceType
        paramType.getNameAsString shouldBe "Optional"
        paramType.getTypeArguments.get.get(0).asClassOrInterfaceType.getNameAsString shouldBe "Long"
    })

    val barMethod          = cls.getMethodsByName("bar").get(0)
    val barMethodParamType = barMethod.getParameter(0).getType.asClassOrInterfaceType
    barMethodParamType.getNameAsString shouldBe "SomeSchema"
  }
} 
Example 24
Source File: CaseConvertersTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package tests.core

import com.twilio.guardrail.generators.syntax.RichString
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

object CaseConvertersTest {
  private case class CaseTest(raw: String, expectedPascal: String, expectedCamel: String, expectedSnake: String, expectedDashed: String) {
    override val toString: String = s"""(Test case for: "$raw")"""
  }

  private val TEST_CASES = List(
    CaseTest("foo", "Foo", "foo", "foo", "foo"),
    CaseTest("Foo", "Foo", "foo", "foo", "foo"),
    CaseTest("FOO", "Foo", "foo", "foo", "foo"),
    CaseTest("fooBar", "FooBar", "fooBar", "foo_bar", "foo-bar"),
    CaseTest("fooBarBaz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("foo-bar-baz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("foo.bar.baz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("FooBarBaz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("Foo-Bar-Baz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("Foo.Bar-Baz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("foo-Bar-Baz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("foo.Bar-Baz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("Foo-Bar-BazQuux", "FooBarBazQuux", "fooBarBazQuux", "foo_bar_baz_quux", "foo-bar-baz-quux"),
    CaseTest("Foo-Bar.BazQuux", "FooBarBazQuux", "fooBarBazQuux", "foo_bar_baz_quux", "foo-bar-baz-quux"),
    CaseTest("foo9bar", "Foo9bar", "foo9bar", "foo9bar", "foo9bar"),
    CaseTest("foo9Bar", "Foo9Bar", "foo9Bar", "foo9_bar", "foo9-bar"),
    CaseTest("9fooBar", "9fooBar", "9fooBar", "9foo_bar", "9foo-bar"),
    CaseTest("Foo-_Bar__ baz.", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("FOO BAR BAZ", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("FOO BAR bazQuux", "FooBarBazQuux", "fooBarBazQuux", "foo_bar_baz_quux", "foo-bar-baz-quux"),
    CaseTest("FOOBarBaz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("FooBARBaz", "FooBarBaz", "fooBarBaz", "foo_bar_baz", "foo-bar-baz"),
    CaseTest("UNITS_USD$3", "UnitsUsd$3", "unitsUsd$3", "units_usd$3", "units-usd$3")
  )
}

class CaseConvertersTest extends AnyFreeSpec with Matchers {
  import CaseConvertersTest._

  "Pascal case converter should work" in {
    TEST_CASES.foreach({ testCase =>
      withClue(testCase)(testCase.raw.toPascalCase shouldBe testCase.expectedPascal)
    })
  }

  "Camel case converter should work" in {
    TEST_CASES.foreach({ testCase =>
      withClue(testCase)(testCase.raw.toCamelCase shouldBe testCase.expectedCamel)
    })
  }

  "Snake case converter should work" in {
    TEST_CASES.foreach({ testCase =>
      withClue(testCase)(testCase.raw.toSnakeCase shouldBe testCase.expectedSnake)
    })
  }

  "Dashed case converter should work" in {
    TEST_CASES.foreach({ testCase =>
      withClue(testCase)(testCase.raw.toDashedCase shouldBe testCase.expectedDashed)
    })
  }
} 
Example 25
Source File: JobTests.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import org.scalacheck.Arbitrary
import org.scalatest.BeforeAndAfterAll
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


class JobTests extends AnyFreeSpec with BeforeAndAfterAll with SparkTesting with ScalaCheckDrivenPropertyChecks with Matchers {

  "map" - {
    "identity" in {
      def check[T](implicit arb: Arbitrary[T]) = forAll {
        t: T => Job(t).map(identity).run() shouldEqual Job(t).run()
      }

      check[Int]
    }

    val f1: Int => Int = _ + 1
    val f2: Int => Int = (i: Int) => i * i

    "composition" in forAll {
      i: Int => Job(i).map(f1).map(f2).run() shouldEqual Job(i).map(f1 andThen f2).run()
    }
  }

  "flatMap" - {
    val f1: Int => Job[Int] = (i: Int) => Job(i + 1)
    val f2: Int => Job[Int] = (i: Int) => Job(i * i)

    "left identity" in forAll {
      i: Int => Job(i).flatMap(f1).run() shouldEqual f1(i).run()
    }

    "right identity" in forAll {
      i: Int => Job(i).flatMap(i => Job.apply(i)).run() shouldEqual Job(i).run()
    }

    "associativity" in forAll {
      i: Int => Job(i).flatMap(f1).flatMap(f2).run() shouldEqual Job(i).flatMap(ii => f1(ii).flatMap(f2)).run()
    }
  }

  "properties" - {
    "read back" in forAll {
      (k:String, v: String) =>
        val scopedKey = "frameless.tests." + k
        Job(1).withLocalProperty(scopedKey,v).run()
        sc.getLocalProperty(scopedKey) shouldBe v
    }
  }
} 
Example 26
Source File: SParallelFluxTest.scala    From reactor-scala-extensions   with Apache License 2.0 5 votes vote down vote up
package reactor.core.scala.publisher

import org.mockito.IdiomaticMockito
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import reactor.core.publisher.{Flux => JFlux, ParallelFlux => JParallelFlux}
import reactor.core.scheduler.Schedulers
import reactor.test.StepVerifier

class SParallelFluxTest extends AnyFreeSpec with Matchers with IdiomaticMockito {
  "SParallelFlux" - {
    val data = Seq(1, 2, 3)
    val flux = SFlux.just[Int](data: _*)
    val fluxParallel: SParallelFlux[Int] = flux.parallel()
    ".asJava should convert as Java ParallelFlux" in {
      fluxParallel.asJava shouldBe a[JParallelFlux[_]]
    }

    ".apply should convert Java ParallelFlux into SParallelFlux" in {
      SParallelFlux(JFlux.just(1, 2, 3).parallel()).asJava shouldBe a[JParallelFlux[_]]
    }

    ".filter should filter elements" in {
      StepVerifier.create(fluxParallel.filter((i: Int) => i % 2 == 0))
        .expectNext(2)
        .verifyComplete()
    }

    ".map should map from T to U" in {
      val expected = data.map(_.toString)
      StepVerifier.create(fluxParallel.map(i => i.toString))
        .expectNextMatches((i: String) => expected.contains(i))
        .expectNextMatches((i: String) => expected.contains(i))
        .expectNextMatches((i: String) => expected.contains(i))
        .verifyComplete()
    }

    ".reduce should aggregate the values" - {
      "without initial supplier" in {
        val mono = fluxParallel.reduce(_ + _)
        StepVerifier.create(mono)
          .expectNext(6)
          .verifyComplete()
      }
      "with initial value should aggregate the values with initial one" ignore {
        val parallelFlux = fluxParallel.reduce[String](() => "0", (agg, v) => s"$agg-${v.toString}")
        StepVerifier.create(parallelFlux)
          .expectNext("0-1")
          .expectNext("0-2")
          .expectNext("0-3")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .expectNext("0")
          .verifyComplete()
      }
    }

    ".sequential should merge the rails" in {
      val expected = data.map(_.toString)
      StepVerifier.create(fluxParallel.map(i => i.toString).sequential())
        .expectNextMatches((i: String) => expected.contains(i))
        .expectNextMatches((i: String) => expected.contains(i))
        .expectNextMatches((i: String) => expected.contains(i))
        .verifyComplete()
    }

    ".runOn should run on different thread" in {
      val scheduler = spy(Schedulers.parallel())
      StepVerifier.create(flux.parallel(2).runOn(scheduler))
        .expectNextMatches((i: Int) => data.contains(i))
        .expectNextMatches((i: Int) => data.contains(i))
        .expectNextMatches((i: Int) => data.contains(i))
        .verifyComplete()

      scheduler.createWorker() wasCalled twice
    }
  }
} 
Example 27
Source File: CovariantTest.scala    From reactor-scala-extensions   with Apache License 2.0 5 votes vote down vote up
package reactor.core.scala.publisher

import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import reactor.core.scala.publisher.model.{ComponentExt, ContainerExt}

class CovariantTest extends AnyFreeSpec with Matchers {
  "SFlux and SMono" - {
    "covariance should be proven with the following compiled" in {
      new ContainerExt {
        override def component: ComponentExt = ???

        override def components: List[ComponentExt] = ???

        override def componentsFlux: SFlux[ComponentExt] = ???

        override def componentMono: SMono[ComponentExt] = ???
      } shouldBe a[ContainerExt]
    }
  }
} 
Example 28
Source File: ExecutionContextSchedulerTest.scala    From reactor-scala-extensions   with Apache License 2.0 5 votes vote down vote up
package reactor.core.scala.scheduler

import java.util.concurrent.{Executors, ThreadFactory}

import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import reactor.core.scala.publisher.SMono
import reactor.test.StepVerifier

import scala.concurrent.ExecutionContext


class ExecutionContextSchedulerTest extends AnyFreeSpec with Matchers {
  "ExecutionContextScheduler" - {
    "should create a Scheduler using provided ExecutionContext" - {
      "on SMono" in {
        val executionContext = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(1, new ThreadFactory {
          override def newThread(r: Runnable): Thread = new Thread(r, "THREAD-NAME-SMONO")
        }))
        val mono = SMono.just(1)
          .subscribeOn(ExecutionContextScheduler(executionContext))
          .doOnNext(i => Thread.currentThread().getName shouldBe "THREAD-NAME-SMONO")
        StepVerifier.create(mono)
          .expectNext(1)
          .verifyComplete()
      }
    }
  }
} 
Example 29
Source File: UsingSpec.scala    From Dsl.scala   with Apache License 2.0 5 votes vote down vote up
package com.thoughtworks.dsl
package domains

import com.thoughtworks.dsl.Dsl.{!!, Continuation, reset}
import com.thoughtworks.dsl.keywords.{Using, Yield}
import org.scalatest.Assertion
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


class UsingSpec extends AnyFreeSpec with Matchers {

  def successContinuation[Domain](domain: Domain): (Domain !! Throwable) @reset = Continuation.empty(domain)

  "AutoCloseable" - {

    "scope" - {

      "arm" in {
        var isOpen = false

        def raii: Stream[Int] !! Throwable !! Assertion = Continuation.apply {
          !Yield(1)
          isOpen should be(false)
          val a = !Using {
            !Yield(2)
            new AutoCloseable {
              isOpen should be(false)
              isOpen = true

              def close(): Unit = {
                isOpen should be(true)
                isOpen = false
              }
            }
          }
          !Yield(3)
          isOpen should be(true)
        }

        isOpen should be(false)

        val myException = new Exception

        val stream = raii(_ => _ => Stream.empty)(throw _)

        stream should be(Stream(1, 2, 3))
        isOpen should be(false)
      }
    }

  }
} 
Example 30
Source File: ReturnSpec.scala    From Dsl.scala   with Apache License 2.0 5 votes vote down vote up
package com.thoughtworks.dsl.keywords
import com.thoughtworks.dsl.Dsl.!!
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


final class ReturnSpec extends AnyFreeSpec with Matchers {

  "return a Stream" in {
    def stream: Stream[Int] = !Return[Int](1)
    stream should be(Stream(1))
  }

  "return the left domain" in {
    def continuation: Int !! String = !Return(42)

    continuation { s =>
      throw new AssertionError(s)
    } should be(42)
  }

  "return the right domain" in {
    def continuation: Int !! String = !Return("right value")

    continuation { s =>
      s should be("right value")
      43
    } should be(43)
  }

  "return the middle domain" - {

    "as the return value" in {
      def continuation: Int !! Double !! String = !Return(1.23)

      continuation { s =>
        throw new AssertionError(s)
      } { d =>
        d should be(1.23)
        43
      } should be(43)
    }

    "then the throw expression will not be executed" in {
      def continuation: Int !! Double !! String = {
        throw !Return(1.23)
      }

      continuation { s =>
        throw new AssertionError(s)
      } { d =>
        d should be(1.23)
        43
      } should be(43)
    }
  }

} 
Example 31
Source File: ForEachSpec.scala    From Dsl.scala   with Apache License 2.0 5 votes vote down vote up
package com.thoughtworks.dsl.keywords

import com.thoughtworks.dsl.Dsl.{!!, reset}
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


class ForEachSpec extends AnyFreeSpec with Matchers {

  "foreach" - {

    "val" in {
      val seq = 1 to 10

      def run(): Unit = {
        val plus100 = Seq {
          !ForEach(seq) + 100
        }
        plus100.length should be(1)
        !ForEach(plus100)
      }

      run()
    }
    "def" in {
      val seq = 1 to 10

      def run(): Unit = {
        def plus100 = Seq {
          !Each(seq) + 100
        }
        plus100.length should be(10)
        !ForEach(plus100)
      }

      run()
    }
  }
} 
Example 32
Source File: scalazSpec.scala    From Dsl.scala   with Apache License 2.0 5 votes vote down vote up
package com.thoughtworks.dsl.domains

import com.thoughtworks.dsl.Dsl.!!
import _root_.scalaz.OptionT
import _root_.scalaz.concurrent.Task
import _root_.scalaz.std.stream._
import com.thoughtworks.dsl.domains.scalaz._
import com.thoughtworks.dsl.keywords.{Monadic, Shift, Yield}
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

 "Leaving generator"
          ))
      }

    }

  }

  "Given a monadic expression that contains a Scalaz OptionT" - {
    def myOptionalList: OptionT[Stream, String] = {
      // TODO: Is it possible to have `Yield` expressions here?
      val threadId = !Monadic(Stream(0, 1, 2))
      val subThreadId = !Monadic(OptionT(Stream(Some(10), None, Some(30))))
      val subSubThreadId = !Monadic(OptionT(Stream(Some(100), Some(200), None)))
      OptionT[Stream, String](Stream(Some(s"Fork thread $threadId-$subThreadId-$subSubThreadId")))
    }

    "Then it should skips those elements that contains a None" in {
      myOptionalList.run should be(
        Seq(
          Some("Fork thread 0-10-100"),
          Some("Fork thread 0-10-200"),
          None,
          None,
          Some("Fork thread 0-30-100"),
          Some("Fork thread 0-30-200"),
          None,
          Some("Fork thread 1-10-100"),
          Some("Fork thread 1-10-200"),
          None,
          None,
          Some("Fork thread 1-30-100"),
          Some("Fork thread 1-30-200"),
          None,
          Some("Fork thread 2-10-100"),
          Some("Fork thread 2-10-200"),
          None,
          None,
          Some("Fork thread 2-30-100"),
          Some("Fork thread 2-30-200"),
          None
        ))
    }

  }
} 
Example 33
Source File: BangNotationSpec.scala    From Dsl.scala   with Apache License 2.0 5 votes vote down vote up
package com.thoughtworks.dsl.compilerplugin

import com.thoughtworks.dsl.Dsl.shift
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


class BangNotationSpec extends AnyFreeSpec with Matchers {

  "printf problem" in {

    object IntPlaceholder {
      @shift def unary_! : String = ???
      def cpsApply[Domain](f: String => Domain): Int => Domain = { i: Int =>
        f(i.toString)
      }
    }

    object StringPlaceholder {
      @shift def unary_! : String = ???
      def cpsApply[Domain](f: String => Domain): String => Domain = f
    }

    def f1 = "Hello World!"
    def f2 = "Hello " + !StringPlaceholder + "!"
    def f3 = "The value of " + !StringPlaceholder + " is " + !IntPlaceholder + "."

    f1 should be("Hello World!")
    f2.asInstanceOf[String => String]("World") should be("Hello World!")
    f3.asInstanceOf[String => Int => String]("x")(3) should be("The value of x is 3.")
  }

} 
Example 34
Source File: HttpMessageSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpMessageSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json    = """{"message":"test text"}"""
  private val message = HttpMessage("test text")

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpMessage] should matchTo(message)
    }

    "serialization" in {
      Json.stringify(Json.toJson(message)) should matchTo(json)
    }
  }
} 
Example 35
Source File: HttpV1OrderBookSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.asset.{Asset, AssetPair}
import com.wavesplatform.dex.error.ErrorFormatterContext
import com.wavesplatform.dex.model.LevelAgg
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpV1OrderBookSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json = """{
                       |  "timestamp" : 0,
                       |  "bids" : [ [ "1.18", "43800.00000000" ], [ "1.17", "52187.00000000" ], [ "1.16", "809.00000000" ] ],
                       |  "asks" : [ [ "1.19", "2134.00000000" ], [ "1.20", "747.00000000" ] ]
                       |}""".stripMargin

  private val usd: Asset   = IssuedAsset("USDN".getBytes)
  private val wavesUsdPair = AssetPair(Waves, usd)

  private implicit val efc: ErrorFormatterContext = {
    case `usd` => 2
    case _     => 8
  }

  private val bids = List(LevelAgg(4380000000000L, 118), LevelAgg(5218700000000L, 117), LevelAgg(80900000000L, 116))
  private val asks = List(LevelAgg(213400000000L, 119), LevelAgg(74700000000L, 120))

  private val orderBookV1 =
    HttpV1OrderBook(
      timestamp = 0,
      bids = bids.map(la => HttpV1LevelAgg.fromLevelAgg(la, wavesUsdPair)),
      asks = asks.map(la => HttpV1LevelAgg.fromLevelAgg(la, wavesUsdPair))
    )

  private val orderBookResult = HttpOrderBook(0, wavesUsdPair, bids, asks, Some(8 -> 2))

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpV1OrderBook] should matchTo(orderBookV1)
    }

    "serialization" in {
      Json.prettyPrint(Json.parse(HttpOrderBook toJson orderBookResult)) should matchTo(json)
    }
  }
} 
Example 36
Source File: HttpMarketStatusSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import cats.syntax.option._
import com.wavesplatform.dex.domain.order.OrderType
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.{JsBoolean, JsString, Json}

class HttpMarketStatusSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "lastPrice" : 1000,
      |  "lastAmount" : 2000,
      |  "lastSide" : "sell",
      |  "bid" : 2222,
      |  "bidAmount" : 1111,
      |  "ask" : 4444,
      |  "askAmount" : 3333,
      |  "success" : true,
      |  "status" : "SimpleResponse"
      |}""".stripMargin

  private val marketStatus =
    HttpMarketStatus(
      lastPrice = 1000L.some,
      lastAmount = 2000L.some,
      lastSide = OrderType.SELL.some,
      bid = 2222L.some,
      bidAmount = 1111L.some,
      ask = 4444L.some,
      askAmount = 3333L.some
    )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpMarketStatus] should matchTo(marketStatus)
    }

    "serialization" in {
      val marketStatusJson = Json.toJsObject(marketStatus) + ("success" -> JsBoolean(true)) + ("status" -> JsString("SimpleResponse"))
      Json.prettyPrint(marketStatusJson) should matchTo(json)
    }
  }
} 
Example 37
Source File: HttpSuccessfulBatchCancelSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpSuccessfulBatchCancelSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  // Note, we removed "result" : null , because it effectively equal to a missing field
  private val json =
    """{
      |  "message" : [ [ {
      |    "orderId" : "8D36dK4snBwJHH9qfDyGo6xP5C4rCH2JPhPbbaJn5mLK",
      |    "success" : true,
      |    "status" : "OrderCanceled"
      |  }, {
      |    "error" : 25601,
      |    "message" : "Can not persist event, please retry later or contact with the administrator",
      |    "template" : "Can not persist event, please retry later or contact with the administrator",
      |    "status" : "OrderCancelRejected",
      |    "success" : false
      |  } ] ],
      |  "success" : true,
      |  "status" : "BatchCancelCompleted"
      |}""".stripMargin

  private val message = HttpSuccessfulBatchCancel(
    List(
      Right(HttpSuccessfulSingleCancel(orderId = ByteStr.decodeBase58("8D36dK4snBwJHH9qfDyGo6xP5C4rCH2JPhPbbaJn5mLK").get)),
      Left(
        HttpError(
          error = 25601,
          message = "Can not persist event, please retry later or contact with the administrator",
          template = "Can not persist event, please retry later or contact with the administrator",
          status = "OrderCancelRejected"
        )
      )
    )
  )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpSuccessfulBatchCancel] should matchTo(message)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(message)) should matchTo(json)
    }
  }
} 
Example 38
Source File: HttpOrderBookHistoryItemSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.order.OrderType
import com.wavesplatform.dex.model.{AcceptedOrderType, OrderStatus}
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpOrderBookHistoryItemSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "id" : "7VEr4T9icqopHWLawGAZ7AQiJbjAcnzXn65ekYvbpwnN",
      |  "type" : "buy",
      |  "orderType" : "limit",
      |  "amount" : 7757865201004347,
      |  "filled" : 0,
      |  "price" : 489,
      |  "fee" : 6345852410462127,
      |  "filledFee" : 0,
      |  "feeAsset" : "WAVES",
      |  "timestamp" : 1578074613225,
      |  "status" : "Accepted",
      |  "assetPair" : {
      |    "amountAsset" : "6rRegyHpdvZBENW4mowKYtKMDs2xpxmMbyNMRMZaZQ7",
      |    "priceAsset" : "8pFqaP5CtPB4kP87gpu2T7vB4LxdfoH9e5mSPQduhCc"
      |  },
      |  "avgWeighedPrice" : 0,
      |  "version" : 3
      |}""".stripMargin

  private val historyItem =
    HttpOrderBookHistoryItem(
      id = ByteStr.decodeBase58("7VEr4T9icqopHWLawGAZ7AQiJbjAcnzXn65ekYvbpwnN").get,
      `type` = OrderType.BUY,
      orderType = AcceptedOrderType.Limit,
      amount = 7757865201004347L,
      filled = 0L,
      price = 489L,
      fee = 6345852410462127L,
      filledFee = 0L,
      feeAsset = Waves,
      timestamp = 1578074613225L,
      status = OrderStatus.Accepted.name,
      assetPair = AssetPair(
        IssuedAsset(ByteStr.decodeBase58("6rRegyHpdvZBENW4mowKYtKMDs2xpxmMbyNMRMZaZQ7").get),
        IssuedAsset(ByteStr.decodeBase58("8pFqaP5CtPB4kP87gpu2T7vB4LxdfoH9e5mSPQduhCc").get)
      ),
      avgWeighedPrice = 0L,
      version = 3
    )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpOrderBookHistoryItem] should matchTo(historyItem)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(historyItem)) should matchTo(json)
    }
  }
} 
Example 39
Source File: HttpOrderFeeModeSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.api.http.entities.HttpOrderFeeMode.{FeeModeDynamic, FeeModeFixed, FeeModePercent}
import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.settings.AssetType
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpOrderFeeModeSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val fixedModeJson: String = """{
                                          |  "fixed" : {
                                          |    "assetId" : "6suw3ZHbyk6jrM19n7Pvaih3zSPsAt3gKcY8AZPxQYQf",
                                          |    "minFee" : 1
                                          |  }
                                          |}""".stripMargin

  private val fixedMode: HttpOrderFeeMode = FeeModeFixed(IssuedAsset(Base58.decode("6suw3ZHbyk6jrM19n7Pvaih3zSPsAt3gKcY8AZPxQYQf")), 1)

  private val dynamicModeJson: String = """{
                                          |  "dynamic" : {
                                          |    "baseFee" : 600000,
                                          |    "rates" : {
                                          |      "WAVES" : 1
                                          |    }
                                          |  }
                                          |}""".stripMargin

  private val percentModeJson: String = """{
                                          |  "percent" : {
                                          |    "type" : "price",
                                          |    "minFee" : 0.14
                                          |  }
                                          |}""".stripMargin

  private val percentMode: HttpOrderFeeMode = FeeModePercent(AssetType.PRICE, 0.14)

  private val dynamicMode: HttpOrderFeeMode = FeeModeDynamic(600000, Map(Waves -> 1))

  "ApiOrderFeeMode" - {
    "Dynamic" - {
      "backward JSON compatibility" - {
        "deserialization" in {
          Json.parse(dynamicModeJson).as[HttpOrderFeeMode] should matchTo(dynamicMode)
        }
        "serialization" in {
          Json.prettyPrint(Json.toJson(dynamicMode)) should matchTo(dynamicModeJson)
        }
      }
    }

    "Fixed" - {
      "backward JSON compatibility" - {
        "deserialization" in {
          Json.parse(fixedModeJson).as[HttpOrderFeeMode] should matchTo(fixedMode)
        }
        "serialization" in {
          Json.prettyPrint(Json.toJson(fixedMode)) should matchTo(fixedModeJson)
        }
      }
    }

    "Percent" - {
      "backward JSON compatibility" - {
        "deserialization" in {
          Json.parse(percentModeJson).as[HttpOrderFeeMode] should matchTo(percentMode)
        }
        "serialization" in {
          Json.prettyPrint(Json.toJson(percentMode)) should matchTo(percentModeJson)
        }
      }
    }
  }
} 
Example 40
Source File: HttpSnapshotOffsetsSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpSnapshotOffsetsSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "2gCPcEnoZa9LtZzZPFK9fJf7aWzvdBJUABayd1Zj5qFh-WAVES" : 1
      |}""".stripMargin

  private val issuedAsset = IssuedAsset(Base58.decode("2gCPcEnoZa9LtZzZPFK9fJf7aWzvdBJUABayd1Zj5qFh"))

  private val snapshotOffsets = Map(
    AssetPair(issuedAsset, Waves) -> 1L
  )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpSnapshotOffsets] should matchTo(snapshotOffsets)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(snapshotOffsets)) should matchTo(json)
    }
  }
} 
Example 41
Source File: HttpMatcherPublicSettingsSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.account.PublicKey
import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpMatcherPublicSettingsSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "matcherPublicKey" : "2eEUvypDSivnzPiLrbYEW39SM8yMZ1aq4eJuiKfs4sEY",
      |  "matcherVersion" : "2.1.3.3",
      |  "priceAssets" : [ "WAVES", "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8" ],
      |  "orderFee" : {
      |    "fixed" : {
      |      "assetId" : "4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8",
      |      "minFee" : 300000
      |    }
      |  },
      |  "orderVersions" : [ 1, 2, 3 ],
      |  "networkByte" : 83
      |}""".stripMargin

  private val issuedAsset = IssuedAsset(Base58.decode("4LHHvYGNKJUg5hj65aGD5vgScvCBmLpdRFtjokvCjSL8"))

  private val matcherPublicSettings =
    HttpMatcherPublicSettings(
      matcherPublicKey = PublicKey.fromBase58String("2eEUvypDSivnzPiLrbYEW39SM8yMZ1aq4eJuiKfs4sEY").right.get,
      matcherVersion = "2.1.3.3",
      priceAssets = Seq(Waves, issuedAsset),
      orderFee = HttpOrderFeeMode.FeeModeFixed(
        assetId = issuedAsset,
        minFee = 300000
      ),
      orderVersions = Seq(1, 2, 3),
      networkByte = 83
    )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpMatcherPublicSettings] should matchTo(matcherPublicSettings)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(matcherPublicSettings)) should matchTo(json)
    }
  }
} 
Example 42
Source File: HttpOrderBookInfoSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpOrderBookInfoSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "restrictions" : {
      |    "stepAmount" : "0.00000001",
      |    "minAmount" : "0.0000002",
      |    "maxAmount" : "3000",
      |    "stepPrice" : "0.000004",
      |    "minPrice" : "0.00005",
      |    "maxPrice" : "6000"
      |  },
      |  "matchingRules" : {
      |    "tickSize" : "0.7"
      |  }
      |}""".stripMargin

  private val orderBookInfo = HttpOrderBookInfo(
    restrictions = Some(
      HttpOrderRestrictions(
        stepAmount = 0.00000001,
        minAmount = 0.0000002,
        maxAmount = 3000,
        stepPrice = 0.000004,
        minPrice = 0.00005,
        maxPrice = 6000
      )
    ),
    matchingRules = HttpMatchingRules(
      tickSize = 0.7
    )
  )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpOrderBookInfo] should matchTo(orderBookInfo)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(orderBookInfo)) should matchTo(json)
    }
  }
} 
Example 43
Source File: HttpV0OrderBookSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset.Waves
import com.wavesplatform.dex.domain.asset.{Asset, AssetPair}
import com.wavesplatform.dex.model.LevelAgg
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpV0OrderBookSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json = """{
                       |  "timestamp" : 0,
                       |  "pair" : {
                       |    "amountAsset" : "LWbazpyvj625QB6EMC1vQoMkrvn2DdKjYbuuEw2T2UF",
                       |    "priceAsset" : "WAVES"
                       |  },
                       |  "bids" : [ {
                       |    "amount" : 10000000000000,
                       |    "price" : 41
                       |  }, {
                       |    "amount" : 2500000000000,
                       |    "price" : 40
                       |  }, {
                       |    "amount" : 300000000000000,
                       |    "price" : 1
                       |  } ],
                       |  "asks" : [ {
                       |    "amount" : 50000000000,
                       |    "price" : 50
                       |  }, {
                       |    "amount" : 2500000000000,
                       |    "price" : 51
                       |  } ]
                       |}""".stripMargin

  private val assetPair = AssetPair(Asset.fromString("LWbazpyvj625QB6EMC1vQoMkrvn2DdKjYbuuEw2T2UF").get, Waves)
  private val bids      = List(LevelAgg(10000000000000L, 41), LevelAgg(2500000000000L, 40), LevelAgg(300000000000000L, 1))
  private val asks      = List(LevelAgg(50000000000L, 50), LevelAgg(2500000000000L, 51))

  private val orderBookV0     = HttpV0OrderBook(0, assetPair, bids.map(HttpV0LevelAgg.fromLevelAgg), asks.map(HttpV0LevelAgg.fromLevelAgg))
  private val orderBookResult = HttpOrderBook(0, assetPair, bids, asks)

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpV0OrderBook] should matchTo(orderBookV0)
    }

    "serialization" in {
      Json.prettyPrint(Json.parse(HttpOrderBook toJson orderBookResult)) should matchTo(json)
    }
  }
} 
Example 44
Source File: HttpErrorSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpErrorSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  // Note, we removed "result" : null , because it effectively equal to a missing field
  private val json =
    """{
      |  "error" : 3148040,
      |  "message" : "The order 979P14dmPrcmcYhLeMpJFMuDDchdBeL9ouMPUvvYu1YU has already been placed",
      |  "template" : "The order {{id}} has already been placed",
      |  "params" : {
      |    "id" : "979P14dmPrcmcYhLeMpJFMuDDchdBeL9ouMPUvvYu1YU"
      |  },
      |  "status" : "OrderRejected",
      |  "success" : false
      |}""".stripMargin

  private val message: HttpError = HttpError(
    error = 3148040,
    message = "The order 979P14dmPrcmcYhLeMpJFMuDDchdBeL9ouMPUvvYu1YU has already been placed",
    template = "The order {{id}} has already been placed",
    params = Json.obj("id" -> "979P14dmPrcmcYhLeMpJFMuDDchdBeL9ouMPUvvYu1YU"),
    status = "OrderRejected"
  )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpError] should matchTo(message)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(message)) should matchTo(json)
    }
  }
} 
Example 45
Source File: HttpBalanceSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpBalanceSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "WAVES" : 100,
      |  "2gCPcEnoZa9LtZzZPFK9fJf7aWzvdBJUABayd1Zj5qFh" : 300
      |}""".stripMargin

  private val issuedAsset = IssuedAsset(Base58.decode("2gCPcEnoZa9LtZzZPFK9fJf7aWzvdBJUABayd1Zj5qFh"))

  private val balance =
    Map(
      Waves       -> 100L,
      issuedAsset -> 300L
    )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpBalance] should matchTo(balance)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(balance)) should matchTo(json)
    }
  }
} 
Example 46
Source File: HttpTradingMarketsSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import cats.syntax.option._
import com.wavesplatform.dex.domain.account.PublicKey
import com.wavesplatform.dex.domain.asset.Asset
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpTradingMarketsSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val marketDataWithMetaJson = """{
                                         |  "amountAsset" : "89M5b2chgRya9A5WnJx4irNuKzXExdEko2m8jmzdFMX",
                                         |  "amountAssetName" : "AmountAsset",
                                         |  "amountAssetInfo" : {
                                         |    "decimals" : 8
                                         |  },
                                         |  "priceAsset" : "Chn6MVRNBk7mHNBQg67Zhc81aigaoZsLwwNo9QiJ5bd",
                                         |  "priceAssetName" : "PriceAsset",
                                         |  "priceAssetInfo" : {
                                         |    "decimals" : 8
                                         |  },
                                         |  "created" : 1591105681300,
                                         |  "matchingRules" : {
                                         |    "tickSize" : "0.1"
                                         |  }
                                         |}""".stripMargin

  private val tradingMarketsJson = """{
                                     |  "matcherPublicKey" : "J6ghck2hA2GNJTHGSLSeuCjKuLDGz8i83NfCMFVoWhvf",
                                     |  "markets" : [ {
                                     |    "amountAsset" : "89M5b2chgRya9A5WnJx4irNuKzXExdEko2m8jmzdFMX",
                                     |    "amountAssetName" : "AmountAsset",
                                     |    "amountAssetInfo" : {
                                     |      "decimals" : 8
                                     |    },
                                     |    "priceAsset" : "Chn6MVRNBk7mHNBQg67Zhc81aigaoZsLwwNo9QiJ5bd",
                                     |    "priceAssetName" : "PriceAsset",
                                     |    "priceAssetInfo" : {
                                     |      "decimals" : 8
                                     |    },
                                     |    "created" : 1591105681300,
                                     |    "matchingRules" : {
                                     |      "tickSize" : "0.1"
                                     |    }
                                     |  } ]
                                     |}""".stripMargin

  private val marketData =
    HttpMarketDataWithMeta(
      amountAsset = Asset.fromString("89M5b2chgRya9A5WnJx4irNuKzXExdEko2m8jmzdFMX").get,
      amountAssetName = "AmountAsset",
      amountAssetInfo = HttpAssetInfo(8).some,
      priceAsset = Asset.fromString("Chn6MVRNBk7mHNBQg67Zhc81aigaoZsLwwNo9QiJ5bd").get,
      priceAssetName = "PriceAsset",
      priceAssetInfo = HttpAssetInfo(8).some,
      created = 1591105681300L,
      restrictions = None,
      matchingRules = HttpMatchingRules(0.1)
    )

  private val tradingMarkets =
    HttpTradingMarkets(
      PublicKey.fromBase58String("J6ghck2hA2GNJTHGSLSeuCjKuLDGz8i83NfCMFVoWhvf").right.get,
      Seq(marketData)
    )

  "backward JSON compatibility" - {

    "Market data with meta" - {
      "deserialization" in {
        Json.parse(marketDataWithMetaJson).as[HttpMarketDataWithMeta] should matchTo(marketData)
      }

      "serialization" in {
        Json.prettyPrint(Json.toJson(marketData)) should matchTo(marketDataWithMetaJson)
      }
    }

    "Trading markets" - {
      "deserialization" in {
        Json.parse(tradingMarketsJson).as[HttpTradingMarkets] should matchTo(tradingMarkets)
      }

      "serialization" in {
        Json.prettyPrint(Json.toJson(tradingMarkets)) should matchTo(tradingMarketsJson)
      }
    }
  }
} 
Example 47
Source File: HttpSuccessfulSingleCancelSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpSuccessfulSingleCancelSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "orderId" : "CijYneWqeJwtYLQvP3T6nRNueTFSmB977ULUDBxPZJNH",
      |  "success" : true,
      |  "status" : "OrderCanceled"
      |}""".stripMargin

  private val message = HttpSuccessfulSingleCancel(orderId = ByteStr.decodeBase58("CijYneWqeJwtYLQvP3T6nRNueTFSmB977ULUDBxPZJNH").get)

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpSuccessfulSingleCancel] should matchTo(message)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(message)) should matchTo(json)
    }
  }
} 
Example 48
Source File: HttpOrderStatusSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.model.OrderStatus
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpOrderStatusSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  "backward JSON compatibility and converting from OrderStatus" - {
    Map[OrderStatus, String](
      OrderStatus.Accepted                 -> """{"status":"Accepted"}""",
      OrderStatus.NotFound                 -> """{"status":"NotFound","message":"The limit order is not found"}""",
      OrderStatus.PartiallyFilled(200, 10) -> """{"status":"PartiallyFilled","filledAmount":200,"filledFee":10}""",
      OrderStatus.Filled(201, 11)          -> """{"status":"Filled","filledAmount":201,"filledFee":11}""",
      OrderStatus.Cancelled(202, 12)       -> """{"status":"Cancelled","filledAmount":202,"filledFee":12}"""
    ).foreach {
      case (status, json) =>
        val apiStatus = HttpOrderStatus.from(status)

        status.name - {
          "deserialization" in {
            Json.parse(json).as[HttpOrderStatus] should matchTo(apiStatus)
          }

          "serialization" in {
            Json.stringify(Json.toJson(apiStatus)) should matchTo(json)
          }
        }
    }
  }
} 
Example 49
Source File: HttpSuccessfulPlaceSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.account.PublicKey
import com.wavesplatform.dex.domain.asset.Asset.IssuedAsset
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.domain.order.{OrderType, OrderV1}
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpSuccessfulPlaceSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json = """{
                       |  "message" : {
                       |    "version" : 1,
                       |    "id" : "6KUFD9a6acDVM2Y8wqiFrdt35FPE1WF5QgjpPJqtKrP9",
                       |    "sender" : "3MyE3MtSi6MkXLCu1m7fCsUoJYRt4iibUGS",
                       |    "senderPublicKey" : "CsoEGd7UrxjBWEdoXbwh1x5fT64NNP8nBJ65xuJRx851",
                       |    "matcherPublicKey" : "G67KDhqHdjNNb2tnHRgNbDppQEM9ySXdiBip577n2Xoj",
                       |    "assetPair" : {
                       |      "amountAsset" : "6RQYnag6kTXaoGi3yPmX9JMpPya8WQntSohisKKCMGr",
                       |      "priceAsset" : "8pBLJDEwWgrxxHHnVLYbjhUySKy1qteiZGqK8dJeHUA"
                       |    },
                       |    "orderType" : "buy",
                       |    "amount" : 7235959396154477,
                       |    "price" : 399,
                       |    "timestamp" : 1580225937287,
                       |    "expiration" : 1582677054923,
                       |    "matcherFee" : 5273291907571414,
                       |    "signature" : "5GHs8aQQ3pMEipyotwz6NyzzAQfxizRpzFg7vBsptkQDhxR58cuzkwL2P7XtkTB7KQU7vq6GyZnJTWab2bK3Nixj",
                       |    "proofs" : [ "5GHs8aQQ3pMEipyotwz6NyzzAQfxizRpzFg7vBsptkQDhxR58cuzkwL2P7XtkTB7KQU7vq6GyZnJTWab2bK3Nixj" ]
                       |  },
                       |  "success" : true,
                       |  "status" : "OrderAccepted"
                       |}""".stripMargin

  private val order = OrderV1(
    senderPublicKey = PublicKey(Base58.decode("CsoEGd7UrxjBWEdoXbwh1x5fT64NNP8nBJ65xuJRx851")),
    matcherPublicKey = PublicKey(Base58.decode("G67KDhqHdjNNb2tnHRgNbDppQEM9ySXdiBip577n2Xoj")),
    assetPair = AssetPair(
      amountAsset = IssuedAsset(ByteStr.decodeBase58("6RQYnag6kTXaoGi3yPmX9JMpPya8WQntSohisKKCMGr").get),
      priceAsset = IssuedAsset(ByteStr.decodeBase58("8pBLJDEwWgrxxHHnVLYbjhUySKy1qteiZGqK8dJeHUA").get),
    ),
    orderType = OrderType.BUY,
    amount = 7235959396154477L,
    price = 399L,
    timestamp = 1580225937287L,
    expiration = 1582677054923L,
    matcherFee = 5273291907571414L,
    signature = Base58.decode("5GHs8aQQ3pMEipyotwz6NyzzAQfxizRpzFg7vBsptkQDhxR58cuzkwL2P7XtkTB7KQU7vq6GyZnJTWab2bK3Nixj")
  )

  private val message = HttpSuccessfulPlace(order)

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpSuccessfulPlace] should matchTo(message)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(message)) should matchTo(json)
    }
  }
} 
Example 50
Source File: AskActorSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.actors

import akka.actor.ActorRef
import akka.testkit.TestProbe
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import com.wavesplatform.dex.time.SystemTime
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

import scala.concurrent.duration.DurationInt
import scala.concurrent.{Await, Future, TimeoutException}

class AskActorSpec
    extends AnyFreeSpec
    with Matchers
    with SystemTime
    with MatcherSpecLike
    with DiffMatcherWithImplicits {

  private val defaultTimeout  = 5.seconds
  private val defaultResponse = "foo"

  "AskActor" - {
    "happy path" in test { (ref, future) =>
      ref ! defaultResponse
      val actual = Await.result(future, defaultTimeout)
      actual should matchTo(defaultResponse)
    }

    "timeout" in test { (_, future) =>
      Await.result(future.failed, defaultTimeout) shouldBe a[TimeoutException]
    }

    "unexpected response type" in test { (ref, future) =>
      ref ! 100500
      Await.result(future.failed, defaultTimeout) shouldBe a[IllegalArgumentException]
    }
  }

  private def test(f: (ActorRef, Future[String]) => Unit): Unit = {
    val (ref, future) = AskActor.mk[String](100.millis)
    val p             = TestProbe()
    p.watch(ref)

    f(ref, future)

    p.expectTerminated(ref, defaultTimeout)
  }

  override protected def actorSystemName: String = "AskActorSpec"
} 
Example 51
Source File: ExampleFileTests.scala    From circe-yaml   with Apache License 2.0 5 votes vote down vote up
package io.circe.yaml

import java.io.{ File, InputStreamReader }

import org.scalatest.freespec.AnyFreeSpec
import scala.io.Source

class ExampleFileTests extends AnyFreeSpec {

  "yaml test files" - {

    val testFiles = new File(getClass.getClassLoader.getResource("test-yamls").getPath).listFiles
      .filter(_.getName.endsWith(".yml"))
      .map { file =>
        file.getName -> file.getName.replaceFirst("yml$", "json")
      }

    testFiles.foreach {
      case (yamlFile, jsonFile) =>
        yamlFile in {
          val jsonStream = getClass.getClassLoader.getResourceAsStream(s"test-yamls/$jsonFile")
          val json = Source.fromInputStream(jsonStream).mkString
          jsonStream.close()
          val parsedJson = io.circe.jawn.parse(json)
          def yamlStream = getClass.getClassLoader.getResourceAsStream(s"test-yamls/$yamlFile")
          def yamlReader = new InputStreamReader(yamlStream)
          val yaml = Source.fromInputStream(yamlStream).mkString
          val parsedYamlString = parser.parse(yaml)
          val parsedStreamString = parser.parseDocuments(yaml)
          val parsedYamlReader = parser.parse(yamlReader)
          val parsedStreamReader = parser.parseDocuments(yamlReader)
          assert(parsedJson == parsedYamlString)
          assert(parsedJson == parsedStreamString.head)
          assert(parsedJson == parsedYamlReader)
          assert(parsedJson == parsedStreamReader.head)
        }
    }
  }
} 
Example 52
Source File: HttpRatesSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset.{IssuedAsset, Waves}
import com.wavesplatform.dex.domain.bytes.codec.Base58
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import play.api.libs.json.Json

class HttpRatesSpec extends AnyFreeSpec with Matchers with DiffMatcherWithImplicits {

  private val json =
    """{
      |  "WAVES" : 1,
      |  "2gCPcEnoZa9LtZzZPFK9fJf7aWzvdBJUABayd1Zj5qFh" : 3
      |}""".stripMargin

  private val issuedAsset = IssuedAsset(Base58.decode("2gCPcEnoZa9LtZzZPFK9fJf7aWzvdBJUABayd1Zj5qFh"))

  private val rates =
    Map(
      Waves       -> 1d,
      issuedAsset -> 3d
    )

  "backward JSON compatibility" - {
    "deserialization" in {
      Json.parse(json).as[HttpRates] should matchTo(rates)
    }

    "serialization" in {
      Json.prettyPrint(Json.toJson(rates)) should matchTo(json)
    }
  }
} 
Example 53
Source File: OrderInfoSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model

import com.wavesplatform.dex.domain.order.Order
import com.wavesplatform.dex.model.OrderInfoSpec.OrderExt
import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class OrderInfoSpec extends AnyFreeSpec with Matchers with MatcherSpecBase with PropertyChecks with NoShrink {

  private def finalizedOrderInfoGen(o: Order, orderInfoVersion: Byte): Gen[OrderInfo[OrderStatus.Final]] =
    for {
      filledAmount    <- Gen.choose(0, o.amount)
      filledFee       <- if (orderInfoVersion == 1) Gen.const((BigInt(filledAmount) * 300000 / o.amount).toLong) else Gen.choose(0, o.matcherFee)
      status          <- Gen.oneOf(OrderStatus.Filled(filledAmount, filledFee), OrderStatus.Cancelled(filledAmount, filledFee))
      aoType          <- if (orderInfoVersion <= 2) Gen.const(AcceptedOrderType.Limit) else Gen.oneOf(AcceptedOrderType.Limit, AcceptedOrderType.Market)
      avgWeighedPrice <- if (orderInfoVersion <= 3) Gen.const(o.price) else Gen.choose(0, o.price)
    } yield o.toInfo(orderInfoVersion, status, aoType, avgWeighedPrice)

  private val finalizedOrderInfoGen: Gen[OrderInfo[OrderStatus.Final]] = for {
    (o, _) <- orderGenerator
    v      <- Gen.choose[Byte](1, 4)
    result <- finalizedOrderInfoGen(o, v)
  } yield result

  "OrderInfo" - {
    "x == decode(encode(x))" in forAll(finalizedOrderInfoGen) { oi =>
      OrderInfo.decode(OrderInfo encode oi) == oi
    }
  }
}

object OrderInfoSpec {

  implicit class OrderExt(val o: Order) extends AnyVal {
    def toInfo[A <: OrderStatus](version: Byte, status: A, aoType: AcceptedOrderType, avgWeighedPrice: Long): OrderInfo[A] = version match {
      case 1 => OrderInfo.v1[A](o.orderType, o.amount, o.price, o.timestamp, status, o.assetPair)
      case 2 => OrderInfo.v2[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair)
      case 3 => OrderInfo.v3[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair, aoType)
      case 4 => OrderInfo.v4[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair, aoType, avgWeighedPrice)
      case 5 =>
        OrderInfo
          .v5[A](o.orderType, o.amount, o.price, o.matcherFee, o.feeAsset, o.timestamp, status, o.assetPair, aoType, avgWeighedPrice, o.version)
    }
  }
} 
Example 54
Source File: EventSpecification.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.model

import com.wavesplatform.dex.MatcherSpecBase
import com.wavesplatform.dex.domain.account.KeyPair
import com.wavesplatform.dex.domain.asset.Asset.Waves
import com.wavesplatform.dex.domain.asset.AssetPair
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class EventSpecification extends AnyFreeSpec with Matchers with MatcherSpecBase {

  "Proper rounding scenario 1" in {
    val pair      = AssetPair(Waves, mkAssetId("BTC"))
    val counter   = sell(pair, 840340L, 0.00000238, matcherFee = Some(300000L))
    val submitted = buy(pair, 425532L, 0.00000238, matcherFee = Some(300000L))
    val exec      = mkOrderExecutedRaw(submitted, counter)
    exec.executedAmount shouldBe 420169L
    exec.counterRemainingAmount shouldBe 420171L
    exec.counterRemainingAmount shouldBe counter.amount - exec.executedAmount

    exec.counterRemainingFee shouldBe 150001L

    exec.submittedRemainingAmount shouldBe 5363L
    exec.submittedRemainingAmount shouldBe submitted.amount - exec.executedAmount

    exec.submittedRemainingFee shouldBe 3781L
  }

  "Remaining fee and amount checks" in {
    val pair      = AssetPair(Waves, mkAssetId("BTC"))
    val counter   = sell(pair, 100000000, 0.0008, matcherFee = Some(2000L))
    val submitted = buy(pair, 120000000, 0.00085, matcherFee = Some(1000L))

    val exec = mkOrderExecutedRaw(submitted, counter)
    exec.submittedRemainingAmount shouldBe 20000000L
    exec.submittedRemainingFee shouldBe 167L
  }

  "Reserved balance should empty after full rounded execution" in {
    val pair = AssetPair(mkAssetId("BTC"), mkAssetId("ETH"))

    val alicePk   = KeyPair("alice".getBytes("utf-8"))
    val counter   = buy(pair, 923431000L, 0.00031887, matcherFee = Some(300000), sender = Some(alicePk))
    val bobPk     = KeyPair("bob".getBytes("utf-8"))
    val submitted = sell(pair, 223345000L, 0.00031887, matcherFee = Some(300000), sender = Some(bobPk))

    val exec = mkOrderExecutedRaw(submitted, counter)
    exec.executedAmount shouldBe 223344937L
  }
} 
Example 55
Source File: AssetPairsDBSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.db

import com.wavesplatform.dex.domain.asset.Asset.Waves
import com.wavesplatform.dex.domain.asset.AssetPair
import com.wavesplatform.dex.{MatcherSpecBase, NoShrink}
import org.scalacheck.Gen
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks}

class AssetPairsDBSpec extends AnyFreeSpec with Matchers with WithDB with MatcherSpecBase with PropertyChecks with NoShrink {

  private val fixedAssetPairGen = assetPairGen.filterNot(x => x.amountAsset == Waves && x.priceAsset == Waves)

  "Default AssetPairsDB implementation" - {
    "stores and reads all asset pairs" in {
      val g = Gen.containerOf[Set, AssetPair](fixedAssetPairGen)
      forAll(g) { assetPairs =>
        test { apdb =>
          assetPairs.foreach(apdb.add)
          apdb.all() shouldBe assetPairs
        }
      }
    }

    "removes asset pair" in {
      val g = for {
        xs <- Gen.nonEmptyContainerOf[Vector, AssetPair](fixedAssetPairGen)
        indexGen = Gen.choose(0, xs.size - 1)
        is <- Gen.nonEmptyListOf(indexGen)
      } yield (xs.toSet, is.toSet.map(xs.apply))

      forAll(g) {
        case (assetPairs, toRemove) =>
          test { apdb =>
            assetPairs.foreach(apdb.add)
            toRemove.foreach(apdb.remove)
            apdb.all() shouldBe (assetPairs -- toRemove)
          }
      }
    }

  }

  private def test(f: AssetPairsDB => Any): Any = tempDb(db => f(AssetPairsDB(db)))

} 
Example 56
Source File: MatcherErrorDocSpec.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.doc

import com.wavesplatform.dex.meta.getSimpleName
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class MatcherErrorDocSpec extends AnyFreeSpec with Matchers {
  "MatcherErrorDoc" - {
    "should not contain two equal error codes" in {
      val samples = MatcherErrorDoc.errorSamples.run.sortBy(_.code)
      samples.zip(samples.tail).foreach {
        case (e1, e2) =>
          withClue(s"${getSimpleName(e1)} and ${getSimpleName(e2)}") {
            e1.code shouldNot be(e2.code)
          }
      }
    }
  }
} 
Example 57
Source File: MatcherSuiteBase.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.it

import java.nio.charset.StandardCharsets
import java.util.concurrent.ThreadLocalRandom

import cats.instances.FutureInstances
import com.wavesplatform.dex.asset.DoubleOps
import com.wavesplatform.dex.domain.account.KeyPair
import com.wavesplatform.dex.domain.asset.Asset
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.utils.ScorexLogging
import com.wavesplatform.dex.it.api.BaseContainersKit
import com.wavesplatform.dex.it.api.node.HasWavesNode
import com.wavesplatform.dex.it.config.{GenesisConfig, PredefinedAccounts, PredefinedAssets}
import com.wavesplatform.dex.it.dex.HasDex
import com.wavesplatform.dex.it.matchers.ItMatchers
import com.wavesplatform.dex.it.test.InformativeTestStart
import com.wavesplatform.dex.it.waves.{MkWavesEntities, ToWavesJConversions}
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import com.wavesplatform.dex.waves.WavesFeeConstants
import com.wavesplatform.it.api.ApiExtensions
import org.scalatest.concurrent.Eventually
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, CancelAfterFailure}

import scala.concurrent.duration.DurationInt

trait MatcherSuiteBase
    extends AnyFreeSpec
    with Matchers
    with CancelAfterFailure
    with BeforeAndAfterAll
    with BeforeAndAfterEach
    with Eventually
    with BaseContainersKit
    with HasDex
    with HasWavesNode
    with MkWavesEntities
    with ApiExtensions
    with ItMatchers
    with DoubleOps
    with WavesFeeConstants
    with PredefinedAssets
    with PredefinedAccounts
    with DiffMatcherWithImplicits
    with InformativeTestStart
    with FutureInstances
    with ToWavesJConversions
    with ScorexLogging {

  GenesisConfig.setupAddressScheme()

  override protected val moduleName: String = "dex-it"

  override implicit def patienceConfig: PatienceConfig = super.patienceConfig.copy(timeout = 30.seconds, interval = 1.second)

  override protected def beforeAll(): Unit = {
    log.debug(s"Perform beforeAll")
    kafkaServer.foreach { _ =>
      createKafkaTopic(dexRunConfig.getString("waves.dex.events-queue.kafka.topic"))
    }
    wavesNode1.start()
    dex1.start()
  }

  override protected def afterAll(): Unit = {
    log.debug(s"Perform afterAll")
    stopBaseContainers()
    super.afterAll()
  }

  def createAccountWithBalance(balances: (Long, Asset)*): KeyPair = {
    val account = KeyPair(ByteStr(s"account-test-${ThreadLocalRandom.current().nextInt()}".getBytes(StandardCharsets.UTF_8)))

    balances.foreach {
      case (balance, asset) =>
        assert(
          wavesNode1.api.balance(alice, asset) >= balance,
          s"Alice doesn't have enough balance in ${asset.toString} to make a transfer"
        )
        broadcastAndAwait(mkTransfer(alice, account.toAddress, balance, asset))
    }
    account
  }
} 
Example 58
Source File: IntegrationSuiteBase.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.grpc.integration

import com.wavesplatform.dex.asset.DoubleOps
import com.wavesplatform.dex.domain.utils.ScorexLogging
import com.wavesplatform.dex.it.api.BaseContainersKit
import com.wavesplatform.dex.it.api.node.{HasWavesNode, NodeApiExtensions}
import com.wavesplatform.dex.it.config.{GenesisConfig, PredefinedAccounts, PredefinedAssets}
import com.wavesplatform.dex.it.test.InformativeTestStart
import com.wavesplatform.dex.it.waves.{MkWavesEntities, ToWavesJConversions}
import com.wavesplatform.dex.test.matchers.DiffMatcherWithImplicits
import com.wavesplatform.dex.waves.WavesFeeConstants
import org.scalatest.concurrent.Eventually
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach}

import scala.concurrent.duration.DurationInt

trait IntegrationSuiteBase
    extends AnyFreeSpec
    with Matchers
    with BeforeAndAfterAll
    with BeforeAndAfterEach
    with Eventually
    with BaseContainersKit
    with HasWavesNode
    with MkWavesEntities
    with WavesFeeConstants
    with NodeApiExtensions
    with PredefinedAssets
    with PredefinedAccounts
    with DoubleOps
    with DiffMatcherWithImplicits
    with InformativeTestStart
    with ToWavesJConversions
    with ScorexLogging {

  GenesisConfig.setupAddressScheme()

  override protected val moduleName: String = "waves-integration-it"

  override implicit def patienceConfig: PatienceConfig = super.patienceConfig.copy(timeout = 30.seconds, interval = 1.second)

  override protected def beforeAll(): Unit = {
    log.debug(s"Perform beforeAll")
    wavesNode1.start()
  }

  override protected def afterAll(): Unit = {
    log.debug(s"Perform afterAll")
    stopBaseContainers()
    super.afterAll()
  }
} 
Example 59
Source File: FlatMapRemove.scala    From Binding.scala   with MIT License 5 votes vote down vote up
package com.thoughtworks.binding.regression

import com.thoughtworks.binding.Binding._
import com.thoughtworks.binding._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

import scala.collection.mutable.ArrayBuffer


final class FlatMapRemove extends AnyFreeSpec with Matchers {
  "removed source of a flatMap" in {

    val data = Vars.empty[Either[String, String]]

    val left = for {
      s <- data
      if s.isLeft
    } yield s

    val events = ArrayBuffer.empty[String]
    val autoPrint = Binding {
      if (left.length.bind > 0) {
        events += "has left"
      } else {
        events += "does not has left"
      }
    }
    assert(events.forall(_ == "does not has left"))
    autoPrint.watch()
    assert(events.forall(_ == "does not has left"))
    data.value += Right("1")
    assert(events.forall(_ == "does not has left"))
    data.value += Right("2")
    assert(events.forall(_ == "does not has left"))
    data.value += Right("3")
    assert(events.forall(_ == "does not has left"))
    data.value(1) = Left("left 2")
    assert(events.last == "has left")
    data.value --= Seq(Left("left 2"))
    assert(events.last == "does not has left")
  }
} 
Example 60
Source File: Issue56.scala    From Binding.scala   with MIT License 5 votes vote down vote up
package com.thoughtworks.binding.regression

import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.{Var, Vars}
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


final class Issue56 extends AnyFreeSpec with Matchers {

  "test" in {
    var dataSource = Var[Int](100)
    val isEnabled = Var[Boolean](false)

    val mappedData = Binding {
      dataSource.bind + 1
    }

    val result = Binding {
      if (isEnabled.bind) {
        mappedData.bind
      } else {
        0
      }
    }

    result.watch()
    dataSource.value = 300
    isEnabled.value = true
    result.get should be(301)
  }

} 
Example 61
Source File: Issue188.scala    From Binding.scala   with MIT License 5 votes vote down vote up
package com.thoughtworks.binding.regression

import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.{Var, Vars}
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

final class Issue188 extends AnyFreeSpec with Matchers {
  "non-regression test for https://github.com/ThoughtWorksInc/Binding.scala/issues/188" in {

    val objectCache: Var[Int] = Var(1)

    val objectValue: Binding[Int] = Binding {
      val cache = objectCache.bind

      if (cache == 1) {
        objectCache.value = 2
        2
      } else {
        cache
      }
    }

    an[IllegalStateException] should be thrownBy objectValue.watch()

  }
} 
Example 62
Source File: InsertThenClear.scala    From Binding.scala   with MIT License 5 votes vote down vote up
package com.thoughtworks.binding.regression

import com.thoughtworks.binding.Binding._
import com.thoughtworks.binding._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

import scala.collection.mutable.ArrayBuffer


final class InsertThenClear extends AnyFreeSpec with Matchers {
  "insert then clear" in {
    val items = Vars(1 to 10: _*)

    val mapped = items.map(-_)
    mapped.watch()
    assert(mapped.get sameElements Seq(-1, -2, -3, -4, -5, -6, -7, -8, -9, -10))

    items.value.insertAll(3, 100 to 103)
    assert(mapped.get sameElements Seq(-1, -2, -3, -100, -101, -102, -103, -4, -5, -6, -7, -8, -9, -10))

    items.value.clear()
    assert(mapped.get sameElements Seq.empty)
  }
} 
Example 63
Source File: Stackoverflow58206168.scala    From Binding.scala   with MIT License 5 votes vote down vote up
package com.thoughtworks.binding
package regression
import org.scalatest.{FreeSpec, Matchers}
import Binding._
import scala.collection.mutable
import Binding.BindingInstances.functorSyntax._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

final class Stackoverflow58206168 extends AnyFreeSpec with Matchers {
  // See https://stackoverflow.com/questions//binding-scala-vars-bind-seems-to-not-work-correctly
  "Binding.scala: Vars.bind seems to not work correctly" in {
    val events = mutable.Buffer.empty[List[Int]]
    val test: Vars[Int] = Vars(1, 2, 3, 4)

    test.all.map {
      events += _.toList
    }.watch()

    test.value.append(1111)
    assert(events == mutable.Buffer(List(1, 2, 3, 4), List(1, 2, 3, 4, 1111)))
  }

} 
Example 64
Source File: Zhihu50863924.scala    From Binding.scala   with MIT License 5 votes vote down vote up
package com.thoughtworks.binding.regression

import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.Var
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers


final class Zhihu50863924 extends AnyFreeSpec with Matchers {

  "Newly created Binding expression should not re-render immediately" in {

    var renderCount0 = 0
    var renderCount1 = 0

    def subComponent(value: Var[Option[String]]) = Binding {
      renderCount0 += 1
      assert(value.bind == Some("Changed"))
      renderCount1 += 1
      Right(value.bind.get)
    }

    val value: Var[Option[String]] = Var(None)

    val render = Binding {
      if (value.bind.isDefined) {
        subComponent(value).bind
      } else {
        Left("None here!")
      }
    }

    render.watch()
    assert(render.get == Left("None here!"))
    value.value = Some("Changed")
    assert(render.get == Right("Changed"))
    assert(renderCount0 == 1)
    assert(renderCount1 == 1)
  }
} 
Example 65
Source File: DSLSpec.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres.generic

import com.twitter.finagle.postgres.Param
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import patchless.Patch
import shapeless.record.Record

class DSLSpec extends AnyFreeSpec with Matchers {

  "Columns" - {

    "should snake case by default" in {
      case class Camels(camelOne: String, camelTwoWords: Int, camelWith2NumbersAnd5Words: Boolean)
      Columns[Camels].names shouldEqual List("camel_one", "camel_two_words", "camel_with_2_numbers_and_5_words")
    }

  }

  "Updates" - {

    "should recover updates from record of options" in {
      val record = Record(foo = Some(22):Option[Int], bar = None:Option[String])
      Updates(record) shouldEqual Updates(List("foo" -> Param(22)))
    }

    "should recover updates from a case class" in {
      case class Foo(foo: String, bar: Int)
      val foo = Foo("hello", 22)
      Updates(foo) shouldEqual Updates(List("foo" -> Param("hello"), "bar" -> Param(22)))
    }

    "should recover updates from a patchless Patch" in {
      case class Foo(foo: String, bar: Int)
      val a = Foo("hello", 22)
      val b = Foo("updated", 22)
      val patch = Patch.diff(a, b)
      Updates(patch) shouldEqual Updates(List("foo" -> Param("updated")))
    }

    "uses snake case namer by default" in {
      val record = Record(fooCamel = Some(22):Option[Int], barCamel = None:Option[String])
      Updates(record) shouldEqual Updates(List("foo_camel" -> Param(22)))

      case class Foo(fooCamel: String, barCamel: Int)
      val foo = Foo("hello", 22)
      Updates(foo) shouldEqual Updates(List("foo_camel" -> Param("hello"), "bar_camel" -> Param(22)))
    }

  }

} 
Example 66
Source File: ReadsRecoverOpsSpec.scala    From play-json-ops   with MIT License 5 votes vote down vote up
package play.api.libs.json.ops.v4

import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers._
import play.api.libs.json._

class ReadsRecoverOpsSpec extends AnyFreeSpec {

  private val it = classOf[ReadsRecoverOps[_]].getSimpleName

  s"$it.recoverJsError should recover from exceptions with a JsError" in {
    val readStringAsInt = Reads.of[String].map(_.toInt).recoverJsError
    readStringAsInt.reads(JsString("not a number")) match {
      case JsError(Seq((JsPath, Seq(JsonValidationError(Seq(message), ex))))) =>
        assertResult("error.expected.int")(message)
        ex shouldBe a[NumberFormatException]
      case o => fail(s"Expected a single error message with a single exception, not $o")
    }
  }

  s"$it.recoverWith should throw any exception not caught by the partial function" in {
    val readStringAsIntInverted = Reads.of[String].map(1 / _.toInt).recoverWith {
      case ex: NumberFormatException => RecoverOps.expectedTypeError(classOf[Int], ex)
    }
    // it should catch format exceptions
    assert(readStringAsIntInverted.reads(JsString("not a number")).isError)
    // but math exceptions are uncaught
    an[ArithmeticException] shouldBe thrownBy {
      readStringAsIntInverted.reads(JsString("0"))
    }
  }

  s"$it.recoverTotal should call the recover function" in {
    val readStringAsIntInverted = Reads.of[String].map(_.toInt.abs).recoverTotal(_ => -1)
    assertResult(JsSuccess(-1))(readStringAsIntInverted.reads(JsString("not a number")))
  }
}