org.scalactic.source.Position Scala Examples
The following examples show how to use org.scalactic.source.Position.
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: AdditionalAssertions.scala From ScalaWebTest with Apache License 2.0 | 5 votes |
package org.scalawebtest.integration import org.scalactic.source.Position import org.scalatest.{Assertion, Succeeded, Suite} import scala.reflect.ClassTag trait AdditionalAssertions {self: Suite => def assertThrowsAndTestMessage[T <: AnyRef](f: => Any)(messageTest: String => Assertion)(implicit classTag: ClassTag[T], pos: Position): Assertion = { val clazz = classTag.runtimeClass val threwExpectedException = try { f false } catch { case u: Throwable => messageTest(u.getMessage) if (!clazz.isAssignableFrom(u.getClass)) { fail(s"didn't throw expected exception ${clazz.getCanonicalName}") } else true } if (threwExpectedException) { Succeeded } else { fail(s"didn't throw expected exception ${clazz.getCanonicalName}") } } }
Example 2
Source File: FutureAwaitWithFailFastFnTest.scala From kafka-connect-common with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.concurrent import java.util.concurrent.Executors import com.datamountaineer.streamreactor.connect.concurrent.ExecutorExtension._ import org.scalactic.source.Position import org.scalatest.concurrent.{Eventually, TimeLimits} import org.scalatest.matchers.should.Matchers import org.scalatest.time.{Millis, Span} import org.scalatest.wordspec.AnyWordSpec import scala.util.{Failure, Try} class FutureAwaitWithFailFastFnTest extends AnyWordSpec with Matchers with Eventually with TimeLimits { "FutureAwaitWithFailFastFn" should { "return when all the futures have completed" in { val exec = Executors.newFixedThreadPool(10) val futures = (1 to 5).map(i => exec.submit { Thread.sleep(300) i }) eventually { val result = FutureAwaitWithFailFastFn(exec, futures) exec.isTerminated shouldBe true result shouldBe Seq(1, 2, 3, 4, 5) } } "stop when the first futures times out" in { val exec = Executors.newFixedThreadPool(6) val futures = for (i <- 1 to 10) yield { exec.submit { if (i == 4) { Thread.sleep(1000) sys.error("this task failed.") } else { Thread.sleep(50000) } } } eventually { val t = Try(FutureAwaitWithFailFastFn(exec, futures)) t.isFailure shouldBe true t.asInstanceOf[Failure[_]].exception.getMessage shouldBe "this task failed." exec.isTerminated shouldBe true } } } }
Example 3
Source File: RedisJsonDataStoreTest.scala From izanami with Apache License 2.0 | 5 votes |
package specs.redis.store import java.time.Duration import env.Master import org.scalactic.source.Position import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import store.AbstractJsonDataStoreTest import test.FakeApplicationLifecycle import scala.jdk.CollectionConverters._ import store.redis.RedisWrapper import store.redis.RedisClientBuilder import store.redis.RedisJsonDataStore import zio.{Exit, Reservation} class RedisJsonDataStoreTest extends AbstractJsonDataStoreTest("Redis") with BeforeAndAfter with BeforeAndAfterAll { val redisWrapper: Reservation[Any, Throwable, Option[RedisWrapper]] = runtime.unsafeRun( RedisClientBuilder .redisClient( Some(Master("localhost", 6380, 5)), system ) .reserve ) private val maybeRedisWrapper: Option[RedisWrapper] = runtime.unsafeRun(redisWrapper.acquire) override def dataStore(name: String): RedisJsonDataStore = RedisJsonDataStore(maybeRedisWrapper.get, name) override protected def before(fun: => Any)(implicit pos: Position): Unit = { super.before(fun) deleteAllData } override protected def afterAll(): Unit = { super.afterAll() deleteAllData runtime.unsafeRun(redisWrapper.release(Exit.unit)) } private def deleteAllData = maybeRedisWrapper.get.connection.sync().del(maybeRedisWrapper.get.connection.sync().keys("*").asScala.toSeq: _*) }
Example 4
Source File: ExperimentVariantEventRedisServiceTest.scala From izanami with Apache License 2.0 | 5 votes |
package specs.redis.abtesting import java.time.Duration import domains.abtesting.events.impl.ExperimentVariantEventRedisService import domains.abtesting.AbstractExperimentServiceTest import domains.abtesting.events.ExperimentVariantEventService import env.{DbDomainConfig, DbDomainConfigDetails, Master} import org.scalactic.source.Position import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import store.redis.{RedisClientBuilder, RedisWrapper} import test.FakeApplicationLifecycle import zio.{Exit, Reservation} import scala.jdk.CollectionConverters._ class ExperimentVariantEventRedisServiceTest extends AbstractExperimentServiceTest("Redis") with BeforeAndAfter with BeforeAndAfterAll { import zio.interop.catz._ val redisWrapper: Reservation[Any, Throwable, Option[RedisWrapper]] = runtime.unsafeRun( RedisClientBuilder .redisClient( Some(Master("localhost", 6380, 5)), system ) .reserve ) private val maybeRedisWrapper: Option[RedisWrapper] = runtime.unsafeRun(redisWrapper.acquire) override def dataStore(name: String): ExperimentVariantEventService.Service = ExperimentVariantEventRedisService(DbDomainConfig(env.Redis, DbDomainConfigDetails(name, None), None), maybeRedisWrapper) override protected def before(fun: => Any)(implicit pos: Position): Unit = { super.before(fun) deleteAllData } override protected def afterAll(): Unit = { super.afterAll() deleteAllData runtime.unsafeRun(redisWrapper.release(Exit.unit)) } private def deleteAllData = maybeRedisWrapper.get.connection .sync() .del(maybeRedisWrapper.get.connection.sync().keys("*").asScala.toSeq: _*) }
Example 5
Source File: ElasticJsonDataStoreTest.scala From izanami with Apache License 2.0 | 5 votes |
package specs.elastic.store import elastic.api.Elastic import env.{DbDomainConfig, DbDomainConfigDetails, ElasticConfig} import org.scalactic.source.Position import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import play.api.libs.json.JsValue import store.AbstractJsonDataStoreTest import store.elastic._ class ElasticJsonDataStoreTest extends AbstractJsonDataStoreTest("Elastic") with BeforeAndAfter with BeforeAndAfterAll { private val config = ElasticConfig("localhost", 9210, "http", None, None, true) val elastic: Elastic[JsValue] = ElasticClient(config, system) override def dataStore(dataStore: String): ElasticJsonDataStore = ElasticJsonDataStore( elastic, config, DbDomainConfig(env.Elastic, DbDomainConfigDetails(dataStore, None), None) ) override protected def before(fun: => Any)(implicit pos: Position): Unit = { super.before(fun) cleanUpElastic } private def cleanUpElastic = { import _root_.elastic.implicits._ import _root_.elastic.codec.PlayJson._ elastic.deleteIndex("*").futureValue } override protected def afterAll(): Unit = { super.afterAll() cleanUpElastic } }
Example 6
Source File: ExperimentVariantEventElasticServiceTest.scala From izanami with Apache License 2.0 | 5 votes |
package specs.elastic.abtesting import domains.abtesting.events.impl.ExperimentVariantEventElasticService import domains.abtesting.AbstractExperimentServiceTest import domains.abtesting.events.ExperimentVariantEventService import elastic.api.Elastic import env.{DbDomainConfig, DbDomainConfigDetails, ElasticConfig} import org.scalactic.source.Position import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import play.api.libs.json.JsValue import store.elastic.ElasticClient class ExperimentVariantEventElasticServiceTest extends AbstractExperimentServiceTest("Elastic") with BeforeAndAfter with BeforeAndAfterAll { private val config = ElasticConfig("localhost", 9210, "http", None, None, true) val elastic: Elastic[JsValue] = ElasticClient(config, system) override def dataStore(name: String): ExperimentVariantEventService.Service = ExperimentVariantEventElasticService( elastic, config, DbDomainConfig(env.Elastic, DbDomainConfigDetails(name, None), None) ) override protected def before(fun: => Any)(implicit pos: Position): Unit = { cleanUpElastic super.before(fun) } override protected def afterAll(): Unit = { cleanUpElastic super.afterAll() } private def cleanUpElastic = { import _root_.elastic.codec.PlayJson._ elastic.deleteIndex("*").futureValue } }
Example 7
Source File: MongoJsonDataStoreTest.scala From izanami with Apache License 2.0 | 5 votes |
package specs.mongo.store import env.{DbDomainConfig, DbDomainConfigDetails, Mongo} import org.scalactic.source.Position import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import play.api.Configuration import play.modules.reactivemongo.DefaultReactiveMongoApi import reactivemongo.api.MongoConnection import store.AbstractJsonDataStoreTest import test.FakeApplicationLifecycle import scala.concurrent.duration.DurationLong import scala.concurrent.Await import scala.util.Random import store.mongo.MongoJsonDataStore class MongoJsonDataStoreTest extends AbstractJsonDataStoreTest("Mongo") with BeforeAndAfter with BeforeAndAfterAll { val mongoApi = new DefaultReactiveMongoApi( Await.result(MongoConnection.fromString("mongodb://localhost:27017"), 5.seconds), s"dbtest-${Random.nextInt(50)}", false, Configuration.empty, new FakeApplicationLifecycle() ) override def dataStore(name: String): MongoJsonDataStore = MongoJsonDataStore( mongoApi, DbDomainConfig(Mongo, DbDomainConfigDetails(name, None), None) ) override protected def before(fun: => Any)(implicit pos: Position): Unit = { super.before(fun) deleteAllData } override protected def afterAll(): Unit = { super.afterAll() deleteAllData } private def deleteAllData = Await.result(mongoApi.database.flatMap { _.drop() }, 30.seconds) }
Example 8
Source File: ExperimentVariantEventMongoServiceTest.scala From izanami with Apache License 2.0 | 5 votes |
package specs.mongo.abtesting import domains.abtesting.events.impl.ExperimentVariantEventMongoService import domains.abtesting.AbstractExperimentServiceTest import domains.abtesting.events.ExperimentVariantEventService import env.{DbDomainConfig, DbDomainConfigDetails, Mongo} import org.scalactic.source.Position import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import play.api.Configuration import play.modules.reactivemongo.DefaultReactiveMongoApi import reactivemongo.api.MongoConnection import test.FakeApplicationLifecycle import scala.concurrent.duration.DurationLong import scala.concurrent.Await import scala.util.Random class ExperimentVariantEventMongoServiceTest extends AbstractExperimentServiceTest("Mongo") with BeforeAndAfter with BeforeAndAfterAll { import zio.interop.catz._ val mongoApi = new DefaultReactiveMongoApi( Await.result(MongoConnection.fromString("mongodb://localhost:27017"), 5.seconds), s"dbtest-${Random.nextInt(50)}", false, Configuration.empty, new FakeApplicationLifecycle() ) override def dataStore(name: String): ExperimentVariantEventService.Service = ExperimentVariantEventMongoService( DbDomainConfig(Mongo, DbDomainConfigDetails(name, None), None), mongoApi ) override protected def before(fun: => Any)(implicit pos: Position): Unit = { super.before(fun) deleteAllData } override protected def afterAll(): Unit = { super.afterAll() deleteAllData } private def deleteAllData = Await.result(mongoApi.database.flatMap { _.drop() }, 30.seconds) }
Example 9
Source File: RunEnforcementJobTest.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.testing import com.spotify.scio.testing.{JobTest => InnerJobTest} import org.scalactic.source.Position import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.{Failed, Outcome} import scala.collection.mutable.ArrayBuffer import scala.reflect.ClassTag trait RunEnforcementJobTest extends AnyFlatSpec { this: PipelineSpec => private val tests = ArrayBuffer.empty[InnerJobTest.Builder] def JobTest[T: ClassTag]: InnerJobTest.Builder = { val jt = InnerJobTest[T] tests += jt jt } private[testing] def JobTest[T: ClassTag](enforceRun: Boolean = true): InnerJobTest.Builder = { val jt = InnerJobTest[T] if (enforceRun) tests += jt jt } def JobTest(className: String): InnerJobTest.Builder = { val jt = InnerJobTest(className) tests += jt jt } override protected def withFixture(test: NoArgTest): Outcome = { // Tests within Suites are executed sequentially, thus we need to clear the tests, if // ParallelTestExecution was enabled, clear is obsolete given the OneInstancePerTest tests.clear() val outcome = super.withFixture(test) if (outcome.isSucceeded) { val notRun = tests.filterNot(_.wasRunInvoked) if (notRun.nonEmpty) { val m = notRun.mkString(start = "Missing run(): ", sep = "\nMissing run(): ", end = "") Failed(s"Did you forget run()?\n$m")(test.pos.getOrElse(Position.here)) } else { outcome } } else { outcome } } }
Example 10
Source File: ActivationStatusRequest.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.it.sync.activation import com.wavesplatform.features.BlockchainFeatureStatus import com.wavesplatform.features.api.{FeatureActivationStatus, NodeFeatureStatus} import org.scalactic.source.Position import org.scalatest.Matchers trait ActivationStatusRequest extends Matchers { def assertVotingStatus( fas: FeatureActivationStatus, supportedBlocks: Int, blockchainFeatureStatus: BlockchainFeatureStatus, nodeFeatureStatus: NodeFeatureStatus )(implicit pos: Position): Unit = { withClue("supportedBlocks") { fas.supportingBlocks should contain(supportedBlocks) } withClue("blockchainStatus") { fas.blockchainStatus shouldBe blockchainFeatureStatus } withClue("nodeStatus") { fas.nodeStatus shouldBe nodeFeatureStatus } } def assertApprovedStatus(fas: FeatureActivationStatus, height: Int, nodeFeatureStatus: NodeFeatureStatus)(implicit pos: Position): Unit = { withClue("activationHeight") { fas.activationHeight should contain(height) } withClue("blockchainStatus") { fas.blockchainStatus shouldBe BlockchainFeatureStatus.Approved } withClue("nodeStatus") { fas.nodeStatus shouldBe nodeFeatureStatus } } def assertActivatedStatus(fas: FeatureActivationStatus, height: Int, nodeFeatureStatus: NodeFeatureStatus)(implicit pos: Position): Unit = { withClue("activationHeight") { fas.activationHeight should contain(height) } withClue("blockchainStatus") { fas.blockchainStatus shouldBe BlockchainFeatureStatus.Activated } withClue("nodeStatus") { fas.nodeStatus shouldBe nodeFeatureStatus } } def assertUndefinedStatus(fas: FeatureActivationStatus, nodeFeatureStatus: NodeFeatureStatus)(implicit pos: Position): Unit = { withClue("supportedBlocks") { fas.supportingBlocks should contain(0) } withClue("blockchainStatus") { fas.blockchainStatus shouldBe BlockchainFeatureStatus.Undefined } withClue("nodeStatus") { fas.nodeStatus shouldBe nodeFeatureStatus } } }
Example 11
Source File: IOAsyncTests.scala From cats-effect with Apache License 2.0 | 5 votes |
package cats.effect import org.scalactic.source.Position import org.scalatest.Assertion import org.scalatest.matchers.should.Matchers import org.scalatest.funsuite.AsyncFunSuite import scala.concurrent.{ExecutionContext, Future, Promise} import scala.concurrent.duration._ import scala.util.{Failure, Success, Try} class IOAsyncTests extends AsyncFunSuite with Matchers { implicit override def executionContext = ExecutionContext.global implicit val timer: Timer[IO] = IO.timer(executionContext) implicit val cs: ContextShift[IO] = IO.contextShift(executionContext) def testEffectOnRunAsync(source: IO[Int], expected: Try[Int])(implicit pos: Position): Future[Assertion] = { val effect = Promise[Int]() val attempt = Promise[Try[Int]]() effect.future.onComplete(attempt.success) val io = source.runAsync { case Right(a) => IO { effect.success(a); () } case Left(e) => IO { effect.failure(e); () } } for (_ <- io.toIO.unsafeToFuture(); v <- attempt.future) yield { v shouldEqual expected } } test("IO.pure#runAsync") { testEffectOnRunAsync(IO.pure(10), Success(10)) } test("IO.apply#runAsync") { testEffectOnRunAsync(IO(10), Success(10)) } test("IO.apply#shift#runAsync") { testEffectOnRunAsync(IO.shift.flatMap(_ => IO(10)), Success(10)) } test("IO.raiseError#runAsync") { val dummy = new RuntimeException("dummy") testEffectOnRunAsync(IO.raiseError(dummy), Failure(dummy)) } test("IO.raiseError#shift#runAsync") { val dummy = new RuntimeException("dummy") testEffectOnRunAsync(IO.shift.flatMap(_ => IO.raiseError(dummy)), Failure(dummy)) } test("IO.sleep(10.ms)") { val io = IO.sleep(10.millis).map(_ => 10) for (r <- io.unsafeToFuture()) yield { r shouldBe 10 } } test("IO.sleep(negative)") { val io = IO.sleep(-10.seconds).map(_ => 10) for (r <- io.unsafeToFuture()) yield { r shouldBe 10 } } }
Example 12
Source File: XTestUtils.scala From scalaz-deriving with GNU Lesser General Public License v3.0 | 5 votes |
// Copyright: 2017 - 2020 Sam Halliday // License: http://www.gnu.org/licenses/lgpl-3.0.en.html package xmlformat import scalaz._ import org.scalatest.matchers.should.Matchers._ import org.scalactic.source.Position object XTestUtils { import XDecoder.ops._ import XStrDecoder.ops._ implicit class BetterEitherValuesOps[L, R](e: Either[L, R]) { def rightValue(implicit P: Position): R = e match { case Left(left) => fail(s"got Left: $left") case Right(right) => right } def leftValue(implicit P: Position): L = e match { case Left(left) => left case Right(right) => fail(s"got Right: $right") } } implicit class DisjunctionValuesOps[L, R](e: L \/ R) { def rightValue(implicit P: Position): R = e match { case -\/(left) => fail(s"got Left: $left") case \/-(right) => right } def leftValue(implicit P: Position): L = e match { case -\/(left) => left case \/-(right) => fail(s"got Right: $right") } } implicit class XHelper(xml: XChildren) { def as[T: XDecoder](implicit P: Position): T = xml.decode[T].rightValue } implicit class XStrHelper(xml: XString) { def as[T: XStrDecoder](implicit P: Position): T = xml.decode[T].rightValue } implicit class XTagHelper(tag: XTag) { def as[T: XDecoder](implicit P: Position): T = tag.asChild.as[T] } }
Example 13
Source File: ValueJsonConversionTest.scala From ingraph with Eclipse Public License 1.0 | 5 votes |
package ingraph.compiler.sql.driver import ingraph.compiler.sql.driver.ValueJsonConversion._ import ingraph.compiler.sql.driver.ValueJsonConversionTest._ import org.neo4j.driver.internal.value._ import org.neo4j.driver.internal.{InternalNode, InternalPath, InternalRelationship} import org.neo4j.driver.v1.Value import org.scalactic.source import org.scalactic.source.Position import org.scalatest.FunSuite import scala.collection.JavaConverters._ import scala.collection.mutable.ArrayBuffer class ValueJsonConversionTest extends FunSuite { testParameters.foreach { case (value, testName, pos) => test(testName) { println(value) val jsonString = gson.toJson(value, classOf[Value]) println(jsonString) val deserialized = gson.fromJson(jsonString, classOf[Value]) assert(value == deserialized) }(pos) } } object ValueJsonConversionTest { val testValues: ArrayBuffer[Value] = ArrayBuffer.empty val testParameters: ArrayBuffer[(Value, String, Position)] = ArrayBuffer.empty def addTest(value: Value, testName: String = null)(implicit pos: source.Position): Unit = { testValues += value testParameters += ((value, Option(testName).getOrElse(value.getClass.getSimpleName), pos)) } private val stringValue = new StringValue("John") private val integerValue = new IntegerValue(101) private val propertiesMap = Map[String, Value]("name" -> stringValue).asJava addTest(new MapValue(propertiesMap)) addTest(new BytesValue(Array[Byte](0, 42, 127, -128))) addTest(new ListValue(stringValue, integerValue)) addTest(new NodeValue(new InternalNode(5, List("Label1", "Label2").asJavaCollection, propertiesMap))) addTest(new RelationshipValue(new InternalRelationship(42, 10, 20, "Edge_Type_1", propertiesMap))) addTest(new PathValue(new InternalPath( new InternalNode(0), new InternalRelationship(101, 0, 1, "TYPE_A"), new InternalNode(1) ))) addTest(BooleanValue.FALSE) addTest(BooleanValue.TRUE) addTest(NullValue.NULL) addTest(stringValue) addTest(integerValue) addTest(new FloatValue(3.14)) }
Example 14
Source File: HiveVersionSuite.scala From Spark-2.3.1 with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.hive.client import org.apache.hadoop.conf.Configuration import org.scalactic.source.Position import org.scalatest.Tag import org.apache.spark.SparkFunSuite import org.apache.spark.sql.hive.HiveUtils private[client] abstract class HiveVersionSuite(version: String) extends SparkFunSuite { protected var client: HiveClient = null protected def buildClient(hadoopConf: Configuration): HiveClient = { // Hive changed the default of datanucleus.schema.autoCreateAll from true to false and // hive.metastore.schema.verification from false to true since 2.0 // For details, see the JIRA HIVE-6113 and HIVE-12463 if (version == "2.0" || version == "2.1") { hadoopConf.set("datanucleus.schema.autoCreateAll", "true") hadoopConf.set("hive.metastore.schema.verification", "false") } HiveClientBuilder .buildClient(version, hadoopConf, HiveUtils.formatTimeVarsForHiveClient(hadoopConf)) } override def suiteName: String = s"${super.suiteName}($version)" override protected def test(testName: String, testTags: Tag*)(testFun: => Any) (implicit pos: Position): Unit = { super.test(s"$version: $testName", testTags: _*)(testFun) } }
Example 15
Source File: Discipline.scala From discipline-scalatest with MIT License | 5 votes |
package org.typelevel.discipline package scalatest import org.scalactic.Prettifier import org.scalactic.source.Position import org.scalatest.flatspec.AnyFlatSpecLike import org.scalatest.funspec.AnyFunSpecLike import org.scalatest.funsuite.AnyFunSuiteLike import org.scalatest.prop.Configuration import org.scalatest.wordspec.AnyWordSpec import org.scalatestplus.scalacheck.Checkers trait Discipline { self: Configuration => final protected[this] def convertConfiguration( config: PropertyCheckConfiguration ): Checkers.PropertyCheckConfiguration = Checkers.PropertyCheckConfiguration( config.minSuccessful, config.maxDiscardedFactor, config.minSize, config.sizeRange, config.workers ) def checkAll(name: String, ruleSet: Laws#RuleSet)(implicit config: PropertyCheckConfiguration, prettifier: Prettifier, pos: Position ): Unit } trait FlatSpecDiscipline extends Discipline { self: AnyFlatSpecLike with Configuration => final def checkAll(name: String, ruleSet: Laws#RuleSet )(implicit config: PropertyCheckConfiguration, prettifier: Prettifier, pos: Position): Unit = ruleSet.all.properties match { case first +: rest => name should first._1 in Checkers.check(first._2)(convertConfiguration(config), prettifier, pos) for ((id, prop) <- rest) it should id in Checkers.check(prop)(convertConfiguration(config), prettifier, pos) } } trait FunSpecDiscipline extends Discipline { self: AnyFunSpecLike with Configuration => final def checkAll(name: String, ruleSet: Laws#RuleSet )(implicit config: PropertyCheckConfiguration, prettifier: Prettifier, pos: Position): Unit = describe(name) { for ((id, prop) <- ruleSet.all.properties) it(id) { Checkers.check(prop)(convertConfiguration(config), prettifier, pos) } } } trait FunSuiteDiscipline extends Discipline { self: AnyFunSuiteLike with Configuration => final def checkAll(name: String, ruleSet: Laws#RuleSet )(implicit config: PropertyCheckConfiguration, prettifier: Prettifier, pos: Position): Unit = for ((id, prop) <- ruleSet.all.properties) test(s"${name}.${id}") { Checkers.check(prop)(convertConfiguration(config), prettifier, pos) } } trait WordSpecDiscipline extends Discipline { self: AnyWordSpec with Configuration => def checkAll(name: String, ruleSet: Laws#RuleSet )(implicit config: PropertyCheckConfiguration, prettifier: Prettifier, pos: Position): Unit = for ((id, prop) <- ruleSet.all.properties) registerTest(s"${name}.${id}") { Checkers.check(prop)(convertConfiguration(config), prettifier, pos) } }
Example 16
Source File: AnalyzerTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package analyzer import org.scalactic.source.Position import org.scalatest.Assertions import scala.reflect.internal.util.BatchSourceFile import scala.tools.nsc.plugins.Plugin import scala.tools.nsc.{Global, Settings} trait AnalyzerTest { this: Assertions => val settings = new Settings settings.usejavacp.value = true settings.pluginOptions.value ++= List("AVSystemAnalyzer:+_") val compiler: Global = new Global(settings) { global => override protected def loadRoughPluginsList(): List[Plugin] = new AnalyzerPlugin(global) :: super.loadRoughPluginsList() } def compile(source: String): Unit = { compiler.reporter.reset() val run = new compiler.Run run.compileSources(List(new BatchSourceFile("test.scala", source))) } def assertErrors(source: String)(implicit pos: Position): Unit = { compile(source) assert(compiler.reporter.hasErrors) } def assertErrors(errors: Int, source: String)(implicit pos: Position): Unit = { compile(source) assert(compiler.reporter.errorCount == errors) } def assertNoErrors(source: String)(implicit pos: Position): Unit = { compile(source) assert(!compiler.reporter.hasErrors) } }
Example 17
Source File: FileBasedSuite.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package testutil import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite abstract class FileBasedSuite(testdir: String) extends AnyFunSuite { def updateTestFiles: Boolean = System.getProperty("updateTestFiles").opt.map(_.toBoolean).contains(true) def separator: String = "-----\n" def testFile(file: String)(process: String => String)(implicit position: Position): Unit = { val path = s"$testdir/$file" val contents = IO.readTestResource(path) val (input, expectedOutput) = contents.indexOf(separator) match { case -1 => (contents, "") case idx => (contents.take(idx), contents.drop(idx + separator.length)) } val output = process(input) if (updateTestFiles && output != expectedOutput) { IO.writeTestResource(path, input + separator + output) } assert(output == expectedOutput) } def assertContents(actual: String, expectedFile: String): Unit = { val filePath = s"$testdir/$expectedFile" val expected = IO.readTestResource(filePath) if (updateTestFiles) { IO.writeTestResource(filePath, actual) } assert(actual == expected) } }
Example 18
Source File: ApplierUnapplierTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons.misc import com.avsystem.commons import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite case class Empty() case class Single(str: String) case class Multiple(str: String, int: Int) case class Varargs(str: String, ints: Int*) case class Generic[T](str: String, value: T) case class Over22( p01: String = "01", p02: String = "02", p03: String = "03", p04: String = "04", p05: String = "05", p06: String = "06", p07: String = "07", p08: String = "08", p09: String = "09", p10: String = "10", p11: String = "11", p12: String = "12", p13: String = "13", p14: String = "13", p15: String = "15", p16: String = "16", p17: String = "17", p18: String = "18", p19: String = "18", p20: String = "18", p21: String = "21", p22: String = "22", p23: String = "23", p24: String = "24", p25: String = "25" ) class Custom(val str: String, val i: Int) { override def hashCode(): Int = (str, i).hashCode() override def equals(obj: Any): Boolean = obj match { case c: Custom => str == c.str && i == c.i case _ => false } } object Custom { def apply(str: String, i: Int): Custom = new Custom(str, i) def unapply(custom: Custom): commons.Opt[(String, Int)] = Opt((custom.str, custom.i)) } class ApplierUnapplierTest extends AnyFunSuite { def roundtrip[T](value: T)(implicit applier: Applier[T], unapplier: Unapplier[T], applierUnapplier: ApplierUnapplier[T], pos: Position ): Unit = { assert(value == applier(unapplier.unapply(value))) assert(value == applierUnapplier(applierUnapplier.unapply(value))) } test("no params") { roundtrip(Empty()) } test("single param") { roundtrip(Single("")) } test("multiple params") { roundtrip(Multiple("", 42)) } test("varargs") { roundtrip(Varargs("", 1, 2, 3)) } test("generic") { roundtrip(Generic("a", "b")) } test("more than 22 params") { roundtrip(Over22()) } test("custom") { roundtrip(Custom("", 42)) } test("tuple") { roundtrip(("", 42, 3.14)) } }
Example 19
Source File: JavaClassNameTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package macros import com.avsystem.commons.misc.{JavaClassName, TypeString} import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite object JavaClassNameTest { class Inner { class MoreInner { class SuperInner } } object Inner { class EvenInner object EvenInner } } class JavaClassNameTest extends AnyFunSuite { def test[T: ClassTag : JavaClassName : TypeString](implicit pos: Position): Unit = test(TypeString.of[T])(assert(JavaClassName.of[T] == classTag[T].runtimeClass.getName)) test[Any] test[AnyRef] test[AnyVal] test[Unit] test[Boolean] test[Char] test[Byte] test[Short] test[Int] test[Long] test[Float] test[Double] test[String] test[Nothing] test[Array[Boolean]] test[Array[Char]] test[Array[Byte]] test[Array[Short]] test[Array[Int]] test[Array[Long]] test[Array[Float]] test[Array[Double]] test[Array[String]] test[Array[Nothing]] test[JavaClassNameTest] test[JavaClassNameTest.type] test[JavaClassNameTest.Inner] test[JavaClassNameTest.Inner#MoreInner] test[JavaClassNameTest.Inner#MoreInner#SuperInner] test[JavaClassNameTest.Inner.type] test[JavaClassNameTest.Inner.EvenInner] test[JavaClassNameTest.Inner.EvenInner.type] }
Example 20
Source File: AbstractCodecTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite trait AbstractCodecTest extends AnyFunSuite { def assertSameTypeValue[T](v1: T, v2: T)(implicit pos: Position): Unit = { assert(v1 == v2) assert(v1 == null || v1.getClass == v2.getClass) } type Raw def writeToOutput(write: Output => Unit): Raw def createInput(raw: Raw): Input def testWrite[T: GenCodec](value: T, expectedRepr: Raw)(implicit pos: Position): Unit = { val repr = writeToOutput(GenCodec.write[T](_, value)) assert(repr == expectedRepr) } def testRead[T: GenCodec](repr: Raw, expected: T)(implicit pos: Position): Unit = { assert(expected == GenCodec.read[T](createInput(repr))) } def testRoundtrip[T: GenCodec](value: T)(implicit pos: Position): Unit = { val written: Raw = writeToOutput(GenCodec.write[T](_, value)) val readBack = GenCodec.read[T](createInput(written)) assertSameTypeValue(value, readBack) } }
Example 21
Source File: HFloatTest.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization.cbor import org.scalactic.source.Position import org.scalatest.funsuite.AnyFunSuite class HFloatTest extends AnyFunSuite { def testConv(name: String)(floatBits: Int, hfloatBits: Int, roundedBits: Int)(implicit pos: Position): Unit = { val float = java.lang.Float.intBitsToFloat(floatBits) test(name) { val hfloat = HFloat.fromFloat(float) assert(hfloat.raw.toHexString == hfloatBits.toShort.toHexString) assert(java.lang.Float.floatToIntBits(hfloat.toFloat).toHexString == roundedBits.toHexString) } } private def mkHFloat(exponent: Int, significand: Int): Int = ((exponent + 15) << 10) | significand private def mkFloat(exponent: Int, significand: Int): Int = ((exponent + 127) << 23) | significand testConv("zero")(0x00000000, 0x0000, 0x00000000) testConv("-zero")(0x80000000, 0x8000, 0x80000000) testConv("Inf")(0x7F800000, 0x7C00, 0x7F800000) testConv("-Inf")(0xFF800000, 0xFC00, 0xFF800000) testConv("1.0")(mkFloat(0, 0), mkHFloat(0, 0), mkFloat(0, 0)) testConv("2.0")(mkFloat(1, 0), mkHFloat(1, 0), mkFloat(1, 0)) testConv("very small float")(0x00000001, 0x0000, 0x00000000) testConv("rounding down")(mkFloat(0, 0xFFF), mkHFloat(0, 0), mkFloat(0, 0)) testConv("rounding up")(mkFloat(0, 0x1000), mkHFloat(0, 0x1), mkFloat(0, 0x2000)) testConv("rounding up exponent")(mkFloat(0, 0x7FFF000), mkHFloat(1, 0), mkFloat(1, 0)) testConv("subnormal")(mkFloat(-15, 0), mkHFloat(-15, 0x200), mkFloat(-15, 0)) testConv("subnormal with rounding")(mkFloat(-16, 0x7FE000), mkHFloat(-15, 0x200), mkFloat(-15, 0)) testConv("subnormal with exp rounding")(mkFloat(-15, 0x7FE000), mkHFloat(-14, 0), mkFloat(-14, 0)) }
Example 22
Source File: MongoObservableReactivePublisherTest.scala From scala-commons with MIT License | 5 votes |
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 23
Source File: ParentTest.scala From Soteria with MIT License | 5 votes |
package com.leobenkel.soteria import org.apache.commons.logging.{Log, LogFactory} import org.scalactic.source.Position import org.scalatest.{FunSuite, Tag} trait ParentTest extends FunSuite { lazy val log: Log = LogFactory.getLog(this.getClass) protected def assertEquals[T]( expected: T, result: T )( implicit pos: Position ): Unit = { assertResult(expected)(result) () } override protected def test( testName: String, testTags: Tag* )( testFun: => Any )( implicit pos: Position ): Unit = { super.test(testName, testTags: _*) { log.debug(s">>> Starting - $testName") testFun } } def time[R](block: => R): (R, Long) = { val t0 = System.nanoTime() val result = block val t1 = System.nanoTime() val time_ns: Long = t1 - t0 (result, time_ns) } }
Example 24
Source File: RestApiTest.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash package rest import com.avsystem.commons._ import io.udash.rest.raw.RawRest import io.udash.rest.raw.RawRest.HandleRequest import org.scalactic.source.Position import org.scalatest.concurrent.ScalaFutures import org.scalatest.funsuite.AnyFunSuite abstract class RestApiTest extends AnyFunSuite with ScalaFutures { final val serverHandle: RawRest.HandleRequest = RawRest.asHandleRequest[RestTestApi](RestTestApi.Impl) def clientHandle: RawRest.HandleRequest lazy val proxy: RestTestApi = RawRest.fromHandleRequest[RestTestApi](clientHandle) def testCall[T](call: RestTestApi => Future[T])(implicit pos: Position): Unit = assert( call(proxy).wrapToTry.futureValue.map(mkDeep) == call(RestTestApi.Impl).catchFailures.wrapToTry.futureValue.map(mkDeep) ) def mkDeep(value: Any): Any = value match { case arr: Array[_] => IArraySeq.empty[AnyRef] ++ arr.iterator.map(mkDeep) case _ => value } } trait RestApiTestScenarios extends RestApiTest { test("trivial GET") { testCall(_.trivialGet) } test("failing GET") { testCall(_.failingGet) } test("more failing GET") { testCall(_.moreFailingGet) } test("complex GET") { testCall(_.complexGet(0, "a/ +&", 1, "b/ +&", 2, "ć/ +&", 3, "ó /&f")) } test("multi-param body POST") { testCall(_.multiParamPost(0, "a/ +&", 1, "b/ +&", 2, "ć/ +&", 3, "l\"l")) } test("single body PUT") { testCall(_.singleBodyPut(RestEntity(RestEntityId("id"), "señor"))) } test("form POST") { testCall(_.formPost("ó", "ą=ę", 42)) } test("prefixed GET") { testCall(_.prefix("", "h0", "q0").subget(0, 1, 2)) } test("custom response with headers") { testCall(_.customResponse("walue")) } test("binary request and response") { testCall(_.binaryEcho(Array.fill[Byte](5)(5))) } test("large binary request and response") { testCall(_.binaryEcho(Array.fill[Byte](1024 * 1024)(5))) } test("body using third party type") { testCall(_.thirdPartyBody(HasThirdParty(ThirdParty(5)))) } } class DirectRestApiTest extends RestApiTestScenarios { def clientHandle: HandleRequest = serverHandle }
Example 25
Source File: AsyncUdashSharedTest.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.testing import org.scalactic.source.Position import org.scalajs.dom import org.scalatest.{Assertion, Succeeded} import scala.concurrent.{ExecutionContext, Future, Promise} import scala.scalajs.concurrent.JSExecutionContext import scala.scalajs.js.Date import scala.util.{Failure, Success} trait AsyncUdashSharedTest extends AsyncUdashSharedTestBase { override implicit def executionContext: ExecutionContext = JSExecutionContext.queue override def retrying(code: => Any)(implicit patienceConfig: PatienceConfig, pos: Position): Future[Assertion] = { val start = Date.now() val p = Promise[Assertion] var lastEx: Option[Throwable] = None def startTest(): Unit = { dom.window.setTimeout(() => { if (patienceConfig.timeout.toMillis > Date.now() - start) { try { code p.complete(Success(Succeeded)) } catch { case ex: Throwable => lastEx = Some(ex) startTest() } } else { p.complete(Failure(lastEx.getOrElse(RetryingTimeout()))) } }, patienceConfig.interval.toMillis.toDouble) } startTest() p.future } }
Example 26
Source File: SerializationIntegrationTestBase.scala From udash-core with Apache License 2.0 | 5 votes |
package io.udash.rpc import com.avsystem.commons.serialization.{GenCodec, Input, Output} import io.udash.testing.UdashSharedTest import org.scalactic.source.Position import scala.util.Random class SerializationIntegrationTestBase extends UdashSharedTest with Utils { val repeats = 1000 def tests(implicit pos: Position): Unit = { "serialize and deserialize all types" in { for (i <- 1 to repeats) { def cc() = TestCC(Random.nextInt(), Random.nextLong(), 123, Random.nextBoolean(), Random.nextString(200), List.fill(Random.nextInt(200))('a')) def ncc() = NestedTestCC(Random.nextInt(), cc(), cc()) def dncc(counter: Int = 0): DeepNestedTestCC = if (counter < 200) DeepNestedTestCC(ncc(), dncc(counter + 1)) else DeepNestedTestCC(ncc(), null) val test: DeepNestedTestCC = dncc() val serialized = write(test) val deserialized = read[DeepNestedTestCC](serialized) deserialized should be(test) } } "serialize and deserialize types with custom gencodec" in { implicit def optionGencodec[T: GenCodec]: GenCodec[Option[T]] = new GenCodec[Option[T]] { override def write(output: Output, value: Option[T]): Unit = value match { case Some(v) => implicitly[GenCodec[T]].write(output, v) case None => output.writeNull() } override def read(input: Input): Option[T] = if (input.readNull()) None else Some(implicitly[GenCodec[T]].read(input)) } val testOpts = Seq( None, Some(10L), Some(Long.MaxValue) ) testOpts.foreach(opt => { val serialized = write(opt) val deserialized = read[Option[Long]](serialized) deserialized should be(opt) }) } } }
Example 27
Source File: HiveVersionSuite.scala From XSQL with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.hive.client import org.apache.hadoop.conf.Configuration import org.scalactic.source.Position import org.scalatest.Tag import org.apache.spark.SparkFunSuite import org.apache.spark.sql.hive.HiveUtils private[client] abstract class HiveVersionSuite(version: String) extends SparkFunSuite { override protected val enableAutoThreadAudit = false protected var client: HiveClient = null protected def buildClient( hadoopConf: Configuration, sharesHadoopClasses: Boolean = true): HiveClient = { // Hive changed the default of datanucleus.schema.autoCreateAll from true to false and // hive.metastore.schema.verification from false to true since 2.0 // For details, see the JIRA HIVE-6113 and HIVE-12463 if (version == "2.0" || version == "2.1" || version == "2.2" || version == "2.3") { hadoopConf.set("datanucleus.schema.autoCreateAll", "true") hadoopConf.set("hive.metastore.schema.verification", "false") } HiveClientBuilder.buildClient( version, hadoopConf, HiveUtils.formatTimeVarsForHiveClient(hadoopConf), sharesHadoopClasses = sharesHadoopClasses) } override def suiteName: String = s"${super.suiteName}($version)" override protected def test(testName: String, testTags: Tag*)(testFun: => Any) (implicit pos: Position): Unit = { super.test(s"$version: $testName", testTags: _*)(testFun) } }