org.scalatest.FunSpec Scala Examples
The following examples show how to use org.scalatest.FunSpec.
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: ScalaTestDataGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.{ WithModel, string_formats_yaml } import org.scalatest.{ FunSpec, MustMatchers } class ScalaTestDataGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "test_data/" describe("ScalaGenerator should generate a test data generators") { (examples ++ model).foreach { file => testScalaFormParserGenerator(file) } } def testScalaFormParserGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).generateGenerators(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 2
Source File: MathExpScannerSuite.scala From math-expression-parser with MIT License | 5 votes |
package io.github.facaiy.math.expression.compiler.scanner import org.scalatest.FunSpec import io.github.facaiy.math.expression.MathExpScannerError class MathExpScannerSuite extends FunSpec { describe("For tokens") { import io.github.facaiy.math.expression.compiler.scanner.MathExpScanner._ def parse(token: Parser[MathExpToken]) (expression: String): Either[MathExpScannerError, MathExpToken] = { MathExpScanner.parse(token, expression) match { case NoSuccess(msg, next) => Left(MathExpScannerError(msg)) case Success(result, next) => Right(result) } } it("float") { val p = parse(MathExpScanner.number) _ // Float assert(p(".1") === Right(NUMBER(0.1))) assert(p("1.") === Right(NUMBER(1))) assert(p("1f") === Right(NUMBER(1))) assert(p("1.0") === Right(NUMBER(1))) assert(p("-1.0") === Right(NUMBER(-1.0))) assert(p("1.02") === Right(NUMBER(1.02))) // Int assert(p("1") === Right(NUMBER(1))) // Long assert(p("1L") === Right(NUMBER(1))) // Invaild assert(p("+1.0").isLeft) } it("variable") { val p = parse(MathExpScanner.variable) _ assert(p("$hello") === Right(VAR_NAME("hello"))) assert(p("hello").isLeft) assert(p("$1hello").isLeft) } } describe("For math expression") { it("parse string to tokens correctly") { val expression = "1.0 + 2 * $data - power(2, 10) / 4." assert( MathExpScanner(expression) === Right( List(NUMBER(1), ADD, NUMBER(2), MULTIPLY, VAR_NAME("data"), MINUS, FUNC_NAME("power"), LEFT_PARENTHESIS, NUMBER(2), COMMA, NUMBER(10), RIGHT_PARENTHESIS, DIVIDE, NUMBER(4)))) } } }
Example 3
Source File: MathExpParserSuite.scala From math-expression-parser with MIT License | 5 votes |
package io.github.facaiy.math.expression.compiler.parser import org.scalatest.FunSpec import io.github.facaiy.math.expression.compiler.MathExpCompiler class MathExpParserSuite extends FunSpec { describe("For math expression") { it("parse string to tokens correctly") { val expression = "1.0 ** 2 + 2 * $data - power(2, 10) / 4." val tokens = MathExpCompiler(expression) assert(tokens === Right( Operator2("-", Operator2("+", Operator2("**", Constant(1.0), Constant(2.0)), Operator2("*", Constant(2.0), Variable("data"))), Operator2("/", OperatorN("power", List(Constant(2.0), Constant(10.0))), Constant(4.0))))) } } }
Example 4
Source File: MathExpSuite.scala From math-expression-parser with MIT License | 5 votes |
package io.github.facaiy.math.expression import org.scalatest.FunSpec class MathExpSuite extends FunSpec { describe("MathExp") { it("valid string") { val str = "1.0 + sqrt(2 * $a1) + $a2 ** 2" val ex = MathExp.parse(str) assert(ex.eval(Map("a1" -> 0.0, "a2" -> 0)) === 1) assert(ex.eval(Map("a1" -> 2.0, "a2" -> 1)) === 4) assert(ex.eval(Map("a1" -> 8.0, "a2" -> 2)) === 9) } it("valid string - two arguments operation") { val str = "pow($a1, $a2)" val ex = MathExp.parse(str) assert(ex.eval(Map("a1" -> 2, "a2" -> 0)) === 1) assert(ex.eval(Map("a1" -> 2, "a2" -> 10)) === 1024) } it("invalid string") { val str = "1.0 + sqrt( - 2" assertThrows[IllegalArgumentException] { MathExp.parse(str) } } } }
Example 5
Source File: RandomForestRegressionSpec.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.core.regression import com.truecar.mleap.core.tree.{ContinuousSplit, InternalNode, LeafNode} import com.truecar.mleap.core.linalg import org.scalatest.FunSpec class RandomForestRegressionSpec extends FunSpec { describe("#predict") { it("uses the forest to make a prediction") { val tree1 = buildDecisionTree(.5, 0, goLeft = true) val tree2 = buildDecisionTree(.75, 1, goLeft = false) val tree3 = buildDecisionTree(.1, 2, goLeft = true) val regression = RandomForestRegression(Seq(tree1, tree2, tree3), 5) val features = linalg.Vector.dense(Array(.2, .8, .4)) assert(tree1.predict(features) == .5) assert(tree2.predict(features) == .75) assert(tree3.predict(features) == .1) assert(regression.predict(features) == (.5 + .75 + .1) / 3) } } private def buildDecisionTree(prediction: Double, featureIndex: Int, goLeft: Boolean): DecisionTreeRegression = { val node1 = LeafNode(prediction, .33) val node2 = LeafNode(42.34, 6.7) val split = ContinuousSplit(featureIndex, .5) val node = if(goLeft) { InternalNode(.77, 6.7, 3.4, node1, node2, split) } else { InternalNode(.77, 6.7, 3.4, node2, node1, split) } DecisionTreeRegression(node, 5) } }
Example 6
Source File: DecisionTreeRegressionSpec.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.core.regression import com.truecar.mleap.core.tree.{ContinuousSplit, InternalNode, LeafNode} import com.truecar.mleap.core.linalg import org.scalatest.FunSpec class DecisionTreeRegressionSpec extends FunSpec { describe("#predict") { it("returns the prediction for the decision tree") { val leftNode = LeafNode(.78, .33) val rightNode = LeafNode(.34, 6.7) val split = ContinuousSplit(0, .5) val node = InternalNode(.77, 6.7, 3.4, leftNode, rightNode, split) val features = linalg.Vector.dense(Array(0.3, 1.0, 43.23, -21.2, 66.7)) val regression = DecisionTreeRegression(node, 5) assert(regression.predict(features) == .78) } } }
Example 7
Source File: NodeSpec.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.core.tree import org.scalatest.FunSpec import com.truecar.mleap.core.linalg class InternalNodeSpec extends FunSpec { describe("#typeName") { it("is InternalNode") { } } describe("#predictImpl") { val leftNode = LeafNode(.45, 5.6) val rightNode = LeafNode(.33, 3.5) val features = linalg.Vector.dense(Array(0.3)) describe("when split goes left") { it("returns the left node") { val node = InternalNode(.37, 5.5, .88, leftNode, rightNode, ContinuousSplit(0, 0.4)) assert(node.predictImpl(features) == leftNode) } } describe("when split goes right") { it("returns the right node") { val node = InternalNode(.37, 5.5, .88, leftNode, rightNode, ContinuousSplit(0, 0.2)) assert(node.predictImpl(features) == rightNode) } } } } class LeafNodeSpec extends FunSpec { describe("#predictImpl") { it("returns itself") { val node = LeafNode(.45, 5.6) assert(node.predictImpl(linalg.Vector.dense(Array(.67))) == node) } } }
Example 8
Source File: VectorAssemblerSpec.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.core.feature import com.truecar.mleap.core.linalg import org.scalatest.FunSpec class VectorAssemblerSpec extends FunSpec { describe("#apply") { it("assembles doubles and vectors into a new vector") { val assembler = VectorAssembler.default val expectedArray = Array(45.0, 76.8, 23.0, 45.6, 0.0, 22.3, 45.6, 0.0, 99.3) assert(assembler(45.0, 76.8, linalg.Vector.dense(Array(23.0, 45.6)), linalg.Vector.sparse(5, Array(1, 2, 4), Array(22.3, 45.6, 99.3))).toArray.sameElements(expectedArray)) } } }
Example 9
Source File: StandardScalerSpec.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.core.feature import com.truecar.mleap.core.linalg import org.scalatest.FunSpec class StandardScalerSpec extends FunSpec { describe("#apply") { describe("with mean") { it("scales based off of the mean") { val scaler = StandardScaler(None, Some(linalg.Vector.dense(Array(50.0, 20.0, 30.0)))) val expectedVector = Array(5.0, 5.0, 3.0) assert(scaler(linalg.Vector.dense(Array(55.0, 25.0, 33.0))).toArray.sameElements(expectedVector)) } } describe("with stdev") { it("scales based off the standard deviation") { val scaler = StandardScaler(Some(linalg.Vector.dense(Array(2.5, 8.0, 10.0))), None) val expectedVector = Array(1.6, .4375, 1.0) assert(scaler(linalg.Vector.dense(Array(4.0, 3.5, 10.0))).toArray.sameElements(expectedVector)) } } describe("with mean and stdev") { it("scales based off the mean and standard deviation") { val scaler = StandardScaler(Some(linalg.Vector.dense(Array(2.5, 8.0, 10.0))), Some(linalg.Vector.dense(Array(50.0, 20.0, 30.0)))) val expectedVector = Array(1.6, .4375, 1.0) assert(scaler(linalg.Vector.dense(Array(54.0, 23.5, 40.0))).toArray.sameElements(expectedVector)) } } } }
Example 10
Source File: StringIndexerSpec.scala From mleap with Apache License 2.0 | 5 votes |
package com.truecar.mleap.core.feature import org.scalatest.FunSpec class StringIndexerSpec extends FunSpec { describe("#apply") { it("returns the index of the string") { val indexer = StringIndexer(Array("hello", "there", "dude")) assert(indexer("hello") == 0.0) assert(indexer("there") == 1.0) assert(indexer("dude") == 2.0) } } }
Example 11
Source File: ScalaSecurityGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{ FunSpec, MustMatchers } class ScalaSecurityGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "security/" describe("ScalaSecurityGenerator should generate security plumbing files") { examples.foreach { ast => testScalaSecurityGenerator(ast) } } describe("ScalaSecurityGenerator should generate security helper files") { examples.foreach { ast => testScalaSecurityExtractorsGenerator(ast) } } def testScalaSecurityGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaSecurity(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } def testScalaSecurityExtractorsGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaSecurityExtractors(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "extractor.scala") if (expected.isEmpty) dump(scalaModel, name, "extractor.scala") clean(scalaModel) mustBe clean(expected) } } }
Example 12
Source File: ScalaModelGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{ FunSpec, MustMatchers } class ScalaModelGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder: String = super.expectationsFolder + "model/" describe("ScalaGenerator should generate scala model") { (model ++ examples ++ validations).foreach { ast => testScalaModelGenerator(ast) } } def testScalaModelGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).generateModel(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 13
Source File: GraphHelperSpec.scala From cave with MIT License | 5 votes |
package views.alerts import org.scalatest.{FunSpec, Matchers} import com.gilt.cavellc.models.Aggregator.Sum import com.gilt.cavellc.models.AlertMetric class GraphHelperSpec extends FunSpec with Matchers { describe("generateLink") { it("should generate the correct link if there is no team and no aggregator, period or tags") { val expected = "/organizations/myOrg/metrics/graph/my_metric?aggregator=count&period=1&tags=" GraphHelper.generateLink("myOrg", None, AlertMetric("my_metric", Map.empty[String, String], None, None)) should be(expected) } it("should generate the correct link if there is an aggregator, period and tags") { val expected = "/organizations/myOrg/metrics/graph/my_metric?aggregator=sum&period=5&tags=foo:bar,boom:bang" GraphHelper.generateLink("myOrg", None, AlertMetric("my_metric", Map("foo" -> "bar", "boom" -> "bang"), Some(Sum), Some(300))) should be(expected) } it("should generate a link even if the period isn't an exact match") { val expected = "/organizations/myOrg/metrics/graph/my_metric?aggregator=sum&period=5&tags=foo:bar,boom:bang" GraphHelper.generateLink("myOrg", None, AlertMetric("my_metric", Map("foo" -> "bar", "boom" -> "bang"), Some(Sum), Some(280))) should be(expected) } it("should generate a link even if the period is far too big") { val expected = "/organizations/myOrg/metrics/graph/my_metric?aggregator=sum&period=1440&tags=foo:bar,boom:bang" GraphHelper.generateLink("myOrg", None, AlertMetric("my_metric", Map("foo" -> "bar", "boom" -> "bang"), Some(Sum), Some(100000))) should be(expected) } } }
Example 14
Source File: ScalaFormParserGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{ FunSpec, MustMatchers } class ScalaFormParserGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "form_parsers/" describe("ScalaGenerator should generate a form parser") { examples.foreach { file => testScalaFormParserGenerator(file) } } def testScalaFormParserGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaFormParsers(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 15
Source File: ScalaControllerGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{ FunSpec, MustMatchers } class ScalaControllerGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "controllers/" describe("ScalaSecurityGenerator should generate controlers") { (model ++ examples).foreach { ast => testScalaControllerGenerator(ast) } } def testScalaControllerGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val expected = asInFile(name, "scala") val scalaModel = new ScalaGenerator(model).playScalaControllers(name, ast.model.packageName.getOrElse(name), expected) if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 16
Source File: ScalaBaseControllerGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model._ import org.scalatest.{ FunSpec, MustMatchers } class ScalaBaseControllerGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "base_controllers/" describe("ScalaBaseControllerGenerator should generate controller bases") { (model ++ examples).foreach { ast => testScalaBaseControllerGenerator(ast) } } def testScalaBaseControllerGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaControllerBases(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "base.scala") if (expected.isEmpty) dump(scalaModel, name, "base.scala") clean(scalaModel) mustBe clean(expected) } } }
Example 17
Source File: ScalaPlayTestsGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{ FunSpec, MustMatchers } class ScalaPlayTestsGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "tests/" describe("ScalaGenerator should generate tests") { (examples ++ model ++ validations).foreach { file => testScalaFormParserGenerator(file) } } def testScalaFormParserGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaTests(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 18
Source File: ScalaValidatorsGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.{ WithModel, all_of_imports_yaml } import org.scalatest.{ FunSpec, MustMatchers } class ScalaValidatorsGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "validation/" describe("ScalaGenerator should generate play validators") { (model ++ examples ++ validations).foreach { ast => testScalaModelGenerator(ast) } } def testScalaModelGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playValidators(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 19
Source File: ScalaMarshallersGeneratorIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{ FunSpec, MustMatchers } class ScalaMarshallersGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "marshallers/" describe("ScalaGenerator should generate marshallers") { examples.foreach { file => testScalaMarshallersGenerator(file) } } def testScalaMarshallersGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaMarshallers(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 20
Source File: TypeConverterTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{ FunSpec, MustMatchers } class TypeConverterTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "types/" val modelFixtures = new File(resourcesPath + "model").listFiles val exampleFixtures = new File(resourcesPath + "examples").listFiles describe("Strict Swagger Parser model") { modelFixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testTypeConverter(file) } } describe("Strict Swagger Parser examples") { exampleFixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testTypeConverter(file) } } def testTypeConverter(file: File): Unit = { it(s"should parse the yaml swagger file ${file.getName} as specification") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val typeDefs = ModelConverter.fromModel(base, model, Some(file)).typeDefs val typeMap = typeDefs map { case (k, v) => k -> ("\n\t" + de.zalando.apifirst.util.ShortString.toShortString("\t\t")(v)) } val typesStr = typeMap.toSeq.sortBy(_._1.parts.size).map(p => p._1 + " ->" + p._2).mkString("\n") val expected = asInFile(file, "types") if (expected.isEmpty) dump(typesStr, file, "types") clean(typesStr) mustBe clean(expected) } } }
Example 21
Source File: SecurityDefinitionDeserializerTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.swagger.strictModel._ import org.scalatest.{ MustMatchers, FunSpec } class SecurityDefinitionDeserializerTest extends FunSpec with MustMatchers with ExpectedResults { val file = new File(resourcesPath + "examples/security.api.yaml") describe("SecurityDefinitionDeserializer") { it(s"should parse security definitions in the ${file.getName}") { val (uri, model) = StrictYamlParser.parse(file) val result = model.securityDefinitions result.size mustBe 6 result("petstoreImplicit") mustBe a[Oauth2ImplicitSecurity] result("githubAccessCode") mustBe a[Oauth2AccessCodeSecurity] result("petstorePassword") mustBe a[Oauth2PasswordSecurity] result("justBasicStuff") mustBe a[BasicAuthenticationSecurity] result("petstoreApplication") mustBe a[Oauth2ApplicationSecurity] result("internalApiKey") mustBe a[ApiKeySecurity] } } }
Example 22
Source File: StrictParseExamplesTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import java.net.URI import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{ FunSpec, MustMatchers } class StrictParseExamplesTest extends FunSpec with MustMatchers with ExpectedResults { val fixtures = new File(resourcesPath + "examples").listFiles ++ new File(resourcesPath + "schema_examples").listFiles describe("Strict Swagger Parser") { fixtures.filter(_.getName.endsWith(".yaml")).foreach { file => it(s"should parse the yaml swagger file ${file.getName} as specification") { val result = StrictYamlParser.parse(file) result._1 mustBe a[URI] result._2 mustBe a[SwaggerModel] } } } }
Example 23
Source File: SecurityConverterIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{ FunSpec, MustMatchers } class SecurityConverterIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "security_definitions/" val fixtures = new File(resourcesPath + "examples").listFiles describe("Swagger Security Converter") { fixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testSecurityConverter(file) } } def testSecurityConverter(file: File): Unit = { it(s"should convert security definitions from ${file.getName}") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val securityDefs = SecurityConverter.convertDefinitions(model.securityDefinitions) val fullResult = securityDefs.mkString("\n") val expected = asInFile(file, "types") if (expected.isEmpty) dump(fullResult, file, "types") clean(fullResult) mustBe clean(expected) } } }
Example 24
Source File: TimeUtils$Test.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.utils.time import org.scalatest.FunSpec class TimeUtils$Test extends FunSpec { describe("TimeUtils transforms UTC to timestamp and vice-versa") { it("should be reversible for Universal format") { val actual = TimeUtils.timestampToUniversalTime(TimeUtils.universalTimeToTimeStamp("2016-03-30 15:34:27")) assert(actual === "2016-03-30 15:34:27") } it("should be reversible for File format") { val actual = TimeUtils.timestampToFileTime(TimeUtils.fileTimeToTimeStamp("2016-03-30_15.34.27")) assert(actual === "2016-03-30_15.34.27") } } describe("TimeUtils ensure all date representations are UTC") { it("should read timestamps in UTC") { assert(TimeUtils.universalTimeToTimeStamp("2016-03-30 13:34:27") === 1459344867000L) assert(TimeUtils.fileTimeToTimeStamp("2016-03-30_13.34.27") === 1459344867000L) } it("should position 0 at 1970-01-01 00:00:00") { assert(TimeUtils.timestampToUniversalTime(0L) === "1970-01-01 00:00:00") } } }
Example 25
Source File: SassCompilerTest.scala From sbt-sass with Apache License 2.0 | 5 votes |
package org.madoushi.sbt.sass import java.io.File import org.scalatest.{FunSpec, MustMatchers} class SassCompilerTest extends FunSpec with MustMatchers { describe("SassCompiler") { describe("using well formed scss input") { describe("without includes") { it("should compile") { val input = new File(getClass.getResource("/org/madoushi/sbt/sass/well-formed.scss").toURI) val output = File.createTempFile("sbt-sass-test", ".css") val outputMinified = File.createTempFile("sbt-sass-test", ".min.css") val processOutput = SassCompiler.compileWithDefaultSass(input, output, Some(outputMinified)) val css = scala.io.Source.fromFile(output).mkString val cssMin = scala.io.Source.fromFile(outputMinified).mkString css.length must be > cssMin.length val testCss = css.replaceAll("\\/\\*.*?\\*\\/", "").replaceAll("\\s+", "") testCss must include(".test{font-size:10px;}") testCss must include(".test.hidden{display:none;}") processOutput.size must be(1) processOutput.head must include("well-formed.scss") } } describe("with includes") { it("should compile") { val input = new File(getClass.getResource("/org/madoushi/sbt/sass/well-formed-using-import.scss").toURI) val output = File.createTempFile("sbt-sass-test", ".css") val outputMinified = File.createTempFile("sbt-sass-test", ".min.css") val processOutput = SassCompiler.compileWithDefaultSass(input, output, Some(outputMinified)) val css = scala.io.Source.fromFile(output).mkString val cssMin = scala.io.Source.fromFile(outputMinified).mkString css.length must be > cssMin.length val testCss = css.replaceAll("\\/\\*.*?\\*\\/", "").replaceAll("\\s+", "") testCss must include(".test-import{font-weight:bold;}") testCss must include(".test{font-size:10px;}") testCss must include(".test.hidden{display:none;}") processOutput.size must be(2) println(processOutput) processOutput.find(_.contains("_well-formed-import.scss")) must not be None } } } describe("using broken scss input") { it("should throw an exception") { val input = new File(getClass.getResource("/org/madoushi/sbt/sass/broken-input.scss").toURI) val output = File.createTempFile("sbt-sass-test", ".css") val outputMinified = File.createTempFile("sbt-sass-test", ".min.css") val exception = the [SassCompilerException] thrownBy SassCompiler.compileWithDefaultSass(input, output, Some(outputMinified)) exception.getMessage must include("Invalid CSS after") } } } }
Example 26
Source File: ParseResultSpec.scala From vizsql with Apache License 2.0 | 5 votes |
package com.criteo.vizatra.vizsql.js.common import org.scalatest.{FunSpec, Matchers} import com.criteo.vizatra.vizsql import com.criteo.vizatra.vizsql.INTEGER import scala.scalajs.js.JSON class ParseResultSpec extends FunSpec with Matchers { describe("Column") { describe("from()") { it("converts scala Column to JS object") { val col = Column.from(vizsql.Column("col1", INTEGER(true))) JSON.stringify(col) shouldEqual """{"name":"col1","type":"integer","nullable":true}""" } } } describe("Table") { describe("from()") { it("converts scala Table to JS object") { val table = Table.from(vizsql.Table("table1", List(vizsql.Column("col1", INTEGER(true)))), Some("schema1")) JSON.stringify(table) shouldEqual """{"name":"table1","columns":[{"name":"col1","type":"integer","nullable":true}],"schema":"schema1"}""" } } } }
Example 27
Source File: ReleaseableSemanticVersionSpec.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import com.rallyhealth.sbt.versioning.SemVerReleaseType.{Major, Minor, Patch, ReleaseableSemanticVersion} import org.scalactic.TypeCheckedTripleEquals import org.scalatest.{FunSpec, Matchers} class ReleaseableSemanticVersionSpec extends FunSpec with Matchers with TypeCheckedTripleEquals { private val testCases = Seq( TestCase( name = "Clean snapshots should be bumped, for everything but patch", version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false, "0123abc", 1), expectedReleases = Seq( Patch -> ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false), Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = false), Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = false) ) ), TestCase( name = "Dirty snapshots should stay dirty", version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true, "0123abc", 1), expectedReleases = Seq( Patch -> ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true), Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = true), Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = true) ) ), TestCase( name = "Snapshot identifiers should be stripped", version = SnapshotVersion(1, 2, 3, Seq("identifier"), isDirty = true, "0123abc", 1), expectedReleases = Seq( Patch -> ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true), Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = true), Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = true) ) ), TestCase( name = "Release versions should be bumped", version = ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false), expectedReleases = Seq( Patch -> ReleaseVersion(1, 2, 4, SemVerIdentifierList.empty, isDirty = false), Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = false), Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = false) ) ), TestCase( name = "Release identifiers should be stripped", version = ReleaseVersion(1, 2, 3, Seq("identifier"), isDirty = false), expectedReleases = Seq( Patch -> ReleaseVersion(1, 2, 4, SemVerIdentifierList.empty, isDirty = false), Minor -> ReleaseVersion(1, 3, 0, SemVerIdentifierList.empty, isDirty = false), Major -> ReleaseVersion(2, 0, 0, SemVerIdentifierList.empty, isDirty = false) ) ) ) for (tc <- testCases) { describe(s"${tc.name} for ${tc.version.toString}") { for ((releaseType, expected) <- tc.expectedReleases) { it(s"$releaseType -> $expected") { val actual = tc.version.release(releaseType) assert(actual === expected) } } } } } case class TestCase( name: String, version: SemanticVersion, expectedReleases: Seq[(SemVerReleaseType, SemanticVersion)] )
Example 28
Source File: HashSemVerIdentifierSpec.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import org.scalatest.FunSpec import scala.util.Random class HashSemVerIdentifierSpec extends FunSpec { describe("constructor") { it("without 'g' prefix") { val tag = HashSemVerIdentifier("0123456") assert(tag.hash === "0123456") assert(tag.toString === "0123456") } it("with 'g' prefix") { intercept[IllegalArgumentException] { HashSemVerIdentifier("g0123456") } } } describe("safeMake") { it("without 'g' prefix") { val tag = HashSemVerIdentifier.safeMake("0123456") assert(tag.hash === "0123456") assert(tag.toString === "0123456") } it("with 'g' prefix") { val tag = HashSemVerIdentifier.safeMake("g0123456") assert(tag.hash === "0123456") assert(tag.toString === "0123456") } } describe("hash length") { it("less than 7") { val random = new Random (0 until 7).foreach { len => val hash = Iterator.continually(random.nextInt(10)).take(len).map(_.toString).mkString("") intercept[IllegalArgumentException] { HashSemVerIdentifier(hash) } } } it("more than 40") { val random = new Random (41 until 50).foreach { len => val hash = Iterator.continually(random.nextInt(10)).take(len).map(_.toString).mkString("") // no exception (Git claims only 40 but there's no reason we can't support more) HashSemVerIdentifier(hash) } } } } object HashSemVerIdentifierSpec { def expandHash(abbreviatedHash: String): String = abbreviatedHash.padTo(40, '0') }
Example 29
Source File: LowerBoundedSemanticVersionSpec.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import com.rallyhealth.sbt.versioning.LowerBoundedSemanticVersion._ import org.scalatest.{FunSpec, Matchers} import scala.language.implicitConversions class LowerBoundedSemanticVersionSpec extends FunSpec with Matchers { private val hash1 = HashSemVerIdentifier("0123abc") // for these tests we need a full hash, not an abbreviation private val hashAndCount1 = HashAndCount(hash1, 1) describe("BoundedSemanticVersion") { describe("ReleaseVersion") { it("equal bound") { val version = ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false) val bound = LowerBound(1, 2, 3) val result = version.lowerBound(bound, hashAndCount1) assert(result === version) } it("lower bound") { val version = ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false) val bound = LowerBound(1, 0, 0) val result = version.lowerBound(bound, hashAndCount1) assert(result === version) } it("higher bound") { val version = ReleaseVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false) val bound = LowerBound(1, 2, 4) an[IllegalArgumentException] shouldBe thrownBy { version.lowerBound(bound, hashAndCount1) } } } describe("SnapshotVersion") { it("equal bound") { val version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false, hashAndCount1, 1) val result = version.lowerBound(LowerBound(1, 2, 3), hashAndCount1) assert(result === version) } it("lower bound") { val version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false, hashAndCount1, 1) val bound = LowerBound(1, 0, 0) val result = version.lowerBound(bound, hashAndCount1) assert(result === version) assert(result.toString === s"1.2.3-1-$hash1-SNAPSHOT") } it("greater bound") { val version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false, hashAndCount1, 1) val bound = LowerBound(2, 0, 0) val result = version.lowerBound(bound, hashAndCount1) assert(result.toString === s"2.0.0-1-$hash1-SNAPSHOT") } it("version is dirty") { val version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = true, hashAndCount1, 1) val bound = LowerBound(2, 0, 0) val result = version.lowerBound(bound, hashAndCount1) assert(result.toString === s"2.0.0-1-$hash1-dirty-SNAPSHOT") } it("bound is dirty") { val version = SnapshotVersion(1, 2, 3, SemVerIdentifierList.empty, isDirty = false, hashAndCount1, 1) val bound = LowerBound(2, 0, 0) val result = version.lowerBound(bound, hashAndCount1) assert(result.toString === s"2.0.0-1-$hash1-SNAPSHOT") } it("identifiers") { val version = SnapshotVersion(1, 0, 0, Seq("rc.0"), isDirty = false, hashAndCount1, 1) val bound = LowerBound(2, 0, 0) val result = version.lowerBound(bound, hashAndCount1) assert(result === SnapshotVersion(2, 0, 0, SemVerIdentifierList.empty, false, hashAndCount1, 1)) } } } implicit def hashAndCountAsHash(hc: HashAndCount): HashSemVerIdentifier = hc.hash }
Example 30
Source File: GitCommitSpec.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import com.rallyhealth.sbt.versioning.GitCommit._ import com.rallyhealth.sbt.versioning.HashSemVerIdentifierSpec._ import org.scalatest.FunSpec class GitCommitSpec extends FunSpec { describe("fromGitLog") { // Most of the weird test caes here from RCU it("without identifier") { val result = fromGitLog(s"${expandHash("dc96343")} (tag: v1.2.3) Setting version to 0.3.0", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags === Seq("v1.2.3")) } it("no tag") { val result = fromGitLog(s"${expandHash("dc96343")} Setting version to 0.3.0", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags.isEmpty) } it("ancient form of our tags -- we don't support them :p") { val result = fromGitLog(s"${expandHash("dc96343")} (tag: release/v1.99.0) Merge pull request #9964", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags === Seq("release/v1.99.0")) } it("junk tag") { val result = fromGitLog(s"${expandHash("dc96343")} (tag: JUNK) Setting version to 0.3.0", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags === Seq("JUNK")) } it("HEAD decoration but no tags") { val result = fromGitLog(s"${expandHash("dc96343")} (HEAD -> master) First version with 'real' code", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags.isEmpty) } it("decoration but no tag") { val result = fromGitLog(s"${expandHash("dc96343")} (upstream/SEIT) Merge pull request #9955", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags.isEmpty) } it("HEAD decorations with tag (before)") { val result = fromGitLog(s"${expandHash("dc96343")} (tag: v1.2.3, HEAD -> master) First version", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags === Seq("v1.2.3")) } it("multiple tags") { val result = fromGitLog(s"${expandHash("dc96343")} (tag: v1.92.1, tag: v1.92.0) Merge pull request #9606", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags === Seq("v1.92.1", "v1.92.0")) } it("tags are sorted") { val result = fromGitLog(s"${expandHash("dc96343")} (tag: v1.92.1, tag: v1.92.0, tag: v1.92.2) Stuff", 7) assert(result.fullHash === expandHash("dc96343")) assert(result.tags === Seq("v1.92.2", "v1.92.1", "v1.92.0")) assert(result.tags.head === "v1.92.2") } } }
Example 31
Source File: StringSemVerIdentifierSpec.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import org.scalatest.FunSpec class StringSemVerIdentifierSpec extends FunSpec { // http://semver.org/#spec-item-9 it("from SemVer docs #9") { val versionsFromDocs = Seq("1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-0.3.7", "1.0.0-x.7.z.92") val identifiersFromDocs = versionsFromDocs.map(_.dropWhile(_ != '-').drop(1)) // drop prefix val identifiers = identifiersFromDocs.map(StringSemVerIdentifier(_).value) assert(identifiers === identifiersFromDocs) val versions = versionsFromDocs.flatMap(SemanticVersion.fromString).map(_.toString) assert(versions === versionsFromDocs) } }
Example 32
Source File: SemVerIdentifierListSpec.scala From sbt-git-versioning with MIT License | 5 votes |
package com.rallyhealth.sbt.versioning import com.rallyhealth.sbt.versioning.StringSemVerIdentifier.string2StringIdentifier import org.scalatest.FunSpec class SemVerIdentifierListSpec extends FunSpec { describe("even lists") { it("equal") { val x = SemVerIdentifierList(Seq("a", "b")) val y = SemVerIdentifierList(Seq("a", "b")) assert(x === y) assert(y === x) } it("head !=") { val x = SemVerIdentifierList(Seq("a", "b")) val y = SemVerIdentifierList(Seq("c", "b")) assert(x < y) assert(y > x) assert(x !== y) assert(y !== x) } it("last !=") { val x = SemVerIdentifierList(Seq("a", "b")) val y = SemVerIdentifierList(Seq("a", "c")) assert(x < y) assert(y > x) assert(x !== y) assert(y !== x) } it("empty") { val x = SemVerIdentifierList(Seq.empty) val y = SemVerIdentifierList(Seq.empty) assert(x === y) assert(y === x) } } describe("uneven lists") { it("one off") { val x = SemVerIdentifierList(Seq("a")) val y = SemVerIdentifierList(Seq("a", "b")) assert(x < y) assert(y > x) assert(x !== y) assert(y !== x) } it("one off (not equal)") { val x = SemVerIdentifierList(Seq("a")) val y = SemVerIdentifierList(Seq("b", "c")) assert(x < y) assert(y > x) assert(x !== y) assert(y !== x) } it("multiple off") { val x = SemVerIdentifierList(Seq("a")) val y = SemVerIdentifierList(Seq("a", "b", "c")) assert(x < y) assert(y > x) assert(x !== y) assert(y !== x) } it("multiple off (not equal)") { val x = SemVerIdentifierList(Seq("a")) val y = SemVerIdentifierList(Seq("b", "c", "d")) assert(x < y) assert(y > x) assert(x !== y) assert(y !== x) } it("one empty") { // an empty list of identifiers is considered GREATER than a non-empty list, see http://semver.org/#spec-item-11 val x = SemVerIdentifierList(Seq.empty) val y = SemVerIdentifierList(Seq("a", "b")) assert(x > y) assert(y < x) assert(x !== y) assert(y !== x) } } }
Example 33
Source File: FlamyContextTest.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.conf import com.flaminem.flamy.model.Variables import com.typesafe.config._ import com.typesafe.config.impl.{ConfigString, Parseable} import org.scalatest.FunSpec import scala.collection.JavaConversions._ import scala.collection.mutable class FlamyContextTest extends FunSpec { describe("a FlamyContext") { it("should correctly read variables"){ val context: FlamyContext = new FlamyContext( "flamy.model.dir.paths" -> "src/test/resources/test", "flamy.variables.path" -> "${flamy.model.dir.paths}/VARIABLES.properties" ) val expected: Variables = new Variables expected.put("DATE", "\"2014-01-01\"") expected.put("LOOKBACK_WINDOW", "90") expected.put("SINCE_DAY", "> \"2014-01-01\"") expected.put("SC_ARRAY", "a ; b ; c ; d") expected.put("COLON_ARRAY", "(a , b , c , d)") expected.put("partition:day", "\"2014-01-01\"") val actual: Variables = context.getVariables assert(expected === actual) } } }
Example 34
Source File: ItemNameTest.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.model import com.flaminem.flamy.model.names.{ItemName, SchemaName, TableName, TablePartitionName} import org.scalatest.FunSpec import scala.language.implicitConversions class ItemNameTest extends FunSpec { describe("a SchemaName") { it("should be recognised from a String"){ assert(ItemName("db").isInstanceOf[SchemaName]) } it("should not recognize incorrect Strings"){ intercept[Exception]{ItemName("db.table").asInstanceOf[SchemaName]} intercept[Exception]{ItemName("col = true").asInstanceOf[SchemaName]} } it("should have correct attributes"){ val schemaName = ItemName("db").asInstanceOf[SchemaName] assert(schemaName.name === "db") assert(schemaName.fullName === "db") } it("should have correct membership methods"){ val schemaName = ItemName("db").asInstanceOf[SchemaName] assert(schemaName.isInOrEqual("db")) assert(!schemaName.isInOrEqual("db.table")) assert(!schemaName.isInOrEqual("db.table/part1=val1/part2=val2")) assert(!schemaName.isInOrEqual("toto")) assert(!schemaName.isInOrEqual("db.toto")) assert(!schemaName.isInOrEqual("db.table/part1=val1/part2=toto")) } } describe("a TableName") { val name = "db.table" it("should be recognised from a String") { val itemName = ItemName(name) assert(itemName.isInstanceOf[TableName]) } it("should have correct attributes"){ val tableName = ItemName(name).asInstanceOf[TableName] assert(tableName.name === "table") assert(tableName.schemaName.name === "db") assert(tableName.fullName === "db.table") } it("should have correct membership methods"){ val tableName = ItemName(name).asInstanceOf[TableName] assert(tableName.isInSchema("db")) assert(!tableName.isInSchema("toto")) assert(tableName.isInOrEqual("db")) assert(tableName.isInOrEqual("db.table")) assert(!tableName.isInOrEqual("db.table/part1=val1/part2=val2")) assert(!tableName.isInOrEqual("toto")) assert(!tableName.isInOrEqual("db.toto")) assert(!tableName.isInOrEqual("db.table/part1=val1/part2=toto")) } } describe("a TablePartitionName") { val name = "db.table/part1=val1/part2=val2" it("should be recognised from a String"){ val itemName = ItemName(name) assert(itemName.isInstanceOf[TablePartitionName]) } it("should have correct attributes"){ val partitionName = ItemName(name).asInstanceOf[TablePartitionName] assert(partitionName.tableName.fullName=== "db.table") assert(partitionName.tableName.name === "table") assert(partitionName.schemaName.name === "db") assert(partitionName.partitionName === "part1=val1/part2=val2") } it("should have correct membership methods"){ val partitionName = ItemName(name).asInstanceOf[TablePartitionName] assert(partitionName.isInSchema("db")) assert(!partitionName.isInSchema("toto")) assert(partitionName.isInTable("db.table")) assert(!partitionName.isInTable("db")) assert(!partitionName.isInTable("db.toto")) assert(!partitionName.isInTable("toto.table")) assert(partitionName.isInOrEqual("db")) assert(partitionName.isInOrEqual("db.table")) assert(partitionName.isInOrEqual("db.table/part1=val1/part2=val2")) assert(!partitionName.isInOrEqual("toto")) assert(!partitionName.isInOrEqual("db.toto")) assert(!partitionName.isInOrEqual("db.table/part1=val1/part2=toto")) } } }
Example 35
Source File: HypermediaConverterTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.apifirst.Hypermedia.State import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{ FunSpec, MustMatchers } class HypermediaConverterTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "hypermedia/" val exampleFixtures = new File(resourcesPath + "extensions").listFiles describe("Strict Swagger Parser hypermedia converter") { exampleFixtures.filter(_.getName.startsWith("hypermedia.ok")).foreach { file => testTransitionsConverter(file) testStateDefinitions(file) } } def testTransitionsConverter(file: File): Unit = { it(s"should parse the yaml swagger file ${file.getName} with hypermedia information") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val ast = ModelConverter.fromModel(base, model, Some(file)) val hypermedia = ast.stateTransitions val expected = asInFile(file, "hypermedia") val media = State.toDot(hypermedia).mkString("\n") if (expected.isEmpty && media.nonEmpty) dump(media, file, "hypermedia") clean(media) mustBe clean(expected) } } def testStateDefinitions(file: File): Unit = { it(s"should parse the yaml swagger file ${file.getName} with state name information") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val ast = ModelConverter.fromModel(base, model, Some(file)) val targetStates = ast.calls.map(_.targetStates) val expected = asInFile(file, "states") val media = targetStates.mkString("\n") if (expected.isEmpty && media.nonEmpty) dump(media, file, "states") clean(media) mustBe clean(expected) } } }
Example 36
Source File: SimpleFileSystemWithoutTrashTest.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.utils.hadoop import org.apache.hadoop.fs.Trash import org.scalatest.FunSpec class SimpleFileSystemWithoutTrashTest extends FunSpec with FileSystemWithoutTrashTesting { var sfs: SimpleFileSystem = null ; override def beforeEach() = { super.beforeEach sfs = new SimpleFileSystem(fs) ; } val testDir = f"$testRootDir/dir" val testSubDir = f"$testRootDir/dir/subDir" describe("for a FileSystemExtensions without a Trash") { describe("trash") { it("should be disabled"){ val trash = new Trash(fs.getConf) assert(!trash.isEnabled) } } describe("mkdirs and delete") { it("should work") { assert(!fs.exists(testDir)) assert(fs.mkdirs(testDir)) assert(fs.exists(testDir)) assert(fs.delete(testDir,true)) assert(!fs.exists(testDir)) } } describe("moveToTrash") { it("should fail") { assert(!fs.exists(testDir)) assert(fs.mkdirs(testDir)) assert(fs.exists(testDir)) assert(!sfs.moveToTrash(testDir)) assert(fs.exists(testDir)) } } describe("makeEmptyFolder") { it("should create an empty directory if it does not exist") { assert(!fs.exists(testDir)) assert(sfs.makeEmptyFolder(testDir)) assert(fs.exists(testDir)) assert(fs.listStatus(testDir).length===0) } ignore("should remove the directory and create a new one if it does already exist") { assert(!fs.exists(testDir)) assert(fs.mkdirs(testDir)) assert(fs.mkdirs(testSubDir)) assert(fs.listStatus(testDir).length===1) assert(sfs.makeEmptyFolder(testDir)) assert(fs.exists(testDir)) assert(fs.listStatus(testDir).length===0) } } } }
Example 37
Source File: DummyHivePartitionFetcherTest.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.exec.hive import com.flaminem.flamy.conf.FlamyContext import com.flaminem.flamy.model.core.Model import com.flaminem.flamy.model.exceptions.FlamyException import org.scalatest.FunSpec class DummyHivePartitionFetcherTest extends FunSpec { val context = new FlamyContext("flamy.model.dir.paths" -> "src/test/resources/DummyHivePartitionFetcher") val model: Model = Model.getCompleteModel(context, Nil) describe("a DummyHivePartitionFetcher") { describe("when the partitioning info is not consistent with the table partition definition") { it("should throw a FlamyException") { intercept[FlamyException]{ val fetcher = new DummyHivePartitionFetcher(model, Seq(("less_partition_columns.table1/part2=A", "anyloc", "2000-01-01 02:22:33"))) fetcher.getTablePartitioningInfo("less_partition_columns.table1") } } } describe("when the partitioning info is not consistent with the table partition definition bis") { it("should throw a FlamyException") { intercept[FlamyException]{ val fetcher = new DummyHivePartitionFetcher(model, Seq(("more_partition_columns.table2/part1=A", "anyloc", "2000-01-01 02:22:33"))) fetcher.getTablePartitioningInfo("more_partition_columns.table2") } } } describe("when the partitioning info is not consistent with the table partition definition ter") { it("should throw a FlamyException") { intercept[FlamyException]{ val fetcher = new DummyHivePartitionFetcher(model, Seq(("more_partition_columns.table2/part2=B", "anyloc", "2000-01-01 02:22:33"))) fetcher.getTablePartitioningInfo("more_partition_columns.table2") } } } describe("when the partitioning info is consistent") { it("should be ok") { val fetcher = new DummyHivePartitionFetcher(model, Seq(("more_partition_columns.table2/part1=A/part2=B", "anyloc", "2000-01-01 02:22:33"))) fetcher.getTablePartitioningInfo("more_partition_columns.table2") } } describe("when the partitioning info is consistent but the partition order is different") { it("should be ok") { val fetcher = new DummyHivePartitionFetcher(model, Seq(("more_partition_columns.table2/part2=B/part1=A", "anyloc", "2000-01-01 02:22:33"))) fetcher.getTablePartitioningInfo("more_partition_columns.table2") } } } }
Example 38
Source File: MacroPegCallByValueParSpec.scala From macro_peg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.github.kmizu.macro_peg import com.github.kmizu.macro_peg.EvaluationResult.Success import com.github.kmizu.macro_peg.Runner.evalGrammar import org.scalatest.{DiagrammedAssertions, FunSpec} class MacroPegCallByValueParSpec extends FunSpec with DiagrammedAssertions { describe("Macro PEG with call by value par example") { it("simple") { val results = evalGrammar( """ |S = F("a"); F(A) = A A A; """.stripMargin, Seq("aaa"), EvaluationStrategy.CallByValuePar ) assertResult(Seq(Success("")))(results) } it("xml") { val results = evalGrammar( """ |S = "<" F([a-zA-Z_]+); F(N) = N ">" ("<" F([a-zA-Z_]+))* "</" N ">"; """.stripMargin, Seq( "<a><b></b></a>"), EvaluationStrategy.CallByValuePar ) assertResult(Seq(Success("")))(results) } } }
Example 39
Source File: MacroPegCallByValueSeqSpec.scala From macro_peg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.github.kmizu.macro_peg import com.github.kmizu.macro_peg.Runner.evalGrammar import org.scalatest.{DiagrammedAssertions, FunSpec} import com.github.kmizu.macro_peg.EvaluationResult.Success class MacroPegCallByValueSeqSpec extends FunSpec with DiagrammedAssertions { describe("Macro PEG with call by value seq example") { it("simple") { val results = evalGrammar( """ |S = F("a", "b", "c"); F(A, B, C) = "abc"; """.stripMargin, Seq("abcabc"), EvaluationStrategy.CallByValueSeq ) assertResult(Seq(Success("")))(results) } it("xml") { val results = evalGrammar( """ |S = F("<", [a-zA-Z_]+, ">"); F(LT, N, GT) = F("<", [a-zA-Z_]+, ">")* LT "/" N GT; """.stripMargin, Seq( "<a></a>"), EvaluationStrategy.CallByValueSeq ) assertResult(Seq(Success("")))(results) } } }
Example 40
Source File: MacroPegCallByNameSpec.scala From macro_peg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.github.kmizu.macro_peg import com.github.kmizu.macro_peg.EvaluationResult.{Failure, Success} import com.github.kmizu.macro_peg.Runner.evalGrammar import org.scalatest.{DiagrammedAssertions, FunSpec} class MacroPegCallByNameSpec extends FunSpec with DiagrammedAssertions { describe("Macro PEG with call by name example") { it("palindrome") { val results = evalGrammar( """ |S = P("") !.; |P(r) = "a" P("a" r) / "b" P("b" r) / r; """.stripMargin, Seq("abba", "abba","abbbba", "a"), EvaluationStrategy.CallByName ) assertResult(Seq(Success(""), Success(""), Success(""), Failure))(results) } } }
Example 41
Source File: PackageSpec.scala From sparkpipe-core with Apache License 2.0 | 5 votes |
package software.uncharted.sparkpipe.ops.core.rdd.text import org.scalatest.FunSpec import software.uncharted.sparkpipe.Spark class PackageSpec extends FunSpec { describe("ops.core.rdd.text") { describe("#regexFilter()") { it("Should pass through only strings that match the given regular expression") { val data = Spark.sc.parallelize(Seq("abc def ghi", "abc d e f ghi", "the def quick", "def ghi", "abc def")) assertResult(List("abc def ghi", "the def quick", "def ghi"))(regexFilter(".*def.+")(data).collect.toList) assertResult(List("abc d e f ghi", "def ghi"))(regexFilter(".+def.*", true)(data).collect.toList) } } } }
Example 42
Source File: ListFunSpec.scala From scala-tutorials with MIT License | 5 votes |
package com.baeldung.scala.scalatest import org.scalatest.FunSpec class ListFunSpec extends FunSpec { describe("A List") { describe("when empty") { it("should have size 0") { assert(List.empty.size == 0) } it("should throw an IndexOutOfBoundsException when to access an element") { val emptyList = List() assertThrows[IndexOutOfBoundsException] { emptyList(1) } } } } }
Example 43
Source File: SkewJoinOperationsSpec.scala From spark-skewjoin with Apache License 2.0 | 5 votes |
package com.tresata.spark.skewjoin import org.scalatest.FunSpec import com.tresata.spark.skewjoin.Dsl._ import com.twitter.algebird.CMSHasherImplicits._ import org.apache.spark.Partitioner.defaultPartitioner case object DummySkewReplication extends SkewReplication { override def getReplications(leftCount: Long, rightCount: Long, numPartitions: Int) = (2, 2) } class SkewJoinOperationsSpec extends FunSpec { lazy val sc = SparkSuite.sc lazy val rdd1 = sc.parallelize(Array(1, 1, 2, 3, 4)).map(s => (s, 1)).repartition(2) lazy val rdd2 = sc.parallelize(Array(1, 1, 6, 4, 5)).map(s => (s, 2)).repartition(2) describe("SkewJoin") { it("should inner join two datasets using skewJoin correctly") { assert(rdd1.skewJoin(rdd2, defaultPartitioner(rdd1, rdd2), DefaultSkewReplication(1)).sortByKey(true).collect.toList === Seq((1, (1, 2)), (1, (1, 2)), (1, (1, 2)), (1, (1, 2)), (4, (1, 2)))) } it("should left join two datasets using skewLeftOuterJoin correctly") { assert(rdd1.skewLeftOuterJoin(rdd2, defaultPartitioner(rdd1, rdd2), DefaultSkewReplication(1)).sortByKey(true).collect.toList === Seq((1, (1, Some(2))), (1, (1, Some(2))), (1, (1, Some(2))), (1, (1, Some(2))), (2, (1, None)), (3, (1, None)), (4, (1, Some(2))))) } it("should right join two datasets using skewRightOuterJoin correctly") { assert(rdd1.skewRightOuterJoin(rdd2, defaultPartitioner(rdd1, rdd2), DefaultSkewReplication(1)).sortByKey(true).collect.toList === Seq((1, (Some(1), 2)), (1, (Some(1), 2)), (1, (Some(1), 2)), (1, (Some(1), 2)), (4, (Some(1), 2)), (5, (None, 2)), (6, (None, 2)))) } } }
Example 44
Source File: BlockJoinOperationsSpec.scala From spark-skewjoin with Apache License 2.0 | 5 votes |
package com.tresata.spark.skewjoin import org.scalatest.FunSpec import com.tresata.spark.skewjoin.Dsl._ class BlockJoinOperationsSpec extends FunSpec { lazy val sc = SparkSuite.sc describe("BlockJoin") { it ("should block inner join") { val rdd1 = sc.parallelize(Array((1, 1), (1, 2), (2, 1), (2, 2), (3, 1))) val rdd2 = sc.parallelize(Array((1, 'x'), (2, 'y'), (2, 'z'), (4, 'w'))) val joined = rdd1.blockJoin(rdd2, 5, 5).collect() assert(joined.size === 6) assert(joined.toSet === Set( (1, (1, 'x')), (1, (2, 'x')), (2, (1, 'y')), (2, (1, 'z')), (2, (2, 'y')), (2, (2, 'z')) )) } it("should block left outer join") { val rdd1 = sc.parallelize(Array((1, 1), (1, 2), (2, 1), (2, 2), (3, 1))) val rdd2 = sc.parallelize(Array((1, 'x'), (2, 'y'), (2, 'z'), (4, 'w'))) val joined = rdd1.blockLeftOuterJoin(rdd2, 5).collect() assert(joined.size === 7) assert(joined.toSet === Set( (1, (1, Some('x'))), (1, (2, Some('x'))), (2, (1, Some('y'))), (2, (1, Some('z'))), (2, (2, Some('y'))), (2, (2, Some('z'))), (3, (1, None)) )) } it("should block right outer join") { val rdd1 = sc.parallelize(Array((1, 1), (1, 2), (2, 1), (2, 2), (3, 1))) val rdd2 = sc.parallelize(Array((1, 'x'), (2, 'y'), (2, 'z'), (4, 'w'))) val joined = rdd1.blockRightOuterJoin(rdd2, 5).collect() assert(joined.size === 7) assert(joined.toSet === Set( (1, (Some(1), 'x')), (1, (Some(2), 'x')), (2, (Some(1), 'y')), (2, (Some(1), 'z')), (2, (Some(2), 'y')), (2, (Some(2), 'z')), (4, (None, 'w')) )) } } }
Example 45
Source File: SkewReplicationSpec.scala From spark-skewjoin with Apache License 2.0 | 5 votes |
package com.tresata.spark.skewjoin import org.scalatest.FunSpec class SkewReplicationSpec extends FunSpec { describe("SkewReplication") { it("should return correct replications") { val replicator1 = DefaultSkewReplication(1) val replicator2 = DefaultSkewReplication(1e-6) assert(replicator1.getReplications(5, 4, 1) === (1, 1)) assert(replicator1.getReplications(80, 5, 90) === (5, 80)) assert(replicator2.getReplications(10, 50, 80) === (1, 1)) } it("should not return replications bigger than numPartitions") { val replicator = DefaultSkewReplication(50) assert(replicator.getReplications(5, 4, 100) === (100, 100)) assert(replicator.getReplications(5, 1, 100) === (50, 100)) } } }
Example 46
Source File: ClientCommManagerSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.comm import org.apache.toree.kernel.protocol.v5 import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.client.ActorLoader import org.apache.toree.kernel.protocol.v5.content.CommContent import org.scalatest.mock.MockitoSugar import org.mockito.Mockito._ import org.mockito.Matchers._ import org.scalatest.{BeforeAndAfter, FunSpec, Matchers} class ClientCommManagerSpec extends FunSpec with Matchers with BeforeAndAfter with MockitoSugar { private val TestTargetName = "some target" private var mockActorLoader: ActorLoader = _ private var mockKMBuilder: KMBuilder = _ private var mockCommRegistrar: CommRegistrar = _ private var clientCommManager: ClientCommManager = _ private var generatedCommWriter: CommWriter = _ before { mockActorLoader = mock[ActorLoader] mockKMBuilder = mock[KMBuilder] mockCommRegistrar = mock[CommRegistrar] clientCommManager = new ClientCommManager( mockActorLoader, mockKMBuilder, mockCommRegistrar ) { override protected def newCommWriter(commId: UUID): CommWriter = { val commWriter = super.newCommWriter(commId) generatedCommWriter = commWriter val spyCommWriter = spy(commWriter) doNothing().when(spyCommWriter) .sendCommKernelMessage(any[KernelMessageContent with CommContent]) spyCommWriter } } } describe("ClientCommManager") { describe("#open") { it("should return a wrapped instance of ClientCommWriter") { clientCommManager.open(TestTargetName, v5.MsgData.Empty) // Exposed hackishly for testing generatedCommWriter shouldBe a [ClientCommWriter] } } } }
Example 47
Source File: SocketFactorySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel.socket import org.scalatest.{FunSpec, Matchers} class SocketFactorySpec extends FunSpec with Matchers { describe("SocketFactory"){ describe("HeartbeatConnection"){ it("should be composed of transport ip and heartbeat port"){ val config: SocketConfig = SocketConfig(-1,-1,8000,-1, -1, "<STRING-IP>", "<STRING-TRANSPORT>","<STRING-SCHEME>","<STRING-KEY>") val factory: SocketFactory = SocketFactory(config) factory.HeartbeatConnection.toString should be ("<STRING-TRANSPORT>://<STRING-IP>:8000") } } } }
Example 48
Source File: SocketConnectionSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel.socket import org.scalatest.{FunSpec, Matchers} class SocketConnectionSpec extends FunSpec with Matchers { describe("SocketConnection"){ describe("#toString"){ it("should properly format connection string"){ val connection: SocketConnection = SocketConnection("tcp", "127.0.0.1", 1234) connection.toString should be ("tcp://127.0.0.1:1234") } } } }
Example 49
Source File: SocketConfigSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel.socket import com.typesafe.config.ConfigFactory import org.scalatest.{FunSpec, Matchers} import org.slf4j.LoggerFactory import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class SocketConfigSpec extends FunSpec with Matchers { val logger = LoggerFactory.getLogger("jt4") //logger.error("WOOT!") private val jsonString: String = """ { "stdin_port": 10000, "control_port": 10001, "hb_port": 10002, "shell_port": 10003, "iopub_port": 10004, "ip": "1.2.3.4", "transport": "tcp", "signature_scheme": "hmac-sha256", "key": "" } """.stripMargin val socketConfigJson: JsValue = Json.parse(jsonString) val socketConfigFromConfig = SocketConfig.fromConfig(ConfigFactory.parseString(jsonString)) val socketConfig = SocketConfig( 10000, 10001, 10002, 10003, 10004, "1.2.3.4", "tcp", "hmac-sha256", "" ) describe("SocketConfig") { describe("implicit conversions") { it("should implicitly convert from valid json to a SocketConfig instance") { // This is the least safe way to convert as an error is thrown if it fails socketConfigJson.as[SocketConfig] should be (socketConfig) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = socketConfigJson.asOpt[SocketConfig] newCompleteRequest.get should be (socketConfig) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = socketConfigJson.validate[SocketConfig] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: SocketConfig) => valid ) should be (socketConfig) } it("should implicitly convert from a SocketConfig instance to valid json") { Json.toJson(socketConfig) should be (socketConfigJson) } } describe("#toConfig") { it("should implicitly convert from valid json to a SocketConfig instance") { // This is the least safe way to convert as an error is thrown if it fails socketConfigFromConfig should be (socketConfig) } it("should convert json file to SocketConfig object") { socketConfigFromConfig.stdin_port should be (10000) } } } }
Example 50
Source File: JavaScriptSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic.builtin import org.scalatest.mock.MockitoSugar import org.scalatest.{FunSpec, Matchers} import org.apache.toree.magic.CellMagicOutput import org.apache.toree.kernel.protocol.v5.MIMEType class JavaScriptSpec extends FunSpec with Matchers with MockitoSugar { describe("JavaScript"){ describe("#execute") { it("should return the entire cell's contents with the MIME type of text/javascript") { val javaScriptMagic = new JavaScript val code = "some code on a line\nmore code on another line" val expected = CellMagicOutput(MIMEType.ApplicationJavaScript -> code) javaScriptMagic.execute(code) should be (expected) } } } }
Example 51
Source File: HtmlSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic.builtin import org.apache.toree.kernel.protocol.v5.MIMEType import org.apache.toree.magic.CellMagicOutput import org.scalatest.mock.MockitoSugar import org.scalatest.{FunSpec, Matchers} class HtmlSpec extends FunSpec with Matchers with MockitoSugar { describe("Html"){ describe("#execute") { it("should return the entire cell's contents with the MIME type of " + "text/html") { val htmlMagic = new Html val code = "some code on a line\nanother line" val expected = CellMagicOutput(MIMEType.TextHtml -> code) htmlMagic.execute(code) should be (expected) } } } }
Example 52
Source File: BuiltinLoaderSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic.builtin import org.scalatest.mock.MockitoSugar import org.scalatest.{Matchers, FunSpec} class BuiltinLoaderSpec extends FunSpec with Matchers with MockitoSugar { describe("BuiltinLoader") { describe("#getClasses") { it("should return classes in a package") { val pkg = this.getClass.getPackage.getName val classes = new BuiltinLoader().getClasses(pkg) classes.size shouldNot be(0) } } describe("#loadClasses") { it("should return class objects for classes in a package") { val pkg = this.getClass.getPackage.getName val classes = new BuiltinLoader().loadClasses(pkg).toList classes.contains(this.getClass) should be (true) } } } }
Example 53
Source File: LSMagicSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic.builtin import java.io.OutputStream import java.net.URL import org.apache.toree.interpreter.Interpreter import org.apache.toree.magic.dependencies.{IncludeOutputStream, IncludeInterpreter} import org.apache.toree.magic.{CellMagic, LineMagic} import org.apache.spark.SparkContext import org.scalatest.{Matchers, FunSpec} import org.scalatest.mock.MockitoSugar import org.mockito.Mockito._ import org.mockito.Matchers._ class TestLSMagic(sc: SparkContext, intp: Interpreter, os: OutputStream) extends LSMagic with IncludeInterpreter with IncludeOutputStream { override val interpreter: Interpreter = intp override val outputStream: OutputStream = os } class LSMagicSpec extends FunSpec with Matchers with MockitoSugar { describe("LSMagic") { describe("#execute") { it("should call println with a magics message") { val lsm = spy(new TestLSMagic( mock[SparkContext], mock[Interpreter], mock[OutputStream]) ) val classList = new BuiltinLoader().loadClasses() lsm.execute("") verify(lsm).magicNames("%", classOf[LineMagic], classList) verify(lsm).magicNames("%%", classOf[CellMagic], classList) } } describe("#magicNames") { it("should filter classnames by interface") { val prefix = "%" val interface = classOf[LineMagic] val classes : List[Class[_]] = List(classOf[LSMagic], classOf[Integer]) val lsm = new TestLSMagic( mock[SparkContext], mock[Interpreter], mock[OutputStream]) lsm.magicNames(prefix, interface, classes).length should be(1) } it("should prepend prefix to each name"){ val prefix = "%" val className = classOf[LSMagic].getSimpleName val interface = classOf[LineMagic] val expected = s"${prefix}${className}" val classes : List[Class[_]] = List(classOf[LSMagic], classOf[Integer]) val lsm = new TestLSMagic( mock[SparkContext], mock[Interpreter], mock[OutputStream]) lsm.magicNames(prefix, interface, classes) should be(List(expected)) } } } }
Example 54
Source File: KernelCommManagerSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.comm import org.apache.toree.kernel.protocol.v5 import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content.CommContent import org.apache.toree.kernel.protocol.v5.kernel.ActorLoader import org.scalatest.mock.MockitoSugar import org.mockito.Mockito._ import org.mockito.Matchers._ import org.scalatest.{BeforeAndAfter, FunSpec, Matchers} class KernelCommManagerSpec extends FunSpec with Matchers with BeforeAndAfter with MockitoSugar { private val TestTargetName = "some target" private var mockActorLoader: ActorLoader = _ private var mockKMBuilder: KMBuilder = _ private var mockCommRegistrar: CommRegistrar = _ private var kernelCommManager: KernelCommManager = _ private var generatedCommWriter: CommWriter = _ before { mockActorLoader = mock[ActorLoader] mockKMBuilder = mock[KMBuilder] mockCommRegistrar = mock[CommRegistrar] kernelCommManager = new KernelCommManager( mockActorLoader, mockKMBuilder, mockCommRegistrar ) { override protected def newCommWriter(commId: UUID): CommWriter = { val commWriter = super.newCommWriter(commId) generatedCommWriter = commWriter val spyCommWriter = spy(commWriter) doNothing().when(spyCommWriter) .sendCommKernelMessage(any[KernelMessageContent with CommContent]) spyCommWriter } } } describe("KernelCommManager") { describe("#open") { it("should return a wrapped instance of KernelCommWriter") { kernelCommManager.open(TestTargetName, v5.MsgData.Empty) // Exposed hackishly for testing generatedCommWriter shouldBe a [KernelCommWriter] } } } }
Example 55
Source File: DataFrameConverterSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.utils import org.apache.spark.sql.types.StructType import org.apache.spark.sql.{DataFrame, Row} import org.mockito.Mockito._ import org.scalatest.mock.MockitoSugar import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers} import play.api.libs.json.{JsArray, JsString, Json} import test.utils.SparkContextProvider import scala.collection.mutable class DataFrameConverterSpec extends FunSpec with MockitoSugar with Matchers with BeforeAndAfterAll { lazy val spark = SparkContextProvider.sparkContext override protected def afterAll(): Unit = { spark.stop() super.afterAll() } val dataFrameConverter: DataFrameConverter = new DataFrameConverter val mockDataFrame = mock[DataFrame] val mockRdd = spark.parallelize(Seq(Row(new mutable.WrappedArray.ofRef(Array("test1", "test2")), 2, null))) val mockStruct = mock[StructType] val columns = Seq("foo", "bar").toArray doReturn(mockStruct).when(mockDataFrame).schema doReturn(columns).when(mockStruct).fieldNames doReturn(mockRdd).when(mockDataFrame).rdd describe("DataFrameConverter") { describe("#convert") { it("should convert to a valid JSON object") { val someJson = dataFrameConverter.convert(mockDataFrame, "json") val jsValue = Json.parse(someJson.get) jsValue \ "columns" should be (JsArray(Seq(JsString("foo"), JsString("bar")))) jsValue \ "rows" should be (JsArray(Seq( JsArray(Seq(JsString("[test1, test2]"), JsString("2"), JsString("null"))) ))) } it("should convert to csv") { val csv = dataFrameConverter.convert(mockDataFrame, "csv").get val values = csv.split("\n") values(0) shouldBe "foo,bar" values(1) shouldBe "[test1, test2],2,null" } it("should convert to html") { val html = dataFrameConverter.convert(mockDataFrame, "html").get html.contains("<th>foo</th>") should be(true) html.contains("<th>bar</th>") should be(true) html.contains("<td>[test1, test2]</td>") should be(true) html.contains("<td>2</td>") should be(true) html.contains("<td>null</td>") should be(true) } it("should convert limit the selection") { val someLimited = dataFrameConverter.convert(mockDataFrame, "csv", 1) val limitedLines = someLimited.get.split("\n") limitedLines.length should be(2) } it("should return a Failure for invalid types") { val result = dataFrameConverter.convert(mockDataFrame, "Invalid Type") result.isFailure should be(true) } } } }
Example 56
Source File: ExecutionCounterSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.global import org.scalatest.{FunSpec, Matchers} class ExecutionCounterSpec extends FunSpec with Matchers { describe("ExecutionCounter") { describe("#increment( String )"){ it("should increment value when key is not present"){ ExecutionCounter incr "foo" should be(1) } it("should increment value for key when it is present"){ ExecutionCounter incr "bar" should be(1) ExecutionCounter incr "bar" should be(2) } } } }
Example 57
Source File: UtilitiesSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel import akka.util.ByteString import org.apache.toree.communication.ZMQMessage import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} class UtilitiesSpec extends FunSpec with Matchers { val header: Header = Header( "<UUID>", "<STRING>", "<UUID>", "<STRING>", "<FLOAT>" ) val parentHeader : ParentHeader = ParentHeader( "<PARENT-UUID>", "<PARENT-STRING>", "<PARENT-UUID>", "<PARENT-STRING>", "<PARENT-FLOAT>" ) val kernelMessage = KernelMessage( Seq("<STRING-1>","<STRING-2>").map(x => x.getBytes), "<SIGNATURE>", header, parentHeader, Map(), "<STRING>" ) val zmqMessage = ZMQMessage( ByteString("<STRING-1>".replaceAll("""\s""", "").getBytes), ByteString("<STRING-2>".replaceAll("""\s""", "").getBytes), ByteString("<IDS|MSG>".replaceAll("""\s""", "").getBytes), ByteString("<SIGNATURE>".replaceAll("""\s""", "").getBytes), ByteString( """ { "msg_id": "<UUID>", "username": "<STRING>", "session": "<UUID>", "msg_type": "<STRING>", "version": "<FLOAT>" } """.stripMargin.replaceAll("""\s""", "").getBytes), ByteString( """ { "msg_id": "<PARENT-UUID>", "username": "<PARENT-STRING>", "session": "<PARENT-UUID>", "msg_type": "<PARENT-STRING>", "version": "<PARENT-FLOAT>" } """.stripMargin.replaceAll("""\s""", "").getBytes), ByteString("{}".replaceAll("""\s""", "").getBytes), ByteString("<STRING>".replaceAll("""\s""", "").getBytes) ) describe("Utilities") { describe("implicit #KernelMessageToZMQMessage") { it("should correctly convert a kernel message to a ZMQMessage") { Utilities.KernelMessageToZMQMessage(kernelMessage) should equal (zmqMessage) } } describe("implicit #ZMQMessageToKernelMessage") { it("should correctly convert a ZMQMessage to a kernel message") { Utilities.ZMQMessageToKernelMessage(zmqMessage) should equal (kernelMessage) } } describe("implicit conversions should be inverses of each other") { it("should convert back to the original message, ZMQ -> Kernel -> ZMQ") { Utilities.KernelMessageToZMQMessage( Utilities.ZMQMessageToKernelMessage(zmqMessage) ) should equal (zmqMessage) } it("should convert back to the original message, Kernel -> ZMQ -> Kernel") { Utilities.ZMQMessageToKernelMessage( Utilities.KernelMessageToZMQMessage(kernelMessage) ) should equal (kernelMessage) } } describe("implicit #StringToByteString") { it("should correctly convert a string to a ByteString") { val someString = "some content" val expected = ByteString(someString) Utilities.StringToByteString(someString) should be (expected) } } describe("implicit #ByteStringToString") { it("should correctly convert a ByteString to a string") { val expected = "some content" val byteString = ByteString(expected) Utilities.ByteStringToString(byteString) should be (expected) } } } }
Example 58
Source File: JVMReprSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package integration.interpreter.scala import java.util import java.io.ByteArrayOutputStream import jupyter.{Displayer, Displayers, MIMETypes} import org.apache.toree.global.StreamState import org.apache.toree.interpreter.Interpreter import org.apache.toree.interpreter.Results.Success import org.apache.toree.kernel.api.{DisplayMethodsLike, KernelLike} import org.apache.toree.kernel.interpreter.scala.ScalaInterpreter import org.mockito.Mockito.doReturn import org.scalatest.{BeforeAndAfter, FunSpec, Matchers} import org.scalatest.mock.MockitoSugar import scala.util.Random class JVMReprSpec extends FunSpec with Matchers with MockitoSugar with BeforeAndAfter { private val outputResult = new ByteArrayOutputStream() private var interpreter: Interpreter = _ before { val mockKernel = mock[KernelLike] val mockDisplayMethods = mock[DisplayMethodsLike] doReturn(mockDisplayMethods).when(mockKernel).display interpreter = new ScalaInterpreter().init(mockKernel) StreamState.setStreams(outputStream = outputResult) } after { interpreter.stop() outputResult.reset() } describe("ScalaInterpreter") { describe("#interpret") { it("should display Scala int as a text representation") { val (result, outputOrError) = interpreter.interpret("val a = 12") result should be(Success) outputOrError.isLeft should be(true) outputOrError.left.get should be(Map(MIMETypes.TEXT -> "12")) } it("should display Scala Some(str) as a text representation") { val (result, outputOrError) = interpreter.interpret("""val a = Some("str")""") result should be(Success) outputOrError.isLeft should be(true) outputOrError.left.get should be(Map(MIMETypes.TEXT -> "Some(str)")) } ignore("should use the Jupyter REPR API for display representation") { Displayers.register(classOf[DisplayerTest], new Displayer[DisplayerTest] { override def display(t: DisplayerTest): util.Map[String, String] = { val output = new util.HashMap[String, String]() output.put("text/plain", s"test object: ${t.id}") output.put("application/json", s"""{"id": ${t.id}""") output } }) val inst = DisplayerTest() interpreter.bind("inst", classOf[DisplayerTest].getName, inst, List()) val (result, outputOrError) = interpreter.interpret("""inst""") result should be(Success) outputOrError.isLeft should be(true) outputOrError.left.get should be(Map( MIMETypes.TEXT -> s"test object: ${inst.id}", "application/json" -> s"""{"id": ${inst.id}""" )) } } } } case class DisplayerTest(id: Long = new Random().nextLong())
Example 59
Source File: HmacSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.communication.security import java.security.NoSuchAlgorithmException import org.scalatest.{FunSpec, Matchers} class HmacSpec extends FunSpec with Matchers { describe("Hmac Object") { describe("#apply") { it("should fail if the algorithm is not available") { val nonEmptyKey = "FILL" val badAlgorithm = "One day, I want to be a real algorithm" intercept[NoSuchAlgorithmException] { val hmac = Hmac(nonEmptyKey, HmacAlgorithm(badAlgorithm)) } } it("should succeed if the algorithm is available") { val goodAlgorithm = HmacAlgorithm.SHA256 val hmac = Hmac("", goodAlgorithm) hmac.algorithm should be (goodAlgorithm) } } describe("#newMD5") { it("should produce an Hmac with the algorithm set to MD5") { val hmac = Hmac.newMD5("") hmac.algorithm should be(HmacAlgorithm.MD5) } } describe("#newSHA1") { it("should produce an Hmac with the algorithm set to SHA1") { val hmac = Hmac.newSHA1("") hmac.algorithm should be(HmacAlgorithm.SHA1) } } describe("#newSHA256") { it("should produce an Hmac with the algorithm set to SHA256") { val hmac = Hmac.newSHA256("") hmac.algorithm should be(HmacAlgorithm.SHA256) } } } describe("Hmac Class") { describe("#apply") { // TODO: This should really be mocked since we don't care about the // results, just the send/receive to the underlying implementation it("should produce the correct digest") { val key = "12345" val message = "This is a test of SHA256 in action." val expected = "e60e1494b0650875fa5eb8384e357d731358c3559c1f223d69dc43ffe13570bc" val hmac = new Hmac(key, HmacAlgorithm.SHA256) hmac(message) should be(expected) } } describe("#digest") { // TODO: This should really be mocked since we don't care about the // results, just the send/receive to the underlying implementation it("should produce the correct digest") { val key = "12345" val message = List("This is a test of SHA256 in action.") val expected = "e60e1494b0650875fa5eb8384e357d731358c3559c1f223d69dc43ffe13570bc" val hmac = new Hmac(key, HmacAlgorithm.SHA256) hmac.digest(message) should be(expected) } } } describe("HmacAlgorithm") { describe("#apply") { it("should return a value wrapping the string input") { val resultTypeName = HmacAlgorithm("").getClass.getName // NOTE: Test written this way since unable to check directly against // the Scala enumeration value resultTypeName should be ("scala.Enumeration$Val") } } } }
Example 60
Source File: JeroMQSocketSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.communication.socket import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import org.scalatest.{Matchers, BeforeAndAfter, OneInstancePerTest, FunSpec} import org.scalatest.mock.MockitoSugar import org.mockito.Mockito._ import org.zeromq.ZMsg class JeroMQSocketSpec extends FunSpec with MockitoSugar with OneInstancePerTest with BeforeAndAfter with Matchers { private val runnable = mock[ZeroMQSocketRunnable] @volatile private var running = true // Mock the running of the runnable for the tests doAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = while (running) { Thread.sleep(1) } }).when(runnable).run() // Mock the close of the runnable to shutdown doAnswer(new Answer[Unit] { override def answer(invocation: InvocationOnMock): Unit = running = false }).when(runnable).close() private val socket: JeroMQSocket = new JeroMQSocket(runnable) after { running = false } describe("JeroMQSocket") { describe("#send") { it("should offer a message to the runnable") { val message: String = "Some Message" val expected = ZMsg.newStringMsg(message) socket.send(message.getBytes) verify(runnable).offer(expected) } it("should thrown and AssertionError when socket is no longer alive") { socket.close() intercept[AssertionError] { socket.send("".getBytes) } } } describe("#close") { it("should close the runnable") { socket.close() verify(runnable).close() } it("should close the socket thread") { socket.close() socket.isAlive should be (false) } } describe("#isAlive") { it("should evaluate to true when the socket thread is alive") { socket.isAlive should be (true) } it("should evaluate to false when the socket thread is dead") { socket.close() socket.isAlive should be (false) } } } }
Example 61
Source File: HeaderBuilderSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5 import org.scalatest.{Matchers, FunSpec} class HeaderBuilderSpec extends FunSpec with Matchers { describe("HeaderBuilder") { describe("#create") { it("should set the msg_id field to a unique ID if none is provided") { HeaderBuilder.create("").msg_id should not be empty } it("should set the msg_id field to the argument if provided") { val expected = "some id" HeaderBuilder.create("", expected).msg_id should be (expected) } it("should set the username field to the SparkKernelInfo property") { val expected = SparkKernelInfo.username HeaderBuilder.create("").username should be (expected) } it("should set the session field to the SparkKernelInfo property") { val expected = SparkKernelInfo.session HeaderBuilder.create("").session should be (expected) } it("should set the msg_type field to the argument provided") { val expected = "some type" HeaderBuilder.create(expected).msg_type should be (expected) } it("should set the version field to the SparkKernelInfo property") { val expected = SparkKernelInfo.protocolVersion HeaderBuilder.create("").version should be (expected) } } } }
Example 62
Source File: InspectReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectReplyErrorSpec extends FunSpec with Matchers { val inspectReplyErrorJson: JsValue = Json.parse(""" { "status": "error", "data": {}, "metadata": {}, "ename": "<STRING>", "evalue": "<STRING>", "traceback": [] } """) val inspectReplyError: InspectReplyError = InspectReplyError( Data(), Metadata(), Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("InspectReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyErrorJson.as[InspectReplyError] should be (inspectReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReplyError = inspectReplyErrorJson.asOpt[InspectReplyError] newInspectReplyError.get should be (inspectReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyErrorResults = inspectReplyErrorJson.validate[InspectReplyError] InspectReplyErrorResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReplyError) => valid ) should be (inspectReplyError) } it("should implicitly convert from a InspectReplyError instance to valid json") { Json.toJson(inspectReplyError) should be (inspectReplyErrorJson) } } } }
Example 63
Source File: KernelStatusSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class KernelStatusSpec extends FunSpec with Matchers { val kernelStatusJson: JsValue = Json.parse(""" { "execution_state": "<STRING>" } """) val kernelStatus: KernelStatus = KernelStatus("<STRING>") describe("KernelStatus") { describe("#toTypeString") { it("should return correct type") { KernelStatus.toTypeString should be ("status") } } describe("implicit conversions") { it("should implicitly convert from valid json to a kernelStatus instance") { // This is the least safe way to convert as an error is thrown if it fails kernelStatusJson.as[KernelStatus] should be (kernelStatus) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelStatus = kernelStatusJson.asOpt[KernelStatus] newKernelStatus.get should be (kernelStatus) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val kernelStatusResults = kernelStatusJson.validate[KernelStatus] kernelStatusResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelStatus) => valid ) should be (kernelStatus) } it("should implicitly convert from a kernelStatus instance to valid json") { Json.toJson(kernelStatus) should be (kernelStatusJson) } } } }
Example 64
Source File: HistoryReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class HistoryReplySpec extends FunSpec with Matchers { val historyReplyJson: JsValue = Json.parse(""" { "history": ["<STRING>", "<STRING2>", "<STRING3>"] } """) val historyReply = HistoryReply( List("<STRING>", "<STRING2>", "<STRING3>") ) describe("HistoryReply") { describe("#toTypeString") { it("should return correct type") { HistoryReply.toTypeString should be ("history_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a HistoryReply instance") { // This is the least safe way to convert as an error is thrown if it fails historyReplyJson.as[HistoryReply] should be (historyReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = historyReplyJson.asOpt[HistoryReply] newCompleteRequest.get should be (historyReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = historyReplyJson.validate[HistoryReply] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: HistoryReply) => valid ) should be (historyReply) } it("should implicitly convert from a HistoryReply instance to valid json") { Json.toJson(historyReply) should be (historyReplyJson) } } } }
Example 65
Source File: ExecuteInputSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteInputSpec extends FunSpec with Matchers { val executeInputJson: JsValue = Json.parse(""" { "code": "<STRING>", "execution_count": 42 } """) val executeInput: ExecuteInput = ExecuteInput( "<STRING>", 42 ) describe("ExecuteInput") { describe("#toTypeString") { it("should return correct type") { ExecuteInput.toTypeString should be ("execute_input") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeInput instance") { // This is the least safe way to convert as an error is thrown if it fails executeInputJson.as[ExecuteInput] should be (executeInput) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteInput = executeInputJson.asOpt[ExecuteInput] newExecuteInput.get should be (executeInput) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeInputResults = executeInputJson.validate[ExecuteInput] executeInputResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteInput) => valid ) should be (executeInput) } it("should implicitly convert from a executeInput instance to valid json") { Json.toJson(executeInput) should be (executeInputJson) } } } }
Example 66
Source File: DisplayDataSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.FunSuite import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class DisplayDataSpec extends FunSpec with Matchers { val displayDataJson: JsValue = Json.parse(""" { "source": "<STRING>", "data": {}, "metadata": {} } """) val displayData: DisplayData = DisplayData( "<STRING>", Map(), Map() ) describe("DisplayData") { describe("#toTypeString") { it("should return correct type") { DisplayData.toTypeString should be ("display_data") } } describe("implicit conversions") { it("should implicitly convert from valid json to a displayData instance") { // This is the least safe way to convert as an error is thrown if it fails displayDataJson.as[DisplayData] should be (displayData) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newDisplayData = displayDataJson.asOpt[DisplayData] newDisplayData.get should be (displayData) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val displayDataResults = displayDataJson.validate[DisplayData] displayDataResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: DisplayData) => valid ) should be (displayData) } it("should implicitly convert from a displayData instance to valid json") { Json.toJson(displayData) should be (displayDataJson) } } } }
Example 67
Source File: ShutdownReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ShutdownReplySpec extends FunSpec with Matchers { val shutdownReplyJson: JsValue = Json.parse(""" { "restart": true } """) val shutdownReply: ShutdownReply = ShutdownReply( true ) describe("ShutdownReply") { describe("#toTypeString") { it("should return correct type") { ShutdownReply.toTypeString should be ("shutdown_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ShutdownReply instance") { // This is the least safe way to convert as an error is thrown if it fails shutdownReplyJson.as[ShutdownReply] should be (shutdownReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newShutdownReply = shutdownReplyJson.asOpt[ShutdownReply] newShutdownReply.get should be (shutdownReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ShutdownReplyResults = shutdownReplyJson.validate[ShutdownReply] ShutdownReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ShutdownReply) => valid ) should be (shutdownReply) } it("should implicitly convert from a ShutdownReply instance to valid json") { Json.toJson(shutdownReply) should be (shutdownReplyJson) } } } }
Example 68
Source File: BrokerBridgeSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.interpreter.broker import org.apache.toree.kernel.api.KernelLike import org.scalatest.mock.MockitoSugar import org.scalatest.{FunSpec, Matchers, OneInstancePerTest} class BrokerBridgeSpec extends FunSpec with Matchers with OneInstancePerTest with MockitoSugar { private val mockBrokerState = mock[BrokerState] private val mockKernel = mock[KernelLike] private val brokerBridge = new BrokerBridge( mockBrokerState, mockKernel ) describe("BrokerBridge") { describe("#state") { it("should return the broker state from the constructor") { brokerBridge.state should be (mockBrokerState) } } describe("#kernel") { it("should return the kernel from the constructor") { brokerBridge.kernel should be (mockKernel) } } } }
Example 69
Source File: ParseVendorExtensionsTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import com.fasterxml.jackson.core.JsonParseException import com.fasterxml.jackson.dataformat.yaml.snakeyaml.parser.ParserException import de.zalando.apifirst.Application.ApiCall import de.zalando.apifirst.Http.{ GET, POST, PUT } import org.scalatest.{ FunSpec, MustMatchers } class ParseVendorExtensionsTest extends FunSpec with MustMatchers with ExpectedResults { val ok = new File(resourcesPath + "extensions/extensions.ok.yaml") val nok = new File(resourcesPath + "extensions/extensions.nok.yaml") val hypermediaOk = new File(resourcesPath + "extensions/hypermedia.ok.yaml") val hypermediaNOk1 = new File(resourcesPath + "extensions/hypermedia.nok1.yaml") val hypermediaNOk2 = new File(resourcesPath + "extensions/hypermedia.nok2.yaml") val errorMapping = new File(resourcesPath + "extensions/error_mapping.yaml") describe("The swagger parser") { it("should read valid vendor extensions") { implicit val (uri, swagger) = StrictYamlParser.parse(ok) swagger.info.vendorExtensions contains "x-info-extension" mustBe true swagger.paths("/").vendorExtensions contains "x-path-extension" mustBe true swagger.paths("/").get.vendorExtensions contains "x-operation-extension" mustBe true swagger.paths("/").get.responses("200").vendorExtensions contains "x-response-extension" mustBe true swagger.tags.head.vendorExtensions contains "x-tag-extension" mustBe true swagger.securityDefinitions("internalApiKey").vendorExtensions contains "x-security-extension" mustBe true } it("should read hypermedia definitions") { implicit val (uri, swagger) = StrictYamlParser.parse(hypermediaOk) val expected = Map( "resource created" -> Map("resource updated" -> Map("condition" -> "some rule to show the transition"), "subresource added" -> null), "resource updated" -> Map( "subresource added" -> Map("condition" -> ""), "self" -> Map("condition" -> "non-empty rule") ), "resource deleted" -> Map("self" -> null), "subresource added" -> Map("resource updated" -> null, "self" -> null, "resource deleted" -> null) ) swagger.transitions.nonEmpty mustBe true swagger.transitions mustEqual expected swagger.paths("/").get.responses("200").targetState mustEqual Some("resource created") swagger.paths("/").get.responses("default").targetState mustEqual None } it("should reject hypermedia definitions without well-formed definition") { val exception = intercept[JsonParseException] { StrictYamlParser.parse(hypermediaNOk1) } exception.getMessage mustEqual "Malformed transition definitions" } it("should reject hypermedia definitions with incorrect initial state") { intercept[ParserException] { StrictYamlParser.parse(hypermediaNOk2) }.getClass mustBe classOf[ParserException] } it("should read error mappings and assign right preference to them") { val (uri, model) = StrictYamlParser.parse(errorMapping) val ast = ModelConverter.fromModel(errorMapping.toURI, model, Option(errorMapping)) val expectedForPUT = Map( "404" -> List(classOf[java.util.NoSuchElementException]), "403" -> List(classOf[java.lang.SecurityException]), "405" -> List(classOf[java.lang.IllegalStateException]), "400" -> List(classOf[java.util.NoSuchElementException]) ) val expectedForPOST = Map( "403" -> List(classOf[java.lang.SecurityException]), "404" -> List(classOf[java.util.NoSuchElementException]), "405" -> List(classOf[java.lang.IllegalStateException]) ) ast.calls.foreach { case ApiCall(POST, _, _, _, _, mapping, _, _, _) => mapping must contain theSameElementsAs expectedForPOST case ApiCall(PUT, _, _, _, _, mapping, _, _, _) => mapping must contain theSameElementsAs expectedForPUT } } } }
Example 70
Source File: SecurityConstraintsIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import org.scalatest.{ FunSpec, MustMatchers } class SecurityConstraintsIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "security_constraints/" val fixtures = new File("swagger-parser/src/test/resources/examples").listFiles describe("Swagger ApiCall Converter with security constraints") { fixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testSecurityConverter(file) } } def testSecurityConverter(file: File): Unit = { it(s"should convert security constraints in ${file.getName}") { val (base, model) = StrictYamlParser.parse(file) val ast = ModelConverter.fromModel(base, model, Option(file)) val fullResult = ast.calls.filter(_.security.nonEmpty).flatMap(_.security).distinct.mkString("\n") val expected = asInFile(file, "types") if (expected.isEmpty && fullResult.trim.nonEmpty) dump(fullResult, file, "types") clean(fullResult) mustBe clean(expected) } } }
Example 71
Source File: Rfc3339UtilTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.play.controllers import java.time.{ LocalDateTime, ZoneId, ZoneOffset, ZonedDateTime } import org.scalatest.{ FunSpec, MustMatchers } class Rfc3339UtilTest extends FunSpec with MustMatchers { val dtz = ZoneId.of("UTC") val offset = ZoneOffset.UTC //noinspection ScalaStyle val date = ZonedDateTime.of(LocalDateTime.ofEpochSecond(1451911387L, 0, offset), dtz) describe("Rfc3339UtilTest") { it("should parse RFC3339 DateTime") { Rfc3339Util.parseDateTime("2007-05-01T15:43:26-00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]" Rfc3339Util.parseDateTime("2007-05-01T15:43:26+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]" Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452-01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T16:43:26.345200Z[UTC]" Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T14:43:26.345200Z[UTC]" Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26.345200Z[UTC]" } it("should parse RFC3339 Date") { Rfc3339Util.parseDate("2007-05-01").toString mustBe "2007-05-01" Rfc3339Util.parseDate("2008-05-01").toString mustBe "2008-05-01" Rfc3339Util.parseDate("2007-08-01").toString mustBe "2007-08-01" Rfc3339Util.parseDate("2007-05-08").toString mustBe "2007-05-08" } it("should write DateTime") { Rfc3339Util.writeDateTime(date) mustBe "2016-01-04T12:43:07.0000+0000" } it("should write Date") { Rfc3339Util.writeDate(date.toLocalDate) mustBe "2016-01-04" } } }
Example 72
Source File: RuleGeneratorTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.play.generator.routes import de.zalando.apifirst.Application.StrictModel import de.zalando.apifirst.naming.Path import org.scalatest.{ FunSpec, MustMatchers } import play.routes.compiler.{ DynamicPart, StaticPart } class RuleGeneratorTest extends FunSpec with MustMatchers { implicit val model = StrictModel(Nil, Map.empty, Map.empty, Map.empty, "/base/", None, Map.empty, Map.empty) val routes = Map( "/" -> Nil, "/a/b/c/d" -> List(StaticPart("a/b/c/d")), "/a/b/c/d/" -> List(StaticPart("a/b/c/d/")), "/a/{b}/c/{d}" -> List(StaticPart("a/"), DynamicPart("b", """[^/]+""", true), StaticPart("/c/"), DynamicPart("d", """[^/]+""", true)), "/{a}/{b}/{c}/{d}/" -> List(DynamicPart("a", """[^/]+""", true), StaticPart("/"), DynamicPart("b", """[^/]+""", true), StaticPart("/"), DynamicPart("c", """[^/]+""", true), StaticPart("/"), DynamicPart("d", """[^/]+""", true), StaticPart("/")), "/{a}/b/{c}/d/" -> List(DynamicPart("a", """[^/]+""", true), StaticPart("/b/"), DynamicPart("c", """[^/]+""", true), StaticPart("/d/")) ) describe("RuleGeneratorTest") { routes.foreach { case (path, expected) => it(s"should parse $path as expected") { val result = RuleGenerator.convertPath(Path(path)).parts result must contain theSameElementsInOrderAs expected } } } }
Example 73
Source File: ReferenceTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst import de.zalando.apifirst.Domain._ import de.zalando.apifirst.naming._ import de.zalando.apifirst.naming.dsl._ import org.scalatest.{ FunSpec, MustMatchers } class ReferenceTest extends FunSpec with MustMatchers { describe("Reference") { it("can be created from absolute URI strings, optionally containing pointer fragments") { Reference("file:/swagger.yaml") mustBe Reference("file:/swagger.yaml") Reference("http://goo.gl/swagger.yaml") mustBe Reference("http://goo.gl/swagger.yaml") Reference("file:/swagger.yaml#/foo/bar") mustBe Reference("file:/swagger.yaml#/foo/bar") } it("can be created containing pointer fragments identifying a path segment") { ("{foo}" / "{bar}").parent mustBe Reference("{foo}") } it("must be able to append pointer tokens") { val base = Reference("file:/swagger.yaml") base / "foo" mustBe "file:/swagger.yaml" / "foo" base / "foo" / "bar" mustBe "file:/swagger.yaml" / "foo" / "bar" } it("must be able to append pointers") { val base = Reference("file:/swagger.yaml") val foo = Reference("foo") val bar = Reference("bar") base / foo mustBe "file:/swagger.yaml" / "foo" base / foo / bar mustBe "file:/swagger.yaml" / "foo" / "bar" base / foo / "" / bar mustBe "file:/swagger.yaml" / "foo" / "" / "bar" } it("must be able to prepend pointer tokens") { val reference = "file:/swagger.yaml" / "bar" reference.prepend("foo") mustBe "foo" / "file:/swagger.yaml" / "bar" } it("must return a pointers parent reference or itself if no parent pointer reference exists") { val base = Reference("file:/swagger.yaml") (base / "foo" / "bar").parent mustBe "file:/swagger.yaml" / "foo" (base / "foo").parent mustBe Reference("file:/swagger.yaml") base.parent mustBe Reference("") } it("must ignore starting # while comparing references") { val one = TypeDef(Reference("/definitions/ErrorModel"), Seq( new Field(Reference("/definitions/ErrorModel/message"), Str(None, TypeMeta(None))), new Field(Reference("/definitions/ErrorModel/code"), Intgr(TypeMeta(None))) ), TypeMeta(None)) val two = TypeDef(Reference("#/definitions/ErrorModel"), Seq( new Field(Reference("#/definitions/ErrorModel/message"), Str(None, TypeMeta(None))), new Field(Reference("#/definitions/ErrorModel/code"), Intgr(TypeMeta(None))) ), TypeMeta(None)) } } }
Example 74
Source File: PathTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst import de.zalando.apifirst.naming.Path import org.scalatest.{ FunSpec, MustMatchers } class PathTest extends FunSpec with MustMatchers { describe("Path") { it("should convert the root path") { val root = Path("/") root.asSwagger mustBe "/" root.prepend("/echo/").asSwagger mustBe "/echo/" root.prepend("/echo").asSwagger mustBe "/echo/" } it("should convert absolute segments") { val a = Path("/a") a.asSwagger mustBe "/a" a.prepend("/echo/").asSwagger mustBe "/echo/a" a.prepend("/echo").asSwagger mustBe "/echo/a" } it("should convert relative segments") { val a = Path("a") a.asSwagger mustBe "/a" a.prepend("/echo/").asSwagger mustBe "/echo/a" a.prepend("/echo").asSwagger mustBe "/echo/a" } it("should convert absolute segments with trailing slash") { val a = Path("/a/") a.asSwagger mustBe "/a/" a.prepend("/echo/").asSwagger mustBe "/echo/a/" a.prepend("/echo").asSwagger mustBe "/echo/a/" } it("should convert nested path segments") { val a = Path("a/b") a.asSwagger mustBe "/a/b" a.prepend("/echo/").asSwagger mustBe "/echo/a/b" a.prepend("/echo").asSwagger mustBe "/echo/a/b" } it("should convert in-path parameters") { val a = Path("/{a}") a.asSwagger mustBe "/{a}" a.prepend("/echo/").asSwagger mustBe "/echo/{a}" a.prepend("/echo").asSwagger mustBe "/echo/{a}" a.interpolated mustBe "/${toPath(a)}" a.prepend("/echo/").interpolated mustBe "/echo/${toPath(a)}" a.prepend("/echo").interpolated mustBe "/echo/${toPath(a)}" a.asPlay mustBe "/:a" a.prepend("/echo/").asPlay mustBe "/echo/:a" a.prepend("/echo").asPlay mustBe "/echo/:a" a.asMethod mustBe "byA" a.prepend("/echo/").asMethod mustBe "echoByA" a.prepend("/echo").asMethod mustBe "echoByA" } it("should convert in-path parameters with trailing slash") { val a = Path("/a/{a}/") a.asSwagger mustBe "/a/{a}/" a.prepend("/echo/").asSwagger mustBe "/echo/a/{a}/" a.prepend("/echo").asSwagger mustBe "/echo/a/{a}/" a.interpolated mustBe "/a/${toPath(a)}/" a.prepend("/echo/").interpolated mustBe "/echo/a/${toPath(a)}/" a.prepend("/echo").interpolated mustBe "/echo/a/${toPath(a)}/" a.asPlay mustBe "/a/:a/" a.prepend("/echo/").asPlay mustBe "/echo/a/:a/" a.prepend("/echo").asPlay mustBe "/echo/a/:a/" a.asMethod mustBe "aByA" a.prepend("/echo/").asMethod mustBe "echoAByA" a.prepend("/echo").asMethod mustBe "echoAByA" } it("should convert multiple in-path parameters") { val a = Path("/a/{b}/{c}/d/{e}") a.asSwagger mustBe "/a/{b}/{c}/d/{e}" a.prepend("/echo/").asSwagger mustBe "/echo/a/{b}/{c}/d/{e}" a.prepend("/echo").asSwagger mustBe "/echo/a/{b}/{c}/d/{e}" a.interpolated mustBe "/a/${toPath(b)}/${toPath(c)}/d/${toPath(e)}" a.prepend("/echo/").interpolated mustBe "/echo/a/${toPath(b)}/${toPath(c)}/d/${toPath(e)}" a.prepend("/echo").interpolated mustBe "/echo/a/${toPath(b)}/${toPath(c)}/d/${toPath(e)}" a.asPlay mustBe "/a/:b/:c/d/:e" a.prepend("/echo/").asPlay mustBe "/echo/a/:b/:c/d/:e" a.prepend("/echo").asPlay mustBe "/echo/a/:b/:c/d/:e" a.asMethod mustBe "aByBByCDByE" a.prepend("/echo/").asMethod mustBe "echoAByBByCDByE" a.prepend("/echo").asMethod mustBe "echoAByBByCDByE" } } }
Example 75
Source File: ScalaNameTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst import de.zalando.apifirst.ScalaName._ import de.zalando.apifirst.naming.dsl._ import org.scalatest.{ FunSpec, MustMatchers } class ScalaNameTest extends FunSpec with MustMatchers { it("must correctly capitalize names") { ("one" / "two" / "three").names mustBe (("one", "Two", "three")) ("ONE" / "TWO" / "THREE").names mustBe (("one", "TWO", "tHREE")) ("OnE" / "TwO" / "ThReE").names mustBe (("one", "TwO", "thReE")) } it("must correctly recognize short names") { ("one" / "two").names mustBe (("one", "Two", "two")) } it("must correctly escape scala names") { ("catch" / "if" / "match").names mustBe (("`catch`", "If", "`match`")) } it("must be able to produce import statemets") { ("java.util" / "date").qualifiedName("", "") mustBe (("java.util", "Date")) } it("must correctly concat names") { ("definitions" / "Example" / "nestedArrays" / "Opt" / "Arr:").names mustBe (("definitions", "Example", "arr_esc")) } }
Example 76
Source File: TypeFlattenerIntegrationTest.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.apifirst import java.io.File import de.zalando.apifirst.util.ScalaPrinter import org.scalatest.{ FunSpec, MustMatchers } import scala.io.Source class TypeFlattenerIntegrationTest extends FunSpec with MustMatchers { val expectation_path = "play-scala-generator/src/test/scala/model/" val prefix = "resources." import de.zalando.model._ val plainModels = Seq[WithModel]( additional_properties_yaml, basic_auth_api_yaml, basic_extension_yaml, basic_polymorphism_yaml, cross_spec_references_yaml, echo_api_yaml, error_in_array_yaml, expanded_polymorphism_yaml, form_data_yaml, full_petstore_api_yaml, hackweek_yaml, heroku_petstore_api_yaml, instagram_api_yaml, minimal_api_yaml, nakadi_yaml, nested_arrays_yaml, nested_arrays_validation_yaml, nested_objects_yaml, nested_objects_validation_yaml, nested_options_yaml, nested_options_validation_yaml, numbers_validation_yaml, options_yaml, security_api_yaml, simple_petstore_api_yaml, split_petstore_api_yaml, string_formats_yaml, string_formats_validation_yaml, type_deduplication_yaml, uber_api_yaml ) describe("TypeFlattener") { plainModels.foreach { model => testTypeFlattener(model) } } def testTypeFlattener(ast: WithModel): Unit = { val name = ScalaPrinter.nameFromModel(ast) it(s"should flatten API model $name") { val scalaModel = TypeNormaliser.flatten(ast.model) val expected = asInFile(name, ".scala") clean(ScalaPrinter.asScala(name, scalaModel)) mustBe clean(expected) } } def asInFile(name: String, suffix: String): String = { val expectedFile = new File(expectation_path, prefix + name + suffix) if (expectedFile.canRead) { val src = Source.fromFile(expectedFile) val result = src.getLines().mkString("\n") src.close() result } else "" } def clean(str: String): String = str.split("\n").map(_.trim).filter(_.nonEmpty).mkString("\n") }
Example 77
Source File: ImplicitsSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.plugins import org.apache.toree.plugins.dependencies.Dependency import org.scalatest.{OneInstancePerTest, Matchers, FunSpec} class ImplicitsSpec extends FunSpec with Matchers with OneInstancePerTest { describe("Implicits") { describe("#$dep") { it("should convert values to dependencies with generated names") { import scala.reflect.runtime.universe._ import org.apache.toree.plugins.Implicits._ val value = new Object val d: Dependency[_] = value d.name should not be (empty) d.`type` should be (typeOf[Object]) d.value should be (value) } it("should convert tuples of (string, value) to dependencies with the specified names") { import scala.reflect.runtime.universe._ import org.apache.toree.plugins.Implicits._ val name = "some name" val value = new Object val d: Dependency[_] = name -> value d.name should be (name) d.`type` should be (typeOf[Object]) d.value should be (value) } } } }
Example 78
Source File: PluginManagerSpecForIntegration.scala From incubator-toree with Apache License 2.0 | 5 votes |
package integration import org.apache.toree.plugins.{PluginManager, Plugin} import org.apache.toree.plugins.annotations.Init import org.scalatest.{OneInstancePerTest, Matchers, FunSpec} class PluginManagerSpecForIntegration extends FunSpec with Matchers with OneInstancePerTest { private val pluginManager = new PluginManager describe("PluginManager") { it("should be able to load and initialize internal plugins") { val plugins = pluginManager.initialize() plugins.map(_.name) should contain allOf ( classOf[NonCircularPlugin].getName, classOf[RegisterPluginA].getName, classOf[ConsumePluginA].getName ) } it("should be able to initialize plugins with dependencies provided by other plugins") { val cpa = pluginManager.loadPlugin("", classOf[ConsumePluginA]).get val rpa = pluginManager.loadPlugin("", classOf[RegisterPluginA]).get val results = pluginManager.initializePlugins(Seq(cpa, rpa)) results.forall(_.isSuccess) should be (true) } it("should fail when plugins have circular dependencies") { val cp = pluginManager.loadPlugin("", classOf[CircularPlugin]).get val results = pluginManager.initializePlugins(Seq(cp)) results.forall(_.isFailure) should be (true) } it("should be able to handle non-circular dependencies within the same plugin") { val ncp = pluginManager.loadPlugin("", classOf[NonCircularPlugin]).get val results = pluginManager.initializePlugins(Seq(ncp)) results.forall(_.isSuccess) should be (true) } } } private class DepA private class DepB private class CircularPlugin extends Plugin { @Init def initMethodA(depA: DepA) = register(new DepB) @Init def initMethodB(depB: DepB) = register(new DepA) } private class NonCircularPlugin extends Plugin { @Init def initMethodB(depB: DepB) = {} @Init def initMethodA(depA: DepA) = register(new DepB) @Init def initMethod() = register(new DepA) } private class RegisterPluginA extends Plugin { @Init def initMethod() = register(new DepA) } private class ConsumePluginA extends Plugin { @Init def initMethod(depA: DepA) = {} }
Example 79
Source File: HistoryRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class HistoryRequestSpec extends FunSpec with Matchers { val historyRequestJson: JsValue = Json.parse(""" { "output": true, "ras": true, "hist_access_type": "<STRING>", "session": 1, "start": 0, "stop": 5, "n": 1, "pattern": "<STRING>", "unique": true } """) val historyRequest = HistoryRequest( true, true, "<STRING>", 1, 0, 5, 1, "<STRING>", true ) describe("HistoryRequest") { describe("#toTypeString") { it("should return correct type") { HistoryRequest.toTypeString should be ("history_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a HistoryRequest instance") { // This is the least safe way to convert as an error is thrown if it fails historyRequestJson.as[HistoryRequest] should be (historyRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = historyRequestJson.asOpt[HistoryRequest] newCompleteRequest.get should be (historyRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = historyRequestJson.validate[HistoryRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: HistoryRequest) => valid ) should be (historyRequest) } it("should implicitly convert from a HistoryRequest instance to valid json") { Json.toJson(historyRequest) should be (historyRequestJson) } } } }
Example 80
Source File: BrokerProcessHandlerSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.interpreter.broker import org.apache.commons.exec.ExecuteException import org.scalatest.mock.MockitoSugar import org.scalatest.{FunSpec, Matchers, OneInstancePerTest} import org.mockito.Mockito._ import org.mockito.Matchers._ class BrokerProcessHandlerSpec extends FunSpec with Matchers with OneInstancePerTest with MockitoSugar { private val mockBrokerBridge = mock[BrokerBridge] private val brokerProcessHandler = new BrokerProcessHandler( mockBrokerBridge, restartOnFailure = true, restartOnCompletion = true ) describe("BrokerProcessHandler") { describe("#onProcessFailed") { it("should invoke the reset method") { val mockResetMethod = mock[String => Unit] brokerProcessHandler.setResetMethod(mockResetMethod) brokerProcessHandler.onProcessFailed(mock[ExecuteException]) verify(mockResetMethod).apply(anyString()) } it("should invoke the restart method if the proper flag is set to true") { val mockRestartMethod = mock[() => Unit] brokerProcessHandler.setRestartMethod(mockRestartMethod) brokerProcessHandler.onProcessFailed(mock[ExecuteException]) verify(mockRestartMethod).apply() } } describe("#onProcessComplete") { it("should invoke the reset method") { val mockResetMethod = mock[String => Unit] brokerProcessHandler.setResetMethod(mockResetMethod) brokerProcessHandler.onProcessComplete(0) verify(mockResetMethod).apply(anyString()) } it("should invoke the restart method if the proper flag is set to true") { val mockRestartMethod = mock[() => Unit] brokerProcessHandler.setRestartMethod(mockRestartMethod) brokerProcessHandler.onProcessComplete(0) verify(mockRestartMethod).apply() } } } }
Example 81
Source File: BrokerTransformerSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.interpreter.broker import org.apache.toree.interpreter.{ExecuteError, Results} import org.scalatest.concurrent.Eventually import scala.concurrent.Promise import org.scalatest.{FunSpec, Matchers, OneInstancePerTest} class BrokerTransformerSpec extends FunSpec with Matchers with OneInstancePerTest with Eventually { private val brokerTransformer = new BrokerTransformer describe("BrokerTransformer") { describe("#transformToInterpreterResult") { it("should convert to success with result output if no failure") { val codeResultPromise = Promise[BrokerTypes.CodeResults]() val transformedFuture = brokerTransformer.transformToInterpreterResult( codeResultPromise.future ) val successOutput = "some success" codeResultPromise.success(successOutput) eventually { val result = transformedFuture.value.get.get result should be((Results.Success, Left(Map("text/plain" -> successOutput)))) } } it("should convert to error with broker exception if failure") { val codeResultPromise = Promise[BrokerTypes.CodeResults]() val transformedFuture = brokerTransformer.transformToInterpreterResult( codeResultPromise.future ) val failureException = new BrokerException("some failure") codeResultPromise.failure(failureException) eventually { val result = transformedFuture.value.get.get result should be((Results.Error, Right(ExecuteError( name = failureException.getClass.getName, value = failureException.getLocalizedMessage, stackTrace = failureException.getStackTrace.map(_.toString).toList )))) } } } } }
Example 82
Source File: CoursierDependencyDownloaderSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.dependencies import java.net.URL import java.nio.file.Files import org.scalatest.{FunSpec, Matchers, OneInstancePerTest} class CoursierDependencyDownloaderSpec extends FunSpec with Matchers with OneInstancePerTest { private val coursierDependencyDownloader = new CoursierDependencyDownloader describe("CoursierDependencyDownloader") { describe("#addMavenRepository") { it("should add to the list of repositories") { val repo = new URL("http://some-repo.com") coursierDependencyDownloader.addMavenRepository(repo, None) val repos = coursierDependencyDownloader.getRepositories repos should contain (repo.toURI) } } describe("#removeMavenRepository") { it("should remove from the list of repositories") { val repo = new URL("http://some-repo.com") coursierDependencyDownloader.addMavenRepository(repo, None) coursierDependencyDownloader.removeMavenRepository(repo) val repos = coursierDependencyDownloader.getRepositories repos should not contain (repo.toURI) } } describe("#setDownloadDirectory") { it("should set the new download directory if valid") { val validDir = Files.createTempDirectory("tmpdir").toFile validDir.deleteOnExit() val result = coursierDependencyDownloader.setDownloadDirectory(validDir) result should be (true) val dir = coursierDependencyDownloader.getDownloadDirectory dir should be (validDir.getAbsolutePath) } it("should not change the directory if given a file") { val invalidDir = Files.createTempFile("tmp", "file").toFile invalidDir.deleteOnExit() val result = coursierDependencyDownloader.setDownloadDirectory(invalidDir) result should be (false) val dir = coursierDependencyDownloader.getDownloadDirectory dir should not be (invalidDir.getAbsolutePath) } it("should support creating missing directories") { val baseDir = Files.createTempDirectory("tmpdir").toFile val validDir = baseDir.toPath.resolve("otherdir").toFile validDir.deleteOnExit() baseDir.deleteOnExit() val result = coursierDependencyDownloader.setDownloadDirectory(validDir) result should be (true) val dir = coursierDependencyDownloader.getDownloadDirectory dir should be (validDir.getAbsolutePath) } } describe("#getRepositories") { it("should have the default repositories") { val expected = Seq(DependencyDownloader.DefaultMavenRepository.toURI) val actual = coursierDependencyDownloader.getRepositories actual should be (expected) } } describe("#getDownloadDirectory") { it("should have the default download directory") { val expected = DependencyDownloader.DefaultDownloadDirectory.getAbsolutePath val actual = coursierDependencyDownloader.getDownloadDirectory actual should be (expected) } } } }
Example 83
Source File: InternalClassLoaderSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.magic import org.scalatest.{Matchers, FunSpec} import org.scalatest.mock.MockitoSugar class InternalClassLoaderSpec extends FunSpec with Matchers with MockitoSugar { abstract class MockClassLoader extends ClassLoader(null) { override def loadClass(name: String): Class[_] = null } describe("InternalClassLoader") { describe("#loadClass") { it("should invoke super loadClass with loader's package prepended") { val expected = classOf[Class[_]] val packageName = "org.apache.toree.magic" val className = "SomeClass" var parentLoadClassCorrectlyInvoked = false val internalClassLoader = new InternalClassLoader(null) { override private[magic] def parentLoadClass(name: String, resolve: Boolean): Class[_] = { parentLoadClassCorrectlyInvoked = name == s"$packageName.$className" && resolve expected } } internalClassLoader.loadClass(className, true) should be (expected) parentLoadClassCorrectlyInvoked should be (true) } it("should use loader's package instead of provided package first") { val expected = classOf[Class[_]] val forcedPackageName = "org.apache.toree.magic" val packageName = "some.other.package" val className = "SomeClass" var parentLoadClassCorrectlyInvoked = false val internalClassLoader = new InternalClassLoader(null) { override private[magic] def parentLoadClass(name: String, resolve: Boolean): Class[_] = { parentLoadClassCorrectlyInvoked = name == s"$forcedPackageName.$className" && resolve expected } } internalClassLoader.loadClass(s"$packageName.$className", true) should be (expected) parentLoadClassCorrectlyInvoked should be (true) } it("should invoke super loadClass with given package if internal missing") { val expected = classOf[Class[_]] val packageName = "some.other.package" val className = "SomeClass" var parentLoadClassCorrectlyInvoked = false var methodCalled = false val internalClassLoader = new InternalClassLoader(null) { override private[magic] def parentLoadClass(name: String, resolve: Boolean): Class[_] = { if (!methodCalled) { methodCalled = true throw new ClassNotFoundException() } parentLoadClassCorrectlyInvoked = name == s"$packageName.$className" && resolve expected } } internalClassLoader.loadClass(s"$packageName.$className", true) should be (expected) parentLoadClassCorrectlyInvoked should be (true) } } } }
Example 84
Source File: ConditionalOutputStreamSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.utils import java.io.OutputStream import org.scalatest.mock.MockitoSugar import org.mockito.Mockito._ import org.mockito.Matchers._ import org.scalatest.{Matchers, FunSpec} class ConditionalOutputStreamSpec extends FunSpec with Matchers with MockitoSugar { describe("ConditionalOutputStream") { describe("#()") { it("should throw an exception if the output stream is null") { intercept[IllegalArgumentException] { new ConditionalOutputStream(null, true) } } } describe("#write") { it("should call the underlying write if the condition is true") { val mockOutputStream = mock[OutputStream] val conditionalOutputStream = new ConditionalOutputStream(mockOutputStream, true) val expected = 101 conditionalOutputStream.write(expected) verify(mockOutputStream).write(expected) } it("should call the underlying write if the condition becomes true") { val mockOutputStream = mock[OutputStream] var condition = false val conditionalOutputStream = new ConditionalOutputStream(mockOutputStream, condition) condition = true val expected = 101 conditionalOutputStream.write(expected) verify(mockOutputStream).write(expected) } it("should not call the underlying write if the condition is false") { val mockOutputStream = mock[OutputStream] val conditionalOutputStream = new ConditionalOutputStream(mockOutputStream, false) val expected = 101 conditionalOutputStream.write(expected) verify(mockOutputStream, never()).write(any[Byte]) } it("should not call the underlying write if the condition becomes false") { val mockOutputStream = mock[OutputStream] var condition = true val conditionalOutputStream = new ConditionalOutputStream(mockOutputStream, condition) condition = false val expected = 101 conditionalOutputStream.write(expected) verify(mockOutputStream, never()).write(any[Byte]) } } } }
Example 85
Source File: ArgumentParsingSupportSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.utils import org.scalatest.{BeforeAndAfter, Matchers, FunSpec} import joptsimple.{OptionSet, OptionSpec, OptionParser} import org.scalatest.mock.MockitoSugar import org.mockito.Mockito._ import org.mockito.Matchers._ import collection.JavaConverters._ class ArgumentParsingSupportSpec extends FunSpec with Matchers with BeforeAndAfter with MockitoSugar { private var mockOptions: OptionSet = _ private var mockParser: OptionParser = _ private var argumentParsingInstance: ArgumentParsingSupport = _ before { mockOptions = mock[OptionSet] mockParser = mock[OptionParser] doReturn(mockOptions).when(mockParser).parse(anyVararg[String]()) argumentParsingInstance = new Object() with ArgumentParsingSupport { override protected lazy val parser: OptionParser = mockParser } } describe("ArgumentParsingSupport") { describe("#parseArgs") { it("should invoke the underlying parser's parse method") { doReturn(Nil.asJava).when(mockOptions).nonOptionArguments() argumentParsingInstance.parseArgs("") verify(mockParser).parse(anyString()) } it("should return an empty list if there are no non-option arguments") { val expected = Nil doReturn(expected.asJava).when(mockOptions).nonOptionArguments() val actual = argumentParsingInstance.parseArgs(( "--transitive" :: expected ).mkString(" ")) actual should be (expected) } it("should return a list containing non-option arguments") { val expected = "non-option" :: Nil doReturn(expected.asJava).when(mockOptions).nonOptionArguments() val actual = argumentParsingInstance.parseArgs(( "--transitive" :: expected ).mkString(" ")) actual should be (expected) } } } }
Example 86
Source File: KeyValuePairUtilsSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.utils import joptsimple.util.KeyValuePair import org.scalatest.{Matchers, FunSpec} class KeyValuePairUtilsSpec extends FunSpec with Matchers { private object TestKeyValuePair { def apply(key: String, value: String) = KeyValuePair.valueOf(s"$key=$value") } describe("KeyValuePairUtils") { describe("#stringToKeyValuePairSeq") { it("should throw an exception when given a null string") { intercept[IllegalArgumentException] { KeyValuePairUtils.stringToKeyValuePairSeq(null) } } it("should convert an empty string to an empty sequence") { val expected = Nil val actual = KeyValuePairUtils.stringToKeyValuePairSeq("") actual should be (expected) } it("should convert a single key-value pair to a sequence with one pair") { val expected = Seq(TestKeyValuePair("key", "value")) val actual = KeyValuePairUtils.stringToKeyValuePairSeq("key=value") actual should be (expected) } it("should convert multiple key-value pairs using the provided delimiter") { val expected = Seq( TestKeyValuePair("key1", "value1"), TestKeyValuePair("key2", "value2") ) val actual = KeyValuePairUtils.stringToKeyValuePairSeq( "key1=value1, key2=value2", ",") actual should be (expected) } it("should fail if the string does not contain valid key-value pairs") { KeyValuePairUtils.stringToKeyValuePairSeq("not valid") } } describe("#keyValuePairSeqToString") { it("should throw an exception when given a null sequence") { intercept[IllegalArgumentException] { KeyValuePairUtils.keyValuePairSeqToString(null) } } it("should return an empty string if the sequence is empty") { val expected = "" val actual = KeyValuePairUtils.keyValuePairSeqToString(Nil) actual should be (expected) } it("should generate key=value for a key-value pair") { val expected = "key=value" val actual = KeyValuePairUtils.keyValuePairSeqToString( Seq(TestKeyValuePair("key", "value"))) actual should be (expected) } it("should use the provided delimiter to separate key-value pairs") { val expected = "key1=value1,key2=value2" val actual = KeyValuePairUtils.keyValuePairSeqToString(Seq( TestKeyValuePair("key1", "value1"), TestKeyValuePair("key2", "value2") ), ",") actual should be (expected) } it("should trim whitespace from keys and values") { val expected = "key1=value1,key2=value2" val actual = KeyValuePairUtils.keyValuePairSeqToString(Seq( TestKeyValuePair(" key1", " value1 "), TestKeyValuePair("\tkey2 ", "value2\t") ), ",") actual should be (expected) } } } }
Example 87
Source File: MultiOutputStreamSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.utils import java.io.OutputStream import org.scalatest.mock.MockitoSugar import org.scalatest.{BeforeAndAfter, Matchers, FunSpec} import org.mockito.Matchers._ import org.mockito.Mockito._ class MultiOutputStreamSpec extends FunSpec with Matchers with MockitoSugar with BeforeAndAfter { describe("MultiOutputStream") { val listOfMockOutputStreams = List(mock[OutputStream], mock[OutputStream]) val multiOutputStream = MultiOutputStream(listOfMockOutputStreams) describe("#close") { it("should call #close on all internal output streams") { multiOutputStream.close() listOfMockOutputStreams.foreach(mockOutputStream => verify(mockOutputStream).close()) } } describe("#flush") { it("should call #flush on all internal output streams") { multiOutputStream.flush() listOfMockOutputStreams.foreach(mockOutputStream => verify(mockOutputStream).flush()) } } describe("#write(int)") { it("should call #write(int) on all internal output streams") { multiOutputStream.write(anyInt()) listOfMockOutputStreams.foreach( mockOutputStream => verify(mockOutputStream).write(anyInt())) } } describe("#write(byte[])") { it("should call #write(byte[]) on all internal output streams") { multiOutputStream.write(any[Array[Byte]]) listOfMockOutputStreams.foreach( mockOutputStream => verify(mockOutputStream).write(any[Array[Byte]])) } } describe("#write(byte[], int, int)") { it("should call #write(byte[], int, int) on all internal output streams") { multiOutputStream.write(any[Array[Byte]], anyInt(), anyInt()) listOfMockOutputStreams.foreach( mockOutputStream => verify(mockOutputStream).write(any[Array[Byte]], anyInt(), anyInt())) } } } }
Example 88
Source File: DownloadSupportSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.utils import java.io.FileNotFoundException import java.net.URL import org.scalatest.{BeforeAndAfter, Matchers, FunSpec} import scala.io.Source import scala.tools.nsc.io.File class DownloadSupportSpec extends FunSpec with Matchers with BeforeAndAfter { val downloadDestinationUrl = new URL("file:///tmp/testfile2.ext") val testFileContent = "This is a test" val testFileName = "/tmp/testfile.txt" // Create a test file for downloading before { File(testFileName).writeAll(testFileContent) } // Cleanup what we made after { if (File(testFileName).exists) File(testFileName).delete() if (File(downloadDestinationUrl.getPath).exists) File(downloadDestinationUrl.getPath).delete() } describe("DownloadSupport"){ describe("#downloadFile( String, String )"){ it("should download a file to the download directory"){ val testFileUrl = "file:///tmp/testfile.txt" // Create our utility and download the file val downloader = new Object with DownloadSupport downloader.downloadFile( testFileUrl, downloadDestinationUrl.getProtocol + "://" + downloadDestinationUrl.getPath) // Verify the file contents are what was in the original file val downloadedFileContent: String = Source.fromFile(downloadDestinationUrl.getPath).mkString downloadedFileContent should be (testFileContent) } } describe("#downloadFile( URL, URL )"){ it("should download a file to the download directory"){ val testFileUrl = new URL("file:///tmp/testfile.txt") val downloader = new Object with DownloadSupport downloader.downloadFile(testFileUrl, downloadDestinationUrl) // Verify the file contents are what was in the original file val downloadedFileContent: String = Source.fromFile(downloadDestinationUrl.getPath).mkString downloadedFileContent should be (testFileContent) } it("should throw FileNotFoundException if the download URL is bad"){ val badFilename = "file:///tmp/testbadfile.txt" if (File(badFilename).exists) File(badFilename).delete() val badFileUrl = new URL(badFilename) val downloader = new Object with DownloadSupport intercept[FileNotFoundException] { downloader.downloadFile(badFileUrl, downloadDestinationUrl) } } it("should throw FileNotFoundException if the download ") { val testFileUrl = new URL("file:///tmp/testfile.txt") val badDestinationUrl = new URL("file:///tmp/badloc/that/doesnt/exist.txt") val downloader = new Object with DownloadSupport intercept[FileNotFoundException] { downloader.downloadFile(testFileUrl, badDestinationUrl) } } } } }
Example 89
Source File: StdinForSystemSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package system import org.apache.toree.kernel.protocol.v5.client.SparkKernelClient import org.scalatest.concurrent.Eventually import org.scalatest.time.{Seconds, Milliseconds, Span} import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers} import test.utils.root.{SparkKernelClientDeployer, SparkKernelDeployer} describe("Stdin for System") { describe("when the kernel requests input") { ignore("should receive input based on the client's response function") { var response: String = "" client.setResponseFunction((_, _) => TestReplyString) // Read in a chunk of data (our reply string) and return it as a string // to be verified by the test client.execute( """ |var result: Array[Byte] = Array() |val in = kernel.in |do { | result = result :+ in.read().toByte |} while(in.available() > 0) |new String(result) """.stripMargin ).onResult { result => response = result.data("text/plain") }.onError { _ => fail("Client execution to trigger kernel input request failed!") } eventually { response should contain (TestReplyString) } } } } }
Example 90
Source File: ParseVendorExtensionsTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import com.fasterxml.jackson.core.JsonParseException import com.fasterxml.jackson.dataformat.yaml.snakeyaml.parser.ParserException import de.zalando.apifirst.Application.ApiCall import de.zalando.apifirst.Http.{GET, POST, PUT} import org.scalatest.{FunSpec, MustMatchers} class ParseVendorExtensionsTest extends FunSpec with MustMatchers with ExpectedResults { val ok = new File(resourcesPath + "extensions/extensions.ok.yaml") val nok = new File(resourcesPath + "extensions/extensions.nok.yaml") val hypermediaOk = new File(resourcesPath + "extensions/hypermedia.ok.yaml") val hypermediaNOk1 = new File(resourcesPath + "extensions/hypermedia.nok1.yaml") val hypermediaNOk2 = new File(resourcesPath + "extensions/hypermedia.nok2.yaml") val errorMapping = new File(resourcesPath + "extensions/error_mapping.yaml") describe("The swagger parser") { it("should read valid vendor extensions") { implicit val (uri, swagger) = StrictYamlParser.parse(ok) swagger.info.vendorExtensions contains "x-info-extension" mustBe true swagger.paths("/").vendorExtensions contains "x-path-extension" mustBe true swagger.paths("/").get.vendorExtensions contains "x-operation-extension" mustBe true swagger.paths("/").get.responses("200").vendorExtensions contains "x-response-extension" mustBe true swagger.tags.head.vendorExtensions contains "x-tag-extension" mustBe true swagger.securityDefinitions("internalApiKey").vendorExtensions contains "x-security-extension" mustBe true } it("should reject invalid vendor extensions") { intercept[JsonParseException] { StrictYamlParser.parse(nok) }.getClass mustBe classOf[JsonParseException] } it("should read hypermedia definitions") { implicit val (uri, swagger) = StrictYamlParser.parse(hypermediaOk) val expected = Map("resource created" -> Map("resource updated" -> Map("condition" -> "some rule to show the transition"), "subresource added" -> null), "resource updated" -> Map("subresource added" -> Map("condition" -> ""), "self" -> Map("condition" -> "non-empty rule")), "resource deleted" -> Map("self" -> null), "subresource added" -> Map("resource updated" -> null, "self" -> null, "resource deleted" -> null)) swagger.transitions.nonEmpty mustBe true swagger.transitions mustEqual expected swagger.paths("/").get.responses("200").targetState mustEqual Some("resource created") swagger.paths("/").get.responses("default").targetState mustEqual None } it("should reject hypermedia definitions without well-formed definition") { val exception = intercept[JsonParseException] { StrictYamlParser.parse(hypermediaNOk1) } exception.getMessage mustEqual "Malformed transition definitions" } it("should reject hypermedia definitions with incorrect initial state") { intercept[ParserException] { StrictYamlParser.parse(hypermediaNOk2) }.getClass mustBe classOf[ParserException] } it("should read error mappings and assign right preference to them") { val (uri, model) = StrictYamlParser.parse(errorMapping) val ast = ModelConverter.fromModel(errorMapping.toURI, model, Option(errorMapping)) val expectedForPUT = Map( "404" -> List(classOf[java.util.NoSuchElementException]), "403" -> List(classOf[java.lang.SecurityException]), "405" -> List(classOf[java.lang.IllegalStateException]), "400" -> List(classOf[java.util.NoSuchElementException]) ) val expectedForPOST = Map( "403" -> List(classOf[java.lang.SecurityException]), "404" -> List(classOf[java.util.NoSuchElementException]), "405" -> List(classOf[java.lang.IllegalStateException]) ) ast.calls.foreach { case ApiCall(POST, _, _, _, _, mapping, _, _, _) => mapping must contain theSameElementsAs expectedForPOST case ApiCall(PUT, _, _, _, _, mapping, _, _, _) => mapping must contain theSameElementsAs expectedForPUT } } } }
Example 91
Source File: HypermediaConverterTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.apifirst.Hypermedia.State import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{FunSpec, MustMatchers} class HypermediaConverterTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "hypermedia/" val exampleFixtures = new File(resourcesPath + "extensions").listFiles describe("Strict Swagger Parser hypermedia converter") { exampleFixtures.filter(_.getName.startsWith("hypermedia.ok")).foreach { file => testTransitionsConverter(file) testStateDefinitions(file) } } def testTransitionsConverter(file: File): Unit = { it(s"should parse the yaml swagger file ${file.getName} with hypermedia information") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val ast = ModelConverter.fromModel(base, model, Some(file)) val hypermedia = ast.stateTransitions val expected = asInFile(file, "hypermedia") val media = State.toDot(hypermedia).mkString("\n") if (expected.isEmpty && media.nonEmpty) dump(media, file, "hypermedia") clean(media) mustBe clean(expected) } } def testStateDefinitions(file: File): Unit = { it(s"should parse the yaml swagger file ${file.getName} with state name information") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val ast = ModelConverter.fromModel(base, model, Some(file)) val targetStates = ast.calls.map(_.targetStates) val expected = asInFile(file, "states") val media = targetStates.mkString("\n") if (expected.isEmpty && media.nonEmpty) dump(media, file, "states") clean(media) mustBe clean(expected) } } }
Example 92
Source File: SecurityConverterIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{FunSpec, MustMatchers} class SecurityConverterIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "security_definitions/" val fixtures = new File(resourcesPath + "examples").listFiles describe("Swagger Security Converter") { fixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testSecurityConverter(file) } } def testSecurityConverter(file: File): Unit = { it(s"should convert security definitions from ${file.getName}") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val securityDefs = SecurityConverter.convertDefinitions(model.securityDefinitions) val fullResult = securityDefs.mkString("\n") val expected = asInFile(file, "types") if (expected.isEmpty) dump(fullResult, file, "types") clean(fullResult) mustBe clean(expected) } } }
Example 93
Source File: StrictParseExamplesTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import java.net.URI import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{FunSpec, MustMatchers} class StrictParseExamplesTest extends FunSpec with MustMatchers with ExpectedResults { val fixtures = new File(resourcesPath + "examples").listFiles ++ new File(resourcesPath + "schema_examples").listFiles describe("Strict Swagger Parser") { fixtures.filter(_.getName.endsWith(".yaml")).foreach { file => it(s"should parse the yaml swagger file ${file.getName} as specification") { val result = StrictYamlParser.parse(file) result._1 mustBe a [URI] result._2 mustBe a [SwaggerModel] } } } }
Example 94
Source File: SecurityDefinitionDeserializerTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.swagger.strictModel._ import org.scalatest.{MustMatchers, FunSpec} class SecurityDefinitionDeserializerTest extends FunSpec with MustMatchers with ExpectedResults { val file = new File(resourcesPath + "examples/security.api.yaml") describe("SecurityDefinitionDeserializer") { it(s"should parse security definitions in the ${file.getName}") { val (uri, model) = StrictYamlParser.parse(file) val result = model.securityDefinitions result.size mustBe 6 result("petstoreImplicit") mustBe a[Oauth2ImplicitSecurity] result("githubAccessCode") mustBe a[Oauth2AccessCodeSecurity] result("petstorePassword") mustBe a[Oauth2PasswordSecurity] result("justBasicStuff") mustBe a[BasicAuthenticationSecurity] result("petstoreApplication") mustBe a[Oauth2ApplicationSecurity] result("internalApiKey") mustBe a[ApiKeySecurity] } } }
Example 95
Source File: TypeConverterTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.swagger import java.io.File import de.zalando.swagger.strictModel.SwaggerModel import org.scalatest.{FunSpec, MustMatchers} class TypeConverterTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "types/" val modelFixtures = new File(resourcesPath + "model").listFiles val exampleFixtures = new File(resourcesPath + "examples").listFiles describe("Strict Swagger Parser model") { modelFixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testTypeConverter(file) } } describe("Strict Swagger Parser examples") { exampleFixtures.filter(_.getName.endsWith(".yaml")).foreach { file => testTypeConverter(file) } } def testTypeConverter(file: File): Unit = { it(s"should parse the yaml swagger file ${file.getName} as specification") { val (base, model) = StrictYamlParser.parse(file) model mustBe a[SwaggerModel] val typeDefs = ModelConverter.fromModel(base, model, Some(file)).typeDefs val typeMap = typeDefs map { case (k, v) => k -> ("\n\t" + de.zalando.apifirst.util.ShortString.toShortString("\t\t")(v)) } val typesStr = typeMap.toSeq.sortBy(_._1.parts.size).map(p => p._1 + " ->" + p._2).mkString("\n") val expected = asInFile(file, "types") if (expected.isEmpty) dump(typesStr, file, "types") clean(typesStr) mustBe clean(expected) } } }
Example 96
Source File: RuleGeneratorTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.play.compiler import de.zalando.apifirst.Application.StrictModel import de.zalando.apifirst.naming.Path import org.scalatest.{FunSpec, MustMatchers} import play.routes.compiler.{DynamicPart, StaticPart} class RuleGeneratorTest extends FunSpec with MustMatchers { implicit val model = StrictModel(Nil, Map.empty, Map.empty, Map.empty, "/base/", None, Map.empty, Map.empty) val routes = Map( "/" -> Nil ,"/a/b/c/d" -> List(StaticPart("a/b/c/d")) ,"/a/b/c/d/" -> List(StaticPart("a/b/c/d/")) ,"/a/{b}/c/{d}" -> List(StaticPart("a/"), DynamicPart("b", """[^/]+""",true), StaticPart("/c/"), DynamicPart("d", """[^/]+""",true)) ,"/{a}/{b}/{c}/{d}/" -> List(DynamicPart("a", """[^/]+""",true), StaticPart("/"), DynamicPart("b", """[^/]+""",true), StaticPart("/"), DynamicPart("c", """[^/]+""",true), StaticPart("/"), DynamicPart("d", """[^/]+""",true), StaticPart("/")) ,"/{a}/b/{c}/d/" -> List(DynamicPart("a", """[^/]+""",true), StaticPart("/b/"), DynamicPart("c", """[^/]+""",true), StaticPart("/d/")) ) describe("RuleGeneratorTest") { routes.foreach { case (path, expected) => it(s"should parse $path as expected") { val result = RuleGenerator.convertPath(Path(path)).parts result must contain theSameElementsInOrderAs expected } } } }
Example 97
Source File: ScalaMarshallersGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaMarshallersGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "marshallers/" describe("ScalaGenerator should generate marshallers") { examples.foreach { file => testScalaMarshallersGenerator(file) } } def testScalaMarshallersGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaMarshallers(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 98
Source File: ScalaValidatorsGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaValidatorsGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "validation/" describe("ScalaGenerator should generate play validators") { (model ++ examples ++ validations).foreach { ast => testScalaModelGenerator(ast) } } def testScalaModelGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playValidators(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 99
Source File: ScalaPlayTestsGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaPlayTestsGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "tests/" describe("ScalaGenerator should generate tests") { (examples ++ model ++ validations).foreach { file => testScalaFormParserGenerator(file) } } def testScalaFormParserGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaTests(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 100
Source File: ScalaControllerGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaControllerGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "controllers/" describe("ScalaSecurityGenerator should generate controlers") { (model ++ examples).foreach { ast => testScalaControllerGenerator(ast) } } describe("ScalaSecurityGenerator should generate controller bases") { (model ++ examples).foreach { ast => testScalaBaseControllerGenerator(ast) } } def testScalaControllerGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val expected = asInFile(name, "scala") val scalaModel = new ScalaGenerator(model).playScalaControllers(name, ast.model.packageName.getOrElse(name), expected) if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } def testScalaBaseControllerGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaControllerBases(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "base.scala") if (expected.isEmpty) dump(scalaModel, name, "base.scala") clean(scalaModel) mustBe clean(expected) } } }
Example 101
Source File: ScalaFormParserGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaFormParserGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "form_parsers/" describe("ScalaGenerator should generate a form parser") { examples.foreach { file => testScalaFormParserGenerator(file) } } def testScalaFormParserGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaFormParsers(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 102
Source File: ScalaTestDataGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaTestDataGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "test_data/" describe("ScalaGenerator should generate a test data generators") { (examples ++ model).foreach { file => testScalaFormParserGenerator(file) } } def testScalaFormParserGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).generateGenerators(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 103
Source File: ScalaModelGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaModelGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "model/" describe("ScalaGenerator should generate scala model") { (model ++ examples ++ validations).foreach { ast => testScalaModelGenerator(ast) } } def testScalaModelGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).generateModel(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } }
Example 104
Source File: ScalaSecurityGeneratorIntegrationTest.scala From play-swagger with MIT License | 5 votes |
package de.zalando.apifirst.generators import de.zalando.ExpectedResults import de.zalando.model.WithModel import org.scalatest.{FunSpec, MustMatchers} class ScalaSecurityGeneratorIntegrationTest extends FunSpec with MustMatchers with ExpectedResults { override val expectationsFolder = super.expectationsFolder + "security/" describe("ScalaSecurityGenerator should generate security plumbing files") { examples.foreach { ast => testScalaSecurityGenerator(ast) } } describe("ScalaSecurityGenerator should generate security helper files") { examples.foreach { ast => testScalaSecurityExtractorsGenerator(ast) } } def testScalaSecurityGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaSecurity(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "scala") if (expected.isEmpty) dump(scalaModel, name, "scala") clean(scalaModel) mustBe clean(expected) } } def testScalaSecurityExtractorsGenerator(ast: WithModel): Unit = { val name = nameFromModel(ast) it(s"from model $name") { val model = ast.model val scalaModel = new ScalaGenerator(model).playScalaSecurityExtractors(name, ast.model.packageName.getOrElse(name)) val expected = asInFile(name, "extractor.scala") if (expected.isEmpty) dump(scalaModel, name, "extractor.scala") clean(scalaModel) mustBe clean(expected) } } }
Example 105
Source File: MsgPackFormatTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.formats import com.twitter.io.Buf import io.fintrospect.formats.MsgPack.Format._ import org.scalatest.{FunSpec, Matchers} import org.velvia.InvalidMsgPackDataException class MsgPackFormatTest extends FunSpec with Matchers { describe("roundtrips") { val aLetter = Letter(StreetAddress("my house"), StreetAddress("your house"), "hi there") it("roundtrips to JSON and back") { decode[Letter](encode(aLetter)) shouldBe aLetter } it("invalid extracted Msg throws up") { intercept[InvalidMsgPackDataException](decode[Letter](Buf.Empty)) } } }
Example 106
Source File: BookLookupTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.extended import com.twitter.finagle.http.Request import com.twitter.finagle.http.Status.NotFound import io.fintrospect.formats.Argo.JsonFormat.parse import io.fintrospect.testing.TestingFintrospectRoute import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import org.scalatest.{FunSpec, Matchers} class BookLookupTest extends FunSpec with Matchers with TestingFintrospectRoute { override val route = new BookLookup(new Books()).route describe("Book Lookup") { it("can lookup an existing book") { parse(responseFor(Request("/book/hp1")).contentString) shouldBe Book("hairy porker", "j.k oinking", 799).toJson } } it("non-existing book") { statusAndContentFrom(responseFor(Request("/book/hp8")))._1 shouldBe NotFound } }
Example 107
Source File: CompositeTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.parameters import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import io.fintrospect.RequestBuilder import io.fintrospect.util.{Extracted, Extraction, ExtractionError, ExtractionFailed} import org.scalatest.{FunSpec, Matchers} class CompositeTest extends FunSpec with Matchers { case class FooBar(foo: String, bar: Int) object FooBar extends Composite[FooBar] { val foo = add(Query.required.string("foo")) val bar = add(Query.required.int("bar")) override def -->(foobar: FooBar): Iterable[Binding] = (foo --> foobar.foo) ++ (bar --> foobar.bar) override def <--?(req: Request): Extraction[FooBar] = { for { foo <- foo <--? req bar <- bar <--? req } yield FooBar(foo, bar) } } describe("Composite") { it("extraction from request succeeds") { FooBar <--? Request("?foo=foo&bar=123") shouldBe Extracted(FooBar("foo", 123)) } it("extraction from request for invalid field fails") { FooBar <--? Request("?foo=foo") shouldBe ExtractionFailed(ExtractionError.Missing(FooBar.bar)) } it("reports all fields") { FooBar.toSeq shouldBe Seq(FooBar.foo, FooBar.bar) } it("supports binding") { val req = (FooBar --> FooBar("foo", 123)).foldLeft(RequestBuilder(Get)) { (requestBuild, next) => next(requestBuild) }.build() req.uri shouldBe "/?foo=foo&bar=123" } } }
Example 108
Source File: MultipartFileTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.parameters import java.io.File import java.nio.charset.StandardCharsets.UTF_8 import com.google.common.io.Files import com.twitter.io.{Buf, Bufs} import org.scalatest.{FunSpec, Matchers} class MultipartFileTest extends FunSpec with Matchers { describe("OnDiskMultiPartFile") { it("converts toFileElement") { val tempFile = File.createTempFile("temp", "file") Files.write("hello bob", tempFile, UTF_8) tempFile.deleteOnExit() Bufs.asUtf8String(OnDiskMultiPartFile("file", tempFile, None).toFileElement("hello").content) shouldBe "hello bob" } } describe("InMemoryMultiPartFile") { it("converts toFileElement") { Bufs.asUtf8String(InMemoryMultiPartFile("file", Buf.Utf8("hello bob"), None).toFileElement("hello").content) shouldBe "hello bob" } } }
Example 109
Source File: RebindableTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.parameters import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import io.fintrospect.RequestBuilder import org.scalatest.{FunSpec, Matchers} class RebindableTest extends FunSpec with Matchers { describe("Rebinding") { describe("Mandatory") { it("can rebind") { val inRequest = Request() inRequest.headerMap.add("field", "123") val bindings = Header.required.int("field") <-> inRequest val outRequest = bindings.foldLeft(RequestBuilder(Get)) { (requestBuild, next) => next(requestBuild) }.build() outRequest.headerMap("field") shouldBe "123" } } describe("Optional") { it("can rebind present value") { val inRequest = Request() inRequest.headerMap.add("field", "123") val bindings = Header.optional.int("field") <-> inRequest val outRequest = bindings.foldLeft(RequestBuilder(Get)) { (requestBuild, next) => next(requestBuild) }.build() outRequest.headerMap("field") shouldBe "123" } it("does not rebind missing value") { val inRequest = Request() val bindings = Header.optional.int("field") <-> inRequest val outRequest = bindings.foldLeft(RequestBuilder(Get)) { (requestBuild, next) => next(requestBuild) }.build() outRequest.headerMap.get("field") shouldBe None } } } }
Example 110
Source File: ExtractedRouteRequestTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.parameters import com.twitter.finagle.http.Request import io.fintrospect.util.ExtractionError.Missing import io.fintrospect.util.{Extracted, ExtractionFailed} import org.scalatest.{FunSpec, Matchers} class ExtractedRouteRequestTest extends FunSpec with Matchers { describe("ExtractedRouteRequest") { it("uses pre-extracted value if present") { val bob = FormField.required.string("bob") val body = Body.form(bob) ExtractedRouteRequest(Request(), Map(body -> Extracted(Form()))).get(body, (_: Request) => ExtractionFailed(Missing(bob))) shouldBe Extracted(Form()) } it("converts missing parameter to Extraction failed") { val bob = FormField.required.string("bob") val bill = FormField.required.string("bill") val body = Body.form(bob, bill) ExtractedRouteRequest(Request(), Map()).get(body, body.extract) shouldBe ExtractionFailed(Seq(Missing(bob), Missing(bill))) } } }
Example 111
Source File: PathTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.parameters import com.twitter.finagle.http.Method.Get import io.fintrospect.RequestBuilder import org.scalatest.{FunSpec, Matchers} class PathTest extends FunSpec with Matchers { describe("fixed path parameter") { it("unapplies when string matches") { Path.fixed("a path piece").unapply("a path piece") shouldBe Option("a path piece") } it("does not unapply when string mismatches") { Path.fixed("a path piece").unapply("another path piece") shouldBe None } it("does not contains any params to describe") { Path.fixed("a path piece").iterator.isEmpty shouldBe true } } describe("non fixed parameter") { it("contains a single parameter") { Path.string("a path piece").iterator.isEmpty shouldBe false } it("does contain a param to describe") { Path.string("a path piece").map(_.name) shouldBe Seq("a path piece") } it("unapplies strings as url decoded values") { Path.string("urlEncoded").unapply("a%20path%2F+piece") shouldBe Option("a path/+piece") } it("does not url decode reserved characters") { Path.string("urlEncoded").unapply(":@-._~!$&'()*+,;=") shouldBe Option(":@-._~!$&'()*+,;=") } it("handles special characters when binding values") { (Path.string("urlEncoded") --> "a path/+piece").head.apply(RequestBuilder(Get)).build().uri shouldBe "a%20path%2F+piece" } } }
Example 112
Source File: StringValidationsTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.parameters import org.scalatest.{FunSpec, Matchers} class StringValidationsTest extends FunSpec with Matchers { describe("Validations") { it("EmptyIsValid") { StringValidations.EmptyIsValid("") shouldBe "" StringValidations.EmptyIsValid("asd") shouldBe "asd" } it("EmptyIsInvalid") { intercept[Exception](StringValidations.EmptyIsInvalid("")) intercept[Exception](StringValidations.EmptyIsInvalid(null)) } } }
Example 113
Source File: SecurityTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import org.scalatest.{FunSpec, Matchers} class SecurityTest extends FunSpec with Matchers { describe("ApiKey") { val paramName = "name" val param = Query.required.int(paramName) val next = Service.mk[Request, Response](r => Ok("hello")) it("valid API key is granted access and result carried through") { val (status, content) = result(ApiKey(param, Service.const(Future(true))).filter(Request(paramName -> "1"), next) .map(statusAndContentFrom)) status should be(Status.Ok) content should be("hello") } it("missing API key is unauthorized") { val (status, content) = result(ApiKey(param, Service.const(Future(true))).filter(Request(), next) .map(statusAndContentFrom)) status should be(Status.Unauthorized) content should be("") } it("bad API key is unauthorized") { val (status, content) = result(ApiKey(param, Service.const(Future(true))).filter(Request(paramName -> "notAnInt"), next) .map(statusAndContentFrom)) status should be(Status.Unauthorized) content should be("") } it("unknown API key is unauthorized") { val (status, content) = result(ApiKey(param, Service.const(Future(false))).filter(Request(paramName -> "1"), next) .map(statusAndContentFrom)) status should be(Status.Unauthorized) content should be("") } it("failed API key lookup is rethrown") { val e = new RuntimeException("boom") val caught = intercept[RuntimeException](result(ApiKey(param, Service.const(Future.exception(e))).filter(Request(paramName -> "1"), next))) caught should be(e) } } }
Example 114
Source File: ModuleTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Path import com.twitter.finagle.http.{Method, Request, Response, Status} import com.twitter.util.Await.result import io.fintrospect.util.Echo import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import org.scalatest.{FunSpec, Matchers} class ModuleTest extends FunSpec with Matchers { describe("Module") { it("when it matches it responds as expected") { val response = statusAndContentFrom(result(routingWhichMatches((Get, Path("/someUrl")))(Request("/someUrl?field=hello")))) response._1 shouldBe Status.Ok response._2 should include("/someUrl?field=hello") } it("no match responds with default 404") { val response = result(routingWhichMatches((Get, Path("/someUrl")))(Request("/notMyService"))) response.status shouldBe Status.NotFound } } private def routingWhichMatches(methodAndPath: (Method, Path)): Service[Request, Response] = { Module.toService(new PartialFunction[(Method, Path), Service[Request, Response]] { override def isDefinedAt(x: (Method, Path)): Boolean = x === methodAndPath override def apply(v1: (Method, Path)): Service[Request, Response] = Echo() }) } }
Example 115
Source File: ContractProxyModuleTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import com.twitter.util.Await import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import org.scalatest.{FunSpec, Matchers} object TestContract extends Contract { object Endpoint extends ContractEndpoint { val query = Query.required.string("query") override val route = RouteSpec().taking(query).at(Get) / "hello" } } class ContractProxyModuleTest extends FunSpec with Matchers { describe("ContractProxyModule") { it("cretes service which proxies requests to the underlying service") { val svc = Service.mk { req: Request => Ok(TestContract.Endpoint.query <-- req) } Await.result(ContractProxyModule("remote", svc, TestContract).toService(Request("/hello?query=value"))).contentString shouldBe "value" } } }
Example 116
Source File: ResponseBuilderSpec.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.formats import com.twitter.finagle.http.Status import com.twitter.io.{Buf, Bufs} import org.scalatest.{FunSpec, Matchers} abstract class ResponseBuilderSpec[T](bldr: AbstractResponseBuilder[T]) extends FunSpec with Matchers { val message = "some text goes here" val customType: T val customTypeSerialized: Buf val customError: T val customErrorSerialized: Buf describe("Rendering") { it("builds non error with custom type") { val rsp = bldr.Ok(customType) (rsp.status, Bufs.asByteArrayBuf(rsp.content)) shouldBe(Status.Ok, Bufs.asByteArrayBuf(customTypeSerialized)) } it("builds error with message - String") { val rsp = bldr.NotFound(customError) (rsp.status, Bufs.asByteArrayBuf(rsp.content)) shouldBe(Status.NotFound, Bufs.asByteArrayBuf(customErrorSerialized)) } } }
Example 117
Source File: JsonFormatSpec.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.formats import java.math.BigInteger import io.fintrospect.parameters.ParameterSpec import org.scalatest.{FunSpec, Matchers} import scala.util.{Success, Try} abstract class JsonFormatSpec[X <: Y, Y](val jsonLib: JsonLibrary[X, Y]) extends FunSpec with Matchers { val format = jsonLib.JsonFormat val expectedJson = """{"string":"hello","object":{"field1":"aString"},"int":10,"long":2,"double":1.2,"decimal":1.2,"bigInt":12344,"bool":true,"null":null,"array":["world",true]}""" val expected = format.obj("field" -> format.string("value")) describe(format.getClass.getSimpleName) { it("creates JSON objects as expected") { format.compact(format.objSym( 'string -> format.string("hello"), 'object -> format.obj("field1" -> format.string("aString")), 'int -> format.number(10), 'long -> format.number(2L), 'double -> format.number(1.2), 'decimal -> format.number(BigDecimal(1.2)), 'bigInt -> format.number(new BigInteger("12344")), 'bool -> format.boolean(true), 'null -> format.nullNode(), 'array -> format.array(format.string("world"), format.boolean(true)) )) shouldEqual expectedJson } describe("Parse blows up when invalid") { it("parse blows up when invalid") { Try(format.parse("<12312>")).isFailure shouldBe true } } val paramName = "name" describe("ParameterSpec json") { describe(getClass.getName + " Json") { it("retrieves a valid value") { Try(ParameterSpec.json(jsonLib).deserialize(format.compact(expected))) shouldBe Success(expected) } it("does not retrieve an invalid value") { Try(ParameterSpec.json(jsonLib).deserialize("notJson")).isFailure shouldBe true } it("does not retrieve an null value") { Try(ParameterSpec.json(jsonLib).deserialize(null)).isFailure shouldBe true } it("serializes correctly") { ParameterSpec.json(jsonLib).serialize(expected) shouldBe """{"field":"value"}""" } } } } }
Example 118
Source File: RenderViewTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.templating import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Status} import com.twitter.io.Bufs import com.twitter.util.Await.result import io.fintrospect.formats.Html import io.fintrospect.templating.View.Redirect import org.scalatest.{FunSpec, Matchers} class RenderViewTest extends FunSpec with Matchers { describe("RenderView") { val renderView = new RenderView(Html.ResponseBuilder, new TemplateRenderer { override def toBuf(view: View) = Bufs.utf8Buf(view.template) }) it("creates a standard View") { val response = result(renderView(Request(), Service.const(OnClasspath(Nil)))) response.status shouldBe Status.Ok response.contentString shouldBe "io/fintrospect/templating/OnClasspath" } it("creates a standard View with an overridden status") { val response = result(renderView(Request(), Service.const(OnClasspath(Nil, Status.NotFound)))) response.status shouldBe Status.NotFound response.contentString shouldBe "io/fintrospect/templating/OnClasspath" } it("creates redirect when passed a RenderView.Redirect") { val response = result(renderView(Request(), Service.const(Redirect("newLocation", Status.BadGateway)))) response.status shouldBe Status.BadGateway response.headerMap("Location") shouldBe "newLocation" } } }
Example 119
Source File: TemplatesSpec.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.templating import com.twitter.io.Buf import org.scalatest.{FunSpec, Matchers} abstract class TemplatesSpec[T](renderers: Templates, subProjectName: String) extends FunSpec with Matchers { describe(subProjectName + " templating") { describe("caching classpath") { val renderer = renderers.CachingClasspath() it("renders a template from a case class on the classpath") { renderOnClasspath(renderer) } it("renders a template from a case class with overridden template") { renderAtRoot(renderer) } } describe("caching file-based") { val renderer = renderers.Caching(subProjectName + "/src/test/resources") it("renders a template from a case class on the classpath") { renderOnClasspath(renderer) } it("renders a template from a case class with overridden template") { renderAtRoot(renderer) } } describe("hot reload") { val renderer = renderers.HotReload(subProjectName + "/src/test/resources") it("renders a template from a case class on the classpath") { renderOnClasspath(renderer) } it("renders a template from a case class with overridden template") { renderAtRoot(renderer) } } } private val items = Seq( Item("item1", "£1", Seq(Feature("pretty"))), Item("item2", "£3", Seq(Feature("nasty"))) ) private def renderOnClasspath(renderer: TemplateRenderer): Unit = { Buf.Utf8.unapply(renderer.toBuf(OnClasspath(items))).get shouldBe "Name:item1Price:£1Feature:prettyName:item2Price:£3Feature:nasty" } private def renderAtRoot(renderer: TemplateRenderer): Unit = { Buf.Utf8.unapply(renderer.toBuf(AtRoot(items))).get shouldBe "AtRootName:item1Price:£1Feature:prettyAtRootName:item2Price:£3Feature:nasty" } }
Example 120
Source File: ResourceLoaderTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import org.scalatest.{FunSpec, Matchers} import scala.io.Source class ResourceLoaderTest extends FunSpec with Matchers { describe("Classpath loader") { val loader = ResourceLoader.Classpath("/") describe("for an existing file") { it("looks up contents") { Source.fromURL(loader.load("mybob.xml")).mkString shouldBe "<xml>content</xml>" } it("looks up contents of a child file") { Source.fromURL(loader.load("io/index.html")).mkString shouldBe "hello from the io index.html" } } describe("for a missing file") { it("URL is null") { loader.load("notafile") shouldBe null } } } describe("Directory loader") { val loader = ResourceLoader.Directory("./core/src/test/resources") describe("for an existing file") { it("looks up contents") { Source.fromURL(loader.load("mybob.xml")).mkString shouldBe "<xml>content</xml>" } it("looks up contents of a child file") { Source.fromURL(loader.load("io/index.html")).mkString shouldBe "hello from the io index.html" } } describe("for a missing file") { it("URL is null") { loader.load("notafile") shouldBe null } it("URL is a directory") { loader.load("io") shouldBe null } } } }
Example 121
Source File: AuthorityTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.configuration import java.net.InetSocketAddress import org.scalatest.{FunSpec, Matchers} class AuthorityTest extends FunSpec with Matchers { describe("Authority") { it("renders ok") { Authority(Host.localhost, Port(9999)).toString shouldBe "localhost:9999" } it("defaults no port to port 80") { Authority.unapply("localhost") shouldBe Some(Authority(Host.localhost, Port(80))) } it("defaults valid host and port") { Authority.unapply("localhost:123") shouldBe Some(Authority(Host.localhost, Port(123))) } it("invalid port number") { Authority.unapply("localhost:asd") shouldBe None } it("too many parts") { Authority.unapply("localhost:123:123") shouldBe None } it("socket address") { Authority(Host.localhost, Port(9999)).socketAddress shouldBe new InetSocketAddress("localhost", 9999) } } }
Example 122
Source File: ArgoJsonModuleRendererTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.renderers import com.twitter.finagle.Service import com.twitter.finagle.http.Method.{Get, Post} import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Status} import com.twitter.util.{Await, Future} import io.fintrospect.ContentTypes.{APPLICATION_ATOM_XML, APPLICATION_JSON, APPLICATION_SVG_XML} import io.fintrospect._ import io.fintrospect.formats.Argo import io.fintrospect.formats.Argo.JsonFormat.{number, obj, parse} import io.fintrospect.parameters._ import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import io.fintrospect.util.{Echo, ExtractionError} import org.scalatest.{FunSpec, Matchers} import scala.io.Source abstract class ArgoJsonModuleRendererTest() extends FunSpec with Matchers { def name: String = this.getClass.getSimpleName def renderer: ModuleRenderer describe(name) { it("renders as expected") { val customBody = Body.json("the body of the message", obj("anObject" -> obj("notAStringField" -> number(123)))) val module = RouteModule(Root / "basepath", renderer) .securedBy(ApiKey(Header.required.string("the_api_key"), Service.const(Future(true)))) .withRoute( RouteSpec("summary of this route", "some rambling description of what this thing actually does") .producing(APPLICATION_JSON) .taking(Header.optional.string("header", "description of the header")) .returning(ResponseSpec.json(Status.Ok -> "peachy", obj("anAnotherObject" -> obj("aNumberField" -> number(123))))) .returning(ResponseSpec.json(Status.Accepted -> "peachy", obj("anAnotherObject" -> obj("aNumberField" -> number(123))))) .returning(Status.Forbidden -> "no way jose") .taggedWith("tag3") .taggedWith("tag1") .at(Get) / "echo" / Path.string("message") bindTo ((s: String) => Echo(s))) .withRoute( RouteSpec("a post endpoint") .consuming(APPLICATION_ATOM_XML, APPLICATION_SVG_XML) .producing(APPLICATION_JSON) .returning(ResponseSpec.json(Status.Forbidden -> "no way jose", obj("aString" -> Argo.JsonFormat.string("a message of some kind")))) .taking(Query.required.int("query")) .body(customBody) .taggedWith("tag1") .taggedWith(TagInfo("tag2", "description of tag"), TagInfo("tag2", "description of tag")) .at(Post) / "echo" / Path.string("message") bindTo ((s: String) => Echo(s))) .withRoute( RouteSpec("a friendly endpoint") .taking(Query.required.boolean("query", "description of the query")) .body(Body.form(FormField.required.int("form", "description of the form"))) .at(Get) / "welcome" / Path.string("firstName") / "bertrand" / Path.string("secondName") bindTo ((x: String, y: String, z: String) => Echo(x, y, z))) val expected = parse(Source.fromInputStream(this.getClass.getResourceAsStream(s"$name.json")).mkString) val actual = Await.result(module.toService(Request("/basepath"))).contentString // println(Argo.JsonFormat.pretty(parse(actual))) parse(actual) shouldBe expected } it("can build 400") { val response = statusAndContentFrom(renderer.badRequest(Seq(ExtractionError(Query.required.string("bob"), "missing")))) response._1 shouldBe Status.BadRequest parse(response._2).getStringValue("message") shouldBe "Missing/invalid parameters" } it("can build 404") { val response = statusAndContentFrom(renderer.notFound(Request())) response._1 shouldBe Status.NotFound parse(response._2).getStringValue("message") shouldBe "No route found on this path. Have you used the correct HTTP verb?" } } }
Example 123
Source File: JsonErrorResponseRendererTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.renderers import com.twitter.finagle.http.Status import io.fintrospect.formats.Argo.JsonFormat.parse import io.fintrospect.parameters.Query import io.fintrospect.renderers.JsonErrorResponseRenderer.{badRequest, notFound} import io.fintrospect.util.ExtractionError import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import org.scalatest.{FunSpec, Matchers} class JsonErrorResponseRendererTest extends FunSpec with Matchers { it("can build 400") { val response = statusAndContentFrom(badRequest(Seq(ExtractionError(Query.required.string("bob"), "missing")))) response._1 shouldBe Status.BadRequest parse(response._2).getStringValue("message") shouldBe "Missing/invalid parameters" } it("can build 404") { val response = statusAndContentFrom(notFound()) response._1 shouldBe Status.NotFound parse(response._2).getStringValue("message") shouldBe "No route found on this path. Have you used the correct HTTP verb?" } }
Example 124
Source File: JsonToJsonSchemaTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.renderers.util import io.fintrospect.formats.Argo.JsonFormat._ import org.scalatest.{FunSpec, Matchers} import scala.io.Source.fromInputStream class JsonToJsonSchemaTest extends FunSpec with Matchers { describe("JsonToJsonSchema") { it("renders all different types of json value as expected") { val model = obj( "aString" -> string("aStringValue"), "aNumber" -> number(new java.math.BigDecimal(1.9)), "aBooleanTrue" -> boolean(true), "aBooleanFalse" -> boolean(false), "anArray" -> array(obj("anotherString" -> string("yetAnotherString"))), "anObject" -> obj("anInteger" -> number(1)) ) val actual = new JsonToJsonSchema().toSchema(model) actual.node shouldBe parse(fromInputStream(getClass.getResourceAsStream(s"JsonToJsonSchema_main.json")).mkString) obj(actual.definitions: _*) shouldBe parse(fromInputStream(getClass.getResourceAsStream(s"JsonToJsonSchema_definitions.json")).mkString) } } }
Example 125
Source File: SiteMapModuleRendererTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.renderers import java.net.URL import com.twitter.finagle.Service import com.twitter.finagle.http.Method._ import com.twitter.finagle.http.Status.{BadRequest, NotFound, Ok} import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Method, Request, Response} import com.twitter.util.Future import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import io.fintrospect.{NoSecurity, RouteSpec, ServerRoute} import org.scalatest.{FunSpec, Matchers} class SiteMapModuleRendererTest extends FunSpec with Matchers { it("renders 400") { new SiteMapModuleRenderer(new URL("http://fintrospect.io")).badRequest(Nil).status shouldBe BadRequest } it("renders 404") { new SiteMapModuleRenderer(new URL("http://fintrospect.io")).notFound(Request()).status shouldBe NotFound } it("should describe only GET endpoints of module as a sitemap") { val rsp = new SiteMapModuleRenderer(new URL("http://fintrospect.io")).description(Root / "bob", NoSecurity, Seq( endpointFor(Get), endpointFor(Post), endpointFor(Delete), endpointFor(Put), endpointFor(Options), endpointFor(Connect), endpointFor(Head), endpointFor(Trace) )) val (status, content) = statusAndContentFrom(rsp) status shouldBe Ok content shouldBe <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc> http://fintrospect.io/bob/GET </loc> </url> </urlset>.toString() } private def endpointFor(method: Method): ServerRoute[Request, Response] = { RouteSpec().at(method) / method.toString() bindTo Service.mk[Request, Response]((r) => Future(Response())) } }
Example 126
Source File: StrictContentTypeNegotiationTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import com.twitter.finagle.Service import com.twitter.finagle.http.Status.{NotAcceptable, Ok} import com.twitter.finagle.http.{Request, Response} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.ContentType import io.fintrospect.ContentTypes.{APPLICATION_ATOM_XML, APPLICATION_JSON, TEXT_HTML} import io.fintrospect.formats.ResponseBuilder import org.scalatest.{FunSpec, Matchers} class StrictContentTypeNegotiationTest extends FunSpec with Matchers { describe("StrictContentTypeNegotiation") { it("on no match, return 406") { val r = result(StrictContentTypeNegotiation(serviceForType(APPLICATION_ATOM_XML))(requestWithAcceptHeaders(APPLICATION_JSON.value))) r.status shouldBe NotAcceptable } it("when there are no accept header set, just chooses the first type") { val r = result(StrictContentTypeNegotiation(serviceForType(APPLICATION_ATOM_XML), serviceForType(APPLICATION_JSON))(requestWithAcceptHeaders())) r.status shouldBe Ok r.headerMap("Content-Type") should startWith(APPLICATION_ATOM_XML.value) } it("when there is a wildcard set, just chooses the first type") { val r = result(StrictContentTypeNegotiation(serviceForType(APPLICATION_ATOM_XML), serviceForType(APPLICATION_JSON))(requestWithAcceptHeaders("**;q=0.5"))) r.status shouldBe Ok r.headerMap("Content-Type") should startWith(TEXT_HTML.value) } } private def serviceForType(contentType: ContentType): (ContentType, Service[Request, Response]) = contentType -> Service.mk[Request, Response] { r => Future(ResponseBuilder.HttpResponse(contentType).build()) } private def requestWithAcceptHeaders(headers: String*): Request = { val request = Request() headers.foreach(value => request.headerMap.add("Accept", value)) request } }
Example 127
Source File: PathSegmentEncoderDecoderTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import io.fintrospect.util.PathSegmentEncoderDecoder.{decode, encode} import org.scalatest.{FunSpec, Matchers} class PathSegmentEncoderDecoderTest extends FunSpec with Matchers { describe("encode/decode") { it("roundtrips") { val inputString = " :@-._~!$&'()*+,;=" decode(encode(inputString)) shouldBe inputString } it("does not url encode reserved characters") { encode(":@-._~!$&'()*+,;=") shouldBe ":@-._~!$&'()*+,;=" } it("handles spaces and forward slashes gracefully") { encode("a path/+piece") shouldBe "a%20path%2F+piece" } } }
Example 128
Source File: HeapDumpTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import java.time.Instant import com.twitter.finagle.http.{Request, Status} import com.twitter.util.Await import org.scalatest.{FunSpec, Matchers} class HeapDumpTest extends FunSpec with Matchers { describe("HeapDump") { it("creates the correct heapdump file") { val clock = TestClocks.fixed(Instant.ofEpochMilli(0)) val response = Await.result(new HeapDump("bob", clock).apply(Request())) response.status shouldBe Status.Ok response.headerMap("Content-disposition").startsWith("inline; filename=\"heapdump-bob-1970-01-01") shouldBe true response.contentType shouldBe Some("application/x-heap-dump;charset=utf-8") } } }
Example 129
Source File: MultiBodyTypeTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import com.twitter.finagle.Service import com.twitter.finagle.http.Status.Ok import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.ContentType import io.fintrospect.ContentTypes.APPLICATION_JSON import io.fintrospect.parameters.Body import org.scalatest.{FunSpec, Matchers} class MultiBodyTypeTest extends FunSpec with Matchers { val xmlBody = Body.xml() val xmlAccepting = MultiBodyType(xmlBody -> Service.mk { req: Request => Future(Response(Ok)) }) describe("MultiBodyType") { it("on no match, reject with 415") { val r = result(xmlAccepting(requestFromContentType(APPLICATION_JSON))) r.status shouldBe Status.UnsupportedMediaType } it("when there are no content-type header set, reject with 415") { val r = result(xmlAccepting(requestFromContentType())) r.status shouldBe Status.UnsupportedMediaType } it("when there is an exact (case insensitive) match on a content type, use that service") { val r = Request() r.headerMap("Content-Type") = "application/xml" r.contentString = "<xml/>" val resp = result(xmlAccepting(r)) resp.status shouldBe Ok } } def requestFromContentType(headers: ContentType*): Request = { val request = Request() headers.foreach(value => request.headerMap.add("Content-Type", value.value)) request } }
Example 130
Source File: OverridableHttpServiceTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.testing import com.twitter.finagle.Service import com.twitter.finagle.http.Status.{Accepted, Conflict} import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.{Await, Future} import org.scalatest.{FunSpec, Matchers} class OverridableHttpServiceTest extends FunSpec with Matchers { val originalStatus = Conflict val overridableHttpService = new OverridableHttpService[Request](Service.mk { r: Request => Future(Response(originalStatus)) }) it("will serve routes that are passed to it") { statusShouldBe(originalStatus) } it("can override status") { overridableHttpService.respondWith(Accepted) statusShouldBe(Accepted) } private def statusShouldBe(expected: Status): Unit = { Await.result(overridableHttpService.service(Request())).status shouldBe expected } }
Example 131
Source File: TestHttpServerTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.testing import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Status.{Accepted, Conflict} import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Http, Service} import com.twitter.util.{Await, Future} import io.fintrospect.RouteSpec import org.scalatest.{BeforeAndAfterEach, FunSpec, Matchers} class TestHttpServerTest extends FunSpec with Matchers with BeforeAndAfterEach { val originalStatus = Conflict private val server = new TestHttpServer(9888, RouteSpec().at(Get) bindTo Service.mk { r: Request => Future(Response(originalStatus)) }) override def beforeEach() = { Await.result(server.start()) } override def afterEach() = { Await.result(server.stop()) } it("will serve routes that are passed to it") { statusShouldBe(originalStatus) } it("can override status") { server.respondWith(Accepted) statusShouldBe(Accepted) } private def statusShouldBe(expected: Status): Unit = { Await.result(Http.newService("localhost:9888", "")(Request())).status shouldBe expected } }
Example 132
Source File: ContentTypeTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import org.scalatest.{FunSpec, Matchers} class ContentTypeTest extends FunSpec with Matchers { it("can guess common content types for a file") { ContentType.lookup("foo/bob.html") shouldBe ContentTypes.TEXT_HTML ContentType.lookup("bob.js") shouldBe ContentType("application/javascript") ContentType.lookup("bob.txt") shouldBe ContentTypes.TEXT_PLAIN ContentType.lookup("bob.css") shouldBe ContentType("text/css") ContentType.lookup("bob.xml") shouldBe ContentTypes.APPLICATION_XML ContentType.lookup("bob.csv") shouldBe ContentType("text/csv") ContentType.lookup("bob.jpg") shouldBe ContentType("image/jpeg") ContentType.lookup("bob.svg") shouldBe ContentType("image/svg+xml") ContentType.lookup("bob.bmp") shouldBe ContentType("image/bmp") ContentType.lookup("bob.png") shouldBe ContentType("image/png") } it("defaults to octet-stream") { ContentType.lookup("bob.foo") shouldBe ContentType("application/octet-stream") } }
Example 133
Source File: ScalaObjectHandlerTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.templating import java.io.{StringReader, StringWriter} import java.util.concurrent.Callable import com.github.mustachejava.DefaultMustacheFactory import org.scalatest.{FunSpec, Matchers} class ScalaObjectHandlerTest extends FunSpec with Matchers { describe("ScalaObjectHandler") { it("maps") { render("{{#map}}{{test}}{{test2}}{{/map}}", Map("map" -> Map("test" -> "fred"))) shouldBe "fred" } it("handler") { val model = new { val list = Seq(new { lazy val optionalHello = Some("Hello") val futureWorld = new Callable[String] { def call(): String = "world" } val test = true val num = 0 }, new { val optionalHello = Some("Goodbye") val futureWorld = new Callable[String] { def call(): String = "thanks for all the fish" } lazy val test = false val map = Map("value" -> "test") val num = 1 }) } render("{{#list}}{{optionalHello}}, {{futureWorld}}!" + "{{#test}}?{{/test}}{{^test}}!{{/test}}{{#num}}?{{/num}}{{^num}}!{{/num}}" + "{{#map}}{{value}}{{/map}}\n{{/list}}", model) shouldBe "Hello, world!?!\nGoodbye, thanks for all the fish!!?test\n" } it("steams") { val model = new { val stream = Stream( new { val value = "hello" }, new { val value = "world" }) } render("{{#stream}}{{value}}{{/stream}}", model) shouldBe "helloworld" } it("unit") { val model = new { val test = if (false) "test" } render("{{test}}", model) shouldBe "" } it("options") { val model = new { val foo = Some("Hello") val bar = None } render("{{foo}}{{bar}}", model) shouldBe "Hello" } } private def render(template: String, model: Any): String = { val mf = new DefaultMustacheFactory() mf.setObjectHandler(new ScalaObjectHandler) val m = mf.compile(new StringReader(template), "name") val sw = new StringWriter m.execute(sw, model).close() sw.toString } }
Example 134
Source File: IntegrationTests.scala From scala-typed-holes with Apache License 2.0 | 5 votes |
package holes import java.nio.charset.StandardCharsets import java.nio.file.{Files, Path, Paths} import org.apache.commons.io.FileUtils import org.scalatest.{BeforeAndAfterAll, FunSpec} import scala.sys.process._ class IntegrationTests extends FunSpec with BeforeAndAfterAll { private val pluginJar = sys.props("plugin.jar") private val scalacClasspath = sys.props("scalac.classpath") private val targetDir = Paths.get("target/integration-tests") private def runScalac(args: String*): String = { val buf = new StringBuffer val logger = new ProcessLogger { override def out(s: => String): Unit = { buf.append(s); buf.append('\n') } override def err(s: => String): Unit = { buf.append(s); buf.append('\n') } override def buffer[T](f: => T): T = f } Process( "java" :: "-Dscala.usejavacp=true" :: "-cp" :: scalacClasspath :: "scala.tools.nsc.Main" :: args.toList ).!(logger) buf.toString } private def compileFile(path: Path): String = runScalac( s"-Xplugin:$pluginJar", "-P:typed-holes:log-level:info", "-d", targetDir.toString, path.toString ) override def beforeAll(): Unit = { println(runScalac("-version")) FileUtils.deleteQuietly(targetDir.toFile) Files.createDirectories(targetDir) } describe("produces the expected output") { for (scenario <- Paths.get("src/test/resources").toFile.listFiles().toList.map(_.toPath)) { it(scenario.getFileName.toString) { val expected = new String(Files.readAllBytes(scenario.resolve("expected.txt")), StandardCharsets.UTF_8).trim val actual = compileFile(scenario.resolve("input.scala")).trim if (actual != expected) { println("Compiler output:") println("=====") println(actual) println("=====") } assert(actual === expected) } } } }
Example 135
Source File: TestSpec.scala From AppCrawler with Apache License 2.0 | 5 votes |
package com.testerhome.appcrawler.ut import org.scalatest.FunSpec class TestSpec extends FunSpec{ describe("A Set") { describe("when empty") { it("should have size 0") { assert(Set.empty.size == 0) } it("should produce NoSuchElementException when head is invoked") { assert(1==2) } } } }
Example 136
Source File: BinaryVersionTests.scala From scaladex with BSD 3-Clause "New" or "Revised" License | 5 votes |
package ch.epfl.scala.index.model.release import ch.epfl.scala.index.model.{Milestone, ReleaseCandidate, release} import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{FunSpec, Matchers} class BinaryVersionTests extends FunSpec with Matchers with TableDrivenPropertyChecks { it("should parse any binary version") { val inputs = Table( ("input", "output"), ("1", MajorBinary(1)), ("1.x", MajorBinary(1)), ("2.12", MinorBinary(2, 12)), ("0.6", MinorBinary(0, 6)), ("2.13.0", PatchBinary(2, 13, 0)), ("0.4.0", PatchBinary(0, 4, 0)), ("0.4.0-M2", PreReleaseBinary(0, 4, Some(0), Milestone(2))), ("0.23.0-RC1", release.PreReleaseBinary(0, 23, Some(0), ReleaseCandidate(1))), ("1.1-M1", release.PreReleaseBinary(1, 1, None, Milestone(1))) ) forAll(inputs) { (input, output) => BinaryVersion.parse(input) should contain(output) } } it("should be ordered") { val inputs = Table[BinaryVersion, BinaryVersion]( ("lower", "higher"), (MajorBinary(1), MajorBinary(2)), (MajorBinary(1), MinorBinary(1, 1)), // 1.x < 1.1 (MajorBinary(1), MinorBinary(2, 1)), (release.PreReleaseBinary(1, 2, None, Milestone(1)), MinorBinary(1, 2)), (MajorBinary(1), release.PreReleaseBinary(2, 0, None, Milestone(1))) ) forAll(inputs) { (lower, higher) => lower shouldBe <(higher) } } }
Example 137
Source File: WriteOutDemoPlots.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot import java.io.File import java.nio.file.{Files, Paths} import com.cibo.evilplot.demo.DemoPlots import javax.imageio.ImageIO import org.scalatest.{FunSpec, Matchers} import com.cibo.evilplot.geometry.Drawable import scala.util.Try object WriteOutDemoPlots { def apply(args:Array[String]):Unit = for(plotName <- args; plot <- DemoPlots.get(Symbol(plotName))) plot write new java.io.File(s"$plotName.png") } class WriteOutDemoPlots extends FunSpec with Matchers { //-- DemoPlot name and ratio of colored pixels (to represent an simple hash) val plots = Seq( 'linePlot -> 0.01498, 'heatmap -> 0.81790, 'pieChart -> 0.44209, 'clusteredBarChart -> 0.31712, 'clusteredStackedBarChart -> 0.30259, 'stackedBarChart -> 0.35687, 'barChart -> 0.18869, 'functionPlot -> 0.01728, 'markerPlot -> 0.01008, 'crazyPlot -> 0.10755, 'facetedPlot -> 0.04951, 'marginalHistogram -> 0.04002, 'scatterPlot -> 0.02314, 'boxPlot -> 0.29182, 'facetedPlot -> 0.04951, 'histogramOverlay -> 0.32281 ) val tmpPathOpt = { val tmpPath = Paths.get("/tmp/evilplot") if (Files.notExists(tmpPath)) Try{Files.createDirectories(tmpPath)} if(Files.notExists(tmpPath)) None else { println(s"Saving rendered png's to $tmpPath") Some(tmpPath) } } describe("Demo Plots") { it("render to consistent murmur hash") { for { (name, ratioTruth) <- plots; plot <- DemoPlots.get(name)} { val bi = plot.asBufferedImage def isColored(c:Int):Boolean = { val r = (c >> 16) & 0xFF; val g = (c >> 8) & 0xFF; val b = (c >> 8) & 0xFF; r + g + b > 10 } val ratio:Double = { val pixels = (for(x <- 0 until bi.getWidth; y <- 0 until bi.getHeight) yield bi.getRGB(x,y)).toArray pixels.count(isColored).toDouble/pixels.size } val delta = math.abs(ratioTruth - ratio) println(f"""$name -> $ratio%5.5f, //delta = $delta%8.8f""") assert(delta < 0.0015, s"$name out of range $ratio != $ratioTruth") //--write img to file if the tmp path is available for(_ <- None; tmpPath <- tmpPathOpt){ val file = new File(s"${tmpPath.toAbsolutePath.toString}/${name.name}.png") ImageIO.write(bi, "png", file) file.exists() shouldBe true } } } } }
Example 138
Source File: Graphics2DRenderContextSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.geometry import java.awt.image.BufferedImage import java.awt.{BasicStroke, Color, Graphics2D} import org.scalatest.{FunSpec, Matchers} class Graphics2DRenderContextSpec extends FunSpec with Matchers with Graphics2DSupport { describe("state stack operations") { it("The state should be the same before and after a stack op.") { val graphics = Graphics2DTestUtils.graphics2D val ctx = Graphics2DRenderContext(graphics) val GraphicsState(initialTransform, initialFill, initialColor, initialStroke) = ctx.initialState Graphics2DRenderContext.applyOp(ctx) { ctx.graphics.translate(34, 20) ctx.graphics.setPaint(Color.BLUE) ctx.graphics.setStroke(new BasicStroke(3)) } ctx.graphics.getTransform shouldBe initialTransform ctx.fillColor shouldBe initialFill ctx.strokeColor shouldBe initialColor ctx.graphics.getStroke shouldBe initialStroke } } } object Graphics2DTestUtils { def graphics2D: Graphics2D = { val bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB) bi.createGraphics() } }
Example 139
Source File: MatrixOperationsSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.numeric import org.scalatest.{FunSpec, Matchers} class KernelDensityEstimationSpec extends FunSpec with Matchers { describe("KernelDensityEstimation") { it("should properly calculate the matrix product A * B^T") { val a = Array( Array(0.9477583, 0.7026756, 0.0075461, 0.8175592), Array(0.5654393, 0.7140698, 0.5457264, 0.1904566), Array(0.8049051, 0.5844244, 0.5987555, 0.1988892), Array(0.6323643, 0.2691138, 0.7707659, 0.4891442), Array(0.2572372, 0.6319369, 0.2961405, 0.8173221) ) val b = Array( Array(0.95817, 0.72988, 0.39111, 0.51126), Array(0.42121, 0.98949, 0.41734, 0.76212), Array(0.55427, 0.47121, 0.73324, 0.42507), Array(0.98662, 0.85474, 0.22522, 0.52602), Array(0.94610, 0.54784, 0.21054, 0.92127) ) val answer = Array( Array(1.8419, 1.7207, 1.2095, 1.9674, 2.0364), Array(1.3738, 1.3176, 1.1310, 1.3913, 1.2165), Array(1.5337, 1.3188, 1.2451, 1.5331, 1.3910), Array(1.3539, 1.2271, 1.2504, 1.2848, 1.3586), Array(1.2414, 1.4801, 1.0049, 1.2906, 1.4049) ) val calculatedResult = MatrixOperations.matrixMatrixTransposeMult(a, b).flatten.toSeq (calculatedResult zip answer.flatten.toSeq).foreach { case (calculated, actual) => calculated shouldEqual actual +- 0.003 } } } }
Example 140
Source File: MatrixOperationsSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.numeric import org.scalatest.{FunSpec, Matchers} class KernelDensityEstimationSpec extends FunSpec with Matchers { describe("KernelDensityEstimation") { it("should properly calculate the matrix product A * B^T") { val a = Array( Array(0.9477583, 0.7026756, 0.0075461, 0.8175592), Array(0.5654393, 0.7140698, 0.5457264, 0.1904566), Array(0.8049051, 0.5844244, 0.5987555, 0.1988892), Array(0.6323643, 0.2691138, 0.7707659, 0.4891442), Array(0.2572372, 0.6319369, 0.2961405, 0.8173221) ) val b = Array( Array(0.95817, 0.72988, 0.39111, 0.51126), Array(0.42121, 0.98949, 0.41734, 0.76212), Array(0.55427, 0.47121, 0.73324, 0.42507), Array(0.98662, 0.85474, 0.22522, 0.52602), Array(0.94610, 0.54784, 0.21054, 0.92127) ) val answer = Array( Array(1.8419, 1.7207, 1.2095, 1.9674, 2.0364), Array(1.3738, 1.3176, 1.1310, 1.3913, 1.2165), Array(1.5337, 1.3188, 1.2451, 1.5331, 1.3910), Array(1.3539, 1.2271, 1.2504, 1.2848, 1.3586), Array(1.2414, 1.4801, 1.0049, 1.2906, 1.4049) ) val calculatedResult = MatrixOperations.matrixMatrixTransposeMult(a, b).flatten.toSeq (calculatedResult zip answer.flatten.toSeq).foreach { case (calculated, actual) => calculated shouldEqual actual +- 0.003 } } } }
Example 141
Source File: AffineTransformSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.geometry import org.scalatest.{FunSpec, Matchers} class AffineTransformSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("The AffineTransform") { it("should translate a point") { AffineTransform.identity.translate(1.0, 0.0)(1.0, 1.0) should be((2.0, 1.0)) AffineTransform.identity.translate(0.0, 1.0)(1.0, 1.0) should be((1.0, 2.0)) } it("should scale a point") { AffineTransform.identity.scale(2.0, 1.0)(1.0, 1.0) should be((2.0, 1.0)) AffineTransform.identity.scale(1.0, 2.0)(1.0, 1.0) should be((1.0, 2.0)) } it("should flip a point across the axes") { AffineTransform.identity.flipOverX(0.0, 1.0) should be((0.0, -1.0)) AffineTransform.identity.flipOverY(1.0, 0.0) should be((-1.0, 0.0)) } it("should rotate by 90 degrees") { val (x, y) = AffineTransform.identity.rotateDegrees(90)(1.0, 0.0) x should be(0.0 +- 1e-9) y should be(1.0 +- 1e-9) } it("should compose two affine transforms") { val translate = AffineTransform.identity.translate(1.0, 0.0) val scale = AffineTransform.identity.scale(1.0, 2.0) translate.compose(scale)(2.0, 3.0) should be((3.0, 6.0)) scale.compose(translate)(2.0, 3.0) should be((3.0, 6.0)) } } }
Example 142
Source File: TextMetricsSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.geometry import org.scalatest.{FunSpec, Matchers} import com.cibo.evilplot.DOMInitializer class TextMetricsSpec extends FunSpec with Matchers { DOMInitializer.init() // The size depends on the font which can vary from system to system. describe("measure") { it("returns the right size for a small font") { val extent = TextMetrics.measure(Text("test", 5)) extent.height shouldBe 5.0 +- 0.1 } it("returns the right size for a large font") { val extent = TextMetrics.measure(Text("test", 64)) extent.height shouldBe 64.0 +- 0.1 } } }
Example 143
Source File: DrawableSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.geometry import com.cibo.evilplot.colors.{ColorGradients, FillGradients} import org.scalatest.{FunSpec, Matchers} import io.circe.syntax._ class DrawableSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ def encodeDeocde(before: Drawable) = { val str = Drawable.drawableEncoder(before).noSpaces val after = io.circe.parser.parse(str).right.get.as[Drawable].right.get after } describe("EmptyDrawable") { it("has zero size") { EmptyDrawable().extent shouldBe Extent(0, 0) } it("does nothing") { val context = new MockRenderContext EmptyDrawable().draw(context) // This should not throw an exception } it("can be serialized") { val before = EmptyDrawable() val str = Drawable.drawableEncoder(before).noSpaces val after = io.circe.parser.parse(str).right.get.as[Drawable].right.get after shouldBe before } } describe("Line") { val line = Line(5, 10) it("has the right extent") { line.extent shouldBe Extent(5, 10) } it("renders itself") { var drawn = 0 val context = new MockRenderContext { override def draw(line: Line): Unit = drawn += 1 } line.draw(context) drawn shouldBe 1 } } describe("Disc") { it("has the right extent") { Disc(5).extent shouldBe Extent(10, 10) } } describe("Wedge") { it("has the right extent") { Wedge(180, 5).extent shouldBe Extent(10, 10) } } describe("extent"){ it("can be serialized and deserialized"){ } } describe("Interaction"){ it("can be serialized and deserialized"){ encodeDeocde(Interaction(Disc(10), EmptyEvent())) shouldEqual Interaction(Disc(10), EmptyEvent()) encodeDeocde(Interaction(Disc(10), OnClick(_ => ()))) shouldEqual Interaction(Disc(10), EmptyEvent()) } } describe("Gradient2d"){ it("can be serialized and deserialized"){ val gradient = LinearGradient.bottomToTop(Extent(100, 100), FillGradients.distributeEvenly(ColorGradients.viridis)) encodeDeocde(GradientFill(Rect(10), gradient)) shouldEqual GradientFill(Rect(10), gradient) } } }
Example 144
Source File: GeometrySpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.geometry import org.scalatest.{FunSpec, Matchers} import com.cibo.evilplot.DOMInitializer class GeometrySpec extends FunSpec with Matchers { DOMInitializer.init() describe("Geometry") { // pick different values so that we can tell if they get swapped val width = 1.0 val height = 2.0 val length = 3.0 val strokeWidth = 4.0 it("Line extent") { val extent = Line(length, strokeWidth).extent extent shouldEqual Extent(length, strokeWidth) } it("Rect extent") { val extent = Rect(width, height).extent extent shouldEqual Extent(width, height) } } describe("labels") { class TestContext extends MockRenderContext { var discDrawn: Boolean = false var textDrawn: Boolean = false override def draw(disc: Disc): Unit = discDrawn = true override def draw(text: Text): Unit = textDrawn = true override def draw(translate: Translate): Unit = translate.r.draw(this) } it("titled should draw the drawable and text") { val context = new TestContext val d = Disc(5).titled("message") d.draw(context) context.discDrawn shouldBe true context.textDrawn shouldBe true } it("labeled should draw the drawable and text") { val context = new TestContext val d = Disc(5).labeled("message") d.draw(context) context.discDrawn shouldBe true context.textDrawn shouldBe true } } }
Example 145
Source File: OverlaySpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.{Drawable, EmptyDrawable, Extent} import com.cibo.evilplot.numeric.{Bounds, Point} import com.cibo.evilplot.plot.aesthetics.Theme import com.cibo.evilplot.plot.renderers.PlotRenderer import org.scalatest.{FunSpec, Matchers} class OverlaySpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("Overlay") { it("it gets the bounds right for a single plot") { val inner = ScatterPlot(Seq(Point(1.0, 10.0), Point(2.0, 20.0))) val overlay = Overlay(inner) overlay.xbounds shouldBe inner.xbounds overlay.ybounds shouldBe inner.ybounds } it("combines bounds from multiple plots") { val inner1 = ScatterPlot(Seq(Point(10.0, -1.0))) val inner2 = ScatterPlot(Seq(Point(3.0, 20.0))) val overlay = Overlay(inner1, inner2) overlay.xbounds shouldBe Bounds(inner2.xbounds.min, inner1.xbounds.max) overlay.ybounds shouldBe Bounds(inner1.ybounds.min, inner2.ybounds.max) } it("occupies the right extents") { val inner1 = ScatterPlot(Seq(Point(10.0, -1.0))) val inner2 = ScatterPlot(Seq(Point(11.0, 1.0))) val overlay = Overlay(inner1, inner2) val extent = Extent(600, 400) overlay.render(extent).extent shouldBe extent } it("updates bounds on subplots") { var xbounds: Bounds = Bounds(0, 0) var ybounds: Bounds = Bounds(0, 0) val testRenderer = new PlotRenderer { def render(plot: Plot, plotExtent: Extent)(implicit theme: Theme): Drawable = { xbounds = plot.xbounds ybounds = plot.ybounds EmptyDrawable().resize(plotExtent) } } val inner = new Plot( xbounds = Bounds(1, 2), ybounds = Bounds(3, 4), renderer = testRenderer ) val overlay = Overlay(inner) val updated = overlay.xbounds(5, 6).ybounds(7, 8) updated.render(Extent(100, 200)) xbounds shouldBe Bounds(5, 6) ybounds shouldBe Bounds(7, 8) } it("should throw an exception with no plots") { an[IllegalArgumentException] should be thrownBy Overlay() } } }
Example 146
Source File: FacetsSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.{Drawable, EmptyDrawable, Extent, Rect} import com.cibo.evilplot.numeric.Point import com.cibo.evilplot.plot.aesthetics.Theme import org.scalatest.{FunSpec, Matchers} import com.cibo.evilplot.plot.components.{FacetedPlotComponent, Position} class FacetsSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("Facets") { it("is the correct size with one facet") { val inner = ScatterPlot(Seq(Point(1, 1), Point(2, 2))) val faceted = Facets(Seq(Seq(inner))) faceted.xbounds shouldBe inner.xbounds faceted.ybounds shouldBe inner.ybounds val extent = Extent(600, 400) faceted.plotExtent(extent) shouldBe inner.plotExtent(extent) } it("works with rows of differing sizes") { val inner1 = ScatterPlot(Seq(Point(1, 1), Point(2, 2))) val inner2 = ScatterPlot(Seq(Point(2, 1), Point(4, 2))) val inner3 = ScatterPlot(Seq(Point(3, 1), Point(5, 2))) val faceted = Facets(Seq(Seq(inner1, inner2), Seq(inner3))) val extent = Extent(600, 400) faceted.render(extent).extent shouldBe extent } it("is the correct size with a title") { val titleHeight = 10 val inner = ScatterPlot(Seq(Point(1, 1), Point(2, 2))) val faceted = Facets( Seq( Seq(inner, inner), Seq(inner, inner), Seq(inner, inner) ) ).title(Rect(1, titleHeight)) faceted.xbounds shouldBe inner.xbounds faceted.ybounds shouldBe inner.ybounds val extent = Extent(600, 400) faceted.plotExtent(extent) shouldBe Extent(extent.width, extent.height - titleHeight) } it("has the right plotOffset.x") { val inner1 = ScatterPlot(Seq(Point(1, 1), Point(2, 2))) val inner2 = ScatterPlot(Seq(Point(1, 1), Point(2, 2))) // Plot component that is larger for `inner2` than `inner1`. object TestComponent extends FacetedPlotComponent { val position: Position = Position.Left override val repeated: Boolean = true override def size(plot: Plot): Extent = if (plot == inner2) Extent(10, 10) else Extent(0, 0) def render(plot: Plot, extent: Extent, row: Int, column: Int)( implicit theme: Theme): Drawable = EmptyDrawable() } val faceted = Facets(Seq(Seq(inner1), Seq(inner2))) :+ TestComponent faceted.plotOffset.x shouldBe 10 } it("throws an exception with no facets") { an[IllegalArgumentException] should be thrownBy Facets(Seq.empty) } } }
Example 147
Source File: ScatterPlotSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.numeric.Point import org.scalatest.{FunSpec, Matchers} class ScatterPlotSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("ScatterPlot") { it("sets adheres to bound buffers") { val data = Seq(Point(-1, 10), Point(20, -5)) val plot = ScatterPlot(data, xBoundBuffer = Some(0.1), yBoundBuffer = Some(0.1)) plot.xbounds.min should be < -1.0 plot.xbounds.max should be > 20.0 plot.ybounds.min should be < -5.0 plot.ybounds.max should be > 10.0 } it("sets exact bounds without buffering") { val data = Seq(Point(-1, 10), Point(20, -5)) val plot = ScatterPlot(data) plot.xbounds.min shouldBe -1.0 plot.xbounds.max shouldBe 20.0 plot.ybounds.min shouldBe -5.0 plot.ybounds.max shouldBe 10.0 } it("sets reasonable bounds with only 1 point") { val plot = ScatterPlot(Seq(Point(2, 3))) plot.xbounds.min shouldBe 2.0 +- 0.0000001 plot.xbounds.max shouldBe 2.0 +- 0.0000001 plot.ybounds.min shouldBe 3.0 +- 0.0000001 plot.ybounds.max shouldBe 3.0 +- 0.0000001 } } }
Example 148
Source File: BarChartSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.Bounds import org.scalatest.{FunSpec, Matchers} class BarChartSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("BarChart") { it("should have the right bounds without buffer") { val plot = BarChart(Seq[Double](10, 20, 15)) plot.xbounds shouldBe Bounds(0, 3) plot.ybounds shouldBe Bounds(10, 20) } it("should have the right bounds with buffer") { val plot = BarChart(Seq[Double](10, 20, 15), boundBuffer = Some(.1)) plot.xbounds shouldBe Bounds(0, 3) plot.ybounds.min should be < 10.0 plot.ybounds.max should be > 20.0 } it("should have the right bounds with stacked bars") { val plot = BarChart.stacked(Seq(Seq(10.0, 5), Seq(20.0, 7), Seq(15.0, 0)), boundBuffer = Some(0)) plot.xbounds shouldBe Bounds(0, 3) plot.ybounds shouldBe Bounds(15, 27) } it("should have the right extents") { val plot = BarChart(Seq(10.0, 20, 15)) val extent = Extent(200, 200) plot.render(extent).extent shouldBe extent } it("should not explode if there is no data") { val plot = BarChart(Seq.empty) val extent = Extent(200, 300) plot.render(extent).extent shouldBe extent } } }
Example 149
Source File: CartesianPlotSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.{Bounds, Point} import org.scalatest.{FunSpec, Matchers} class CartesianPlotSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("Cartesian Plot") { it("has the right bounds") { val plot = CartesianPlot( Seq(Point(1, 2), Point(3, 4)), xboundBuffer = Some(0), yboundBuffer = Some(0))() plot.xbounds shouldBe Bounds(1, 3) plot.ybounds shouldBe Bounds(2, 4) } it("works with a single point") { val plot = CartesianPlot(Seq(Point(1, 2)))() val extent = Extent(100, 200) plot.render(extent).extent shouldBe Extent(100, 200) } it("works with no data") { val plot = CartesianPlot(Seq.empty)() val extent = Extent(100, 200) plot.render(extent).extent shouldBe Extent(100, 200) } } }
Example 150
Source File: HeatmapSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.Bounds import org.scalatest.{FunSpec, Matchers} class HeatmapSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("Heatmap") { it("has the right bounds") { val plot = Heatmap(Seq(Seq(1), Seq(2))) plot.xbounds shouldBe Bounds(0, 1) plot.ybounds shouldBe Bounds(0, 2) } it("should work an empty row") { val plot = Heatmap(Seq(Seq.empty)) val extent = Extent(100, 200) plot.render(extent).extent shouldBe extent } it("should work with no data") { val plot = Heatmap(Seq.empty) val extent = Extent(100, 200) plot.render(extent).extent shouldBe extent } } }
Example 151
Source File: BoxPlotSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.Bounds import org.scalatest.{FunSpec, Matchers} class BoxPlotSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("BoxPlot") { it("should have the right extents") { val plot = BoxPlot(Seq(Seq(1.0, 2.0))) val extent = Extent(100, 200) plot.render(extent).extent shouldBe extent } it("should have the right bounds") { val plot = BoxPlot(Seq(Seq(1.0, 2.0)), boundBuffer = Some(0)) plot.xbounds shouldBe Bounds(0, 1) plot.ybounds shouldBe Bounds(1, 2) } it("should not explode with no data") { val plot = BoxPlot(Seq.empty) val extent = Extent(200, 200) plot.render(extent).extent shouldBe extent } it("should not explode when there is no data for a box") { val plot = BoxPlot(Seq(Seq.empty)) val extent = Extent(200, 200) plot.render(extent).extent shouldBe extent } } }
Example 152
Source File: MixedBoundsOverlaySpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.{Drawable, EmptyDrawable, Extent} import com.cibo.evilplot.numeric.{Bounds, Point} import com.cibo.evilplot.plot.aesthetics.Theme import com.cibo.evilplot.plot.renderers.PlotRenderer import org.scalatest.{FunSpec, Matchers} class MixedBoundsOverlaySpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("MixedBoundsOverlay") { it("it has the bounds that are set for it") { val xbounds = Bounds(-2, 2) val ybounds = Bounds(100, 200) val inner1 = ScatterPlot(Seq(Point(10.0, -1.0))) val inner2 = ScatterPlot(Seq(Point(3.0, 20.0))) val overlay = MixedBoundsOverlay(xbounds, ybounds, inner1, inner2) overlay.xbounds shouldBe xbounds overlay.ybounds shouldBe ybounds } it("occupies the right extents") { val inner1 = ScatterPlot(Seq(Point(10.0, -1.0))) val inner2 = ScatterPlot(Seq(Point(11.0, 1.0))) val overlay = MixedBoundsOverlay(Bounds(0, 1), Bounds(0, 1), inner1, inner2) val extent = Extent(600, 400) overlay.render(extent).extent shouldBe extent } it("doesn't update bounds on subplots") { var xbounds: Bounds = Bounds(0, 0) var ybounds: Bounds = Bounds(0, 0) val testRenderer = new PlotRenderer { def render(plot: Plot, plotExtent: Extent)(implicit theme: Theme): Drawable = { xbounds = plot.xbounds ybounds = plot.ybounds EmptyDrawable().resize(plotExtent) } } val inner = new Plot( xbounds = Bounds(1, 2), ybounds = Bounds(3, 4), renderer = testRenderer ) val overlay = MixedBoundsOverlay(Bounds(50, 80), Bounds(50, 80), inner) val updated = overlay.xbounds(5, 6).ybounds(7, 8) updated.render(Extent(100, 200)) xbounds shouldBe Bounds(1, 2) ybounds shouldBe Bounds(3, 4) } it("should throw an exception with no plots") { an[IllegalArgumentException] should be thrownBy MixedBoundsOverlay(Bounds(1, 2), Bounds(1, 2)) } } }
Example 153
Source File: PlotSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.{Drawable, EmptyDrawable, Extent} import com.cibo.evilplot.DOMInitializer import com.cibo.evilplot.numeric.Bounds import com.cibo.evilplot.plot.aesthetics.Theme import com.cibo.evilplot.plot.renderers.PlotRenderer import org.scalatest.{FunSpec, Matchers} class PlotSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ DOMInitializer.init() // Renderer to do nothing. private[evilplot] case object EmptyPlotRenderer extends PlotRenderer { def render(plot: Plot, plotExtent: Extent)(implicit theme: Theme): Drawable = EmptyDrawable().resize(plotExtent) } // Renderer to get the plot extent. private case class PlotExtentPlotRenderer() extends PlotRenderer { var plotExtentOpt: Option[Extent] = None def render(plot: Plot, plotExtent: Extent)(implicit theme: Theme): Drawable = { plotExtentOpt = Some(plotExtent) EmptyDrawable().resize(plotExtent) } } private def newPlot( xbounds: Bounds = Bounds(0, 1), ybounds: Bounds = Bounds(0, 1), renderer: PlotRenderer = EmptyPlotRenderer ): Plot = Plot(xbounds, ybounds, renderer) it("should have the right extent") { val plot = newPlot() val extent = Extent(300, 400) plot.render(extent).extent shouldBe extent } it("should render the full plot area") { val extent = Extent(10, 20) val renderer = PlotExtentPlotRenderer() val plot = newPlot(renderer = renderer) plot.render(extent).extent shouldBe extent renderer.plotExtentOpt shouldBe Some(extent) } it("text should reduce the size of the plot area") { val extent = Extent(100, 200) val renderer = PlotExtentPlotRenderer() val plot = newPlot(renderer = renderer).title("Test") plot.render(extent).extent shouldBe extent renderer.plotExtentOpt.get.height should be < extent.height renderer.plotExtentOpt.get.width shouldBe extent.width } it("a background should not affect the size of the plot area") { val extent = Extent(300, 200) val renderer = PlotExtentPlotRenderer() val plot = newPlot(renderer = renderer).background() plot.render(extent).extent shouldBe extent renderer.plotExtentOpt.get shouldBe extent } it("xbounds/ybounds without parens should access bounds") { val plot = newPlot(xbounds = Bounds(0, 2), ybounds = Bounds(0, 5)) plot.xbounds shouldBe Bounds(0, 2) plot.ybounds shouldBe Bounds(0, 5) } it("partial xbounds/ybounds update should work") { val plot = newPlot(xbounds = Bounds(0, 2), ybounds = Bounds(0, 5)) val updatedX = plot.xbounds(lower = -5) updatedX.xbounds shouldBe Bounds(-5, 2) val doubleUpdatedX = updatedX.xbounds(upper = 5) doubleUpdatedX.xbounds shouldBe Bounds(-5, 5) val updatedY = plot.ybounds(lower = -7) updatedY.ybounds shouldBe Bounds(-7, 5) val doubleUpdatedY = updatedY.ybounds(upper = 7) doubleUpdatedY.ybounds shouldBe Bounds(-7, 7) } }
Example 154
Source File: TransformUtilsSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.{Bounds, Point} import org.scalatest.{FunSpec, Matchers} class TransformUtilsSpec extends FunSpec with Matchers { describe("PlotUtils") { it("computes the correct buffer") { val zeroTen = PlotUtils.boundsWithBuffer(xs = Seq(0.0, 10.0), 0.0) zeroTen shouldEqual Bounds(0.0, 10.0) val zeroTenTen = PlotUtils.boundsWithBuffer(xs = Seq(0.0, 10.0), 0.1) zeroTenTen shouldEqual Bounds(-1.0, 11.0) val negZeroTenTen = PlotUtils.boundsWithBuffer(xs = Seq(0.0, -10.0), buffer = 0.1) negZeroTenTen shouldEqual Bounds(-11.0, 1.0) } it("computes bounds") { val points = Seq(Point(0.0, 0.0), Point(10.0, 10.0)) PlotUtils.bounds(points, 0.1) shouldEqual (Bounds(-1.0, 11.0), Bounds(-1.0, 11.0)) PlotUtils.bounds(points, 0.0, xboundBuffer = Some(0.1)) shouldEqual (Bounds(-1.0, 11.0), Bounds( 0, 10.0)) PlotUtils.bounds(points, 0.0, yboundBuffer = Some(0.1)) shouldEqual (Bounds(0, 10.0), Bounds( -1.0, 11.0)) } } describe("TransformWorldToScreen") { val xTransformer = TransformWorldToScreen.xCartesianTransformer(Bounds(0, 100), extent = Extent(100, 100)) val yTransformer = TransformWorldToScreen.yCartesianTransformer(Bounds(0, 100), extent = Extent(100, 100)) it("default x transformer works properly") { xTransformer(-100) shouldEqual -100.0 +- 0.000001 xTransformer(0) shouldEqual 0.0 +- 0.000001 xTransformer(100) shouldEqual 100.0 +- 0.000001 } it("default y transformer works properly") { yTransformer(-100) shouldEqual 200.0 +- 0.000001 yTransformer(0) shouldEqual 100.0 +- 0.000001 yTransformer(100) shouldEqual 0.0 +- 0.000001 } it("Transforms to screen correctly") { import TransformWorldToScreen._ val transformer = TransformWorldToScreen.yCartesianTransformer(Bounds(0, 10), extent = Extent(100, 100)) transformDatumToWorld(Point(0.0, 0.0), xTransformer, yTransformer) shouldEqual Point( 0.0, 100.0) } } }
Example 155
Source File: PathRendererSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot.renderers import com.cibo.evilplot.geometry.LineStyle import org.scalatest.{FunSpec, Matchers} class PathRendererSpec extends FunSpec with Matchers { describe("Legend stroke lengths") { import LineStyle._ import PathRenderer._ it("should use the default for a solid style") { calcLegendStrokeLength(Solid) shouldBe baseLegendStrokeLength } it("should always return at least the baseLegendStrokeLength") { calcLegendStrokeLength(Dotted) shouldBe 9 calcLegendStrokeLength(evenlySpaced(3)) should be >= baseLegendStrokeLength calcLegendStrokeLength(LineStyle(Seq(1, 1))) shouldBe baseLegendStrokeLength } it("should use at least 4x the pattern length with a single element pattern") { calcLegendStrokeLength(evenlySpaced(6)) shouldBe 24 } it("should use a minimum of 2x the pattern length with a regular element pattern") { calcLegendStrokeLength(DashDot) shouldBe 26 } } }
Example 156
Source File: ContourPlotSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.{Bounds, Point} import org.scalatest.{FunSpec, Matchers} class ContourPlotSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("ContourPlot") { it("it has the right bounds") { val plot = ContourPlot(Seq(Point(1, 2), Point(3, 4)), boundBuffer = Some(0.0)) plot.xbounds shouldBe Bounds(1, 3) plot.ybounds shouldBe Bounds(2, 4) } it("works with no data") { val plot = ContourPlot(Seq.empty) val extent = Extent(100, 200) plot.render(extent).extent shouldBe extent } } }
Example 157
Source File: HistogramSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.geometry.Extent import com.cibo.evilplot.numeric.{Bounds, Point} import org.scalatest.{FunSpec, Matchers} class HistogramSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("Histogram") { val plot = Histogram(Seq(1.0, 1, 1, 2, 3, 4, 4, 5), boundBuffer = Some(0)) it("has the right bounds") { plot.xbounds shouldBe Bounds(1, 5) plot.ybounds shouldBe Bounds(0, 3) } it("has the right extents") { val extent = Extent(300, 400) plot.render(extent).extent.width shouldBe extent.width +- 1e-6 plot.render(extent).extent.height shouldBe extent.height +- 1e-6 } it("works with no data") { val extent = Extent(100, 200) val emptyPlot = Histogram(Seq.empty) emptyPlot.render(extent).extent shouldBe extent } } describe("Binning") { val data = Seq[Double](1, 1, 1, 3, 3, 4, 4, 5) it("works on a simple example") { val bins = Histogram.createBins(data, Bounds(0, 5), 5) bins should contain theSameElementsAs Seq( Point(0, 0), Point(1, 3), Point(2, 0), Point(3, 2), Point(4, 3) ) } it("works when asked to normalize") { val bins = Histogram.normalize(data, Bounds(0, 5), 5) bins.map(_.y) should contain theSameElementsAs Seq( 0, .375, 0, .25, .375 ) bins.map(_.y).sum shouldBe 1.0 +- 1e-5 } it("works for cumulative binner") { val bins = Histogram.cumulative(data, Bounds(0, 5), 5) bins should contain theSameElementsAs Seq( Point(0, 0), Point(1, 3), Point(2, 3), Point(3, 5), Point(4, 8) ) } it("works for density binner") { val bins = Histogram.density(data, Bounds(0, 5), 5) bins.map(_.y) should contain theSameElementsAs Seq( 0, 0.375, 0, 0.25, 0.375 ) } it("works for cumulativeDensity binner") { val bins = Histogram.cumulativeDensity(data, Bounds(0, 5), 5) bins.map(_.y) should contain theSameElementsAs Seq( 0, 0.375, 0.375, 0.625, 1.000 ) } } }
Example 158
Source File: MarkerPlotSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot import com.cibo.evilplot.demo.DemoPlots.{plotAreaSize, theme} import com.cibo.evilplot.geometry.{Extent, Rect, Rotate, Style, Text, Wedge} import com.cibo.evilplot.numeric.{Bounds, Point} import com.cibo.evilplot.plot.components.{Marker, Position} import org.scalatest.{FunSpec, Matchers} class MarkerPlotSpec extends FunSpec with Matchers { describe("Marker Plot") { it("overlay marker displays correctly") { val marker = Marker(Position.Overlay, _ => Rect(25), Extent(25, 25), 0, 0) val data = Seq(Point(-1, 10), Point(20, -5)) val plot = ScatterPlot(data, xBoundBuffer = Some(0.1), yBoundBuffer = Some(0.1)).component(marker) plot.xbounds.min should be < -1.0 plot.xbounds.max should be > 20.0 plot.ybounds.min should be < -5.0 plot.ybounds.max should be > 10.0 marker.size.height should be < 26.0 marker.size.width should be < 26.0 marker.x shouldBe 0 marker.y shouldBe 0 } } }
Example 159
Source File: AxesSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.plot.components import com.cibo.evilplot.numeric.{Bounds, Point} import com.cibo.evilplot.plot.{Bar, BarChart, ScatterPlot} import org.scalatest.{FunSpec, Matchers} class AxesSpec extends FunSpec with Matchers { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ describe("discrete X") { it("should set the default bounds") { val plot = BarChart(Seq(3.0, 4)).xAxis() plot.xbounds shouldBe Bounds(0, 2) } it("should set bounds for labels") { val plot = BarChart(Seq(3.0, 4)).xAxis(Seq("one", "two")) plot.xbounds shouldBe Bounds(0, 2) } it("should set bounds for more labels") { val plot = BarChart(Seq(3.0, 4)).xAxis(Seq("one", "two", "three")) plot.xbounds shouldBe Bounds(0, 3) } it("should set bounds for fewer labels") { val plot = BarChart(Seq(3.0, 4)).xAxis(Seq("one")) plot.xbounds shouldBe Bounds(0, 1) } } describe("continuous X") { it("should set reasonable default bounds") { val plot = ScatterPlot(Seq(Point(3, 4), Point(5, 6)), xBoundBuffer = Some(0), yBoundBuffer = Some(0)) .xAxis() plot.xbounds shouldBe Bounds(3, 5) } it("should not update the bounds multiple times") { val plot = ScatterPlot( Seq(Point(0, 0), Point(1.007, 2)), xBoundBuffer = Some(0), yBoundBuffer = Some(0)) .xbounds(0, 1.1) .xAxis() plot.xbounds.min shouldBe 0.0 +- 1e-6 plot.xbounds.max shouldBe 1.1 +- 1e-6 } } describe("continuous Y") { it("should set reasonable default bounds") { val plot = ScatterPlot(Seq(Point(3, 4), Point(5, 6)), xBoundBuffer = Some(0), yBoundBuffer = Some(0)) .yAxis() plot.ybounds shouldBe Bounds(4, 6) } } }
Example 160
Source File: KernelDensityEstimationSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.numeric import com.cibo.evilplot.numeric.KernelDensityEstimation._ import org.scalatest.{FunSpec, Matchers} import scala.util.Random.nextDouble class KernelDensityEstimationSpec extends FunSpec with Matchers { describe("KernelDensityEstimation") { it("should properly calculate probability densities from the normal distribution") { val doubles: Seq[Double] = Seq(0.383738345, 0.678363183, 0.870892648, 0.955542032, 0.739779717, 0.495273777, 0.346604271, 0.971385358, 0.998761496, 0.222603808, 0.370077565, 0.081424898, 0.775284522, 0.005343148, 0.470091059, 0.510200712, 0.361834899, 0.259037336, 0.806185498, 0.337947191) val densities: Seq[Double] = Seq(0.3706244, 0.3169451, 0.2730322, 0.2527211, 0.3034387, 0.3528943, 0.3756844, 0.2488927, 0.2422704, 0.3891794, 0.3725376, 0.3976220, 0.2953862, 0.3989366, 0.3572100, 0.3502560, 0.3736631, 0.3857797, 0.2882561, 0.3767993) (doubles zip densities).foreach { case (x, d) => probabilityDensityInNormal(x) shouldEqual d +- 1e-5 } } } describe("outer product calculation") { it("should calculate correctly") { val xs = Vector(-.3015008, 0.6520850) val ys = Vector(-.3033709, 0.6459446, 1.7718656) val outer = Array(Array(0.09146657, -0.1947528, -0.5342189), Array(-0.19782361, 0.4212108, 1.1554070)) (outerProduct(xs.toArray, ys.toArray).flatten.toSeq zip outer.flatten.toSeq) foreach { case (calculated, actual) => calculated shouldBe actual +- 1e-6 } } } describe("bandwidth estimation") { it("should always be non-negative") { // no ScalaCheck in scala.js ? (0 until 10) map (_ => Vector.fill(10)(nextDouble)) foreach (bandwidthEstimate(_) should be >= 0.0) } it("should be calculated properly for some sample vectors") { val xs = Vector(-1.06575970, 0.42420074, 0.02938372, 2.04974410, -1.63546604, 0.27436596, -0.90455302, 0.86564478, 1.68234299, 0.19371170) val ys = Vector(-0.7695360, 0.5401861, 0.3025197, 1.8889234, 1.1587218, -0.6744424, 0.9437049) bandwidthEstimate(xs) shouldBe 2.847659 +- 1e-6 bandwidthEstimate(ys) shouldBe 2.652604 +- 1e-6 } it("should reutrn NaN on a one element vector") { val xs = Vector(-1.045696) bandwidthEstimate(xs).isNaN shouldBe true } it("should return NaN on an empty vector") { bandwidthEstimate(Vector[Double]()).isNaN shouldBe true } } }
Example 161
Source File: BoxPlotSummaryStatisticsSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.numeric import org.scalatest.{FunSpec, Matchers} import scala.util.Random class BoxPlotSummaryStatisticsSpec extends FunSpec with Matchers { val tol = 1e-8 val data = List(-2541.335733882479, 1577.0315624249806, -808.0673232141799, 680.9128930911302, -2445.2589645401004, -7.260674159999326, -1762.1261882364997, -776.52236318016, -3198.781083548529, 517.4382306836906, -1982.1566564704299, -1700.7419477605) describe("BoxPlotSummaryStatistics") { it("should correctly calculate quartiles using linear interpolation between values") { val boxPlot = BoxPlotSummaryStatistics(data) // NumPy on this list: [ np.percentile(data, x) for x in xrange(25, 100, 25) ] == val (first, second, third) = (-2097.9322334878475, -1254.4046354873399, 123.91405205092315) // low tolerance because above data is only to hundredths place boxPlot.lowerQuantile shouldEqual first +- tol boxPlot.middleQuantile shouldEqual second +- tol boxPlot.upperQuantile shouldEqual third +- tol } it("should give the maximum when asked for the 1.0 quantile") { val boxPlot = BoxPlotSummaryStatistics(data, quantiles = (0.0, 0.5, 1.0)) boxPlot.upperQuantile shouldEqual data.max +- tol } it( "0.5 quantile w linear interpolation should give the same answer as median (even number of elements in list)") { val medianData: Seq[Double] = Seq.fill(50)(Random.nextDouble()) val sorted = medianData.sorted val median = (sorted(24) + sorted(25)) / 2.0 val boxPlot = BoxPlotSummaryStatistics(medianData) boxPlot.middleQuantile shouldEqual median +- tol } it( "0.5 quantile w linear interpolation should give the same answer as median (odd number of elements in list)") { val medianData: Seq[Double] = Seq.fill(49)(Random.nextDouble()) val sorted = medianData.sorted val median = sorted(24) val boxPlot = BoxPlotSummaryStatistics(medianData) boxPlot.middleQuantile shouldEqual median +- tol } it("correctly classifies as outliers elements outside lowerQ - 1.5*IQR < x < upperQ + 1.5*IQR") { val temperatureData = Seq(94.371, 94.304, 94.216, 94.130, 94.050, 93.961, 93.840, 93.666, 93.430, 93.141, 92.824, 92.515, 92.249, 92.048, 91.920, 91.853, 91.824, 91.810, 91.788, 91.747, 91.685, 91.612, 91.547, 91.511, 91.520, 91.585, 91.710, 91.015, 91.898, 92.146, 92.451, 92.800, 93.178, 93.573, 93.972, 94.360, 94.717, 95.010, 95.211, 95.295, 95.261, 95.127, 94.932, 94.729, 94.565, 94.465, 94.429, 94.440, 94.478, 94.538, 94.632, 94.775, 94.973, 95.202, 95.416, 95.561, 95.592, 95.490, 95.263, 94.945, 94.590, 94.258, 94.003, 93.866, 93.868, 94.015, 94.296, 94.677, 95.107, 95.520, 95.853, 96.058, 96.119, 96.053, 98.032, 95.906, 95.741, 95.616, 95.566, 95.591, 95.668, 95.756, 95.817, 95.824, 95.759, 95.623, 95.432, 95.214, 95.002, 94.819, 94.675, 94.573, 94.514, 94.507, 94.562, 94.682, 94.858, 95.067, 95.278, 95.463, 95.598, 95.664) val outliers = Seq(91.015, 98.032) val boxPlot = BoxPlotSummaryStatistics(temperatureData) boxPlot.outliers.length shouldEqual outliers.length (boxPlot.outliers zip outliers).foreach { case (computed, actual) => computed shouldEqual actual +- tol } } } }
Example 162
Source File: ColoringSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.cibo.evilplot.colors import com.cibo.evilplot.geometry.PointEquivalences import com.cibo.evilplot.plot.aesthetics.DefaultTheme.{DefaultElements, DefaultFonts} import com.cibo.evilplot.plot.aesthetics.{Colors, Elements, Fonts, Theme} import org.scalatest.{FunSpec, Matchers} class ColoringSpec extends FunSpec with Matchers { describe("multi color gradient construction") { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ it("should return a function when Colors has only one element") { val min: Double = 0 val max: Double = 100 val coloring = GradientUtils.multiGradient(Seq(HTMLNamedColors.blue), min, max, GradientMode.Linear) Range.BigDecimal(min, max, 1.0) .map(_.toDouble) .foreach(datum => coloring(datum) shouldBe HTMLNamedColors.blue) } it("should throw an exception when Colors is empty") { an[IllegalArgumentException] shouldBe thrownBy( GradientUtils.multiGradient(Seq(), 0, 100, GradientMode.Linear)) } it("should build multistop gradients") { import HTMLNamedColors.{red, yellow, green} val min = 0 val max = 2 val colors = Seq(red, yellow, green) val gradient = GradientUtils.multiGradient(colors, min, max, GradientMode.Linear) gradient(min) should ===(colors.head) gradient(1) should ===(colors(1)) gradient(max) should ===(colors(2)) } it("should return a function that works between min and max") { val data: Seq[Double] = Seq(0, 5, 20, 40, 70, 100) val gradient = ContinuousColoring.gradient(HTMLNamedColors.red, HTMLNamedColors.blue) val coloring = gradient(data) data.foreach(d => noException shouldBe thrownBy(coloring(d))) } it("should behave properly when asked to render past the edge") { val gradient = ContinuousColoring.gradient(HTMLNamedColors.red, HTMLNamedColors.blue) val coloring = gradient(Seq(1.0, 5.0)) coloring(1.0) shouldBe HTMLNamedColors.red coloring(5.0) shouldBe HTMLNamedColors.blue coloring(6.0) shouldBe HTMLNamedColors.blue } } describe("coloring from the theme") { import com.cibo.evilplot.plot.aesthetics.DefaultTheme.{DefaultColors => AesColors} implicit val overriddenTheme: Theme = Theme( fonts = DefaultFonts, elements = DefaultElements, colors = AesColors.copy(stream = Seq(HTMLNamedColors.red)) ) it("should fail to color when the theme doesn't have enough colors") { val data = 0 to 5 an[IllegalArgumentException] shouldBe thrownBy(CategoricalColoring.themed[Int].apply(data)) } } describe("making a coloring out of a custom mapping") { import com.cibo.evilplot.plot.aesthetics.DefaultTheme._ it("should actually use the mapping") { val f = (s: String) => if (s == "hello") HTMLNamedColors.blue else HTMLNamedColors.red val coloring = CategoricalColoring.fromFunction(Seq("hello", "world"), f) val extractedFunc = coloring(Seq("hello", "world")) extractedFunc("hello") shouldBe HTMLNamedColors.blue extractedFunc("world") shouldBe HTMLNamedColors.red } } }
Example 163
Source File: TemplateLookupTest_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import com.monsanto.arch.cloudformation.model.resource._ import org.scalatest.FunSpec import org.scalatest.Matchers class TemplateLookupTest_UT extends FunSpec with Matchers { describe("CrazyLookup") { it("Should lookup resources with the correct type") { val expected = `AWS::EC2::VPC`( name = "TestVPC", CidrBlock = CidrBlock(0,0,0,0,0), Tags = Seq.empty[AmazonTag] ) val template = Template.fromResource(expected) assert(expected === template.lookupResource[`AWS::EC2::VPC`]("TestVPC")) } it("Should throw exception when given the wrong type") { val expected = `AWS::EC2::VPC`( name = "TestVPC", CidrBlock = CidrBlock(0,0,0,0,0), Tags = Seq.empty[AmazonTag] ) val template = Template.fromResource(expected) intercept[ClassCastException] { template.lookupResource[`AWS::EC2::Subnet`]("TestVPC") } } it("Should throw exception when resources is empty") { val template = Template.EMPTY intercept[RuntimeException] { template.lookupResource[`AWS::EC2::Subnet`]("TestVPC") } } it("Should throw exception when resource doesn't exist") { val otherThing = `AWS::EC2::VPC`( name = "TestVPC", CidrBlock = CidrBlock(0,0,0,0,0), Tags = Seq.empty[AmazonTag] ) val template = Template.fromResource(otherThing) intercept[RuntimeException] { template.lookupResource[`AWS::EC2::VPC`]("NoVPC") } } it("Should throw exception when multiple resources of same name") { val expected = `AWS::EC2::VPC`( name = "TestVPC", CidrBlock = CidrBlock(0,0,0,0,0), Tags = Seq.empty[AmazonTag] ) val template = Template.fromResource(expected) ++ expected intercept[RuntimeException] { template.lookupResource[`AWS::EC2::Subnet`]("TestVPC") } } } }
Example 164
Source File: HasTemplateSpec.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import org.scalatest.{FunSpec, Matchers} class HasTemplateSpec extends FunSpec with Matchers { it("should concat two instances of HasTemplate") { object template1 extends HasTemplate { val param1 = StringParameter("test1") override def template: Template = Template.EMPTY ++ param1 } object template2 extends TemplateBase { val param = StringParameter("test2") } val template = (template1 ++ template2).template template.Parameters.get.contains(template1.param1) should be(true) template.Parameters.get.contains(template2.param) should be(true) } it("should concat HasTemplate with Template") { object hasTemplate1 extends HasTemplate { val param1 = StringParameter("test1") override def template: Template = Template.EMPTY ++ param1 } object hasTemplate2 extends TemplateBase { val param = StringParameter("test2") } val template = (hasTemplate1 ++ hasTemplate2.template).template template.Parameters.get.contains(hasTemplate1.param1) should be(true) template.Parameters.get.contains(hasTemplate2.param) should be(true) } it("should concat Template with HasTemplate") { object hasTemplate1 extends HasTemplate { val param1 = StringParameter("test1") override def template: Template = Template.EMPTY ++ param1 } object hasTemplate2 extends TemplateBase { val param = StringParameter("test2") } val template : Template = hasTemplate1.template ++ hasTemplate2 template.Parameters.get.contains(hasTemplate1.param1) should be(true) template.Parameters.get.contains(hasTemplate2.param) should be(true) } }
Example 165
Source File: FnSplit_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import com.monsanto.arch.cloudformation.model.resource.LambdaVpcConfig import org.scalatest.{FunSpec, Matchers} import spray.json._ class FnSplit_UT extends FunSpec with Matchers { import Token._ describe("Fn::Split"){ it("Should serialize correctly with simple string arguments") { val split: TokenSeq[String] = `Fn::Split`(",", "one,two") val expected = JsObject( "Fn::Split" → JsArray( JsString(","), JsString("one,two") ) ) split.toJson should be(expected) } it("Should serialize correctly with complex argument types") { val split: TokenSeq[String] = `Fn::Split`(",", `Fn::ImportValue`("importKey")) val expected = JsObject( "Fn::Split" → JsArray( JsString(","), JsObject( "Fn::ImportValue" → JsString("importKey") ) ) ) split.toJson should be(expected) } it("Should serialize correctly when used inside a resource") { val resource = LambdaVpcConfig(Seq("sg-groupid"), `Fn::Split`(",", `Fn::ImportValue`("importKey"))) val expected = JsObject( "SecurityGroupIds" → JsArray(JsString("sg-groupid")), "SubnetIds" → JsObject( "Fn::Split" → JsArray( JsString(","), JsObject( "Fn::ImportValue" → JsString("importKey") ) ) ) ) resource.toJson should be(expected) } it("Should implicitly convert inside a seq") { val resource: TokenSeq[String] = Seq("test") val expected = JsArray(JsString("test")) resource.toJson should be(expected) } it("Should implicitly convert inside a seq with a function call") { val resource: TokenSeq[String] = Seq(`Fn::Join`(",", Seq("test"))) val expected = JsArray(JsObject( "Fn::Join" → JsArray(JsString(","), JsArray(JsString("test"))) )) resource.toJson should be(expected) } } }
Example 166
Source File: AwsTokenSpec.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import com.monsanto.arch.cloudformation.model.AwsStringInterpolation.Zipper import org.scalatest.{Matchers, FunSpec} class AwsTokenSpec extends FunSpec with Matchers { it("should generate simple string if no expressions") { val fun = aws"test" fun shouldEqual StringToken("test") } it("should generate simple string if no only string substitutions") { val lost : Token[String] = "lost" val world : Token[String] = "world" val fun = aws"hello$lost$world" fun shouldEqual StringToken("hellolostworld") } it("should join ParameterRef tokens") { val param = ParameterRef(StringParameter("that")) val fun = aws"test$param" fun shouldEqual FunctionCallToken(`Fn::Join`("", Seq( StringToken("test"), param ))) } it("should join Parameter") { val param = StringParameter("that") val fun = aws"test$param" fun shouldEqual FunctionCallToken(`Fn::Join`("", Seq( StringToken("test"), ParameterRef(param) ))) } it("should join multiple Parameters") { val param1 = StringParameter("that") val param2 = StringParameter("this") val param3 = StringParameter("these") val fun = aws"test$param1${param2}hello$param3" fun shouldEqual FunctionCallToken(`Fn::Join`("", Seq( StringToken("test"), ParameterRef(param1), ParameterRef(param2), StringToken("hello"), ParameterRef(param3) ))) } it("should join Fn::GetAtt ref tokens") { val getAtt = `Fn::GetAtt`(Seq("that")) val fun = aws"test${getAtt}something" fun shouldEqual FunctionCallToken(`Fn::Join`("", Seq( StringToken("test"), getAtt, StringToken("something") ))) } it("should join tokens") { val getAtt : Token[String] = `Fn::GetAtt`(Seq("that")) val fun = aws"test${getAtt}something" fun shouldEqual FunctionCallToken(`Fn::Join`("", Seq( StringToken("test"), getAtt, StringToken("something") ))) } it("should optimize join tokens") { val getAtt : Token[String] = `Fn::GetAtt`(Seq("that")) val test1 = "test1" val test2 = "test2" val fun = aws"test$getAtt${test1}something$test2" fun shouldEqual FunctionCallToken(`Fn::Join`("", Seq( StringToken("test"), getAtt, StringToken(s"${test1}something$test2") ))) } describe("zipper") { it("should combine unevent lists") { val zipper = Zipper(Seq("a", "b", "c"), Seq("d", "e"), Seq("f")) zipper.toSeq shouldEqual Seq( "a", "d", "f", "b", "e", "c" ) } } }
Example 167
Source File: TemplateBaseSpec.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import scala.language.reflectiveCalls import com.monsanto.arch.cloudformation.model.resource.`AWS::SQS::Queue` import org.scalatest.{FunSpec, Matchers} class TemplateBaseSpec extends FunSpec with Matchers { it("should find components of templates") { object MyTemplate extends TemplateBase { val param1 = StringParameter("test1", "desc1") def resource1 = `AWS::SQS::Queue`( name = "resource1", QueueName = "test1", DelaySeconds = 5, MessageRetentionPeriod = 2, ReceiveMessageWaitTimeSeconds = 9, VisibilityTimeout = 4 ) lazy val out1 = Output(name = "out1", Description = "desc", Value = `AWS::AccountId`) } MyTemplate.template.Outputs.toSeq.flatten should contain(MyTemplate.out1) MyTemplate.template.Parameters.toSeq.flatten should contain(MyTemplate.param1) MyTemplate.template.Resources should contain(MyTemplate.resource1) } it("should find instances of HasTemplate") { object MyTemplate extends TemplateBase { lazy val anotherTemplate = new TemplateBase { def resource1 = `AWS::SQS::Queue`( name = "resource1", QueueName = "test1", DelaySeconds = 5, MessageRetentionPeriod = 2, ReceiveMessageWaitTimeSeconds = 9, VisibilityTimeout = 4 ) } lazy val anotherTemplate2 = new TemplateBase { def resource = `AWS::SQS::Queue`( name = "resource2", QueueName = "test2", DelaySeconds = 5, MessageRetentionPeriod = 2, ReceiveMessageWaitTimeSeconds = 9, VisibilityTimeout = 4 ) } } MyTemplate.template.Resources should contain(MyTemplate.anotherTemplate.resource1) MyTemplate.template.Resources should contain(MyTemplate.anotherTemplate2.resource) } it("should find instances of Template") { val queue = `AWS::SQS::Queue`( name = "resource1", QueueName = "test1", DelaySeconds = 5, MessageRetentionPeriod = 2, ReceiveMessageWaitTimeSeconds = 9, VisibilityTimeout = 4 ) object MyTemplate extends TemplateBase { lazy val anotherTemplate = Template.EMPTY ++ queue } MyTemplate.template.Resources should contain(queue) } }
Example 168
Source File: CodeCommit_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ ResourceRef, Template, Token } import org.scalatest.{ FunSpec, Matchers } import spray.json._ class CodeCommit_UT extends FunSpec with Matchers { val repo = `AWS::CodeCommit::Repository`( name = "RepoFoo", RepositoryDescription = Some(""), RepositoryName = "RepoBar", Triggers = Some(Seq( CodeCommitTrigger( Branches = Some(Seq("foo")), CustomData = Some("bar"), DestinationArn = Some("arn::::baz"), Events = Some(Seq( CodeCommitEvent.updateReference, CodeCommitEvent.deleteReference )), Name = "BarTrigger" ) )) ) describe("UsagePlan"){ it ("should serialize as expected") { val expectedJson = """ |{ | "Resources": { | "RepoFoo": { | "Properties": { | "RepositoryDescription": "", | "RepositoryName": "RepoBar", | "Triggers": [ | { | "Branches": [ | "foo" | ], | "CustomData": "bar", | "DestinationArn": "arn::::baz", | "Events": [ | "updateReference", | "deleteReference" | ], | "Name": "BarTrigger" | } | ] | }, | "Type": "AWS::CodeCommit::Repository" | } | } |} """.stripMargin.parseJson Template.fromResource(repo).toJson should be (expectedJson) } } }
Example 169
Source File: EmrSpec.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import org.scalatest.{FunSpec, Matchers} import spray.json.{JsArray, JsObject, JsString, JsonWriter} class EmrSpec extends FunSpec with Matchers { describe("ClusterConfiguration") { it("should write non recursive") { val clusterConfiguration = ClusterConfiguration( Classification = Some("hello"), ConfigurationProperties = Some(Map("hello" -> "world")), Configurations = None ) val json = implicitly[JsonWriter[ClusterConfiguration]].write(clusterConfiguration) json should equal(JsObject(Map( "Classification" -> JsString("hello"), "ConfigurationProperties" -> JsObject( "hello" -> JsString("world") ) ))) } it("should write and read recursive") { val clusterConfiguration = ClusterConfiguration( Classification = Some("hello"), ConfigurationProperties = Some(Map("hello" -> "world")), Configurations = Some(Seq( ClusterConfiguration( Classification = Some("hello1"), ConfigurationProperties = Some(Map("hello2" -> "world3")), Configurations = None ) )) ) val json = implicitly[JsonWriter[ClusterConfiguration]].write(clusterConfiguration) json should equal(JsObject(Map( "Classification" -> JsString("hello"), "ConfigurationProperties" -> JsObject( "hello" -> JsString("world") ), "Configurations" -> JsArray( JsObject(Map( "Classification" -> JsString("hello1"), "ConfigurationProperties" -> JsObject( "hello2" -> JsString("world3") ) )) ) ))) } } }
Example 170
Source File: Events_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ Token, `Fn::Sub` } import org.scalatest.{ FunSpec, Matchers } import spray.json._ class Events_UT extends FunSpec with Matchers { describe("RuleTarget") { it("Should serialize") { val t = RuleTarget( Arn = "arn", Id = "id", Input = Some(JsObject( "a" -> JsNumber(5), "b" -> JsBoolean(false) ).compactPrint)) t.toJson.compactPrint shouldEqual raw"""{"Arn":"arn","Id":"id","Input":"{\"a\":5,\"b\":false}"}""" } it("Should serialize sub") { val sub: Token[String] = `Fn::Sub`( JsObject( "a" -> JsString(raw"$${AWS::Region}"), "b" -> JsString(raw"$${FOO}") ).compactPrint, Some(Map("FOO" -> "BAR")) ) val t = RuleTarget( Arn = "arn", Id = "id", Input = Some(sub) ) t.toJson.compactPrint shouldEqual raw"""{"Arn":"arn","Id":"id","Input":{"Fn::Sub":["{\"a\":\"$${AWS::Region}\",\"b\":\"$${FOO}\"}",{"FOO":"BAR"}]}}""" } } }
Example 171
Source File: Kinesis_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model._ import com.monsanto.arch.cloudformation.model.resource.S3VersioningStatus.Enabled import org.scalatest.{FunSpec, Matchers} import spray.json._ class Kinesis_UT extends FunSpec with Matchers { describe("Stream") { val streamName = "stream" val shardCount = 1 val retentionPeriodHours = 5 val stream = `AWS::Kinesis::Stream`( name = streamName, Name = Some("Foo"), RetentionPeriodHours = Some(retentionPeriodHours), ShardCount = shardCount, Tags = Seq(AmazonTag("Name", streamName)) ) it("should write a valid Kinesis stream") { stream.toJson shouldEqual JsObject(Map( "name" -> JsString("stream"), "Name" -> JsString("Foo"), "RetentionPeriodHours" -> JsNumber(5), "ShardCount" -> JsNumber(1), "Tags" -> JsArray(JsObject(Map("Key" -> JsString("Name"), "Value" -> JsString("stream")))) )) } it("should have properly set public fields") { stream.name shouldEqual streamName stream.ShardCount shouldEqual IntToken(shardCount) stream.RetentionPeriodHours foreach (_ shouldEqual IntToken(retentionPeriodHours)) stream.Tags.get shouldEqual Seq(AmazonTag("Name", streamName)) } } describe("FirehoseDeliveryStream") { it("should create a plausible S3 firehose stream config") { val bucket = `AWS::S3::Bucket`("s3bucket", None, VersioningConfiguration = Some(S3VersioningConfiguration(Enabled))) val deliveryRole = `AWS::IAM::Role`("deliveryRole", PolicyDocument(Seq(PolicyStatement( "Allow", Some(DefinedPrincipal(Map("Service" -> Token.fromString("firehose.amazonaws.com")))), Seq("sts:AssumeRole"), Sid = Some(" "), Condition = Some(Map("StringEquals" -> Map("sts:ExternalId" -> SimplePolicyConditionValue("AWS::AccountId")))) )))) val policy = `AWS::IAM::Policy`("deliveryPolicy", PolicyDocument(Seq( PolicyStatement("Allow", Action = Seq("s3:AbortMultipartUpload", "s3:GetBucketLocation", "s3:GetObject", "s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:PutObject" ), Resource = Some(Seq(`Fn::Join`("", Seq(s"arn:aws:s3:::", ResourceRef(bucket))), `Fn::Join`("", Seq(s"arn:aws:s3:::", ResourceRef(bucket), "/*")))) )) ), "firehose_delivery_policy", Roles = Some(Seq(ResourceRef(deliveryRole)))) val stream = `AWS::KinesisFirehose::DeliveryStream`.s3( "deliveryStream", ExtendedS3DestinationConfiguration(`Fn::Join`("", Seq(s"arn:aws:s3:::", ResourceRef(bucket))), ResourceRef(deliveryRole), Some(BufferingHints(Some(60), Some(50))), None, Some(CompressionFormat.UNCOMPRESSED), None, Some("firehose/"), Some(ProcessingConfiguration.enabled( Seq(Processor( Seq(ProcessorParameter("LambdaArn", Token.fromFunction(`Fn::GetAtt`(Seq("myLambda","Arn"))))) )))) ), DependsOn = Some(Seq(policy.name))) val tJson = Template(Resources = Seq(stream, policy,deliveryRole,bucket)) val deliveryJson = tJson.toJson.asJsObject.fields("Resources") .asJsObject.fields("deliveryStream").asJsObject() deliveryJson.fields("DependsOn") shouldBe JsArray(JsString("deliveryPolicy")) deliveryJson.fields("Properties").asJsObject().fields("ExtendedS3DestinationConfiguration") .asJsObject.fields("BufferingHints") shouldBe JsObject( Map("IntervalInSeconds" -> JsNumber(60), "SizeInMBs" -> JsNumber(50)) ) } } }
Example 172
Source File: ApiGateway_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ResourceRef, Template, Token} import org.scalatest.{FunSpec, Matchers} import spray.json._ class ApiGateway_UT extends FunSpec with Matchers { val api = `AWS::ApiGateway::RestApi`( name = "RestApi", Name = Token.fromString("RestApi") ) val stage = `AWS::ApiGateway::Stage`( name = "Stage", DeploymentId = Token.fromString("123"), Variables = Map() ) val apiKey = `AWS::ApiGateway::ApiKey`( name = "ApiKey" ) val usagePlan = `AWS::ApiGateway::UsagePlan`( name = "UsagePlan", ApiStages = Some(Seq( ApiStage( ResourceRef(api), ResourceRef(stage) ) )), Description = Some("UsagePlanDescription"), Quota = Some(QuotaSettings( Limit = Some(1), Offset = Some(2), Period = Some(Period.WEEK)) ), Throttle = Some(ThrottleSettings( BurstLimit = Some(1), RateLimit = Some(2.0) )), UsagePlanName = Some(Token.fromString("UsagePlanName")) ) val usagePlanKey = `AWS::ApiGateway::UsagePlanKey`( name = "UsagePlanKey", KeyId = ResourceRef(apiKey), KeyType = UsagePlanKeyType.API_KEY, UsagePlanId = ResourceRef(usagePlan) ) describe("UsagePlan"){ it ("should serialize as expected") { val expectedJson = """ |{ | "Resources": { | "UsagePlan": { | "Properties": { | "ApiStages": [{"ApiId": {"Ref": "RestApi"}, "Stage": {"Ref": "Stage"}}], | "Description": "UsagePlanDescription", | "Quota": {"Limit": 1, "Offset": 2, "Period": "WEEK"}, | "Throttle": {"BurstLimit": 1, "RateLimit": 2.0}, | "UsagePlanName": "UsagePlanName" | }, | "Type": "AWS::ApiGateway::UsagePlan" | } | } |} """.stripMargin.parseJson Template.fromResource(usagePlan).toJson should be (expectedJson) } } describe("UsagePlanKey"){ it ("should serialize as expected") { val expectedJson = """ |{ | "Resources": { | "UsagePlanKey": { | "Properties": { | "KeyId": {"Ref": "ApiKey"}, | "KeyType": "API_KEY", | "UsagePlanId": {"Ref": "UsagePlan"} | }, | "Type": "AWS::ApiGateway::UsagePlanKey" | } | } |} """.stripMargin.parseJson Template.fromResource(usagePlanKey).toJson should be (expectedJson) } } }
Example 173
Source File: Lambda_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model._ import org.scalatest.{ FunSpec, Matchers } import spray.json._ class Lambda_UT extends FunSpec with Matchers { describe("TracingConfig") { it("should serialize") { def test(t: TracingConfig, rep: String) = { t.toJson shouldEqual JsString(rep) s""" "${rep}" """.parseJson.convertTo[TracingConfig] shouldEqual t } test(TracingConfig.Active, "Active") test(TracingConfig.PassThrough, "PassThrough") } } }
Example 174
Source File: ECR_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model._ import org.scalatest.{FunSpec, Matchers} import spray.json._ class ECR_UT extends FunSpec with Matchers { describe("AWS::ECR::Repository") { val fakePolicyDoc = PolicyDocument(Seq( PolicyStatement( "Allow", Some(DefinedPrincipal(Map("Service" -> Seq("fakePrincipal")))), Seq("fakeAction") ) )) val repositoryName = "repository" val repository = `AWS::ECR::Repository`( repositoryName, Some("myFakeDockerRepository"), Some(fakePolicyDoc) ) it("should create a valid new ECR repository") { val expected = JsObject( repositoryName -> JsObject( "Type" -> JsString("AWS::ECR::Repository"), "Properties" -> JsObject( "RepositoryName" -> JsString("myFakeDockerRepository"), "RepositoryPolicyText" -> fakePolicyDoc.toJson ))) Seq[Resource[_]](repository).toJson should be(expected) } } }
Example 175
Source File: ElasticSearchDomain_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.UNSAFEToken import org.scalatest.{FunSpec, Matchers} import spray.json._ class ElasticSearchDomain_UT extends FunSpec with Matchers { describe("An Elasticsearch::Domain") { it("should be serialize correctly") { val domain = `AWS::Elasticsearch::Domain`( name="testdomain", DomainName="testDomainName", Tags=Some(Seq(AmazonTag("testkey", "testValue"))), VPCOptions = Some(VPCOptions(Seq(UNSAFEToken("sg-1234567")), Seq("subnet-f1234567"))) ) val result = """{ | "name": "testdomain", | "DomainName": "testDomainName", | "Tags": [{ | "Key": "testkey", | "Value": "testValue" | }], | "VPCOptions": { | "SecurityGroupIds": ["sg-1234567"], | "SubnetIds": ["subnet-f1234567"] | } |}""".stripMargin.parseJson domain.toJson shouldBe result } } }
Example 176
Source File: IAMRole_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.ResourceRef import org.scalatest.{FunSpec, Matchers} import spray.json.{JsObject, JsString, _} class IAMRole_UT extends FunSpec with Matchers { describe("AWS::IAM::Role") { it("should handle both AWS Managed and Customer policies into valid json") { val customerPolicy = `AWS::IAM::ManagedPolicy`("customer-policy", PolicyDocument(Seq())) val awsPolicy = AWSManagedPolicy("AdministratorAccess") val fakePolicyDoc = PolicyDocument(Seq( PolicyStatement( "Allow", Some(DefinedPrincipal(Map("Service" -> Seq("config.amazonaws.com")))), Seq("sts:AssumeRole") ) )) val expectedJson = JsObject( "name" -> JsString("role"), "AssumeRolePolicyDocument" -> fakePolicyDoc.toJson, "ManagedPolicyArns" -> JsArray( JsObject("Ref" -> JsString("customer-policy")), JsString("arn:aws:iam::aws:policy/AdministratorAccess") ) ) val role = `AWS::IAM::Role`( "role", fakePolicyDoc, ManagedPolicyArns = Some(Seq(ResourceRef(customerPolicy), awsPolicy)) ) role.toJson should be(expectedJson) } } }
Example 177
Source File: EFS_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.ResourceRef import org.scalatest.{FunSpec, Matchers} import spray.json._ class EFS_UT extends FunSpec with Matchers { describe("AWS::EFS::FileSystem") { val resource = `AWS::EFS::FileSystem`( "test", FileSystemTags = Some( List(AmazonTag("Foo", "Bar")) ), Encrypted = Some(true), KmsKeyId = Some(`AWS::KMS::Key`( name = "test", KeyPolicy = PolicyDocument( Statement = List( PolicyStatement( Effect = "Allow", Action = List("dynamodb:*") ) ) ) )), PerformanceMode = PerformanceMode.generalPurpose ) it("should serialize to JSON") { resource.toJson shouldBe """{ | "name": "test", | "KmsKeyId": { | "Ref": "test" | }, | "Encrypted": true, | "PerformanceMode": "generalPurpose", | "FileSystemTags": [{ | "Key": "Foo", | "Value": "Bar" | }] |}""".stripMargin.parseJson } it("throws an exception when KmsKeyId is set but Encrypted is false") { an [IllegalArgumentException] should be thrownBy resource.copy(Encrypted = None) an [IllegalArgumentException] should be thrownBy resource.copy(Encrypted = Some(false)) } } describe("AWS::EFS::MountTarget") { val vpc = `AWS::EC2::VPC`( "vpc", CidrBlock(198,51,100,0,24), List() ) val subnet = `AWS::EC2::Subnet`( "test", VpcId = ResourceRef(vpc), CidrBlock = CidrBlock(198,51,100,129,25), Tags = List() ) val sg = `AWS::EC2::SecurityGroup`( "test", GroupDescription = "Test", VpcId = ResourceRef(vpc), None, None, List() ) val resource = `AWS::EFS::MountTarget`( "test", FileSystemId = ResourceRef(`AWS::EFS::FileSystem`("test")), IpAddress = Some("198.51.100.1"), SecurityGroups = List(ResourceRef(sg)), SubnetId = ResourceRef(subnet) ) it("should serialize to JSON") { resource.toJson shouldBe """{ | "name": "test", | "SecurityGroups": [{ | "Ref": "test" | }], | "IpAddress": "198.51.100.1", | "FileSystemId": { | "Ref": "test" | }, | "SubnetId": { | "Ref": "test" | } |}""".stripMargin.parseJson } } }
Example 178
Source File: CodePipeline_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ Token, `Fn::GetArtifactAtt`, `Fn::GetParam` } import org.scalatest.{ FunSpec, Matchers } import spray.json._ class CodePipeline_UT extends FunSpec with Matchers { describe("Fns"){ it ("Fn::GetParam should serialize as expected") { val s: Token[String] = `Fn::GetParam`("foo", "bar", "baz") val expected = JsObject("Fn::GetParam" -> JsArray(JsString("foo"), JsString("bar"), JsString("baz"))) s.toJson should be (expected) } it ("Fn::GetArtifactAtt should serialize as expected") { val s: Token[String] = `Fn::GetArtifactAtt`("foo", "bar") val expected = JsObject("Fn::GetArtifactAtt" -> JsArray(JsString("foo"), JsString("bar"))) s.toJson should be (expected) } } }
Example 179
Source File: EKS_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.UNSAFEToken import org.scalatest.{FunSpec, Matchers} import spray.json._ class EKS_UT extends FunSpec with Matchers { describe("AWS::EKS::Cluster") { val resourceVpcConfig: ResourcesVpcConfig = ResourcesVpcConfig( SecurityGroupIds = Seq(UNSAFEToken("sg-01234567")), SubnetIds = Seq(UNSAFEToken("subnet-12345678")) ) val clusterName = "cluster" val cluster = `AWS::EKS::Cluster`( clusterName, "Name", ResourcesVpcConfig = resourceVpcConfig, RoleArn = "ARN" ) it("should create a valid new EKS cluster") { val expected = JsObject( clusterName -> JsObject( "Properties" -> JsObject( "Name" -> JsString("Name"), "ResourcesVpcConfig" -> resourceVpcConfig.toJson, "RoleArn" -> JsString("ARN") ), "Type" -> JsString("AWS::EKS::Cluster") )) Seq[Resource[_]](cluster).toJson should be(expected) } } }
Example 180
Source File: CloudWatchSpec.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import org.scalatest.{FunSpec, Matchers} import spray.json.{JsonFormat, JsString} class CloudWatchSpec extends FunSpec with Matchers { it("should format AWS/EC2") { implicitly[JsonFormat[`AWS::CloudWatch::Alarm::Namespace`]].write(`AWS::CloudWatch::Alarm::Namespace`.`AWS/EC2`) should equal(JsString("AWS/EC2")) } it("should format custom namespace") { implicitly[JsonFormat[`AWS::CloudWatch::Alarm::Namespace`]].write(`AWS::CloudWatch::Alarm::Namespace`("hello")) should equal(JsString("hello")) } it("should format implicit custom namespace") { implicitly[JsonFormat[`AWS::CloudWatch::Alarm::Namespace`]].write("hello" : `AWS::CloudWatch::Alarm::Namespace`) should equal(JsString("hello")) } }
Example 181
Source File: Route53_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{Template, `Fn::GetAtt`, ResourceRef} import org.scalatest.{FunSpec, Matchers} import spray.json import spray.json._ class Route53_UT extends FunSpec with Matchers { describe("Custom::RemoteRecordSet"){ it ("should serialize as expected") { val record = `Custom::RemoteRoute53RecordSet`.generalRecord( "TestRecord", "TestServiceToken", "TestDestinationRole", "TestHostName", Route53RecordType.CNAME, "TestZone", Seq("cnn.com"), "60") val expectedJson = """ |{ | "Resources": { | "TestRecord": { | "Properties": { | "DestinationRole": "TestDestinationRole", | "Name": "TestHostName", | "ServiceToken": "TestServiceToken", | "HostedZoneName": "TestZone", | "ResourceRecords": [ | "cnn.com" | ], | "TTL": "60", | "Type": "CNAME" | }, | "Type": "Custom::RemoteRoute53RecordSet" | } | } |} """.stripMargin.parseJson Template.fromResource(record).toJson should be (expectedJson) } } }
Example 182
Source File: Subnet_Parameter_List_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model._ import org.scalatest.{FunSpec, Matchers} import spray.json.{JsNumber, JsString, _} class Subnet_Parameter_List_UT extends FunSpec with Matchers { describe("AWS::EC2::Subnet_Parameter_List") { it("should serialize into valid json") { val subnetListParam = `AWS::EC2::Subnet_Parameter_List`("subnets", "Select subnets where the RDS instances should be created") val expectedJson = JsObject( "subnets" -> JsObject( "Description" -> JsString("Select subnets where the RDS instances should be created"), "Type" -> JsString("List<AWS::EC2::Subnet::Id>") ) ) Seq[Parameter](subnetListParam).toJson should be (expectedJson) } it("should serialize into valid json as InputParameter") { val subnetListParam = `AWS::EC2::Subnet_Parameter_List`("subnets", "Select subnets where the RDS instances should be created") val expectedJson = JsObject( "ParameterKey" -> JsString("subnets"), "ParameterValue" -> JsString("") ) val inputParam = InputParameter.templateParameterToInputParameter(Some(Seq(subnetListParam))) inputParam.get(0).toJson should be (expectedJson) } it("can be passed as ParameterRef to AWS::RDS::DBSubnetGroup") { val subnetListParam = `AWS::EC2::Subnet_Parameter_List`("subnets", "Select subnets where the RDS instances should be created") val dbSubnetGroup = `AWS::RDS::DBSubnetGroup`( name = "dbSubnetGroup", DBSubnetGroupDescription = "DB subnet group", SubnetIds = ParameterRef(subnetListParam) ) val expected = JsObject( "dbSubnetGroup" -> JsObject( "Type" -> JsString("AWS::RDS::DBSubnetGroup"), "Properties" -> JsObject( "DBSubnetGroupDescription" -> JsString("DB subnet group"), "SubnetIds" -> JsObject("Ref" -> JsString("subnets")) ) ) ) Seq[Resource[_]](dbSubnetGroup).toJson should be (expected) } } }
Example 183
Source File: SecretsManager_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{Template, Token, `Fn::Join`} import org.scalatest.{FunSpec, Matchers} import spray.json._ class SecretManager_UT extends FunSpec with Matchers{ describe("secret target attachment"){ it("should generate code like the documentation example"){ val secret = `AWS::SecretsManager::Secret`("MyRDSSecret", Description = Some("This is a Secrets Manager secret for an RDS DB instance"), GenerateSecretString = GenerateSecretString( SecretStringTemplate = Some("{\"username\": \"admin\"}"), GenerateStringKey = Some("password"), PasswordLength = Some(16), ExcludeCharacters = Some("\"@/\\") ) ) val rdsInstance = `AWS::RDS::DBInstance`("MyRDSInstance",Some(Left(20)),Token.fromString("db.t2.micro"),None, None,None,Some(Token.fromString("0")),Some("rotation-instance"),None,None,None,None,None, Some(`AWS::RDS::DBInstance::Engine`.MySQL),None,None,None,None, Some(`Fn::Join`("",Seq( Token.fromString("{{resolve:secretsmanager:"), Token.fromString(secret.name), Token.fromString(":SecretString:username}}")))), Some(`Fn::Join`("",Seq( Token.fromString("{{resolve:secretsmanager:"), Token.fromString(secret.name), Token.fromString(":SecretString:password}}")))), None,None,None,None,None,None,None,None,None,None,None,None,None,None ) val attachment = `AWS::SecretsManager::SecretTargetAttachment`( "SecretRDSInstanceAttachment", Token.fromResource(secret), Token.fromResource(rdsInstance)) val json = Template(Resources = Seq(secret,rdsInstance,attachment)).toJson val attachmentJson = json.asJsObject.fields("Resources").asJsObject.fields("SecretRDSInstanceAttachment") attachmentJson shouldBe JsObject(Map( "Properties" -> JsObject( Map( "SecretId" -> JsObject(Map("Ref" -> JsString("MyRDSSecret"))), "TargetId" -> JsObject(Map("Ref" -> JsString("MyRDSInstance"))), "TargetType" -> JsString("AWS::RDS::DBInstance") )), "Type" -> JsString("AWS::SecretsManager::SecretTargetAttachment") )) } } }
Example 184
Source File: ApplicationAutoScaling_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{JsonWritingMatcher, ResourceRef} import org.scalatest.{FunSpec, Matchers} class ApplicationAutoScaling_UT extends FunSpec with Matchers with JsonWritingMatcher { val scalableTarget = `AWS::ApplicationAutoScaling::ScalableTarget`( name = "myScalableTarget", MaxCapacity = 100, MinCapacity = 1, ResourceId = "myResourceId", RoleARN = "myRoleArn", ScalableDimension = ApplicationAutoScaling.ScalableDimension.`custom-resource:ResourceType:Property`, ServiceNamespace = ApplicationAutoScaling.ServiceNamespace.`custom-resource`) it("should generate scalable target policy document") { val resource: Resource[`AWS::ApplicationAutoScaling::ScalableTarget`] = scalableTarget resource shouldMatch """ |{ | "Type": "AWS::ApplicationAutoScaling::ScalableTarget", | "Properties": { | "MaxCapacity": 100, | "MinCapacity": 1, | "ResourceId": "myResourceId", | "RoleARN": "myRoleArn", | "ScalableDimension": "custom-resource:ResourceType:Property", | "ServiceNamespace": "custom-resource" | } |} """.stripMargin } it("should error if ScalableDimension doesn't match the ServiceNamespace") { an [java.lang.AssertionError] should be thrownBy `AWS::ApplicationAutoScaling::ScalableTarget`( name = "myScalableTarget", MaxCapacity = 100, MinCapacity = 1, ResourceId = "myResourceId", RoleARN = "myRoleArn", ScalableDimension = ApplicationAutoScaling.ScalableDimension.`custom-resource:ResourceType:Property`, ServiceNamespace = ApplicationAutoScaling.ServiceNamespace.dynamodb ) } it("should generate scaling policy document") { val scalingPolicy = `AWS::ApplicationAutoScaling::ScalingPolicy`( name = "myScalingPolicy", PolicyName = "myPolicyName", PolicyType = ApplicationAutoScaling.PolicyType.StepScaling, ScalingTargetId = Some(ResourceRef(scalableTarget)) ) val resource: Resource[`AWS::ApplicationAutoScaling::ScalingPolicy`] = scalingPolicy resource shouldMatch """ |{ | "Type": "AWS::ApplicationAutoScaling::ScalingPolicy", | "Properties": { | "PolicyName": "myPolicyName", | "PolicyType": "StepScaling", | "ScalingTargetId": { "Ref":"myScalableTarget" } | } |} """.stripMargin } }
Example 185
Source File: IntrinsicFunctions_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import com.monsanto.arch.cloudformation.model.AmazonFunctionCall._ import com.monsanto.arch.cloudformation.model._ import com.monsanto.arch.cloudformation.model.resource._ import Token._ import org.scalatest.{FunSpec, Matchers} import spray.json._ import DefaultJsonProtocol._ class IntrinsicFunctions_UT extends FunSpec with Matchers { describe("Fn::Sub"){ it("no args"){ val test: Token[String] = `Fn::Sub`(s"This is a $${test} template") val expected = JsObject( "Fn::Sub"-> JsString(s"This is a $${test} template") ) test.toJson should be(expected) } it("one arg"){ val test: Token[String] = `Fn::Sub`( s"This is a $${test} template", Some(Map("test" -> "value")) ) val expected = JsObject( "Fn::Sub"-> JsArray( JsString(s"This is a $${test} template"), JsObject("test" -> JsString("value")) ) ) test.toJson should be(expected) } it("two args"){ val test: Token[String] = `Fn::Sub`( s"This is a $${test} template", Some(Map("test" -> "value", "test2" -> "value2")) ) val expected = JsObject( "Fn::Sub"-> JsArray( JsString(s"This is a $${test} template"), JsObject("test" -> JsString("value"), "test2" -> JsString("value2")) ) ) test.toJson should be(expected) } } describe("Fn::ImportValue") { it("should serialize with static string") { val test: Token[String] = `Fn::ImportValue`("Test-Import-Value") val expected = JsObject( "Fn::ImportValue" -> JsString("Test-Import-Value") ) test.toJson should be(expected) } it("should serialize with an embedded function") { val test: Token[String] = `Fn::ImportValue`(`Fn::Join`("", Seq("str1", "str2"))) val expected = JsObject( "Fn::ImportValue" -> JsObject("Fn::Join" -> JsArray( JsString(""), JsArray(JsString("str1"), JsString("str2")) ) )) test.toJson should be(expected) } } }
Example 186
Source File: FnGetAZs_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import org.scalatest.{FunSpec, Matchers} import spray.json._ import DefaultJsonProtocol._ class FnGetAZs_UT extends FunSpec with Matchers { describe("Fn::GetAZs") { it("should serialize correctly") { val p = StringParameter("pAZ") val c = Condition("cAZ", `Fn::Equals`(ParameterRef(p), "")) val ps = StringListParameter("s") val az: Token[String] = `Fn::If`[String]( ConditionRef(c), `Fn::Select`(StringBackedInt(0), `Fn::GetAZs`(`AWS::Region`)), ParameterRef(p) ) val expected = JsObject( "Fn::If"-> JsArray( JsString("cAZ"), JsObject("Fn::Select" -> JsArray( JsString("0"), JsObject("Fn::GetAZs" -> JsObject("Ref" -> JsString("AWS::Region"))) )), JsObject("Ref" -> JsString("pAZ")) ) ) az.toJson should be(expected) } } }
Example 187
Source File: FnIf_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import com.monsanto.arch.cloudformation.model.resource._ import org.scalatest.{Matchers, FunSpec} import spray.json._ class FnIf_UT extends FunSpec with Matchers { describe("Fn::If"){ it("Should serialize correctly with complex argument types"){ val cond = Condition( name = "ServiceELBSSLCertNameIsNotDefined", function = `Fn::Equals`(a = StringToken("true"), b = StringToken("false")) ) val vpcToken: VpcId = "vpc-b5f389d0" val gatewayELBSecGroupResource = `AWS::EC2::SecurityGroup`( "GatewayELBSecurityGroup", GroupDescription = "Rules for allowing access to/from service gateway ELB", VpcId = vpcToken, SecurityGroupEgress = None, SecurityGroupIngress = Some(Seq( CidrIngressSpec( IpProtocol = "tcp", CidrIp = CidrBlock(0, 0, 0, 0, 32), FromPort = "80", ToPort = "80" ), CidrIngressSpec( IpProtocol = "tcp", CidrIp = CidrBlock(0, 0, 0, 0, 32), FromPort = "443", ToPort = "443" ) ) ), Tags = Seq[AmazonTag](), Condition = Some(ConditionRef(cond)) ) val test: Token[ResourceRef[`AWS::EC2::SecurityGroup`]] = `Fn::If`[ResourceRef[`AWS::EC2::SecurityGroup`]]( ConditionRef(cond), ResourceRef(gatewayELBSecGroupResource), ResourceRef(gatewayELBSecGroupResource) ) val expected = JsObject( "Fn::If"-> JsArray( JsString("ServiceELBSSLCertNameIsNotDefined"), JsObject("Ref" -> JsString("GatewayELBSecurityGroup")), JsObject("Ref" -> JsString("GatewayELBSecurityGroup")) ) ) test.toJson should be(expected) } } }
Example 188
Source File: ResourceRef_UT.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
import com.monsanto.arch.cloudformation.model._ import com.monsanto.arch.cloudformation.model.resource._ import org.scalatest.FunSpec import org.scalatest.Matchers import spray.json._ class ResourceRef_UT extends FunSpec with Matchers { describe("ResourceRefs"){ it("should serialize correctly"){ val vpcToken: VpcId = "vpc-b5f389d0" val privateDBSubnet1CidrParam = CidrBlockParameter( name = "PrivateSubnet1", Description = Some("CIDR address range for the private subnet to be created in the second AZ"), Default = Some(CidrBlock(10,56,0,0,25)) ) val DBPriSubnet1Resource = `AWS::EC2::Subnet`( "DBPriSubnet1", VpcId = vpcToken, AvailabilityZone = Some("us-east-1a"), CidrBlock = ParameterRef(privateDBSubnet1CidrParam), Tags = Seq[AmazonTag]() ) val DBPriSubnet2Resource = `AWS::EC2::Subnet`( "DBPriSubnet2", VpcId = vpcToken, AvailabilityZone = Some("us-east-1b"), CidrBlock = ParameterRef(privateDBSubnet1CidrParam), Tags = Seq[AmazonTag]() ) val dbSubnetGroupResource = `AWS::RDS::DBSubnetGroup`( name = "DBSubnetGroup", SubnetIds = Seq( ResourceRef(DBPriSubnet1Resource), ResourceRef(DBPriSubnet2Resource)), DBSubnetGroupDescription = "DB Subnet Group" ) val expected = JsObject( "DBSubnetGroup" -> JsObject( "Type" -> JsString("AWS::RDS::DBSubnetGroup"), "Properties" -> JsObject( "SubnetIds" -> JsArray( JsObject("Ref" -> JsString("DBPriSubnet1")), JsObject("Ref" -> JsString("DBPriSubnet2")) ), "DBSubnetGroupDescription" -> JsString("DB Subnet Group") ) ) ) Seq[Resource[_]](dbSubnetGroupResource).toJson should be (expected) } } }
Example 189
Source File: StringTests.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.util.string.test import java.io.{ByteArrayInputStream, InputStream} import org.scalatest.{FunSpec, Matchers} import cmwell.util.string._ class StringTests extends FunSpec with Matchers { private def mkString(is: InputStream) = { val buffSrc = scala.io.Source.fromInputStream(is) val res = buffSrc.mkString buffSrc.close() res } describe("mapInputStreamLines should") { it("return empty for empty input") { val input = new ByteArrayInputStream(Array.emptyByteArray) val result = mapInputStreamLines(input)(identity) result.read() should be(-1) input.close() result.close() } it("provide the delimiter as well") { val delim = '\n' val s = "provide the\ndelimiter as well" val expectedAmount = s.count(delim.==) val input = stringToInputStream(s) val result = mapInputStreamLines(input)(_.toUpperCase) mkString(result).count(delim.==) should be(expectedAmount) input.close() result.close() } it("not end with the delimiter") { val input = stringToInputStream("not end with\nthe delimiter") val result = mapInputStreamLines(input)(_.toUpperCase) mkString(result).last should be('R') input.close() result.close() } it("handle a concat mapper") { val input = stringToInputStream("handle\na\nconcat\nmapper") val result = mapInputStreamLines(input)(_ + " not") mkString(result) should be("handle not\na not\nconcat not\nmapper not") input.close() result.close() } } }
Example 190
Source File: StreamSpec.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.util.streams.test import akka.actor.ActorSystem import akka.stream.ActorMaterializer import com.typesafe.config.ConfigFactory import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers} import scala.concurrent.duration.DurationInt import scala.concurrent.Await trait StreamSpec extends FunSpec with Matchers with BeforeAndAfterAll { protected implicit val system = { def config = ConfigFactory.load() ActorSystem("default", config) } protected implicit val mat = ActorMaterializer() override protected def afterAll() = { Await.ready(system.terminate(), 42.seconds) super.afterAll() } }
Example 191
Source File: SpanWithTests.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.util.collections.test import cmwell.util.collections.spanWith import org.scalatest.{FunSpec, Matchers} class SpanWithTests extends FunSpec with Matchers {//with OptionValues with EitherValues with TryValues with LazyLogging { describe("scanWith should") { it("span with mapping of the everything on the left side") { val (left,right) = spanWith(List(0,2,4,6,8,7,8,6,4,2)){ i => if(i % 2 == 0) Some(i / 2) else None } left shouldEqual List(0,1,2,3,4) right shouldEqual List(7,8,6,4,2) } it("span with mapping of everything") { val (left,right) = spanWith(List(0,2,4,6,8,8,6,4,2)){ i => if(i % 2 == 0) Some(i / 2) else None } left shouldEqual List(0,1,2,3,4,4,3,2,1) right shouldEqual Nil } it("span with mapping of nothing") { val (left,right) = spanWith(List(1,3,5,7,9,9,7,5,3)){ i => if(i % 2 == 0) Some(i / 2) else None } left shouldEqual Nil right shouldEqual List(1,3,5,7,9,9,7,5,3) } } }
Example 192
Source File: PidUtilsTest.scala From sbt-dynamodb with MIT License | 5 votes |
package com.localytics.sbt.dynamodb import java.io.File import org.scalatest.FunSpec import org.scalatest.Matchers class PidUtilsTest extends FunSpec with Matchers { describe("PidUtils") { val jarPath = if (PidUtils.osName.toLowerCase.contains("windows")) "C:\\Users\\person\\code\\repository\\aws-mocks\\.dynamo-db\\DynamoDBLocal.jar" else "/Users/person/code/repository/aws-mocks/.dynamo-db/DynamoDBLocal.jar" it("should extract PID correctly") { val jpsOutput = s""" |92433 sun.tools.jps.Jps -ml |88818 /usr/local/Cellar/sbt/0.13.7/libexec/sbt-launch.jar |88421 /usr/local/Cellar/sbt/0.13.7/libexec/sbt-launch.jar |5895 com.intellij.database.remote.RemoteJdbcServer com.mysql.jdbc.Driver |92431 $jarPath -port 8000 -inMemory -sharedDb |74414 /usr/local/Cellar/sbt/0.13.7/libexec/sbt-launch.jar """.stripMargin val jar = new File(jarPath) PidUtils.extractPid(jpsOutput, 8000, jar) should equal(Some("92431")) } it("should resolve multiple local dynamodb instances") { val jpsOutput = s""" |92433 sun.tools.jps.Jps -ml |92430 $jarPath -port 8001 -inMemory -sharedDb |92433 $jarPath -port 8002 -inMemory -sharedDb |5895 com.intellij.database.remote.RemoteJdbcServer com.mysql.jdbc.Driver |92431 $jarPath -port 8000 -inMemory -sharedDb |74414 /usr/local/Cellar/sbt/0.13.7/libexec/sbt-launch.jar """.stripMargin val jar = new File(jarPath) PidUtils.extractPid(jpsOutput, 8000, jar) should equal(Some("92431")) } } }
Example 193
Source File: BagTest.scala From morpheus with Apache License 2.0 | 5 votes |
package org.opencypher.okapi.testing import org.opencypher.okapi.api.value.CypherValue.CypherMap import org.scalatest.{FunSpec, Matchers} class BagTest extends BaseTestSuite { it("considers maps with the same content equal") { Bag( CypherMap("p1" -> "a", "p2" -> "a"), CypherMap("p1" -> "a", "p2" -> "b"), CypherMap("p1" -> "b", "p2" -> "a"), CypherMap("p1" -> "b", "p2" -> "b") ) should equal(Bag( CypherMap("p2" -> "a", "p1" -> "a"), CypherMap("p2" -> "b", "p1" -> "a"), CypherMap("p2" -> "a", "p1" -> "b"), CypherMap("p2" -> "b", "p1" -> "b") )) } }
Example 194
Source File: ExampleTest.scala From morpheus with Apache License 2.0 | 5 votes |
package org.opencypher.morpheus.examples import java.io.{ByteArrayOutputStream, PrintStream} import java.net.URI import org.junit.runner.RunWith import org.opencypher.okapi.testing.Bag._ import org.scalatest.{BeforeAndAfterAll, FunSpec, Matchers} import org.scalatestplus.junit.JUnitRunner import scala.io.Source @RunWith(classOf[JUnitRunner]) abstract class ExampleTest extends FunSpec with Matchers with BeforeAndAfterAll { private val oldStdOut = System.out protected val emptyOutput: String = "" protected def validate(app: => Unit, expectedOut: URI): Unit = { validate(app, Source.fromFile(expectedOut).mkString) } protected def validateBag(app: => Unit, expectedOut: URI): Unit = { val source = Source.fromFile(expectedOut) val expectedLines = source.getLines().toList val appLines = capture(app).split(System.lineSeparator()) withClue(s"${appLines.mkString("\n")} not equal to ${expectedLines.mkString("\n")}") { appLines.toBag shouldEqual expectedLines.toBag } } protected def validate(app: => Unit, expectedOut: String): Unit = { capture(app) shouldEqual expectedOut } private def capture(app: => Unit): String = { val charset = "UTF-8" val outCapture = new ByteArrayOutputStream() val printer = new PrintStream(outCapture, true, charset) Console.withOut(printer)(app) outCapture.toString(charset) } override protected def afterAll(): Unit = { System.setOut(oldStdOut) super.afterAll() } }
Example 195
Source File: RowTest.scala From iolap with Apache License 2.0 | 5 votes |
package org.apache.spark.sql import org.apache.spark.sql.catalyst.expressions.{GenericRow, GenericRowWithSchema} import org.apache.spark.sql.types._ import org.scalatest.{Matchers, FunSpec} class RowTest extends FunSpec with Matchers { val schema = StructType( StructField("col1", StringType) :: StructField("col2", StringType) :: StructField("col3", IntegerType) :: Nil) val values = Array("value1", "value2", 1) val sampleRow: Row = new GenericRowWithSchema(values, schema) val noSchemaRow: Row = new GenericRow(values) describe("Row (without schema)") { it("throws an exception when accessing by fieldName") { intercept[UnsupportedOperationException] { noSchemaRow.fieldIndex("col1") } intercept[UnsupportedOperationException] { noSchemaRow.getAs("col1") } } } describe("Row (with schema)") { it("fieldIndex(name) returns field index") { sampleRow.fieldIndex("col1") shouldBe 0 sampleRow.fieldIndex("col3") shouldBe 2 } it("getAs[T] retrieves a value by fieldname") { sampleRow.getAs[String]("col1") shouldBe "value1" sampleRow.getAs[Int]("col3") shouldBe 1 } it("Accessing non existent field throws an exception") { intercept[IllegalArgumentException] { sampleRow.getAs[String]("non_existent") } } it("getValuesMap() retrieves values of multiple fields as a Map(field -> value)") { val expected = Map( "col1" -> "value1", "col2" -> "value2" ) sampleRow.getValuesMap(List("col1", "col2")) shouldBe expected } } }
Example 196
Source File: ConfigModuleSpec.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.commons.config import scala.collection.JavaConversions._ import com.google.inject.Guice import com.typesafe.config.{Config, ConfigFactory} import org.scalatest.{FunSpec, Matchers} import ai.deepsense.commons.config.TestInjectable.Params class ConfigModuleSpec extends FunSpec with Matchers { def loadConfig(fileName: String): Config = { System.setProperty("config.trace", "loads") ConfigFactory.invalidateCaches() ConfigFactory.load(fileName) } def getExpectedValues(config: Config): Params = { TestInjectable.Params( config.getInt("test.int"), config.getDouble("test.double"), config.getBoolean("test.boolean"), config.getStringList("test.stringList"), config.getIntList("test.intList").map(_.intValue).toSeq, config.getDoubleList("test.doubleList").map(_.doubleValue).toSeq, config.getBooleanList("test.booleanList").map(_.booleanValue).toSeq ) } describe ("A module that injects config bindings") { val config = loadConfig("all-types.conf") val injector = Guice.createInjector(new TestModule(config)) it ("Should successfully instantiate a class with @Named constructor parameters") { val expected = getExpectedValues(config) val instance = injector.getInstance(classOf[TestInjectable]) instance.params equals expected } } describe ("A config that contains empty lists should also bind") { val config = loadConfig("empty-lists.conf") val injector = Guice.createInjector(new TestModule(config)) it ("Should successfully instantiate a class with @Named constructor parameters") { val expected = getExpectedValues(config) val instance = injector.getInstance(classOf[TestInjectable]) instance.params equals expected } } }
Example 197
Source File: ConfigFactoryExtSpec.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.commons.config import com.typesafe.config.ConfigFactory import org.scalatest.{FunSpec, Matchers} class ConfigFactoryExtSpec extends FunSpec with Matchers { describe ("-Denv=test specified") { // Specify test environment to load test.conf System.setProperty("env", "test") ConfigFactoryExt.enableEnvOverride() // System property should override value in config file System.setProperty("overridden.by.system.prop", "system") ConfigFactory.invalidateCaches() val config = ConfigFactory.load it ("Value in test.conf should override value in application.conf") { config.getString("defined.in.all.confs") should equal ("test") } it ("Value only in test.conf should be defined") { config.getString("defined.in.test.conf") should equal ("test") } it ("Value only in application.conf should be defined") { config.getString("defined.in.application.conf") should equal ("application") } it ("System property should override value in files") { config.getString("overridden.by.system.prop") should equal ("system") } it ("test.conf value gets substituted into application.conf property value") { config.getString("server.url") should equal ("https://test.crowdpac.com") } } }
Example 198
Source File: SourcepathCommandIntegrationSpec.scala From scala-debugger with Apache License 2.0 | 5 votes |
package org.scaladebugger.tool.commands import java.nio.file.Paths import org.scaladebugger.test.helpers.FixedParallelSuite import org.scaladebugger.tool.Repl import org.scalamock.scalatest.MockFactory import org.scalatest.concurrent.Eventually import org.scalatest.{FunSpec, Matchers, ParallelTestExecution} import test.{ToolConstants, ToolTestUtilities, ToolFixtures} class SourcepathCommandIntegrationSpec extends FunSpec with Matchers with ParallelTestExecution with ToolFixtures with MockFactory with ToolTestUtilities with Eventually with FixedParallelSuite { implicit override val patienceConfig = PatienceConfig( timeout = scaled(ToolConstants.EventuallyTimeout), interval = scaled(ToolConstants.EventuallyInterval) ) describe("SourcepathCommand") { it("should add the provided path to the current list and load sources") { val vt = newVirtualTerminal() val repl = Repl.newInstance(newTerminal = (_,_) => vt) repl.start() val q = "\"" val s = java.io.File.separator // Set some paths to be displayed repl.stateManager.updateSourcePaths(Seq( Paths.get("a"), Paths.get("b"), Paths.get("c") )) // Add '.' as sourcepath vt.newInputLine("sourcepath \".\"") // Verify that we have finished loading our source files eventually { validateNextLine(vt, """Loaded \d+ source files""", success = (text, line) => line should startWith regex text) } eventually { val state = repl.stateManager.state state.sourcePaths.last.getFileName.toString should contain ('.') } } it("should list all current source paths if no argument provided") { val vt = newVirtualTerminal() val repl = Repl.newInstance(newTerminal = (_,_) => vt) repl.start() // Set some paths to be displayed repl.stateManager.updateSourcePaths(Seq( Paths.get("a"), Paths.get("b"), Paths.get("c") )) // Display the source paths vt.newInputLine("sourcepath") val line = vt.nextOutputLine( waitTime = ToolConstants.NextOutputLineTimeout.millisPart ) val s = java.io.File.pathSeparator line.get should be (s"Source paths: a${s}b${s}c\n") } } }
Example 199
Source File: GrabInfoDSLWrapperSpec.scala From scala-debugger with Apache License 2.0 | 5 votes |
package org.scaladebugger.api.dsl.info import com.sun.jdi.ThreadReference import org.scaladebugger.api.profiles.traits.info.{GrabInfoProfile, ThreadInfo} import org.scaladebugger.test.helpers.ParallelMockFunSpec import org.scalamock.scalatest.MockFactory import org.scalatest.{FunSpec, Matchers, ParallelTestExecution} import scala.util.Success class GrabInfoDSLWrapperSpec extends ParallelMockFunSpec { private val mockGrabInfoProfile = mock[GrabInfoProfile] describe("GrabInfoDSLWrapper") { describe("#forThread(ThreadReference)") { it("should invoke the underlying profile method") { import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL val threadReference = mock[ThreadReference] val returnValue = Success(mock[ThreadInfo]) (mockGrabInfoProfile.tryThread(_: ThreadReference)) .expects(threadReference) .returning(returnValue).once() mockGrabInfoProfile.forThread(threadReference) should be (returnValue) } } describe("#forUnsafeThread(ThreadReference)") { it("should invoke the underlying profile method") { import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL val threadReference = mock[ThreadReference] val returnValue = mock[ThreadInfo] (mockGrabInfoProfile.thread(_: ThreadReference)) .expects(threadReference) .returning(returnValue).once() mockGrabInfoProfile.forUnsafeThread(threadReference) should be (returnValue) } } describe("#forThread(Long)") { it("should invoke the underlying profile method") { import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL val threadId = 999L val returnValue = Success(mock[ThreadInfo]) (mockGrabInfoProfile.tryThread(_: Long)) .expects(threadId) .returning(returnValue).once() mockGrabInfoProfile.forThread(threadId) should be (returnValue) } } describe("#forUnsafeThread(Long)") { it("should invoke the underlying profile method") { import org.scaladebugger.api.dsl.Implicits.GrabInfoDSL val threadId = 999L val returnValue = mock[ThreadInfo] (mockGrabInfoProfile.thread(_: Long)) .expects(threadId) .returning(returnValue).once() mockGrabInfoProfile.forUnsafeThread(threadId) should be (returnValue) } } } }
Example 200
Source File: ScalaVirtualMachineSpec.scala From scala-debugger with Apache License 2.0 | 5 votes |
package org.scaladebugger.api.virtualmachines import com.sun.jdi.VirtualMachine import org.scaladebugger.api.profiles.traits.DebugProfile import org.scalamock.scalatest.MockFactory import org.scalatest.{FunSpec, Matchers, ParallelTestExecution} import org.scaladebugger.api.lowlevel.ManagerContainer import org.scaladebugger.api.profiles.ProfileManager import org.scaladebugger.test.helpers.ParallelMockFunSpec class ScalaVirtualMachineSpec extends ParallelMockFunSpec { private class TestManagerContainer extends ManagerContainer( null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ) private def newScalaVirtualMachine( scalaVirtualMachineManager: ScalaVirtualMachineManager, managerContainer: ManagerContainer, _profileManager: ProfileManager ) = new Object with ScalaVirtualMachine { override val cache: ObjectCache = null override val lowlevel: ManagerContainer = managerContainer override val manager: ScalaVirtualMachineManager = scalaVirtualMachineManager override def startProcessingEvents(): Unit = {} override def isInitialized: Boolean = false override def isProcessingEvents: Boolean = false override def suspend(): Unit = {} override def stopProcessingEvents(): Unit = {} override def resume(): Unit = {} override def initialize( defaultProfile: String, startProcessingEvents: Boolean ): Unit = {} override val underlyingVirtualMachine: VirtualMachine = null override def isStarted: Boolean = false override val uniqueId: String = "" override protected val profileManager: ProfileManager = _profileManager override def register(name: String, profile: DebugProfile): Option[DebugProfile] = None override def retrieve(name: String): Option[DebugProfile] = None override def unregister(name: String): Option[DebugProfile] = None } private val mockManagerContainerProcessPendingRequests = mockFunction[ManagerContainer, Unit] private val mockProfileManager = mock[ProfileManager] private val scalaVirtualMachine = newScalaVirtualMachine( ScalaVirtualMachineManager.GlobalInstance, new TestManagerContainer { override def processPendingRequests( managerContainer: ManagerContainer ): Unit = mockManagerContainerProcessPendingRequests(managerContainer) }, mockProfileManager ) describe("ScalaVirtualMachine") { describe("#processPendingRequests") { it("should process the other VM's pending requests using its low-level managers") { val otherManagerContainer = new TestManagerContainer val otherScalaVirtualMachine = newScalaVirtualMachine( null, otherManagerContainer, null ) mockManagerContainerProcessPendingRequests.expects(otherManagerContainer).once() scalaVirtualMachine.processPendingRequests(otherScalaVirtualMachine) } } } }