zio.test.DefaultRunnableSpec Scala Examples
The following examples show how to use zio.test.DefaultRunnableSpec.
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: IteratorTest.scala From spark-tools with Apache License 2.0 | 6 votes |
package io.univalence.sparkzio import zio.{ DefaultRuntime, IO, Ref, Task, UIO, ZIO, ZManaged } import zio.clock.Clock import zio.stream.{ Stream, ZSink, ZStream } import zio.test.DefaultRunnableSpec import zio.test._ import zio.test.Assertion._ object StreamTest { def assertForAll[R, E, A](zstream: ZStream[R, E, A])(f: A => TestResult): ZIO[R, E, TestResult] = zstream.fold(assert(Unit, Assertion.anything))((as, a) => as && f(a)) def isSorted[A: Ordering]: Assertion[Iterable[A]] = Assertion.assertion("sorted")()(x => { val y = x.toList y.sorted == y }) } object IteratorTest extends DefaultRunnableSpec( suite("iterator")( testM("to iterator should be lazy")({ case class Element(n: Int, time: Long) (for { clock <- ZIO.environment[Clock] n <- Ref.make(0) incCounter <- n.update(_ + 1).forever.fork } yield { def element: UIO[Element] = n.get.zipWith(clock.clock.nanoTime)(Element) val in = Stream.repeatEffect(element) val iterator = Iterator.unwrapManaged(Iterator.fromStream(in)) val out: ZStream[Any, Nothing, Element] = ZStream.fromIterator(iterator).mapConcatM(e => element.map(List(e, _))) implicit val ordering: Ordering[Element] = Ordering.by(x => x.n -> x.time) out.take(2000).runCollect.map(e => assert(e, StreamTest.isSorted)) }).flatten }), testM("<=>")({ val in: List[Int] = (1 to 100).toList (for { _ <- UIO.unit.toManaged_ stream1 = ZStream.fromIterator(UIO(in.toIterator)) iterator <- Iterator.fromStream(stream1) stream2 = ZStream.fromIterator(UIO(iterator)) out <- stream2.runCollect.toManaged_ } yield { assert(in, equalTo(out)) }).use(x => ZIO.effect(x)) }), testM("on exit")( (for { isOpen <- Ref.make(false).toManaged_ stream = ZStream.managed(ZManaged.make(isOpen.update(_ => true))(_ => isOpen.set(false))) iterator <- Iterator.fromStream(stream) } yield { assert(iterator.toList, equalTo(List(true))) }).use(x => IO.effect(x)) ) ) )
Example 2
Source File: Slf4jLoggerTest.scala From zio-logging with Apache License 2.0 | 5 votes |
package zio.logging.slf4j import java.util.UUID import zio.{ UIO, ULayer } import zio.test.DefaultRunnableSpec import zio.logging._ import zio.test._ import zio.test.Assertion._ import scala.jdk.CollectionConverters._ object Slf4jLoggerTest extends DefaultRunnableSpec { val logLayer: ULayer[Logging] = Slf4jLogger.makeWithAnnotationsAsMdc( List(LogAnnotation.CorrelationId, LogAnnotation.Level) ) def spec = suite("slf4j logger")( testM("test1") { for { uuid1 <- UIO(UUID.randomUUID()) uuid2 <- UIO(UUID.randomUUID()) _ <- log.locally(_.annotate(LogAnnotation.CorrelationId, Some(uuid1))) { log.info("log stmt 1") *> log.locally(_.annotate(LogAnnotation.CorrelationId, Some(uuid2))) { log.info("log stmt 1_1") *> log.info("log stmt 1_2") } *> log.info("log stmt 2") } } yield { val testEvs = TestAppender.events assert(testEvs.size)(equalTo(4)) && assert(testEvs.map(_.getMessage))( equalTo(List("log stmt 1", "log stmt 1_1", "log stmt 1_2", "log stmt 2")) ) && assert(testEvs.map(_.getMDCPropertyMap.asScala("correlation-id")))( equalTo(List(uuid1.toString, uuid2.toString, uuid2.toString, uuid1.toString)) ) } } ).provideCustomLayer(logLayer) }
Example 3
Source File: ExampleSpec.scala From zio with Apache License 2.0 | 5 votes |
package zio.examples.test import zio.test.{ assert, suite, test, Assertion, DefaultRunnableSpec } object ExampleSpec extends DefaultRunnableSpec { def spec = suite("some suite")( test("failing test") { assert(1)(Assertion.equalTo(2)) }, test("passing test") { assert(1)(Assertion.equalTo(1)) } ) }
Example 4
Source File: ShoppingCartSpec.scala From zio-actors with Apache License 2.0 | 5 votes |
package zio.actors.examples.persistence import java.io.File import java.util.concurrent.TimeUnit import zio.{ Cause, Has, Managed, Schedule, UIO, ZIO, ZLayer } import zio.actors.{ ActorSystem, Supervisor } import zio.duration.Duration import zio.test.Assertion._ import zio.test.{ assert, suite, testM, DefaultRunnableSpec, TestFailure } import ShoppingCart._ import Deps._ object Deps { val actorSystem: Managed[TestFailure[Throwable], ActorSystem] = Managed.make( ActorSystem("testSys", Some(new File("./src/test/resources/application.conf"))) .mapError(e => TestFailure.Runtime(Cause.die(e))) )(_.shutdown.catchAll(_ => UIO.unit)) val actorSystemLayer = ZLayer.fromManaged(actorSystem) val recoverPolicy = Supervisor.retry(Schedule.exponential(Duration(200, TimeUnit.MILLISECONDS))) } object ShoppingCartSpec extends DefaultRunnableSpec { def spec = suite("The Shopping Cart should")( testM("add item") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart1", recoverPolicy, State.empty, ShoppingCart("cart1")) conf <- cart ? AddItem("foo", 42) } yield assert(conf)(equalTo(Accepted(Summary(Map("foo" -> 42), checkedOut = false)))) }, testM("reject already added item") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart2", recoverPolicy, State.empty, ShoppingCart("cart2")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? AddItem("foo", 13) } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)(isSubtype[Rejected](anything)) }, testM("remove item") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart3", recoverPolicy, State.empty, ShoppingCart("cart3")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? RemoveItem("foo") } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)( equalTo(Accepted(Summary(Map.empty, checkedOut = false))) ) }, testM("adjust quantity") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart4", recoverPolicy, State.empty, ShoppingCart("cart4")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? AdjustItemQuantity("foo", 43) } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)( equalTo(Accepted(Summary(Map("foo" -> 43), checkedOut = false))) ) }, testM("checkout") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart5", recoverPolicy, State.empty, ShoppingCart("cart5")) conf1 <- cart ? AddItem("foo", 42) conf2 <- cart ? Checkout } yield assert(conf1)(isSubtype[Accepted](anything)) && assert(conf2)( equalTo(Accepted(Summary(Map("foo" -> 42), checkedOut = true))) ) }, testM("keep its state") { for { as <- ZIO.environment[Has[ActorSystem]].map(_.get) cart <- as.make("cart6", recoverPolicy, State.empty, ShoppingCart("cart6")) conf1 <- cart ? AddItem("foo", 42) _ <- cart.stop cart <- as.make("cart6", recoverPolicy, State.empty, ShoppingCart("cart6")) status <- cart ? Get } yield assert(conf1)(equalTo(Accepted(Summary(Map("foo" -> 42), checkedOut = false)))) && assert(status)(equalTo(Summary(Map("foo" -> 42), checkedOut = false))) } ).provideCustomLayer(actorSystemLayer) }
Example 5
Source File: PersistenceSpec.scala From zio-actors with Apache License 2.0 | 5 votes |
package zio.actors.persistence import java.io.File import zio.actors.{ ActorSystem, Context, Supervisor } import zio.UIO import zio.test.DefaultRunnableSpec import zio.test._ import zio.test.Assertion._ import CounterUtils._ import SpecUtils._ object CounterUtils { sealed trait Message[+_] case object Reset extends Message[Unit] case object Increase extends Message[Unit] case object Get extends Message[Int] sealed trait CounterEvent case object ResetEvent extends CounterEvent case object IncreaseEvent extends CounterEvent } object SpecUtils { val ESCounterHandler = new EventSourcedStateful[Any, Int, Message, CounterEvent](PersistenceId("id1")) { override def receive[A]( state: Int, msg: Message[A], context: Context ): UIO[(Command[CounterEvent], Int => A)] = msg match { case Reset => UIO((Command.persist(ResetEvent), _ => ())) case Increase => UIO((Command.persist(IncreaseEvent), _ => ())) case Get => UIO((Command.ignore, _ => state)) } override def sourceEvent(state: Int, event: CounterEvent): Int = event match { case ResetEvent => 0 case IncreaseEvent => state + 1 } } val configFile = Some(new File("./persistence/src/test/resources/application.conf")) } object PersistenceSpec extends DefaultRunnableSpec { def spec = suite("PersistenceSpec")( suite("Basic persistence operation")( testM("Restarting persisted actor") { for { actorSystem <- ActorSystem("testSystem1", configFile) actor <- actorSystem.make("actor1", Supervisor.none, 0, ESCounterHandler) _ <- actor ! Increase _ <- actor ? Increase _ <- actor.stop actor <- actorSystem.make("actor1", Supervisor.none, 0, ESCounterHandler) _ <- actor ! Increase counter <- actor ? Get } yield assert(counter)(equalTo(3)) }, testM("Corrupt plugin config name") { val program = for { as <- ActorSystem("testSystem3", configFile) _ <- as.make("actor1", Supervisor.none, 0, ESCounterHandler) } yield () assertM(program.run)( fails(isSubtype[Throwable](anything)) && fails( hasField[Throwable, Boolean]( "message", _.toString.contains("corrupt-plugin"), isTrue ) ) ) } ) ) }
Example 6
Source File: NullAndOptionalConfigSpec.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config.typesafe import zio.config.ConfigDescriptor._ import zio.config.read import zio.config.typesafe.EmployeeDetails._ import zio.config.typesafe.TypesafeConfigSource.fromHoconString import zio.test.Assertion._ import zio.test.{ DefaultRunnableSpec, suite, test, _ } final case class EmployeeDetails(employees: List[Employee], accountId: Int) final case class Employee( name: String, state: Option[Either[Int, String]], confidence: Either[Either[Double, Int], String] ) object EmployeeDetails { val employee = (string("name") |@| int("state").orElseEither(string("state")).optional |@| double("confidence") .orElseEither(int("confidence")) // The value can be Double or Int for key confidence .orElseEither( // If not Double or Int, then it could be string, but this time the key can be confidence, confidences or confs! string("confidence") .orElse(string("confidences")) .orElse(string("confs")) ))( Employee.apply, Employee.unapply ) val employeeDetails = nested("details") { (nested("employees")(list(employee)) |@| int("accountId"))( EmployeeDetails.apply, EmployeeDetails.unapply ) } } object NullAndOptionalConfig extends DefaultRunnableSpec { val spec = suite("TypesafeConfig Null and Optional")( test("A config case which keys maybe null or optional") { val hocconSourceList = fromHoconString( """details { | employees = [{ | name: jon | state: CA | confidence: 1.278 | }, | { | name: chris | state: 151 | confidence: High | }, | { | name: martha | confidence: Medium | }, | { | name: susan | confs: f | } | ] | | accountId = 1000 |}""".stripMargin ) val result = hocconSourceList match { case Left(value) => Left(value) case Right(source) => read(employeeDetails from source) } val expectedResult = Right( EmployeeDetails( List( Employee("jon", Some(Right("CA")), Left(Left(1.278))), Employee("chris", Some(Left(151)), Right("High")), Employee("martha", None, Right("Medium")), Employee("susan", None, Right("f")) ), 1000 ) ) assert(result)(equalTo(expectedResult)) } ) }
Example 7
Source File: CommandLineSourceTest.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config import zio.config.ReadError.{ ConversionError, Step } import zio.config.testsupport.MapConfigTestSupport.AppConfig.descriptor import zio.config.testsupport.MapConfigTestSupport.{ genAppConfig, stringNWithInjector, AppConfig } import zio.test.Assertion._ import zio.test.environment.TestEnvironment import zio.test.{ DefaultRunnableSpec, _ } import zio.{ IO, ZIO } object CommandLineSourceTest extends DefaultRunnableSpec { def spec: Spec[TestEnvironment, TestFailure[Nothing], TestSuccess] = suite("Configuration from command-line-style arguments")( testM("Configuration from arguments roundtrip separate args --key value") { checkM(genAppConfig()) { appConfig => val p2: zio.IO[ReadError[String], AppConfig] = for { args <- toSeparateArgs(AppConfig.descriptor, appConfig) reread <- fromArgs(args) } yield reread.get assertM(p2.either)(isRight(equalTo(appConfig))) } }, testM("Configuration from arguments roundtrip single arg --key=value") { checkM(genAppConfig()) { appConfig => val p2: zio.IO[ReadError[String], AppConfig] = for { args <- toSingleArg(AppConfig.descriptor, appConfig) reread <- fromArgs(args) } yield reread.get assertM(p2.either)(isRight(equalTo(appConfig))) } }, testM("Configuration from arguments roundtrip single arg --key=value multiple values take the head") { checkM(genAppConfig()) { appConfig => val p2: zio.IO[ReadError[String], AppConfig] = for { args <- toMultiSingleArg(AppConfig.descriptor, appConfig) reread <- fromArgs(args) } yield reread.get assertM(p2.either)(isRight(equalTo(appConfig))) } }, testM("Configuration from arguments roundtrip singe arg --key-value where value contains = char") { checkM(genAppConfig(stringNWithInjector(1, 15, "="))) { appConfig => val p2: zio.IO[ReadError[String], AppConfig] = for { args <- toSingleArg(AppConfig.descriptor, appConfig) reread <- fromArgs(args) } yield reread.get assertM(p2.either)(isRight(equalTo(appConfig))) } } ) def fromArgs(args: List[String]): ZIO[Any, ReadError[String], Config[AppConfig]] = ZIO.environment.provideLayer(Config.fromCommandLineArgs(args, descriptor, Some('_'), None)) def toSeparateArgs[A]( descriptor: ConfigDescriptor[A], a: A ): ZIO[Any, ReadError[String], List[String]] = IO.fromEither(write(descriptor, a)) .bimap( s => ConversionError[String](List(Step.Index(0)), s), propertyTree => propertyTree.flatten.toList.flatMap { t: (Vector[String], ::[String]) => List(s"--${t._1.mkString("_")}", t._2.mkString) } ) def toSingleArg[A](descriptor: ConfigDescriptor[A], a: A): ZIO[Any, ReadError[String], List[String]] = IO.fromEither(write(descriptor, a)) .bimap( s => ConversionError[String](List(Step.Index(0)), s), propertyTree => propertyTree.flatten.toList.flatMap { t: (Vector[String], ::[String]) => List(s"-${t._1.mkString("_")}=${t._2.mkString}") } ) def toMultiSingleArg[A]( descriptor: ConfigDescriptor[A], a: A ): ZIO[Any, ReadError[String], List[String]] = IO.fromEither(write(descriptor, a)) .bimap( s => ConversionError[String](List(Step.Index(0)), s), propertyTree => propertyTree.flatten.toList.flatMap { t: (Vector[String], ::[String]) => List(s"--${t._1.mkString("_")}=${t._2.mkString}") ++ List(s"--${t._1.mkString("_")}=${t._2.mkString}") // repeated with different value (should be ignored) } ) }
Example 8
Source File: CommandLineListAccumulationTest.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config import zio.ZIO import zio.config.ConfigDescriptor.{ int, list } import zio.test.Assertion._ import zio.test.environment.TestEnvironment import zio.test.{ DefaultRunnableSpec, _ } object CommandLineListAccumulationTest extends DefaultRunnableSpec { def spec: Spec[TestEnvironment, TestFailure[Nothing], TestSuccess] = suite("Configuration of a list from multiple entries")( testM("Using single arg --key=value style") { checkM(Gen.int(1, 10)) { count => val args = renderArgs(count) val p2: zio.IO[ReadError[String], SomeConfig] = fromArgs(args) .map(config => config.get) val expected = (1 to count).toList assertM(p2.either)(isRight(equalTo(SomeConfig(expected)))) } } ) final case class SomeConfig(ints: List[Int]) object SomeConfig { val descriptor: ConfigDescriptor[SomeConfig] = list("ints")(int)(SomeConfig.apply, SomeConfig.unapply) } def renderArgs(count: Int): List[String] = (1 to count) .map(i => s"--ints=$i") .toList def fromArgs(args: List[String]): ZIO[Any, ReadError[String], Config[SomeConfig]] = ZIO.environment.provideLayer(Config.fromCommandLineArgs(args, SomeConfig.descriptor, None, None)) }
Example 9
Source File: SystemTest.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config import zio.ZIO import zio.config.ConfigDescriptor._ import zio.random.Random import zio.test.Assertion._ import zio.test.environment.TestEnvironment import zio.test.{ DefaultRunnableSpec, _ } object SystemTest extends DefaultRunnableSpec { def spec: Spec[TestEnvironment, TestFailure[Nothing], TestSuccess] = suite("Configuration from system")( testM("from system properties") { checkM(genSomeConfig, genDelimiter) { (config, delimiter) => val result = for { _ <- setSystemProperties(config, delimiter) p <- ZIO.environment.provideLayer(Config.fromSystemProperties(SomeConfig.descriptor, Some(delimiter))) _ <- clearSystemProperties(delimiter) } yield p.get assertM(result.either)(isRight(equalTo(config))) } } ) final case class SomeConfig(size: Int, description: String) object SomeConfig { val descriptor: ConfigDescriptor[SomeConfig] = nested("SYSTEMPROPERTIESTEST")( (int("SIZE") |@| string("DESCRIPTION"))(SomeConfig.apply, SomeConfig.unapply) ) } def genSomeConfig: Gen[Random with Sized, SomeConfig] = for { size <- Gen.anyInt desc <- Gen.anyString } yield SomeConfig(size, desc) def genDelimiter: Gen[Random, Char] = Gen.elements('.', '_', '-', ':') def setSystemProperties(config: SomeConfig, delimiter: Char) = ZIO.succeed { java.lang.System.setProperty(s"SYSTEMPROPERTIESTEST${delimiter}SIZE", config.size.toString) java.lang.System.setProperty(s"SYSTEMPROPERTIESTEST${delimiter}DESCRIPTION", config.description) } def clearSystemProperties(delimiter: Char) = ZIO.succeed { java.lang.System.clearProperty(s"SYSTEMPROPERTIESTEST${delimiter}SIZE") java.lang.System.clearProperty(s"SYSTEMPROPERTIESTEST${delimiter}DESCRIPTION") } }
Example 10
Source File: ArgsListAccumulationTest.scala From zio-config with Apache License 2.0 | 5 votes |
package zio.config import zio.ZIO import zio.config.ConfigDescriptor._ import zio.test.Assertion._ import zio.test.environment.TestEnvironment import zio.test.{ DefaultRunnableSpec, _ } object ArgsListAccumulationTest extends DefaultRunnableSpec { def spec: Spec[TestEnvironment, TestFailure[Nothing], TestSuccess] = suite("Configuration of a list from multiple entries")( testM("Using single arg --key=value style") { checkM(Gen.int(1, 10)) { count => val args = renderArgs(count) val p2: zio.IO[ReadError[String], SomeConfig] = fromArgs(args) .map(config => config.get) val expected = (1 to count).toList // O is missing values. assertM(p2.either)(isRight(equalTo(SomeConfig(expected)))) } } ) final case class SomeConfig(ints: List[Int]) object SomeConfig { val descriptor: ConfigDescriptor[SomeConfig] = list("ints")(int)(SomeConfig.apply, SomeConfig.unapply) } def renderArgs(count: Int): List[String] = (1 to count) .map(i => s"--ints=$i") .toList def fromArgs(args: List[String]): ZIO[Any, ReadError[String], Config[SomeConfig]] = ZIO.environment.provideLayer(Config.fromCommandLineArgs(args, SomeConfig.descriptor, None, None)) }
Example 11
Source File: CoreSummonSpec.scala From interop-cats with Apache License 2.0 | 5 votes |
package zio.interop.test import cats.data.NonEmptyList import cats.{ Bifunctor, Monad, MonadError, SemigroupK } import zio._ import zio.interop.catz.core._ import zio.stream.interop.catz.core._ import zio.stream.{ Stream, ZStream } import zio.test.Assertion._ import zio.test.{ DefaultRunnableSpec, test, _ } object CoreSummonSpecextends extends DefaultRunnableSpec { override def spec = suite("summons from catz.core work with only a cats-core dependency")( test("ZIO instances") { val monad = implicitly[Monad[UIO]] val monadError = implicitly[MonadError[Task, Throwable]] val semigroupK = implicitly[SemigroupK[IO[NonEmptyList[Unit], ?]]] val bifunctor = implicitly[Bifunctor[IO]] monad.map(ZIO.unit)(identity) monadError.map(ZIO.unit)(identity) semigroupK.combineK(ZIO.unit, ZIO.unit) bifunctor.leftMap(ZIO.fromOption(None))(identity) assert(())(anything) }, test("ZManaged instances") { val monad = implicitly[Monad[ZManaged[Any, Nothing, ?]]] val monadError = implicitly[MonadError[Managed[Throwable, ?], Throwable]] val semigroupK = implicitly[SemigroupK[Managed[Nothing, ?]]] val bifunctor = implicitly[Bifunctor[Managed]] monad.map(ZManaged.unit)(identity) monadError.map(ZManaged.unit)(identity) semigroupK.combineK(ZManaged.unit, ZManaged.unit) bifunctor.leftMap(ZManaged.fail(()))(identity) assert(())(anything) }, test("ZStream instances") { val monad = implicitly[Monad[ZStream[Any, Nothing, ?]]] val monadError = implicitly[MonadError[Stream[Throwable, ?], Throwable]] val semigroupK = implicitly[SemigroupK[Stream[Nothing, ?]]] val bifunctor = implicitly[Bifunctor[Stream]] monad.map(ZStream.unit)(identity) monadError.map(ZStream.unit)(identity) semigroupK.combineK(ZStream.unit, ZStream.unit) bifunctor.leftMap(ZStream.fail(()))(identity) assert(())(anything) } ) }