org.scalatest.prop.TableDrivenPropertyChecks Scala Examples
The following examples show how to use org.scalatest.prop.TableDrivenPropertyChecks.
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: TranspileSupportTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.chrome.domains import com.programmaticallyspeaking.ncd.testing.UnitTest import org.scalatest.prop.TableDrivenPropertyChecks class TranspileSupportTest extends UnitTest with TableDrivenPropertyChecks { def createSut = new TranspileSupport {} val transpileNeeded = Table( ("desc", "code", "needed"), ("generator function", "function *() {}", true), ("named generator function", "function *foo() {}", true), ("generator function no ws", "function*foo() {}", true), ("no generator", "function foo() {}", false) ) "Transpile support (for Runtime)" - { forAll(transpileNeeded) { (desc, code, needed) => s"detects transpilation need when: $desc" in { val sut = createSut val actual = sut.needsTranspile(code) actual should be (needed) } } } }
Example 2
Source File: NegInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.Type import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory.{int, real} import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class NegInstTest extends FunSuite with TableDrivenPropertyChecks { test("[neg] value, type, strm") { val starts: TableFor3[Obj, Obj, String] = new TableFor3[Obj, Obj, String](("query", "result", "type"), //////// INT (int(2).neg(), int(-2), "value"), (int(2).q(2).neg(), int(-2).q(2), "value"), (int(-2).neg(), int(2), "value"), (int(-2).neg().q(4).neg().q(2), int(-2).q(8), "value"), (int.neg(), int.neg(), "type"), (int(-1, -2, -3).neg(), int(1, 2, 3), "strm"), //////// REAL (real(2.0).neg(), real(-2.0), "value"), (real(-2.0).neg(), real(2.0), "value"), (real.neg(), real.neg(), "type"), (real(-1.0, -2.0, -3.0).neg(), real(1.0, 2.0, 3.0), "strm"), (real(-1.0, -2.0, -3.0).neg().q(10), real(real(1.0).q(10), real(2.0).q(10), real(3.0).q(10)), "strm"), ) forEvery(starts) { (query, result, atype) => { //assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } }
Example 3
Source File: HeadInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.LanguageException import org.mmadt.language.obj.Obj._ import org.mmadt.language.obj.`type`.__ import org.mmadt.language.obj.{Lst, Obj} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor2} class HeadInstTest extends FunSuite with TableDrivenPropertyChecks { test("[head] anonymous type") { assertResult(str("a"))(("a" |) ===> __.head()) assertResult(str("a"))(("a" | "b") ===> __.head()) assertResult(str("a"))(("a" | "b" | "c") ===> __.head()) // assertResult(str("a"))(("a" `;`) ===> __.head()) assertResult(str("a"))(("a" `;` "b") ===> __.head()) assertResult(str("a"))(("a" `;` "b" `;` "c") ===> __.head()) } test("[head] w/ parallel poly") { val check: TableFor2[Lst[_], Obj] = new TableFor2(("parallel", "head"), (str("a") |, "a"), (str("a") | "b", "a"), (str("a") | "b" | "c", "a"), (str("d") | "b" | "c", "d"), ) forEvery(check) { (left, right) => { assertResult(right)(left.head()) } } } test("[head] w/ serial poly") { val check: TableFor2[Lst[_], Obj] = new TableFor2(("serial", "head"), (str("a") `;`, "a"), (str("a") `;` "b", "a"), (str("a") `;` "b" `;` "c", "a"), (str("d") `;` "b" `;` "c", "d"), ) forEvery(check) { (left, right) => { assertResult(right)(left.head()) } } } test("[head] exception") { assertThrows[LanguageException] { lst.head() } } }
Example 4
Source File: DefineInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.trace import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.{Bool, Obj} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor2} class DefineInstTest extends FunSuite with TableDrivenPropertyChecks { test("[define] value, type, strm, anon combinations") { val starts: TableFor2[Obj, Obj] = new TableFor2[Obj, Obj](("query", "result"), (int(2).define(__("nat") <= int.is(int.gt(0))).a(__("nat")), btrue), (int(-2).define(__("nat") <= int.is(int.gt(0))).a(__("nat")), bfalse), (int(-2).define(__("nat") <= int.is(int.gt(0))).a(__("nat").plus(100)), bfalse), (int(2).define(__("abc") <= int.is(int.gt(0))).a(__("abc")), btrue), (int(-2).define(__("abc") <= int.is(int.gt(0))).a(__("abc")), bfalse), ) forEvery(starts) { (query, result) => { assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) assertResult(result)(query) } } } test("[define] play tests") { println(int.define(int.is(int.gt(0))).a(__("nat"))) println(int(-10).define(__("nat") <= int.is(int.gt(0))).a(__("nat").plus(100))) println(__("nat").plus(100).domain) println(int(-10).compute(int.define(__("nat") <= int.is(int.gt(0))).a(__("nat")).asInstanceOf[Type[Bool]])) println(int.define(int.plus(10).mult(20)).plus(2) -< (__("x").plus(100) `,` __("x")) >-) println(new mmlangScriptEngineFactory().getScriptEngine.eval("1[a,[real|str]]")) println(str.a(__.-<(real `|` int) >-)) // TODO } }
Example 5
Source File: GivenInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.branch import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class GivenInstTest extends FunSuite with TableDrivenPropertyChecks { test("[given] value, type, strm") { val check: TableFor3[Obj, Obj, Obj] = new TableFor3[Obj, Obj, Obj](("input", "type", "result"), (int(1), int.-<((int.plus(50).is(__.gt(0)) --> int.plus(20)) `,` (str --> str.plus("a"))), int(21) `,` zeroObj), (int(1), int.-<((int.plus(50).is(__.gt(0)) --> int.plus(20)) | (str --> str.plus("a"))), int(21) | zeroObj), (int(1), int.-<((int.plus(50).is(__.gt(0)) --> int.plus(20)) `,` (int.plus(-10).is(__.lt(0)) --> int.plus(100))), int(21) `,` 101), (int(1), int.-<((int.plus(50).is(__.gt(0)) --> int.plus(20)) | (int.plus(-10).is(__.lt(0)) --> int.plus(100))), int(21) | zeroObj), (int(1), int.-<((int.plus(50).is(__.lt(0)) --> int.plus(20)) `,` (int.plus(-10).is(__.lt(0)) --> int.plus(100))), zeroObj `,` 101), (int(-1), int.plus(2).-<(int.is(int > 5) --> int(34) | int.is(int === 1) --> int.plus(2) | int --> int(20)), zeroObj | 3 | zeroObj), (int(10, int(50).q(2), 60), int.q(4).-<(bool --> btrue | int --> int + 1), strm(List(zeroObj | int(11), zeroObj | int(51).q(2), zeroObj | int(61)))), (int(10, int(50).q(2), 60), int.q(4).-<(bool --> btrue | int --> int + 1).>-, int(int(11), int(51).q(2), int(61))), ) forEvery(check) { (input, atype, result) => { assertResult(result)(input.compute(atype.asInstanceOf[Type[Obj]])) assertResult(result)(input ==> atype.asInstanceOf[Type[Obj]]) assertResult(result)(input ===> atype) assertResult(result)(input ===> (input.range ==> atype.asInstanceOf[Type[Obj]])) assertResult(result)(input ===> (input.range ===> atype)) } } } }
Example 6
Source File: LstTypeTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.language.obj.`type` import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.`type`.__ import org.mmadt.language.obj.{Int, Lst, Obj, Poly} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class LstTypeTest extends FunSuite with TableDrivenPropertyChecks { test("parallel expressions") { val starts: TableFor3[Obj, Lst[Obj], Obj] = new TableFor3[Obj, Lst[Obj], Obj](("lhs", "rhs", "result"), (int(1), int `,` int, int(1).q(2)), (int(1), int `,` int.plus(2), int(1, 3)), (int(1), int `,` int.plus(2).q(10), int(1, int(3).q(10))), (int(1).q(5), int `,` int.plus(2).q(10), int(int(1).q(5), int(3).q(50))), (int(int(1), int(100)), int | int, int(int(1), int(100))), (int(int(1), int(100)), int `,` int, int(1, 1, 100, 100)), (int(int(1), int(100)), int `,` int, int(int(1).q(2), int(100).q(2))), (int(int(1).q(5), int(100)), int `,` int.plus(2).q(10), int(int(1).q(5), int(3).q(50), int(100), int(102).q(10))), (int(int(1).q(5), int(100)), int | int.plus(2).q(10), int(int(1).q(5), int(100))), (int(1, 2), int | (int | int), int(1, 2)), // TODO: this is not computing the lst as a type (int(1, 2), (int | int) | int, int(1, 2)), // TODO: this is not computing the lst as a type //(int(1, 2), (int | int) | (int | int), int(1, 2)), //(int(int(1), int(2)).-<(int `,` (int -< (int | int))), strm[Obj](List(int(1), int(1) |, int(2), int(2) |))), (int(1), str | int, int(1)), //(strm(List(int(1), str("a"))).-<(str | int), strm(List(zeroObj | int(1), str("a") | zeroObj))), ) forEvery(starts) { (lhs, rhs, result) => { assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"(${lhs})>--<${rhs}>-")) assertResult(result)(lhs ===> __.-<(rhs).>-) } } } test("parallel [get] types") { assertResult(str)((str.plus("a") | str).get(0, str).range) } test("parallel structure") { val poly: Poly[Obj] = int.mult(8).split(__.id() | __.plus(2) | 3) assertResult("(int[id]|int[plus,2]|3)<=int[mult,8]-<(int[id]|int[plus,2]|3)")(poly.toString) assertResult(int.id())(poly.glist.head) assertResult(int.plus(2))(poly.glist(1)) assertResult(int(3))(poly.glist(2)) assertResult(int)(poly.glist.head.via._1) assertResult(int)(poly.glist(1).via._1) assert(poly.glist(2).root) assertResult(int.id() | int.plus(2) | int(3))(poly.range) } test("parallel quantifier") { val poly: Poly[Obj] = int.q(2).mult(8).split(__.id() | __.plus(2) | 3) assertResult("(int{2}[id]|int{2}[plus,2]|3)<=int{2}[mult,8]-<(int{2}[id]|int{2}[plus,2]|3)")(poly.toString) assertResult(int.q(2).id())(poly.glist.head) assertResult(int.q(2).plus(2))(poly.glist(1)) assertResult(int(3))(poly.glist(2)) assertResult(int.q(2))(poly.glist.head.via._1) assertResult(int.q(2))(poly.glist(1).via._1) assert(poly.glist(2).root) assertResult(int.q(2).id() | int.q(2).plus(2) | int(3))(poly.range) } test("parallel [split] quantification") { assertResult(int)(int.mult(8).split(__.id() | __.plus(8).mult(2) | int(56)).merge[Int].id().isolate) assertResult(int.q(1, 20))(int.mult(8).split(__.id().q(10, 20) | __.plus(8).mult(2).q(2) | int(56)).merge[Int].id().isolate) assertResult(int.q(1, 40))(int.q(2).mult(8).q(1).split(__.id().q(10, 20) | __.plus(8).mult(2).q(2) | int(56)).merge[Int].id().isolate) assertResult(int(56))(int.q(2).mult(8).q(0).split(__.id().q(10, 20) | __.plus(8).mult(2).q(2) | int(56)).merge[Obj].id().isolate) } }
Example 7
Source File: ScalaTargetTests.scala From scaladex with BSD 3-Clause "New" or "Revised" License | 5 votes |
package ch.epfl.scala.index.model package release import org.scalatest._ import org.scalatest.prop.TableDrivenPropertyChecks class ScalaTargetTests extends FunSpec with Matchers with TableDrivenPropertyChecks { it("should be ordered") { val js067 = PatchBinary(0, 6, 7) val js0618 = PatchBinary(0, 6, 18) val nat03 = PatchBinary(0, 3, 0) val obtained = List( ScalaJs(ScalaVersion.`2.10`, js067), ScalaJs(ScalaVersion.`2.12`, js0618), ScalaJs(ScalaVersion.`2.11`, js067), ScalaJs(ScalaVersion.`2.11`, js0618), ScalaJs(ScalaVersion.`2.10`, js0618), ScalaNative(ScalaVersion.`2.11`, nat03), ScalaJvm(ScalaVersion.`2.12`), ScalaJvm(ScalaVersion.`2.11`), ScalaJvm(ScalaVersion.`2.10`) ).sorted(ScalaTarget.ordering) val expected = List( ScalaNative(ScalaVersion.`2.11`, nat03), ScalaJs(ScalaVersion.`2.10`, js067), ScalaJs(ScalaVersion.`2.11`, js067), ScalaJs(ScalaVersion.`2.10`, js0618), ScalaJs(ScalaVersion.`2.11`, js0618), ScalaJs(ScalaVersion.`2.12`, js0618), ScalaJvm(ScalaVersion.`2.10`), ScalaJvm(ScalaVersion.`2.11`), ScalaJvm(ScalaVersion.`2.12`) ) assert(obtained == expected) } it("should parse any scala target") { val cases = Table( ("input", "target"), ("_2.12", ScalaJvm(ScalaVersion.`2.12`)), ("_sjs0.6_2.12", ScalaJs(ScalaVersion.`2.12`, MinorBinary(0, 6))) ) forAll(cases) { (input, target) => ScalaTarget.parse(input) should contain(target) } } }
Example 8
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 9
Source File: RealRuntimeTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.e2e.java9 import com.programmaticallyspeaking.ncd.chrome.domains.{Runtime => RuntimeD} import com.programmaticallyspeaking.ncd.e2e.RealRuntimeTestFixture import com.programmaticallyspeaking.ncd.nashorn.java9.RunningJava9 import org.scalatest.prop.TableDrivenPropertyChecks class RealRuntimeTest extends RealRuntimeTestFixture with TableDrivenPropertyChecks with RunningJava9 { private def waitForDebugger(testers: Tester*) = { runScript("debugger;")(testers: _*) } private def compileWithError(code: String)(f: RuntimeD.CompileScriptResult => Unit) = { waitForDebugger(_ => { val result = sendRequest(RuntimeD.compileScript(code, "", false, None)) result match { case r: RuntimeD.CompileScriptResult => f(r) case other => fail("unexpected: " + other) } }) } "Runtime (Java 9)" - { "compileScript" - { "reports a _translated_ error if the script is an incomplete template literal (with persist=false)" in { compileWithError("`foo") { r => val Some(desc) = r.exceptionDetails.flatMap(_.exception).flatMap(_.description) desc should startWith ("SyntaxError: Unterminated template literal") } } "doesn't translate a non-template literal related quote error" in { compileWithError("'foo") { r => val desc = r.exceptionDetails.flatMap(_.exception).flatMap(_.description).getOrElse("") desc should not include ("Unterminated template literal") } } } } }
Example 10
Source File: PathUtilsTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.infra import com.programmaticallyspeaking.ncd.testing.UnitTest import org.scalatest.prop.TableDrivenPropertyChecks class PathUtilsTest extends UnitTest with TableDrivenPropertyChecks { val nameSuffixCases = Table( ("path", "suffix", "result"), ("/c/temp/file.js", "_x", "/c/temp/file_x.js"), ("/c/temp/file", "_x", "/c/temp/file_x"), ("/c/te.mp/file", "_x", "/c/te.mp/file_x"), ("c:\\te.mp\\file", "_x", "c:\\te.mp\\file_x") ) "PathUtils.insertNameSuffix" - { forAll(nameSuffixCases) { (path, suffix, result) => s"should add a suffix to $path" in { PathUtils.insertNameSuffix(path, suffix) should be (result) } } } }
Example 11
Source File: VMVersionTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.nashorn import com.programmaticallyspeaking.ncd.testing.UnitTest import org.scalatest.prop.TableDrivenPropertyChecks class VMVersionTest extends UnitTest with TableDrivenPropertyChecks { "VMVersion" - { "parse" - { val cases = Table( ("desc", "input", "expected"), ("Java 8", "1.8.0_151", VMVersion(1, Some(8), Some(0), Some(151), false)), ("Java 9", "9.0.1", VMVersion(9, Some(0), Some(1), None, false)), ("Java 10", "10", VMVersion(10, None, None, None, false)), ("Java 12 EA", "12-ea", VMVersion(12, None, None, None, true)) ) forAll(cases) { (desc, input, expected) => s"parses version string '$input' ($desc)" in { val actual = VMVersion.parse(input) actual should be(expected) } } } "knownBugs" - { val B_8179072_cases = Table( ("version", "has_the_bug"), ("1.8.0_131", true), ("1.8.0_132", false), ("9.0.1", false) ) def testForBug(version: String, bug: KnownBug.EnumVal, expected: Boolean) = { val ver = VMVersion.parse(version) if (expected) ver.knownBugs should contain (bug) else ver.knownBugs should not contain (bug) } forAll(B_8179072_cases) { (version, has_the_bug) => val verb = if (has_the_bug) "includes" else "excludes" s"$verb JDK_8179072 for version $version" in { testForBug(version, KnownBug.JDK_8179072_Abstract_Method_Error, has_the_bug) } } val B_8187143_cases = Table( ("version", "has_the_bug"), ("1.8.0_144", false), ("1.8.1_1", true), ("1.8.0_151", true), ("9.0.1", true), ("10", true) ) forAll(B_8187143_cases) { (version, has_the_bug) => val verb = if (has_the_bug) "includes" else "excludes" s"$verb JDK_8187143 for version $version" in { testForBug(version, KnownBug.JDK_8187143_Frame_Restart_Crash, has_the_bug) } } } } }
Example 12
Source File: ArbitraryObjectPropertyHolderTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.nashorn import com.programmaticallyspeaking.ncd.testing.UnitTest import org.scalatest.prop.TableDrivenPropertyChecks class ArbitraryObjectPropertyHolderTest extends UnitTest with TableDrivenPropertyChecks { val beanNameExtractionCases = Table( ("methodName", "propertyName"), ("getFoo", Some("foo")), ("getFooBar", Some("fooBar")), ("setFoo", Some("foo")), ("getfoo", None), ("random", None) ) "extractJavaBeansPropertyName" - { forAll(beanNameExtractionCases) { (methodName, propertyName) => s"extracts $propertyName from $methodName" in { val actual = ArbitraryObjectPropertyHolder.extractJavaBeansPropertyName(methodName) actual should be (propertyName) } } } }
Example 13
Source File: ObjectPropertyDescriptorTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.nashorn.types import com.programmaticallyspeaking.ncd.chrome.domains.Runtime.PropertyDescriptor import com.programmaticallyspeaking.ncd.host.{FunctionNode, ObjectId, ObjectNode} import com.programmaticallyspeaking.ncd.host.types.{ObjectPropertyDescriptor, PropertyDescriptorType} import com.programmaticallyspeaking.ncd.testing.UnitTest import org.scalatest.prop.TableDrivenPropertyChecks class ObjectPropertyDescriptorTest extends UnitTest with TableDrivenPropertyChecks { private val anObject = ObjectNode("Object", ObjectId("x")) private val aFunction = FunctionNode("fun", "function(){}", ObjectId("x")) val errorDescriptors = Table( ("description", "name", "input"), ("generic with value", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Generic, false, false, false, false, Some(anObject), None, None)), ("generic with getter", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Generic, false, false, false, false, None, Some(aFunction), None)), ("generic with setter", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Generic, false, false, false, false, None, None, Some(aFunction))), ("data without value", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Data, false, false, false, false, None, None, None)), ("accessor without getter or setter", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Accessor, false, false, false, false, None, None, None)), ("accessor with value", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Accessor, false, false, false, false, Some(anObject), Some(aFunction), None)), ("data with getter", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Data, false, false, false, false, Some(anObject), Some(aFunction), None)), ("data with setter", "invalid", () => ObjectPropertyDescriptor(PropertyDescriptorType.Data, false, false, false, false, Some(anObject), None, Some(aFunction))) ) "ObjectPropertyDescriptor" - { forAll(errorDescriptors) { (desc, name, factory) => s"rejects $desc" in { assertThrows[IllegalArgumentException](factory()) } } } }
Example 14
Source File: CallFunctionOnTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.nashorn import com.programmaticallyspeaking.ncd.host._ import com.programmaticallyspeaking.ncd.host.types.{ExceptionData, Undefined} import org.scalatest.prop.TableDrivenPropertyChecks import scala.concurrent.Promise import scala.util.{Failure, Success, Try} class CallFunctionOnTest extends EvaluateTestFixture with TableDrivenPropertyChecks { private def testSuccess[A](tr: Try[A])(tester: (A) => Unit): Unit = tr match { case Success(value) => tester(value) case Failure(t) => fail(t) } def testObjectValue(script: String, objName: String)(f: ObjectId => Unit): Unit = { evaluateInScript(script)({ (host, stackframes) => host.evaluateOnStackFrame(stackframes.head.id, objName) match { case Success(cn: ComplexNode) => f(cn.objectId) case Success(other) => fail("Unexpected evaluate result: " + other) case Failure(t) => fail("Error", t) } }) } def testObjectValue(f: ObjectId => Unit): Unit = { val script = """ |function fun() { | var obj = { value: 42 }; | debugger; | obj.toString(); |} |fun(); """.stripMargin testObjectValue(script, "obj")(f) } "callFunctionOn" - { "works for access to 'this'" in { val funcDecl = "function () { return this.value; }" testObjectValue { objId => val retVal = getHost.callFunctionOn(StackFrame.TopId, Some(objId), funcDecl, Seq.empty) retVal should be(Success(SimpleValue(42))) } } "works with argument" in { val funcDecl = "function (x) { return x.value; }" testObjectValue { objId => val retVal = getHost.callFunctionOn(StackFrame.TopId, None, funcDecl, Seq(objId)) retVal should be(Success(SimpleValue(42))) } } "can access Object in a strict mode function" in { val script = """ |function fun() { | 'use strict'; | var obj = { value: 99 }; | debugger; | obj.toString(); |} |fun(); """.stripMargin testObjectValue(script, "obj") { objId => getHost.callFunctionOn(StackFrame.TopId, None, "function (x) { return Object.getOwnPropertyNames(x); }", Seq(objId)) match { case Success(an: ArrayNode) => an.size should be (1) case Success(other) => fail("Unexpected callFunctionOn result: " + other) case Failure(t) => fail("Error", t) } } } } }
Example 15
Source File: NashornDebuggerHostTest.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.nashorn import com.programmaticallyspeaking.ncd.testing.UnitTest import com.sun.jdi.ThreadReference import org.scalatest.mockito.MockitoSugar import org.scalatest.prop.TableDrivenPropertyChecks import org.mockito.Mockito._ class NashornDebuggerHostTest extends UnitTest with TableDrivenPropertyChecks with MockitoSugar { val threadNames = Table( ("name", "isInfra"), ("Finalizer", true), ("Reference Handler", true), ("Signal Dispatcher", true), ("Attach Listener", true), ("attach listener", true), ("main", false) ) def threadReferenceWithName(name: String) = { val t = mock[ThreadReference] when(t.name()).thenReturn(name) t } "isInfrastructureThread" - { forAll(threadNames) { (name, isInfra) => val verb = if (isInfra) "be" else "not be" s"should consider a thread named '$name' to $verb an infrastructure thread" in { NashornDebuggerHost.isInfrastructureThread(threadReferenceWithName(name)) should be(isInfra) } } } }
Example 16
Source File: LteInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory.{bfalse, bool, btrue, int, real} import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class LteInstTest extends FunSuite with TableDrivenPropertyChecks { test("[lt] value, type, strm, anon combinations") { val starts: TableFor3[Obj, Obj, String] = new TableFor3[Obj, Obj, String](("query", "result", "type"), //////// INT (int(2).lte(1), bfalse, "value"), // value * value = value (int(2).q(10).lte(1), bfalse.q(10), "value"), // value * value = value (int(2).q(10).lte(1).q(20), bfalse.q(200), "value"), // value * value = value (int(2).lte(int(1).q(10)), bfalse, "value"), // value * value = value (int(2).lte(int), btrue, "value"), // value * type = value (int(2).lte(__.mult(int)), btrue, "value"), // value * anon = value (int.lte(int(2)), int.lte(int(2)), "type"), // type * value = type (int.q(10).lte(int(2)), int.q(10).lte(int(2)), "type"), // type * value = type (int.lte(int), int.lte(int), "type"), // type * type = type (int(1, 2, 3).lte(2), bool(true, true, false), "strm"), // strm * value = strm (int(1, 2, 3).lte(int(2).q(10)), bool(true, true, false), "strm"), // strm * value = strm (int(1, 2, 3) ==> __.lte(int(2)).q(10), bool(btrue.q(10), btrue.q(10), bfalse.q(10)), "strm"), // strm * value = strm (int(1, 2, 3).lte(int), bool(true, true, true), "strm"), // strm * type = strm (int(1, 2, 3).lte(__.mult(int)), bool(true, true, true), "strm"), // strm * anon = strm //////// REAL (real(2.0).lte(1.0), bfalse, "value"), // value * value = value (real(2.0).lte(real), btrue, "value"), // value * type = value (real(2.0).lte(__.mult(real)), true, "value"), // value * anon = value (real.lte(real(2.0)), real.lte(2.0), "type"), // type * value = type (real.lte(real), real.lte(real), "type"), // type * type = type (real(1.0, 2.0, 3.0).lte(2.0), bool(true, true, false), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0).lte(real), bool(true, true, true), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0).lte(__.mult(real)), bool(true, true, true), "strm"), // strm * anon = strm ) forEvery(starts) { (query, result, atype) => { //assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } }
Example 17
Source File: SerializationSpecification.scala From sigmastate-interpreter with MIT License | 5 votes |
package sigmastate.serialization import org.ergoplatform.validation.ValidationSpecification import org.scalacheck.Gen import org.scalatest.prop.{PropertyChecks, TableDrivenPropertyChecks, GeneratorDrivenPropertyChecks} import org.scalatest.{PropSpec, Assertion, Matchers} import org.scalacheck.Arbitrary._ import sigmastate.Values._ import sigmastate.SType import sigmastate.serialization.generators._ trait SerializationSpecification extends PropSpec with PropertyChecks with GeneratorDrivenPropertyChecks with TableDrivenPropertyChecks with Matchers with ObjectGenerators with ConcreteCollectionGenerators with OpcodesGen with TransformerGenerators with RelationGenerators with ValidationSpecification { protected def roundTripTest[V <: Value[_ <: SType]](v: V): Assertion = { val bytes = ValueSerializer.serialize(v) predefinedBytesTest(v, bytes) predefinedBytesTestNotFomZeroElement(bytes, v) } protected def predefinedBytesTest[V <: Value[_ <: SType]](v: V, bytes: Array[Byte]): Assertion = { ValueSerializer.serialize(v) shouldEqual bytes val r = SigmaSerializer.startReader(bytes) val positionLimitBefore = r.positionLimit val dv = ValueSerializer.deserialize(r) dv shouldEqual v r.positionLimit shouldBe positionLimitBefore } //check that pos and consumed are being implented correctly protected def predefinedBytesTestNotFomZeroElement[V <: Value[_ <: SType]](bytes: Array[Byte], v: V): Assertion = { val randomInt = Gen.chooseNum(1, 20).sample.get val randomBytes = Gen.listOfN(randomInt, arbByte.arbitrary).sample.get.toArray val parsedVal = ValueSerializer.deserialize(randomBytes ++ bytes, randomInt) parsedVal shouldEqual v } }
Example 18
Source File: ZooKeeperUriSpec.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.cosmos.model import org.scalatest.FreeSpec import org.scalatest.prop.TableDrivenPropertyChecks final class ZooKeeperUriSpec extends FreeSpec with TableDrivenPropertyChecks { import ZooKeeperUriSpec._ "parse()" - { "invalid uris" in { forAll(InvalidUris) { stringToParse => assert(ZooKeeperUri.parse(stringToParse).isLeft) } } "valid uris" in { forAll(ValidUris) { (stringToParse, connectString, path) => val Right(zkUri) = ZooKeeperUri.parse(stringToParse) assertResult(connectString)(zkUri.connectString) assertResult(path)(zkUri.path) } } } "toString" - { "valid uris" in { forAll(ValidUris) { (stringToParse, _, _) => val Right(uri) = ZooKeeperUri.parse(stringToParse) assertResult(stringToParse)(uri.toString) } } } } object ZooKeeperUriSpec extends TableDrivenPropertyChecks { val InvalidUris = Table( "string uri", "", "host1", "host1:2181", "/path/to/znode", "zk://", "zk://host1", "zk://host1/", "zk://host1:2181,host2:2181,host3:2181/invalid//path", "zk://host1:port1/valid/path" ) val ValidUris = Table( ("string uri", "connection string", "path"), ("zk://host1/z", "host1", "/z"), ("zk://host1:2181/path", "host1:2181", "/path"), ("zk://foo:12,bar:34,baz:56/path/to/znode", "foo:12,bar:34,baz:56", "/path/to/znode") ) }
Example 19
Source File: PackagingVersionSpec.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.universe.v3.model import com.mesosphere.universe import com.mesosphere.universe.test.TestingPackages import org.scalatest.FreeSpec import org.scalatest.Matchers import org.scalatest.prop.TableDrivenPropertyChecks final class PackagingVersionSpec extends FreeSpec with Matchers with TableDrivenPropertyChecks { "PackagingVersion.show" - { forAll(TestingPackages.validPackagingVersions) { (version, string) => s"PackagingVersion $string" in { version.show should be(string) } } } "PackagingVersions.allVersions" in { val allVersions = TestingPackages.validPackagingVersions.map(_._1) allVersions should be(universe.v4.model.PackagingVersion.allVersions) } }
Example 20
Source File: JsonUtilSpec.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.universe.common import io.circe.Encoder import io.circe.Json import io.circe.JsonObject import io.circe.generic.semiauto._ import io.circe.syntax._ import org.scalatest.FreeSpec import org.scalatest.prop.TableDrivenPropertyChecks class JsonUtilSpec extends FreeSpec with TableDrivenPropertyChecks { case class Foo(bar: Option[Int],far: Option[Int]) implicit val encodeFoo: Encoder[Foo] = { deriveEncoder[Foo] } "dropNullKeys" in { val ls = Foo(None,None) val string = JsonUtil.dropNullKeysPrinter.pretty(ls.asJson) assertResult("{}")(string) } "Merging JSON objects" - { "should pass on all examples" in { forAll (Examples) { (defaultsJson, optionsJson, mergedJson) => assertResult(mergedJson)(JsonUtil.merge(defaultsJson, optionsJson)) } } } private[this] val Examples = Table( ("defaults JSON", "options JSON", "merged JSON"), (JsonObject.empty, JsonObject.empty, JsonObject.empty), ( JsonObject.empty, JsonObject.singleton("a", Json.False), JsonObject.singleton("a", Json.False) ), ( JsonObject.singleton("a", Json.False), JsonObject.empty, JsonObject.singleton("a", Json.False) ), ( JsonObject.singleton("a", Json.False), JsonObject.singleton("a", Json.True), JsonObject.singleton("a", Json.True) ), ( JsonObject.singleton("a", Json.obj("a" -> Json.False)), JsonObject.singleton("a", Json.obj()), JsonObject.singleton("a", Json.obj("a" -> Json.False)) ), ( JsonObject.singleton("a", Json.obj("a" -> Json.False)), JsonObject.singleton("a", Json.obj("a" -> Json.True)), JsonObject.singleton("a", Json.obj("a" -> Json.True)) ), ( JsonObject.singleton("a", Json.obj("a" -> Json.False)), JsonObject.singleton("a", Json.obj("b" -> Json.False)), JsonObject.singleton("a", Json.obj("a" -> Json.False, "b" -> Json.False)) ), ( JsonObject.singleton("a", Json.obj("a" -> Json.False)), JsonObject.singleton("a", Json.True), JsonObject.singleton("a", Json.True) ) ) }
Example 21
Source File: SingleDimensionPartitionerSpec.scala From Spark-RSVD with Apache License 2.0 | 5 votes |
package com.criteo.rsvd import org.scalatest.FunSuite import org.scalatest.prop.TableDrivenPropertyChecks class SingleDimensionPartitionerSpec extends FunSuite with TableDrivenPropertyChecks with PerTestSparkSession { test( "Partitioner should partition square and skinny matrices with the same " + "number of columns / rows per partition") { val numRowBlocks = 5 val numBlocksPerPartition = 2 val indices = Table( ("SkinnyBlockMatrixIndex", "BlockMatrixIndex", "ExpectedPartitionId"), (0, (0, 0), 0), (0, (1, 0), 0), (0, (0, 1), 0), (1, (4, 0), 0), (2, (3, 2), 1) ) val partitioner = SingleDimensionPartitioner(numRowBlocks, numBlocksPerPartition) forAll(indices) { (skinnyIndex: Int, squareIndex: (Int, Int), expectedPartitionIndex: Int) => assert( partitioner.getPartition(skinnyIndex) === partitioner.getPartition( squareIndex)) assert(partitioner.getPartition(skinnyIndex) === expectedPartitionIndex) } } test("createCompatibleIndicesRDD works") { val numRowBlocks = 5 val numBlocksPerPartition = 2 val partitioner = SingleDimensionPartitioner(numRowBlocks, numBlocksPerPartition) val rdd = partitioner.createCompatibleIndicesRDD(sc) assert(rdd.partitions.length == 3) val data = rdd .mapPartitionsWithIndex { case (idx, it) => Iterator((idx, it.map(_._1).toList)) } .collect() .sortBy(_._1) assert( data === Array( (0, List(0, 1)), (1, List(2, 3)), (2, List(4)) ) ) } }
Example 22
Source File: TestCustomIndexName.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.elastic6.indexname import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.prop.TableDrivenPropertyChecks class TestCustomIndexName extends AnyFlatSpec with TableDrivenPropertyChecks with Matchers { val ValidIndexNames = Table( ("Valid index name", "Expectations"), ("", Vector()), ("abc", Vector(TextFragment("abc"))), ("abc{YYYY-MM-dd}", Vector(TextFragment("abc"), DateTimeFragment("YYYY-MM-dd"))), ("{YYYY-MM-dd}abc", Vector(DateTimeFragment("YYYY-MM-dd"), TextFragment("abc"))), ("{YYYY-MM-dd}abc{HH-MM-ss}", Vector(DateTimeFragment("YYYY-MM-dd"), TextFragment("abc"), DateTimeFragment("HH-MM-ss"))), ("{YYYY-MM-dd}{HH-MM-ss}", Vector(DateTimeFragment("YYYY-MM-dd"), DateTimeFragment("HH-MM-ss"))), ("abc{}", Vector(TextFragment("abc"))), ("{}abc", Vector(TextFragment("abc"))) ) val InvalidIndexNames = Table( ("Invalid index name"), ("}abc"), ("abc}"), ("abc}def") ) "Custom index name" should "parse a valid String with date time formatting options" in { forAll (ValidIndexNames) { case (validIndexName, expectations) => CustomIndexName.parseIndexName(validIndexName) shouldBe CustomIndexName(expectations) } } it should "throw an exception when using invalid index name" in { forAll (InvalidIndexNames) { case (invalidIndexName) => intercept[InvalidCustomIndexNameException] { CustomIndexName.parseIndexName(invalidIndexName) } } } it should "return a valid String from a list of fragments" in new ClockFixture { CustomIndexName( Vector(DateTimeFragment("YYYY-MM-dd", TestClock), TextFragment("ABC"), DateTimeFragment("HH:mm:ss", TestClock)) ).toString shouldBe "2016-10-02ABC14:00:00" } }
Example 23
Source File: AssetUnsupportedTransactionsSuite.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.it.sync.smartcontract.smartasset import com.wavesplatform.common.utils.EitherExt2 import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.sync.{someAssetAmount, _} import com.wavesplatform.it.transactions.BaseTransactionSuite import com.wavesplatform.lang.v1.estimator.v2.ScriptEstimatorV2 import com.wavesplatform.transaction.smart.script.ScriptCompiler import org.scalatest.prop.TableDrivenPropertyChecks class AssetUnsupportedTransactionsSuite extends BaseTransactionSuite with TableDrivenPropertyChecks { forAll( Table( "tx", "SponsorFeeTransaction", "LeaseTransaction", "LeaseCancelTransaction", "CreateAliasTransaction", "SetScriptTransaction", "DataTransaction", "IssueTransaction" )) { tx => test(s"Smart Asset script should not support $tx") { try { sender.issue( firstAddress, "MyAsset", "Test Asset", someAssetAmount, 0, reissuable = true, issueFee, 2, Some( ScriptCompiler( s""" |match tx { | case _: $tx => true | case _ => true |}""".stripMargin, isAssetScript = true, ScriptEstimatorV2 ).explicitGet()._1.bytes.value.base64), waitForTx = true ) fail("ScriptCompiler didn't throw expected error") } catch { case ex: java.lang.Exception => ex.getMessage should include("Matching not exhaustive: possibleTypes are") case _: Throwable => fail("ScriptCompiler works incorrect for orders with smart assets") } } } test("cannot sponsor scripted asset") { val assetId = sender .issue( firstAddress, "MyAsset", "Test Asset", someAssetAmount, 0, reissuable = true, issueFee, 2, Some(scriptBase64), waitForTx = true ) .id assertBadRequestAndMessage(sender.sponsorAsset(firstAddress, assetId, 100, sponsorReducedFee + smartFee), "State check failed. Reason: Sponsorship smart assets is disabled.") } }
Example 24
Source File: RideCreateMerkleRootTestSuite.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.it.sync import com.typesafe.config.Config import com.wavesplatform.account._ import com.wavesplatform.common.merkle.Merkle import com.wavesplatform.common.state.ByteStr import com.wavesplatform.common.utils.{Base58, EitherExt2} import com.wavesplatform.features.BlockchainFeatures import com.wavesplatform.it.api.SyncHttpApi._ import com.wavesplatform.it.api.Transaction import com.wavesplatform.it.transactions.NodesFromDocker import com.wavesplatform.it.{Node, NodeConfigs, ReportingTestName, TransferSending} import com.wavesplatform.lang.v1.compiler.Terms._ import com.wavesplatform.lang.v1.estimator.v3.ScriptEstimatorV3 import com.wavesplatform.state._ import com.wavesplatform.transaction.Asset._ import com.wavesplatform.transaction.{Proofs, TxVersion} import com.wavesplatform.transaction.smart.script.ScriptCompiler import com.wavesplatform.transaction.transfer.TransferTransaction import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{CancelAfterFailure, FunSuite, Matchers} class RideCreateMerkleRootTestSuite extends FunSuite with CancelAfterFailure with TransferSending with NodesFromDocker with ReportingTestName with Matchers with TableDrivenPropertyChecks { override def nodeConfigs: Seq[Config] = NodeConfigs.newBuilder .overrideBase(_.quorum(0)) .overrideBase(_.preactivatedFeatures((14, 1000000), BlockchainFeatures.NG.id.toInt -> 0, BlockchainFeatures.FairPoS.id.toInt -> 0, BlockchainFeatures.Ride4DApps.id.toInt -> 0, BlockchainFeatures.BlockV5.id.toInt -> 0)) .withDefault(1) .buildNonConflicting() private def sender: Node = nodes.last test("Ride createMerkleRoot") { val script = """ |{-# STDLIB_VERSION 4 #-} |{-# CONTENT_TYPE DAPP #-} | | @Callable(inv) |func foo(proof: List[ByteVector], id: ByteVector, index: Int) = [ | BinaryEntry("root", createMerkleRoot(proof, id, index)) |] """.stripMargin val cscript = ScriptCompiler.compile(script, ScriptEstimatorV3).explicitGet()._1.bytes().base64 val node = nodes.head nodes.waitForHeightArise() val tx1 = node.broadcastTransfer(node.keyPair, sender.address, setScriptFee, minFee, None, None, version = TxVersion.V3, waitForTx = false) val txId1 = tx1.id val tx2 = node.broadcastTransfer(node.keyPair, node.address, 1, minFee, None, None, version = TxVersion.V3, waitForTx = false) val txId2 = tx2.id val tx3 = node.broadcastTransfer(node.keyPair, node.address, 1, minFee, None, None, version = TxVersion.V3, waitForTx = false) val txId3 = tx3.id val tx4 = node.broadcastTransfer(node.keyPair, node.address, 1, minFee, None, None, version = TxVersion.V3, waitForTx = false) val txId4 = tx4.id val tx5 = node.broadcastTransfer(node.keyPair, node.address, 1, minFee, None, None, version = TxVersion.V3, waitForTx = false) val txId5 = tx5.id val height = node.height nodes.waitForHeightArise() def tt(tx: Transaction) = TransferTransaction.create( tx.version.get, PublicKey(Base58.decode(tx.senderPublicKey.get)), Address.fromString(tx.recipient.get).explicitGet(), Waves , tx.fee, ByteStr.empty, // attachment tx.timestamp, Proofs(tx.proofs.get.map(v => ByteStr(Base58.decode(v)))) ).explicitGet() val natives = Seq(tx1, tx2, tx3, tx4, tx5).map(tt).map(t => Base58.encode(t.id().arr) -> t).toMap val root = Base58.decode(node.blockAt(height).transactionsRoot.get) val proofs = nodes.head.getMerkleProof(txId1, txId2, txId3, txId4, txId5) sender.setScript(sender.address, Some(cscript), setScriptFee, waitForTx = true).id for(p <- proofs) { node.invokeScript( node.address, sender.address, func = Some("foo"), args = List(ARR(p.merkleProof.map(v => CONST_BYTESTR(ByteStr(Base58.decode(v))).explicitGet()).toIndexedSeq, false).explicitGet(), CONST_BYTESTR(ByteStr(Merkle.hash(natives(p.id).bytes()))).explicitGet(), CONST_LONG(p.transactionIndex.toLong)), payment = Seq(), fee = 2*smartFee+minFee, waitForTx = true ) node.getDataByKey(sender.address, "root") shouldBe BinaryDataEntry("root", ByteStr(root)) } } }
Example 25
Source File: FutureTrySpec.scala From scala-common with Apache License 2.0 | 5 votes |
import com.softwaremill.futuretry._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.matchers.must.Matchers import scala.concurrent.duration.Duration import scala.concurrent.{Future, Await, Promise} import scala.util.{Failure, Success, Try} class FutureTrySpec extends AnyFlatSpec with Matchers with TableDrivenPropertyChecks with ScalaFutures { import scala.concurrent.ExecutionContext.Implicits.global "tried" must "convert a successful result into a Success" in { val p = Promise[String] p.complete(Try("a")) val transformedFuture = p.future.tried transformedFuture.futureValue must be(Success("a")) } it must "convert an exceptional result into a Failure" in { val p = Promise[String] val exception = new RuntimeException("blah") p.complete(Try(throw exception)) val transformedFuture = p.future.tried transformedFuture.futureValue must be(Failure(exception)) } "transform" must "correctly transform between all Try variants in" in { val exception = new RuntimeException("bloh") val scenarios = Table[Try[String], Try[String] => Try[String], Try[String]] ( ("original value", "transform", "expected output"), (Success("a"), identity[Try[String]], Success("a")), (Failure(exception), (x: Try[String]) => x match { case Failure(e) => Success(e.toString); case _ => ??? }, Success(exception.toString)), (Success("a"), (x: Try[String]) => x match { case Success(_) => Failure(exception); case _ => ??? }, Failure(exception)), (Failure(exception), identity[Try[String]], Failure(exception)) ) forAll(scenarios) { (orgValue, f, output) => { val p = Promise[String] p.complete(orgValue) val transformedFuture = p.future.transformTry(f) transformedFuture.tried.futureValue must be(output) } } } }
Example 26
Source File: HiveParsingErrorsSpec.scala From vizsql with Apache License 2.0 | 5 votes |
package com.criteo.vizatra.vizsql.hive import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{EitherValues, Matchers, PropSpec} class HiveParsingErrorsSpec extends PropSpec with Matchers with EitherValues { val invalidSQL99SelectStatements = TableDrivenPropertyChecks.Table( ("SQL", "Expected error"), ( "select bucket from t", """select bucket from t | ^ |Error: *, table or expression expected """ ), ( "select foo from tbl limit 100 order by foo", """select foo from tbl limit 100 order by foo | ^ |Error: ; expected """ ), ( "select foo from bar tablesample (bucket 2 out af 3)", """select foo from bar tablesample (bucket 2 out af 3) | ^ |Error: of expected """.stripMargin ) ) // -- property("report parsing errors on invalid Hive statements") { TableDrivenPropertyChecks.forAll(invalidSQL99SelectStatements) { case (sql, expectedError) => new HiveDialect(Map.empty).parser.parseStatement(sql) .fold(_.toString(sql, ' ').trim, _ => "[NO ERROR]") should be (expectedError.toString.stripMargin.trim) } } }
Example 27
Source File: HiveTypeParserSpec.scala From vizsql with Apache License 2.0 | 5 votes |
package com.criteo.vizatra.vizsql.hive import com.criteo.vizatra.vizsql._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, PropSpec} class HiveTypeParserSpec extends PropSpec with Matchers { val types = TableDrivenPropertyChecks.Table( ("Type string", "Expected type"), ("double", DECIMAL(true)), ("array<int>", HiveArray(INTEGER(true))), ("map<string,struct<a:boolean,b:timestamp>>", HiveMap(STRING(true), HiveStruct(List( Column("a", BOOLEAN(true)), Column("b", TIMESTAMP(true)) )))), ("array<struct<foo:array<map<string,string>>,bar:array<int>,`baz`:double>>", HiveArray(HiveStruct(List( Column("foo", HiveArray(HiveMap(STRING(true), STRING(true)))), Column("bar", HiveArray(INTEGER(true))), Column("baz", DECIMAL(true)) )))), ("struct<timestamp:integer>", HiveStruct(List( Column("timestamp", INTEGER(true)) ))) ) // -- property("parse to correct types") { val parser = new TypeParser TableDrivenPropertyChecks.forAll(types) { case (typeString, expectedType) => parser.parseType(typeString) shouldEqual Right(expectedType) } } }
Example 28
Source File: ParsingErrorsSpec.scala From vizsql with Apache License 2.0 | 5 votes |
package com.criteo.vizatra.vizsql import sql99._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, EitherValues, PropSpec} class ParsingErrorsSpec extends PropSpec with Matchers with EitherValues { val invalidSQL99SelectStatements = TableDrivenPropertyChecks.Table( ("SQL", "Expected error"), ( """xxx""", """|xxx |^ |Error: select expected """ ), ( """select""", """|select | ^ |Error: *, table or expression expected """ ), ( """select 1 +""", """|select 1 + | ^ |Error: expression expected """ ), ( """select 1 + *""", """|select 1 + * | ^ |Error: expression expected """ ), ( """select (1 + 3""", """|select (1 + 3 | ^ |Error: ) expected """ ), ( """select * from""", """|select * from | ^ |Error: table, join or subselect expected """ ), ( """select * from (selet 1)""", """|select * from (selet 1) | ^ |Error: select expected """ ), ( """select * from (select 1sh);""", """|select * from (select 1sh); | ^ |Error: ident expected """ ), ( """select * from (select 1)sh)""", """|select * from (select 1)sh) | ^ |Error: ; expected """ ), ( """SELECT CustomerName; City FROM Customers;""", """|SELECT CustomerName; City FROM Customers; | ^ |Error: end of statement expected """ ), ( """SELECT CustomerName FROM Customers UNION ALL""", """|SELECT CustomerName FROM Customers UNION ALL | ^ |Error: select expected """ ) ) // -- property("report parsing errors on invalid SQL-99 SELECT statements") { TableDrivenPropertyChecks.forAll(invalidSQL99SelectStatements) { case (sql, expectedError) => (new SQL99Parser).parseStatement(sql) .fold(_.toString(sql, ' ').trim, _ => "[NO ERROR]") should be (expectedError.toString.stripMargin.trim) } } }
Example 29
Source File: ParseVerticaDialectSpec.scala From vizsql with Apache License 2.0 | 5 votes |
package com.criteo.vizatra.vizsql import com.criteo.vizatra.vizsql.vertica._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{EitherValues, Matchers, PropSpec} class ParseVerticaDialectSpec extends PropSpec with Matchers with EitherValues { val validVerticaSelectStatements = TableDrivenPropertyChecks.Table( ("SQL", "Expected Columns"), ("""SELECT | NOW() as now, | MAX(last_update) + 3599 / 86400 AS last_update, | CONCAT('The most recent update was on ', TO_CHAR(MAX(last_update) + 3599 / 86400, 'YYYY-MM-DD at HH:MI')) as content |FROM | City""".stripMargin, List( Column("now", TIMESTAMP(nullable = false)), Column("last_update", TIMESTAMP(nullable = false)), Column("content", STRING(nullable = false)) )) ) // -- val SAKILA = DB(schemas = List( Schema( "sakila", tables = List( Table( "City", columns = List( Column("city_id", INTEGER(nullable = false)), Column("city", STRING(nullable = false)), Column("country_id", INTEGER(nullable = false)), Column("last_update", TIMESTAMP(nullable = false)) ) ), Table( "Country", columns = List( Column("country_id", INTEGER(nullable = false)), Column("country", STRING(nullable = false)), Column("last_update", TIMESTAMP(nullable = false)) ) ) ) ) )) // -- property("extract Vertica SELECT statements columns") { TableDrivenPropertyChecks.forAll(validVerticaSelectStatements) { case (sql, expectedColumns) => VizSQL.parseQuery(sql, SAKILA) .fold(e => sys.error(s"Query doesn't parse: $e"), identity) .columns .fold(e => sys.error(s"Invalid query: $e"), identity) should be (expectedColumns) } } }
Example 30
Source File: SchemaErrorsSpec.scala From vizsql with Apache License 2.0 | 5 votes |
package com.criteo.vizatra.vizsql import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{EitherValues, Matchers, PropSpec} import sql99._ class SchemaErrorsSpec extends PropSpec with Matchers with EitherValues { val invalidSQL99SelectStatements = TableDrivenPropertyChecks.Table( ("SQL", "Expected error"), ( "SELECT region from City as C1 JOIN Country as C2 ON C1.country_id = C2.country_id WHERE region < 42", SchemaError("ambiguous column region", 6) ),( "SELECT nonexistent, region from City", SchemaError("column not found nonexistent", 6) ) ) // -- val SAKILA = DB(schemas = List( Schema( "sakila", tables = List( Table( "City", columns = List( Column("city_id", INTEGER(nullable = false)), Column("city", STRING(nullable = false)), Column("country_id", INTEGER(nullable = false)), Column("last_update", TIMESTAMP(nullable = false)), Column("region", INTEGER(nullable = false)) ) ), Table( "Country", columns = List( Column("country_id", INTEGER(nullable = false)), Column("country", STRING(nullable = false)), Column("last_update", TIMESTAMP(nullable = false)), Column("region", INTEGER(nullable = false)) ) ) ) ) )) // -- property("report schema errors on invalid SQL-99 SELECT statements") { TableDrivenPropertyChecks.forAll(invalidSQL99SelectStatements) { case (sql, expectedError) => VizSQL.parseQuery(sql, SAKILA) .fold( e => sys.error(s"Query doesn't parse: $e"), _.error.getOrElse(sys.error(s"Query should not type!")) ) should be (expectedError) } } }
Example 31
Source File: GetInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.LanguageException import org.mmadt.language.obj.Obj._ import org.mmadt.language.obj.op.map.GetOp import org.mmadt.language.obj.value.{IntValue, StrValue} import org.mmadt.language.obj.{Lst, Obj} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class GetInstTest extends FunSuite with TableDrivenPropertyChecks { test("[get] w/ lst values") { val check: TableFor3[Lst[StrValue], IntValue, StrValue] = new TableFor3[Lst[StrValue], IntValue, StrValue](("list", "key", "value"), ("a" |, 0, str("a")), ("a" | "b", 0, "a"), ("a" | "b" | "c", 1, "b"), ("d" | "b" | "c", 2, "c"), ) forEvery(check) { (alst, akey, avalue) => { assertResult(avalue)(alst.get(akey)) assertResult(avalue)(GetOp(akey).exec(alst.asInstanceOf[Obj with GetOp[IntValue, StrValue]])) } } } test("[get] w/ lst value exception") { assertThrows[LanguageException] { (str("a") | "b" | "c").get(-1) } assertThrows[LanguageException] { (str("a") | "b" | "c").get(3) } assertThrows[LanguageException] { lst("|").get(0) } } test("[get] lineage") { val marko = rec(str("name") -> str("marko"), str("age") -> int(29)) assertResult(2)(marko.get(str("name"), str).plus(" rodriguez").trace.length) } test("[get] w/ rec value") { val marko = rec(str("name") -> str("marko"), str("age") -> int(29)) assertResult(str("marko"))(marko.get(str("name"))) assertResult(int(29))(marko.get(str("age"))) //assertThrows[LanguageException] { assertResult(zeroObj)(marko.get(str("bad-key"))) //} } }
Example 32
Source File: TypeSubstSpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.validation import com.daml.lf.language.Ast._ import com.daml.lf.testing.parser.Implicits._ import com.daml.lf.validation.SpecUtil._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, WordSpec} class TypeSubstSpec extends WordSpec with TableDrivenPropertyChecks with Matchers { "A TypeSubst" should { "should be idempotent on terms that do not contain variable from its domain." in { val subst = Map(n"alpha" -> t"gamma") val testCases = Table( "type", t"Int64", t"M:C", t"beta", t"gamma", t"beta1 beta2", t"beta1 -> beta2", t"< field1 : beta1, field2: beta2 >", t"M:C (beta1 beta2) ((beta2 -> beta1) beta2)" ) forEvery(testCases) { typ: Type => TypeSubst.substitute(subst, typ) shouldBe typ } } "should substitutes variables from its domain in terms without quantifiers." in { val subst1 = Map(n"alpha" -> t"gamma") val subst2 = Map(n"alpha" -> t"gamma2") val testCases = Table( "input type" -> "expect result type", t"alpha" -> t"gamma", t"alpha -> beta" -> t"gamma -> beta", t"beta -> alpha" -> t"beta -> gamma", t"alpha -> alpha" -> t"gamma -> gamma", t"alpha beta" -> t"gamma beta", t"beta alpha" -> t"beta gamma", t"alpha alpha" -> t"gamma gamma", t"<a: alpha, b: beta, c: alpha, d: beta>" -> t"<a: gamma, b: beta, c: gamma, d: beta>", t"M:C (alpha beta) ((beta -> alpha) beta)" -> t"M:C (gamma beta) ((beta -> gamma) beta)" ) forEvery(testCases) { (input: Type, expectedOutput: Type) => TypeSubst.substitute(subst1, input: Type) shouldEqual expectedOutput TypeSubst.substitute(subst2, input: Type) should !==(expectedOutput) } } "should handle properly binders" in { val subst = Map(n"alpha" -> t"beta1") TypeSubst.substitute(subst, t"forall beta1. alpha (beta1 gamma)") shouldEqual t"forall beta2. beta1 (beta2 gamma)" TypeSubst.substitute(subst, t"forall beta1. forall beta2. alpha (beta1 beta2)") shouldEqual t"forall gamma. forall beta2. beta1 (gamma beta2)" val subst0 = Map(n"beta2" -> t"beta1") val subst1 = Map(n"beta1" -> t"beta2") val input = t"forall beta1. forall beta2. alpha (beta1 beta2)" TypeSubst.substitute(subst1, TypeSubst.substitute(subst0, input)) shouldEqual input } } }
Example 33
Source File: DamlLfEncoderTest.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.testing.archive import java.io.File import com.daml.bazeltools.BazelRunfiles import com.daml.lf.archive.{Dar, UniversalArchiveReader} import com.daml.lf.data.Ref.{DottedName, PackageId} import com.daml.daml_lf_dev.DamlLf import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, WordSpec} import scala.collection.JavaConverters._ import scala.language.implicitConversions class DamlLfEncoderTest extends WordSpec with Matchers with TableDrivenPropertyChecks with BazelRunfiles { "dar generated by encoder" should { "be readable" in { val modules_1_0 = Set[DottedName]( "UnitMod", "BoolMod", "Int64Mod", "TextMod", "DecimalMod", "DateMod", "TimestampMod", "ListMod", "PartyMod", "RecordMod", "VariantMod", "BuiltinMod", "TemplateMod", ) val modules_1_1 = modules_1_0 + "OptionMod" val modules_1_3 = modules_1_1 + "TextMapMod" val modules_1_6 = modules_1_3 + "EnumMod" val modules_1_7 = modules_1_6 + "NumericMod" val modules_1_8 = modules_1_7 + "SynonymMod" val modules_1_dev = modules_1_8 + "GenMapMod" val versions = Table( "versions" -> "modules", "1.0" -> modules_1_0, "1.1" -> modules_1_1, "1.3" -> modules_1_3, "1.6" -> modules_1_6, "1.7" -> modules_1_7, "1.8" -> modules_1_8, "1.dev" -> modules_1_dev ) forEvery(versions) { (version, expectedModules) => val dar = UniversalArchiveReader() .readFile(new File(rlocation(s"daml-lf/encoder/test-$version.dar"))) dar shouldBe 'success val findModules = dar.toOption.toList.flatMap(getModules).toSet findModules shouldBe expectedModules } } } private val preInternalizationVersions = List.range(0, 7).map(_.toString).toSet private def getModules(dar: Dar[(PackageId, DamlLf.ArchivePayload)]) = { for { pkgWithId <- dar.main +: dar.dependencies (_, pkg) = pkgWithId version = pkg.getMinor internedStrings = pkg.getDamlLf1.getInternedStringsList.asScala.toArray dottedNames = pkg.getDamlLf1.getInternedDottedNamesList.asScala.map( _.getSegmentsInternedStrList.asScala.map(internedStrings(_)) ) segments <- pkg.getDamlLf1.getModulesList.asScala.map( mod => if (preInternalizationVersions(version)) mod.getNameDname.getSegmentsList.asScala else dottedNames(mod.getNameInternedDname) ) } yield DottedName.assertFromSegments(segments) } private implicit def toDottedName(s: String): DottedName = DottedName.assertFromString(s) }
Example 34
Source File: FrontStackSpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.data import com.daml.scalatest.{Unnatural, WordSpecCheckLaws} import org.scalatest.prop.{GeneratorDrivenPropertyChecks, TableDrivenPropertyChecks} import org.scalatest.{Matchers, WordSpec} import scalaz.scalacheck.ScalazProperties import scalaz.std.anyVal._ class FrontStackSpec extends WordSpec with Matchers with GeneratorDrivenPropertyChecks with TableDrivenPropertyChecks with WordSpecCheckLaws { import DataArbitrary._ "apply" when { "1 element is provided" should { "behave the same as prepend" in forAll { x: Int => FrontStack(x) should ===(x +: FrontStack.empty) } } "2 elements are provided" should { "behave the same as prepend" in forAll { (x: Int, y: Int) => FrontStack(x, y) should ===(x +: y +: FrontStack.empty) } } "more than 2 elements are provided" should { "behave the same as prepend" in forAll { (x: Int, y: Int, z: Int, rest: Seq[Int]) => FrontStack(x, y, z, rest: _*) should ===( ImmArray(Seq(x, y, z) ++ rest) ++: FrontStack.empty) } } "a sequence of elements is provided" should { "behave the same as prepend" in forAll { xs: Seq[Int] => FrontStack(xs) should ===(ImmArray(xs) ++: FrontStack.empty) } } } "++:" should { "yield equal results to +:" in forAll { (ia: ImmArray[Int], fs: FrontStack[Int]) => (ia ++: fs) should ===(ia.toSeq.foldRight(fs)(_ +: _)) } } "toImmArray" should { "yield same elements as iterator" in forAll { fs: FrontStack[Int] => fs.toImmArray should ===(fs.iterator.to[ImmArray]) } } "length" should { "be tracked accurately during building" in forAll { fs: FrontStack[Int] => fs.length should ===(fs.iterator.length) } } "slowApply" should { "throw when out of bounds" in forAll { fs: FrontStack[Int] => an[IndexOutOfBoundsException] should be thrownBy fs.slowApply(-1) an[IndexOutOfBoundsException] should be thrownBy fs.slowApply(fs.length) } "preserve Seq's apply" in forAll { fs: FrontStack[Int] => val expected = Table( ("value", "index"), fs.toImmArray.toSeq.zipWithIndex: _* ) forEvery(expected) { (value, index) => fs.slowApply(index) should ===(value) } } } "toBackStack" should { "be retracted by toFrontStack" in forAll { fs: FrontStack[Int] => fs.toBackStack.toFrontStack should ===(fs) } } "Traverse instance" should { checkLaws(ScalazProperties.traverse.laws[FrontStack]) } "Equal instance" should { checkLaws(ScalazProperties.equal.laws[FrontStack[Unnatural[Int]]]) } }
Example 35
Source File: PreprocessorSpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf package engine package preprocessing import com.daml.lf.data._ import com.daml.lf.language.Ast.{TNat, TTyCon} import com.daml.lf.language.Util._ import com.daml.lf.testing.parser.Implicits._ import com.daml.lf.value.Value._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, WordSpec} import scala.language.implicitConversions class PreprocessorSpec extends WordSpec with Matchers with TableDrivenPropertyChecks { import defaultParserParameters.{defaultPackageId => pkgId} private implicit def toName(s: String): Ref.Name = Ref.Name.assertFromString(s) val recordCon = Ref.Identifier(pkgId, Ref.QualifiedName.assertFromString("Module:Record")) val variantCon = Ref.Identifier(pkgId, Ref.QualifiedName.assertFromString("Module:Variant")) val enumCon = Ref.Identifier(pkgId, Ref.QualifiedName.assertFromString("Module:Enum")) val pkg = p""" module Module { record Record = { field : Int64 }; variant Variant = variant1 : Text | variant2 : Int64 ; enum Enum = value1 | value2; } """ "translateValue" should { val testCases = Table( "type" -> "value", TUnit -> ValueUnit, TBool -> ValueTrue, TInt64 -> ValueInt64(42), TTimestamp -> ValueTimestamp(Time.Timestamp.assertFromString("1969-07-20T20:17:00Z")), TDate -> ValueDate(Time.Date.assertFromString("1879-03-14")), TText -> ValueText("daml"), TNumeric(TNat(Decimal.scale)) -> ValueNumeric(Numeric.assertFromString("10.0000000000")), // TNumeric(TNat(9)) -> // ValueNumeric(Numeric.assertFromString("9.000000000")), TParty -> ValueParty(Ref.Party.assertFromString("Alice")), TContractId(TTyCon(recordCon)) -> ValueContractId(ContractId.assertFromString("#contractId")), TList(TText) -> ValueList(FrontStack(ValueText("a"), ValueText("b"))), TTextMap(TBool) -> ValueTextMap(SortedLookupList(Map("0" -> ValueTrue, "1" -> ValueFalse))), TOptional(TText) -> ValueOptional(Some(ValueText("text"))), TTyCon(recordCon) -> ValueRecord(None, ImmArray(Some[Ref.Name]("field") -> ValueInt64(33))), TTyCon(variantCon) -> ValueVariant(None, "variant1", ValueText("some test")), TTyCon(enumCon) -> ValueEnum(None, "value1"), ) val compiledPackage = ConcurrentCompiledPackages() assert(compiledPackage.addPackage(pkgId, pkg) == ResultDone.Unit) val preprocessor = new Preprocessor(compiledPackage) import preprocessor.translateValue "succeeds on well type values" in { forAll(testCases) { (typ, value) => translateValue(typ, value) shouldBe a[ResultDone[_]] } } "fails on non-well type values" in { forAll(testCases) { (typ1, value1) => forAll(testCases) { (_, value2) => if (value1 != value2) translateValue(typ1, value2) shouldBe a[ResultError] } } } } }
Example 36
Source File: GraphsSpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.language import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, WordSpec} import scala.collection.immutable.HashMap class GraphsSpec extends WordSpec with Matchers with TableDrivenPropertyChecks { import Graphs._ "topoSort" should { val dags = Table[Graph[Int]]( "directed acyclic graphs", HashMap.empty, HashMap( 3 -> Set(8, 10), 5 -> Set(11), 7 -> Set(8, 11), 8 -> Set(9), 11 -> Set(2, 9, 10) ) ) val dcgs = Table[Graph[String]]( "directed cyclic graphs", HashMap("1" -> Set("1")), HashMap("A" -> Set("B"), "B" -> Set("A")), HashMap( "A" -> Set("B", "C", "E"), "B" -> Set("C", "E"), "C" -> Set("D"), "D" -> Set("B", "E"), "E" -> Set("E"), ) ) "successfully sort all edges of directed acyclic graph" in { dags.forEvery { dag => val result = topoSort(dag) result shouldBe 'right val Right(sortedEdges) = result val allEdges = dag.values.foldLeft(dag.keySet)(_ | _) sortedEdges.toSet shouldBe allEdges val edgeRank = sortedEdges.zipWithIndex.toMap for { e <- dag.keys e_ <- dag(e) } edgeRank(e_) should be < edgeRank(e) } } "fail on cyclic graph and return a proper cycle" in { dcgs.forEvery { dcg => val result = topoSort(dcg) result shouldBe 'left val Left(Cycle(loop)) = result ((loop.last :: loop) zip loop).foreach { case (e, e_) => dcg(e) should contain(e_) } } } } }
Example 37
Source File: LanguageVersionSpec.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.language import com.daml.lf.language.{LanguageMajorVersion => LVM, LanguageVersion => LV} import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{Matchers, WordSpec} class LanguageVersionSpec extends WordSpec with Matchers with TableDrivenPropertyChecks { "LanguageVersion.ordering order as expected" in { val versionInOrder = List( LV.defaultV0, LV(LVM.V1, "0"), LV(LVM.V1, "1"), LV(LVM.V1, "2"), ) val versionRank = versionInOrder.zipWithIndex.toMap val versions = Table("version", versionInOrder: _*) forEvery(versions)( v1 => forEvery(versions)( v2 => LV.ordering .compare(v1, v2) .signum shouldBe (versionRank(v1) compareTo versionRank(v2)).signum)) } }
Example 38
Source File: ExchangeTransactionCreatorSpecification.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.model import com.wavesplatform.dex.domain.asset.Asset import com.wavesplatform.dex.domain.bytes.ByteStr import com.wavesplatform.dex.domain.crypto import com.wavesplatform.dex.domain.crypto.Proofs import com.wavesplatform.dex.domain.order.Order import com.wavesplatform.dex.domain.order.OrderOps._ import com.wavesplatform.dex.domain.transaction.ExchangeTransactionV2 import com.wavesplatform.dex.domain.utils.EitherExt2 import com.wavesplatform.dex.{MatcherSpecBase, NoShrink} import org.scalacheck.Gen import org.scalamock.scalatest.PathMockFactory import org.scalatest.matchers.should.Matchers import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.wordspec.AnyWordSpec import org.scalatest.{Assertion, BeforeAndAfterAll} import org.scalatestplus.scalacheck.{ScalaCheckPropertyChecks => PropertyChecks} import scala.concurrent.ExecutionContext.Implicits.global class ExchangeTransactionCreatorSpecification extends AnyWordSpec with Matchers with MatcherSpecBase with BeforeAndAfterAll with PathMockFactory with PropertyChecks with NoShrink with TableDrivenPropertyChecks { private def getExchangeTransactionCreator(hasMatcherScript: Boolean = false, hasAssetScripts: Asset => Boolean = _ => false): ExchangeTransactionCreator = { new ExchangeTransactionCreator(MatcherAccount, matcherSettings.exchangeTxBaseFee, hasMatcherScript, hasAssetScripts) } "ExchangeTransactionCreator" should { "create an ExchangeTransactionV2" when { (List(1, 2, 3) ++ List(1, 2, 3)).combinations(2).foreach { case List(counterVersion, submittedVersion) => s"counterVersion=$counterVersion, submittedVersion=$submittedVersion" in { val counter = buy(wavesBtcPair, 100000, 0.0008, matcherFee = Some(2000L), version = counterVersion.toByte) val submitted = sell(wavesBtcPair, 100000, 0.0007, matcherFee = Some(1000L), version = submittedVersion.toByte) val tc = getExchangeTransactionCreator() val oe = mkOrderExecutedRaw(submitted, counter) tc.createTransaction(oe).explicitGet() shouldBe a[ExchangeTransactionV2] } } } "take fee from order executed event" when { "orders are matched fully" in { val preconditions = for { ((_, buyOrder), (_, sellOrder)) <- orderV3MirrorPairGenerator } yield (buyOrder, sellOrder) test(preconditions) } "orders are matched partially" in { val preconditions = for { ((_, buyOrder), (senderSell, sellOrder)) <- orderV3MirrorPairGenerator } yield { val sellOrderWithUpdatedAmount = sellOrder.updateAmount(sellOrder.amount / 2) val newSignature = crypto.sign(senderSell, sellOrderWithUpdatedAmount.bodyBytes()) val correctedSellOrder = sellOrderWithUpdatedAmount.updateProofs(Proofs(Seq(ByteStr(newSignature)))) (buyOrder, correctedSellOrder) } test(preconditions) } def test(preconditions: Gen[(Order, Order)]): Assertion = forAll(preconditions) { case (buyOrder, sellOrder) => val tc = getExchangeTransactionCreator() val oe = mkOrderExecutedRaw(buyOrder, sellOrder) val tx = tc.createTransaction(oe).explicitGet() tx.buyMatcherFee shouldBe oe.submittedExecutedFee tx.sellMatcherFee shouldBe oe.counterExecutedFee } } } }
Example 39
Source File: Json4sHttpRequestResponseFormatsSpec.scala From reliable-http-client with Apache License 2.0 | 5 votes |
package rhttpc.akkahttp.json4s import java.util.UUID import akka.http.scaladsl.model._ import org.json4s.native.Serialization import org.scalatest._ import org.scalatest.prop.TableDrivenPropertyChecks import rhttpc.client.protocol.{Correlated, Exchange, FailureExchange, SuccessExchange} import rhttpc.client.proxy.{ExhaustedRetry, NonSuccessResponse} class Json4sHttpRequestResponseFormatsSpec extends FlatSpec with TableDrivenPropertyChecks with Matchers { implicit val formats = Json4sHttpRequestResponseFormats.formats val requestsData = Table[Correlated[HttpRequest]]( "request", Correlated(HttpRequest().withMethod(HttpMethods.POST).withEntity("foo"), UUID.randomUUID().toString) ) // FIXME: unignore tests when json4s problem with classloaders will be fixed (test fail only from cmd, from IDE work) ignore should "work round-trip for requests" in { forAll(requestsData) { request => val serialized = Serialization.writePretty(request) println("Serialized: " + serialized) withClue("Serialized: " + serialized) { val deserialized = Serialization.read[Correlated[HttpRequest]](serialized) println("Deserialized: " + deserialized) deserialized shouldEqual request } } } val responsesData = Table[Correlated[Exchange[HttpRequest, HttpResponse]]]( "responses", Correlated(SuccessExchange(HttpRequest(), HttpResponse().withEntity("bar")), UUID.randomUUID().toString), Correlated(FailureExchange(HttpRequest(), ExhaustedRetry(NonSuccessResponse)), UUID.randomUUID().toString) ) ignore should "work round-trip for responses" in { forAll(responsesData) { response => val serialized = Serialization.writePretty(response) println("Serialized: " + serialized) withClue("Serialized: " + serialized) { val deserialized = Serialization.read[Correlated[Exchange[HttpRequest, HttpResponse]]](serialized) println("Deserialized: " + deserialized) deserialized shouldEqual response } } } }
Example 40
Source File: StringIndexerModelSpec.scala From mleap with Apache License 2.0 | 5 votes |
package ml.combust.mleap.core.feature import ml.combust.mleap.core.types.{ScalarType, StructField} import org.scalatest.FunSpec import org.scalatest.prop.TableDrivenPropertyChecks class StringIndexerModelSpec extends FunSpec with TableDrivenPropertyChecks { describe("#apply") { it("returns the index of the string") { val indexer = StringIndexerModel(Array("hello", "there", "dude")) assert(indexer("hello") == 0.0) assert(indexer("there") == 1.0) assert(indexer("dude") == 2.0) } it("throws NullPointerException when encounters NULL/None and handleInvalid is not keep") { val indexer = StringIndexerModel(Array("hello")) assertThrows[NullPointerException](indexer(null)) } it("throws NoSuchElementException when encounters unseen label and handleInvalid is not keep") { val indexer = StringIndexerModel(Array("hello")) val unseenLabels = Table("unknown1", "unknown2") forAll(unseenLabels) { (label: Any) => intercept[NoSuchElementException] { indexer(label) } } } it("returns default index for HandleInvalid.keep mode") { val indexer = StringIndexerModel(Array("hello", "there", "dude"), handleInvalid = HandleInvalid.Keep) val invalidLabels = Table("unknown", "other unknown", null, None) forAll(invalidLabels) { (label: Any) => assert(indexer(label) == 3.0) } } } describe("input/output schema") { val indexer = StringIndexerModel(Array("hello", "there", "dude")) it("has the right input schema") { assert(indexer.inputSchema.fields == Seq(StructField("input", ScalarType.String))) } it("has the right output schema") { assert(indexer.outputSchema.fields == Seq(StructField("output", ScalarType.Double.nonNullable))) } } }
Example 41
Source File: DependencyAnalyzerTest.scala From schedoscope with Apache License 2.0 | 5 votes |
package org.schedoscope.lineage import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{FlatSpec, Matchers, PrivateMethodTester} import org.schedoscope.dsl.Parameter.p import org.schedoscope.dsl.views.DateParameterizationUtils.today import org.schedoscope.lineage.DependencyAnalyzer.{analyzeDependencies, analyzeLineage} import test.views.{ClickOfEC01, ProductBrand} class DependencyAnalyzerTest extends FlatSpec with Matchers with PrivateMethodTester with TableDrivenPropertyChecks { private val preprocessSql = PrivateMethod[String]('preprocessSql) "The dependency analyzer" should "analyze lineage for ProductBrand correctly" in { val v = ProductBrand(p("EC0101"), today._1, today._2, today._3) analyzeLineage(v).get shouldEqual Map( v.occurredAt → Set(v.product().occurredAt), v.productId → Set(v.product().id), v.brandName → Set(v.brand().name), v.createdAt → Set(), v.createdBy → Set() ) } it should "analyze dependencies for ProductBrand correctly" in { val v = ProductBrand(p("EC0201"), today._1, today._2, today._3) analyzeDependencies(v).get shouldEqual Map( v.occurredAt → Set(v.product().occurredAt, v.product().year, v.product().month, v.product().day, v.product().brandId, v.brand().id), v.productId → Set(v.product().id, v.product().year, v.product().month, v.product().day, v.product().brandId, v.brand().id), v.brandName → Set(v.brand().name, v.product().year, v.product().month, v.product().day, v.product().brandId, v.brand().id), v.createdAt → Set(), v.createdBy → Set() ) } it should "analyze lineage for ClickOfEC0101 correctly" in { val v = ClickOfEC01(today._1, today._2, today._3) analyzeLineage(v).get shouldEqual Map( v.id → Set(v.click().id), v.url → Set(v.click().url) ) } it should "analyze dependencies for ClickOfEC0101 correctly" in { val v = ClickOfEC01(today._1, today._2, today._3) analyzeDependencies(v).get shouldEqual Map( v.id → Set(v.click().id, v.click().shopCode), v.url → Set(v.click().url, v.click().shopCode) ) } it should "pre-process SQL by emptying double quoted strings" in { val badSql = """regexp_replace(csv_line_to_array.field_array[0] , "\"", "")""" val goodSql = """regexp_replace(csv_line_to_array.field_array[0] , '', '')""" DependencyAnalyzer invokePrivate preprocessSql(badSql) shouldEqual goodSql } it should "pre-process SQL by emptying double quoted strings with single quotes in them" in { val badSql = """"[\\s,\;.:\\u00bb\\u00ab\"'\\u0060\\u00b4|<>\\-_!\\u00a7a%&/()=?{\\[\\]}\\\\]"""" val goodSql = "''" DependencyAnalyzer invokePrivate preprocessSql(badSql) shouldEqual goodSql } it should "pre-process SQL by emptying strings with escaped single quotes" in { val badSql = """unix_timestamp(last_value(wl.occurred_at) OVER session, 'yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX')""" val goodSql = "unix_timestamp(last_value(wl.occurred_at) OVER session, '')" DependencyAnalyzer invokePrivate preprocessSql(badSql) shouldEqual goodSql } }
Example 42
Source File: HierarchyFieldTest.scala From sparta with Apache License 2.0 | 5 votes |
package com.stratio.sparta.plugin.cube.field.hierarchy import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, Matchers, WordSpecLike} @RunWith(classOf[JUnitRunner]) class HierarchyFieldTest extends WordSpecLike with Matchers with BeforeAndAfter with BeforeAndAfterAll with TableDrivenPropertyChecks { var hbs: Option[HierarchyField] = _ before { hbs = Some(new HierarchyField()) } after { hbs = None } "A HierarchyDimension" should { "In default implementation, get 4 precisions for all precision sizes" in { val precisionLeftToRight = hbs.get.precisionValue(HierarchyField.LeftToRightName, "") val precisionRightToLeft = hbs.get.precisionValue(HierarchyField.RightToLeftName, "") val precisionLeftToRightWithWildCard = hbs.get.precisionValue(HierarchyField.LeftToRightWithWildCardName, "") val precisionRightToLeftWithWildCard = hbs.get.precisionValue(HierarchyField.RightToLeftWithWildCardName, "") precisionLeftToRight._1.id should be(HierarchyField.LeftToRightName) precisionRightToLeft._1.id should be(HierarchyField.RightToLeftName) precisionLeftToRightWithWildCard._1.id should be(HierarchyField.LeftToRightWithWildCardName) precisionRightToLeftWithWildCard._1.id should be(HierarchyField.RightToLeftWithWildCardName) } "In default implementation, every proposed combination should be ok" in { val data = Table( ("i", "o"), ("google.com", Seq("google.com", "*.com", "*")) ) forAll(data) { (i: String, o: Seq[String]) => val result = hbs.get.precisionValue(HierarchyField.LeftToRightWithWildCardName, i) assertResult(o)(result._2) } } "In reverse implementation, every proposed combination should be ok" in { hbs = Some(new HierarchyField()) val data = Table( ("i", "o"), ("com.stratio.sparta", Seq("com.stratio.sparta", "com.stratio.*", "com.*", "*")) ) forAll(data) { (i: String, o: Seq[String]) => val result = hbs.get.precisionValue(HierarchyField.RightToLeftWithWildCardName, i.asInstanceOf[Any]) assertResult(o)(result._2) } } "In reverse implementation without wildcards, every proposed combination should be ok" in { hbs = Some(new HierarchyField()) val data = Table( ("i", "o"), ("com.stratio.sparta", Seq("com.stratio.sparta", "com.stratio", "com", "*")) ) forAll(data) { (i: String, o: Seq[String]) => val result = hbs.get.precisionValue(HierarchyField.RightToLeftName, i.asInstanceOf[Any]) assertResult(o)(result._2) } } "In non-reverse implementation without wildcards, every proposed combination should be ok" in { hbs = Some(new HierarchyField()) val data = Table( ("i", "o"), ("google.com", Seq("google.com", "com", "*")) ) forAll(data) { (i: String, o: Seq[String]) => val result = hbs.get.precisionValue(HierarchyField.LeftToRightName, i.asInstanceOf[Any]) assertResult(o)(result._2) } } } }
Example 43
Source File: ClusterCRC16Spec.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class ClusterCRC16Spec extends AnyWordSpec with Matchers with ScalaCheckDrivenPropertyChecks with TableDrivenPropertyChecks { val examples = Table( ("input", "output"), ("", 0x0), ("123456789", 0x31C3), ("sfger132515", 0xA45C), ("hae9Napahngaikeethievubaibogiech", 0x58CE), ("AAAAAAAAAAAAAAAAAAAAAA", 0x92cd), ("Hello, World!", 0x4FD6) ) "getSlot" should { "yield the same hash for a tag within a string as for the plain tag" in { forAll { (tag: String, left:String, right:String) => whenever(!left.contains("{") && tag.nonEmpty && !tag.contains("}")) { val key = s"$left{$tag}$right" ClusterCRC16.getSlot(key) should be(ClusterCRC16.getSlot(tag)) } } } "solve all examples correctly" in { forAll (examples) { (in:String, out:Int) => ClusterCRC16.getCRC16(in) shouldBe out } } } }
Example 44
Source File: HttpErrorFunctionsSpec.scala From http-verbs with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.http import com.github.ghik.silencer.silent import org.scalacheck.Gen import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.TryValues import org.scalatest.wordspec.AnyWordSpec import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import scala.util.Try @silent("deprecated") class HttpErrorFunctionsSpec extends AnyWordSpec with Matchers with ScalaCheckDrivenPropertyChecks with TableDrivenPropertyChecks with TryValues { "HttpErrorFunctions" should { "return the response if the status code is between 200 and 299" in new HttpErrorFunctions { forAll(Gen.choose(200, 299)) { statusCode: Int => val expectedResponse = HttpResponse(statusCode, "") handleResponse(exampleVerb, exampleUrl)(expectedResponse) should be(expectedResponse) } } "return the correct exception if the status code is 400" in { expectA[BadRequestException](forStatus = 400) } "return the correct exception if the status code is 404" in { expectA[NotFoundException](forStatus = 404) } "return the correct exception for all other status codes" in { forAll(Gen.choose(0, 199))(expectA[Exception](_)) forAll(Gen.choose(400, 499).suchThat(!Seq(400, 404).contains(_)))(expectA[Upstream4xxResponse](_, Some(500))) forAll(Gen.choose(500, 599))(expectA[Upstream5xxResponse](_, Some(502))) forAll(Gen.choose(600, 1000))(expectA[Exception](_)) } } val exampleVerb = "GET" val exampleUrl = "http://example.com/something" val exampleBody = "this is the string body" def expectA[T: Manifest](forStatus: Int, reportStatus: Option[Int] = None): Unit = new HttpErrorFunctions { val e = Try(handleResponse(exampleVerb, exampleUrl)(HttpResponse(forStatus, exampleBody))).failure.exception e should be(a[T]) e.getMessage should (include(exampleUrl) and include(exampleVerb) and include(exampleBody)) reportStatus.map { s => e should have('upstreamResponseCode (forStatus)) e should have('reportAs (s)) } } }
Example 45
Source File: IteratorProcessorTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.obj.value import org.mmadt.language.LanguageException import org.mmadt.processor.Processor import org.mmadt.storage.StorageFactory._ import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{FunSuite, Matchers} assertThrows[LanguageException] { int(10) ===> bool.and(bfalse) } assertThrows[LanguageException] { int(10) ===> str } assertThrows[LanguageException] { int(10) ===> str.q(2) } assertThrows[LanguageException] { str("hello") ===> bool } } }
Example 46
Source File: ContractStreamStepTest.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http package util import com.daml.scalatest.FlatSpecCheckLaws import org.scalatest.prop.GeneratorDrivenPropertyChecks import org.scalatest.prop.TableDrivenPropertyChecks import org.scalatest.{FlatSpec, Matchers} import scalaz.scalacheck.ScalaCheckBinding._ import scalaz.scalacheck.ScalazProperties import scalaz.syntax.apply._ import scalaz.syntax.semigroup._ import scalaz.{@@, Equal, Tag} class ContractStreamStepTest extends FlatSpec with FlatSpecCheckLaws with Matchers with GeneratorDrivenPropertyChecks with TableDrivenPropertyChecks { import ContractStreamStepTest._, ContractStreamStep._ import InsertDeleteStepTest._ override implicit val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfiguration(minSuccessful = 100) behavior of "append" it should "be associative for valid streams" in forAll(validStreamGen) { csses => whenever(csses.size >= 3) { forEvery( Table(("a", "b", "c"), csses.sliding(3).map { case Seq(a, b, c) => (a, b, c) }.toSeq: _*)) { case (a, b, c) => (a |+| (b |+| c)) should ===((a |+| b) |+| c) } } } it should "report the last offset" in forAll { (a: CSS, b: CSS) => def off(css: ContractStreamStep[_, _]) = css match { case Acs(_) => None case LiveBegin(off) => off.toOption case Txn(_, off) => Some(off) } off(a |+| b) should ===(off(b) orElse off(a)) } it should "preserve append across toInsertDelete" in forAll { (a: CSS, b: CSS) => (a |+| b).toInsertDelete should ===(a.toInsertDelete |+| b.toInsertDelete) } behavior of "append semigroup" checkLaws(ScalazProperties.semigroup.laws[CSS]) } object ContractStreamStepTest { import InsertDeleteStepTest._, InsertDeleteStep.Inserts, ContractStreamStep._ import org.scalacheck.{Arbitrary, Gen} import Arbitrary.arbitrary type CSS = ContractStreamStep[Unit, Cid] private val offGen: Gen[domain.Offset] = Tag subst Tag.unsubst(arbitrary[String @@ Alpha]) private val acsGen = arbitrary[Inserts[Cid]] map (Acs(_)) private val noAcsLBGen = Gen const LiveBegin(LedgerBegin) private val postAcsGen = offGen map (o => LiveBegin(AbsoluteBookmark(o))) private val txnGen = ^(arbitrary[IDS], offGen)(Txn(_, _)) private val validStreamGen: Gen[Seq[CSS]] = for { beforeAfter <- Gen.zip( Gen.containerOf[Vector, CSS](acsGen), Gen.containerOf[Vector, CSS](txnGen)) (acsSeq, txnSeq) = beforeAfter liveBegin <- if (acsSeq.isEmpty) noAcsLBGen else postAcsGen } yield (acsSeq :+ liveBegin) ++ txnSeq private implicit val `CSS eq`: Equal[CSS] = Equal.equalA private implicit val `anyCSS arb`: Arbitrary[CSS] = Arbitrary(Gen.frequency((4, acsGen), (1, noAcsLBGen), (1, postAcsGen), (4, txnGen))) }
Example 47
Source File: EqsInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.op.map.EqsOp import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor4} class EqsInstTest extends FunSuite with TableDrivenPropertyChecks { test("[eq] value, type, strm, anon combinations") { val starts: TableFor4[Obj, Obj, Obj, String] = new TableFor4[Obj, Obj, Obj, String](("input", "type", "result", "kind"), //////// INT (int.q(qZero), __.eqs(str.q(qZero)), btrue.q(qZero), "value"), (int(2), int.eqs(1), bfalse, "value"), // value * value = value (int(2).q(10), __.eqs(1), bfalse.q(10), "value"), // value * value = value (int(2).q(10), __.eqs(1).q(20), bfalse.q(200), "value"), // value * value = value (int(2), __.eqs(int(1).q(10)), bfalse, "value"), // value * value = value (int(2), __.eqs(int), btrue, "value"), // value * type = value (int(2), __.eqs(__.mult(int)), bfalse, "value"), // value * anon = value (int, __.eqs(int(2)), int.eqs(int(2)), "type"), // type * value = type (int.q(10), __.eqs(int(2)), int.q(10).eqs(2), "type"), // type * value = type (int, __.eqs(int), int.eqs(int), "type"), // type * type = type (int(1, 2, 3), __.eqs(2), bool(false, true, false), "strm"), // strm * value = strm (int(1, 2, 3), __.eqs(int(2).q(10)), bool(false, true, false), "strm"), // strm * value = strm (int(1, 2, 3), __.eqs(int(2)).q(10), bool(bfalse.q(10), btrue.q(10), bfalse.q(10)), "strm"), // strm * value = strm (int(1, 2, 3), __.eqs(int), bool(true, true, true), "strm"), // strm * type = strm (int(1, 2, 3), __.eqs(__.mult(int)), bool(true, false, false), "strm"), // strm * anon = strm //////// REAL (real(2.0), __.eqs(1.0), bfalse, "value"), // value * value = value (real(2.0), __.eqs(real), btrue, "value"), // value * type = value (real(2.0), __.eqs(__.mult(real)), bfalse, "value"), // value * anon = value (real, __.eqs(real(2.0)), real.eqs(2.0), "type"), // type * value = type (real, __.eqs(real), real.eqs(real), "type"), // type * type = type (real(1.0, 2.0, 3.0), __.eqs(2.0), bool(false, true, false), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0), __.eqs(real), bool(true, true, true), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0), __.eqs(__.mult(real)), bool(true, false, false), "strm"), // strm * anon = strm ) forEvery(starts) { (input, atype, result, kind) => { List( EqsOp(atype.trace.head._2.arg0).q(atype.trace.head._2.q).exec(input), input.compute(asType(atype)), input ===> (input.range ===> atype), input ===> atype, input ==> asType(atype)).foreach(x => { assertResult(result)(x) kind match { case "value" => assert(x.isInstanceOf[Value[_]]) case "type" => assert(x.isInstanceOf[Type[_]]) case "strm" => assert(x.isInstanceOf[Strm[_]]) } }) } } } }
Example 48
Source File: PathInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.obj.`type`.__ import org.mmadt.language.obj.op.map.PathOp import org.mmadt.language.obj.value.IntValue import org.mmadt.language.obj.{Lst, Obj} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class PathInstTest extends FunSuite with TableDrivenPropertyChecks { test("[path] value, type, strm") { val starts: TableFor3[Obj, Obj, Obj] = new TableFor3[Obj, Obj, Obj](("input", "type", "result"), (str("a"), __.plus("b").plus("c").path(), str("a") `;` "ab" `;` "abc"), (str("a"), __.plus("b").plus(__.plus("c").plus("d")).plus("e").path(), str("a") `;` "ab" `;` "ababcd" `;` "ababcde"), //(str("a"), __.plus("b").plus(__.plus("c").plus("d")).plus("e").path().get(1).path(), str("a")`;` "ab"`;` "ababcd"`;` "ababcde"), (int(1, 2, 3), __.plus(1).path(), strm(List[Lst[IntValue]](int(1) `;` 2, int(2) `;` 3, int(3) `;` 4))), (int(1, 2, 3), __.plus(1).plus(2).path(), strm(List[Lst[IntValue]](int(1) `;` 2 `;` 4, int(2) `;` 3 `;` 5, int(3) `;` 4 `;` 6))), ) forEvery(starts) { (input, atype, result) => { List( //new mmlangScriptEngineFactory().getScriptEngine.eval(s"${input}${atype}"), PathOp().q(atype.trace.head._2.q).exec(input), input.compute(asType(atype)), input ===> atype.start(), ).foreach(x => { assertResult(result)(x) }) } } } test("[path] w/ int value") { assertResult(int(0) `;` int(1) `;` int(3) `;` int(6) `;` int(10))(int(0).plus(1).plus(2).plus(3).plus(4).path()) } }
Example 49
Source File: LtInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory.{bfalse, bool, btrue, int, real} import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class LtInstTest extends FunSuite with TableDrivenPropertyChecks { test("[lt] value, type, strm, anon combinations") { val starts: TableFor3[Obj, Obj, String] = new TableFor3[Obj, Obj, String](("query", "result", "type"), //////// INT (int(2).lt(1), bfalse, "value"), // value * value = value (int(2).q(10).lt(1), bfalse.q(10), "value"), // value * value = value (int(2).q(10).lt(1).q(20), bfalse.q(200), "value"), // value * value = value (int(2).lt(int(1).q(10)), bfalse, "value"), // value * value = value (int(2).lt(int), bfalse, "value"), // value * type = value (int(2).lt(__.mult(int)), btrue, "value"), // value * anon = value (int.lt(int(2)), int.lt(int(2)), "type"), // type * value = type (int.q(10).lt(int(2)), int.q(10).lt(int(2)), "type"), // type * value = type (int.lt(int), int.lt(int), "type"), // type * type = type (int(1, 2, 3).lt(2), bool(true, false, false), "strm"), // strm * value = strm (int(1, 2, 3).lt(int(2).q(10)), bool(true, false, false), "strm"), // strm * value = strm (int(1, 2, 3) ==> __.lt(int(2)).q(10), bool(btrue.q(10), bfalse.q(10), bfalse.q(10)), "strm"), // strm * value = strm (int(1, 2, 3).lt(int), bool(false, false, false), "strm"), // strm * type = strm (int(1, 2, 3).lt(__.mult(int)), bool(false, true, true), "strm"), // strm * anon = strm //////// REAL (real(2.0).lt(1.0), bfalse, "value"), // value * value = value (real(2.0).lt(real), bfalse, "value"), // value * type = value (real(2.0).lt(__.mult(real)), true, "value"), // value * anon = value (real.lt(real(2.0)), real.lt(2.0), "type"), // type * value = type (real.lt(real), real.lt(real), "type"), // type * type = type (real(1.0, 2.0, 3.0).lt(2.0), bool(true, false, false), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0).lt(real), bool(false, false, false), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0).lt(__.mult(real)), bool(false, true, true), "strm"), // strm * anon = strm ) forEvery(starts) { (query, result, atype) => { //assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } }
Example 50
Source File: JuxtaInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.Tokens import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj._ import org.mmadt.language.obj.op.trace.JuxtaOp import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor2} class JuxtaInstTest extends FunSuite with TableDrivenPropertyChecks { test("[juxta] value, type, strm, anon combinations") { val starts: TableFor2[List[Obj], Obj] = new TableFor2[List[Obj], Obj](("query", "result"), // value/value (List(int(1).q(5)), int(1).q(5)), (List(int(1), int(2), int(3)), int(3)), (List(int(1), int(2).q(10), int(3)), int(3).q(10)), (List(int(1), int(2).q(10), int(3).q(2)), int(3).q(20)), // value/type (List[Int](int(1), int.plus(1)), int(2)), (List[Int](int(1), int.plus(10)), int(11)), (List[Int](int(1), int.plus(int)), int(2)), (List[Int](int(1), int.plus(int.plus(2))), int(4)), (List[Obj](int(1), int.plus(int.plus(2)).as(str), str.plus("a")), str("4a")), (List[Int](int(1), int.plus(1).q(0)), int(2).q(qZero)), // type/value (List[Int](int.plus(1), int(1)), int(1)), (List[Str](str, str("marko")), str("marko")), (List[Real](real.plus(1.0).q(10), real(13.0).q(2)), real(13.0).q(20)), // type/type (List(str), str), (List(str, str.id()), str.id()), (List(int, int.plus(1), int.plus(2)), int.plus(1).plus(2)), ) forEvery(starts) { (left, right) => { println(left.map(_.toString).reduce((a, b) => a + Tokens.juxt_op + b)) // assertResult(right)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${left.map(_.toString).reduce((a, b) => a + "=>" + b)}")) assertResult(right)(left.reduce((a, b) => a `=>` b)) assertResult(right)(left.reduce((a, b) => JuxtaOp(b).exec(a))) } } } }
Example 51
Source File: GteInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory.{bfalse, bool, btrue, int, real} import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class GteInstTest extends FunSuite with TableDrivenPropertyChecks { test("[gte] value, type, strm, anon combinations") { val starts: TableFor3[Obj, Obj, String] = new TableFor3[Obj, Obj, String](("query", "result", "type"), //////// INT (int(2).gte(1), btrue, "value"), // value * value = value (int(2).q(10).gte(1), btrue.q(10), "value"), // value * value = value (int(2).q(10).gte(1).q(20), btrue.q(200), "value"), // value * value = value (int(2).gte(int(1).q(10)), btrue, "value"), // value * value = value (int(2).gte(int), btrue, "value"), // value * type = value (int(2).gte(__.mult(int)), bfalse, "value"), // value * anon = value (int.gte(int(2)), int.gte(int(2)), "type"), // type * value = type (int.q(10).gte(int(2)), int.q(10).gte(2), "type"), // type * value = type (int.gte(int), int.gte(int), "type"), // type * type = type (int(1, 2, 3).gte(2), bool(false, true, true), "strm"), // strm * value = strm (int(1, 2, 3).gte(int(2).q(10)), bool(false, true, true), "strm"), // strm * value = strm //(int(1, 2, 3).gte(int(2)).q(10), bool(bfalse.q(10), btrue.q(10), btrue.q(10)), "strm"), // strm * value = strm //(int(1, 2, 3).gte(int(2)).q(10).id(), bool(bfalse.q(10), btrue.q(10), btrue.q(10)), "strm"), // strm * value = strm //(int(1, 2, 3).gte(int(2)).q(10).id().q(5), bool(bfalse.q(50), btrue.q(50), btrue.q(50)), "strm"), // strm * value = strm (int(1, 2, 3).gte(int), bool(true, true, true), "strm"), // strm * type = strm (int(1, 2, 3).gte(__.mult(int)), bool(true, false, false), "strm"), // strm * anon = strm //////// REAL (real(2.0).gte(1.0), btrue, "value"), // value * value = value (real(2.0).gte(real), btrue, "value"), // value * type = value (real(2.0).gte(__.mult(real)), bfalse, "value"), // value * anon = value (real.gte(real(2.0)), real.gte(2.0), "type"), // type * value = type (real.gte(real), real.gte(real), "type"), // type * type = type (real(1.0, 2.0, 3.0).gte(2.0), bool(false, true, true), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0).gte(real), bool(true, true, true), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0).gte(__.mult(real)), bool(true, false, false), "strm"), // strm * anon = strm ) forEvery(starts) { (query, result, atype) => { assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } }
Example 52
Source File: MapInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} , "value"), // value * value = value (int(2).map(int), int(2), "value"), // value * type = value (int(2).map(__.mult(int)), int(4), "value"), // value * anon = value (int.map(int(2)), int.map(int(2)), "type"), // type * value = type (int.q(10).map(int(2)), int.q(10).map(int(2)), "type"), // type * value = type (int.map(int), int.map(int), "type"), // type * type = type (int(1, 2, 3).map(2), int(2, 2, 2), "strm"), // strm * value = strm //(int(1, 2, 3).map(int(2).q(10)), int(int(2).q(10), int(2).q(10), int(2).q(10)), "strm"), // strm * value = strm (int(1, 2, 3) ===> __.map(int(2)).q(10), int(int(2).q(10), int(2).q(10), int(2).q(10)), "strm"), // strm * value = strm (int(1, 2, 3).map(int), int(1, 2, 3), "strm"), // strm * type = strm (int(1, 2, 3).map(int.mult(int)), int(1, 4, 9), "strm"), // strm * type = strm (int(1, 2, 3).map(__.mult(int)), int(1, 4, 9), "strm"), // strm * anon = strm //////// REAL (real(2.0).map(real(1.0)), real(1.0), "value"), // value * value = value (real(2.0).map(real), real(2.0), "value"), // value * type = value (real(2.0).map(__.mult(real)), real(4.0), "value"), // value * anon = value (real.map(real(2.0)), real.map(2.0), "type"), // type * value = type (real.map(real), real.map(real), "type"), // type * type = type (real(1.0, 2.0, 3.0).map(2.0), real(2.0, 2.0, 2.0), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0).map(real), real(1.0, 2.0, 3.0), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0).map(__.mult(real)), real(1.0, 4.0, 9.0), "strm"), // strm * anon = strm ) forEvery(starts) { (query, result, atype) => { //assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } test("[map] w/ values") { assertResult(int(5))(int(1).plus(1).map(int(5))) assertResult(int(2))(int(1).plus(1).map(int)) assertResult(int(20))(int(1).plus(1).map(int.mult(10))) } test("[map] w/ types") { assertResult("int[plus,1][map,int]")(int.plus(1).map(int).toString) assertResult("int[plus,1][map,int[mult,10]]")(int.plus(1).map(int.mult(10)).toString) assertResult(int(200))(int(18) ==> int.plus(1).map(int.mult(10)).plus(10)) assertResult("int[plus,1][map,int[mult,10]]")(int.plus(1).map(int.mult(10)).toString) // assertResult(int(60))(int(5) ==> int.plus(1).map(int.mult(10))) } }
Example 53
Source File: ZeroInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.__ import org.mmadt.language.obj.op.map.ZeroOp import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class ZeroInstTest extends FunSuite with TableDrivenPropertyChecks { test("[zero] value, type, strm") { val starts: TableFor3[Obj, Obj, Obj] = new TableFor3[Obj, Obj, Obj](("input", "type", "result"), //////// INT (int(2), __.zero(), int(0)), (int(-2), __.zero(), int(0)), (int, __.zero(), int(0)), (int(1, 2, 3), __.zero(), int(0).q(3)), (int(1, 2), __.plus(1).q(10).zero(), int(0).q(20)), //////// REAL (real(2.0), __.zero(), real(0.0)), (real(-2.0), __.zero(), real(0.0)), (real, __.zero(), real(0.0)), (real(-1.0, -2.0, -3.0), __.zero(), real(0.0).q(3)), (real(-1.0, -2.0, -3.0), __.plus(1.0).q(10).zero(), real(0.0).q(30)), (real(-1.0, -2.0, -3.0), __.plus(1.0).q(20).zero(), real(0.0).q(60)), //////// STR (str("a"), __.zero(), str("")), (str("b"), __.zero(), str("")), (str, __.zero(), str("")), (str("a", "b", "c"), __.zero(), str("").q(3)), //////// PROD //(`;`(str("a")), __.zero(), `;`()), //(prod(prod(str("a")), prod(str("b")), prod(str("c"))).zero(), prod().q(3)), ) forEvery(starts) { (input, atype, result) => { List( //new mmlangScriptEngineFactory().getScriptEngine.eval(s"${input}${atype}"), ZeroOp().q(atype.trace.head._2.q).exec(input), input.compute(asType(atype)), input ===> atype.start(), ).foreach(x => { assertResult(result)(x) }) } } } }
Example 54
Source File: IdInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.Type import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class IdInstTest extends FunSuite with TableDrivenPropertyChecks { test("[id] value, type, strm") { val starts: TableFor3[Obj, Obj, String] = new TableFor3[Obj, Obj, String](("query", "result", "type"), //////// INT (int(2).id(), int(2), "value"), (int(-2).id(), int(-2), "value"), (int.id(), int.id(), "type"), (int(1, 2, 3).id(), int(1, 2, 3), "strm"), //////// REAL (real(2.0).id(), real(2.0), "value"), (real(2.0).id().q(10), real(2.0).q(10), "value"), (real(2.0).q(5).id().q(10), real(2.0).q(50), "value"), (real(-2.0).one(), real(1.0), "value"), (real.id(), real.id(), "type"), (real(1.0, 2.0, 3.0).id(), real(1.0, 2.0, 3.0), "strm"), (real(1.0, 2.0, 3.0).id().q(10), real(real(1.0).q(10), real(2.0).q(10), real(3.0).q(10)), "strm"), (real(1.0, 2.0, 3.0).id().q(10).id(), real(real(1.0).q(10), real(2.0).q(10), real(3.0).q(10)), "strm"), (real(1.0, 2.0, 3.0).id().q(10).id().q(5), real(real(1.0).q(50), real(2.0).q(50), real(3.0).q(50)), "strm"), //////// STR (str("a").id(), str("a"), "value"), (str.id(), str.id(), "type"), (str("a", "b", "c").id(), str("a", "b", "c"), "strm"), ) forEvery(starts) { (query, result, atype) => { // assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"[${query}]")) assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } }
Example 55
Source File: PlusInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.obj.Obj._ import org.mmadt.language.obj.`type`.{IntType, RealType, Type, __} import org.mmadt.language.obj.op.map.PlusOp import org.mmadt.language.obj.value.strm.Strm import org.mmadt.language.obj.value.{IntValue, RealValue, Value} import org.mmadt.language.obj.{Int, Obj, Real} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor4} class PlusInstTest extends FunSuite with TableDrivenPropertyChecks { test("[plus] value, type, strm, anon combinations") { val starts: TableFor4[Obj, Obj, Obj, String] = new TableFor4[Obj, Obj, Obj, String](("input", "type", "result", "kind"), //////// INT (int(2), __.plus(2), int(4), "value"), // value * value = value (int(2).q(10), __.plus(2), int(4).q(10), "value"), // value * value = value (int(2).q(10), __.plus(2).q(20), int(4).q(200), "value"), // value * value = value (int(2), __.plus(int(2).q(10)), int(4), "value"), // value * value = value (int(2), __.plus(int), int(4), "value"), // value * type = value (int(2), __.plus(__.plus(int)), int(6), "value"), // value * anon = value (int, __.plus(int(2)), int.plus(int(2)), "type"), // type * value = type (int.q(10), __.plus(int(2)), int.q(10).plus(int(2)), "type"), // type * value = type (int, __.plus(int), int.plus(int), "type"), // type * type = type (int(1, 2, 3), __.plus(2), int(3, 4, 5), "strm"), // strm * value = strm (int(1, 2, 3), __.plus(int(2).q(10)), int(3, 4, 5), "strm"), // strm * value = strm (int(1, 2, 3), int.q(3).plus(int(2)).q(10), int(int(3).q(10), int(4).q(10), int(5).q(10)), "strm"), // strm * value = strm (int(1, 2, 3), __.plus(int(2)).q(10), int(int(3).q(10), int(4).q(10), int(5).q(10)), "strm"), // strm * value = strm (int(1, 2, 3), __.plus(int), int(2, 4, 6), "strm"), // strm * type = strm (int(1, 2, 3), __.plus(__.plus(int)), int(3, 6, 9), "strm"), // strm * anon = strm //////// REAL (real(2.0), __.plus(2.0), real(4), "value"), // value * value = value (real(2.0), __.plus(real), real(4.0), "value"), // value * type = value (real(2.0), __.plus(__.plus(real)), real(6.0), "value"), // value * anon = value (real, __.plus(real(2.0)), real.plus(real(2.0)), "type"), // type * value = type (real, __.plus(real), real.plus(real), "type"), // type * type = type (real(1.0, 2.0, 3.0), __.plus(2.0), real(3.0, 4.0, 5.0), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0), __.plus(real), real(2.0, 4.0, 6.0), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0), __.plus(__.plus(real)), real(3.0, 6.0, 9.0), "strm"), // strm * anon = strm ) forEvery(starts) { (input, atype, result, kind) => { List( // new mmlangScriptEngineFactory().getScriptEngine.eval(s"${input}${atype}"), PlusOp(atype.trace.head._2.arg0).q(atype.trace.head._2.q).exec(input), input.compute(asType(atype)), input ===> (input.range ===> atype), input ===> atype, input ==> asType(atype)).foreach(x => { assertResult(result)(x) kind match { case "value" => assert(x.isInstanceOf[Value[_]]) case "type" => assert(x.isInstanceOf[Type[_]]) case "strm" => assert(x.isInstanceOf[Strm[_]]) } }) } } } /////////////////////////////////////////////////////////////////////// test("[plus] w/ int") { assertResult(int(4))(int(1).plus(int(3))) // value * value = value assert(int(1).plus(int(3)).isInstanceOf[IntValue]) assert(int(1).plus(int(3)).isInstanceOf[Int]) assertResult(int(2))(int(1).plus(int)) // value * type = value assert(int(1).plus(int).isInstanceOf[IntValue]) assert(int(1).plus(int).isInstanceOf[Int]) assertResult(int.plus(int(3)))(int.plus(int(3))) // type * value = type assert(int.plus(int(3)).isInstanceOf[IntType]) assert(int.plus(int(3)).isInstanceOf[Int]) assertResult(int.plus(int))(int.plus(int)) // type * type = type assert(int.plus(int).isInstanceOf[IntType]) assert(int.plus(int).isInstanceOf[Int]) } test("[plus] w/ real") { assertResult(real(4.0))(real(1).plus(real(3))) // value * value = value assert(real(1).plus(real(3)).isInstanceOf[RealValue]) assert(real(1).plus(real(3)).isInstanceOf[Real]) assertResult(real(2))(real(1).plus(real)) // value * type = value assert(real(1).plus(real).isInstanceOf[RealValue]) assert(real(1).plus(real).isInstanceOf[Real]) assertResult(real.plus(real(3)))(real.plus(real(3))) // type * value = type assert(real.plus(real(3)).isInstanceOf[RealType]) assert(real.plus(real(3)).isInstanceOf[Real]) assertResult(real.plus(real))(real.plus(real)) // type * type = type assert(real.plus(real).isInstanceOf[RealType]) assert(real.plus(real).isInstanceOf[Real]) } }
Example 56
Source File: OneInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj import org.mmadt.language.obj.`type`.__ import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor2} class OneInstTest extends FunSuite with TableDrivenPropertyChecks { test("[one] value, type, strm") { val starts: TableFor2[Obj, Obj] = new TableFor2[Obj, Obj](("query", "result"), //////// INT (int(2).one(), int(1)), (int(2).one().q(10), int(1).q(10)), (int(2).q(10).one(), int(1).q(10)), (int(2).q(10).one().q(20), int(1).q(200)), (int(-2).one(), int(1)), (int.one(), int(1)), (int.one().q(10), int(1).q(10)), (int.q(10).one(), int(1).q(10)), (int.q(10).one().q(20), int(1).q(200)), (int(1, 2, 3).one(), int(1).q(3)), //////// REAL (real(2.0).one(), real(1.0)), (real(-2.0).one(), real(1.0)), (real.one(), real(1.0)), (real(-1.0, -2.0, -3.0).one(), real(1.0).q(3)), (real(-1.0, -2.0, -3.0).id().q(10).one(), real(1.0).q(30)), (real(-1.0, -2.0, -3.0) ===> __.q(3).id().q(10).one(), real(1.0).q(30)), (real(-1.0, -2.0, -3.0).id().q(10).one(), real(1.0).q(30)), (real(-1.0, -2.0, -3.0).q(3).id().q(10).one(), real(1.0).q(90)), ) forEvery(starts) { (query, result) => { assertResult(result)(query) assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) } } } }
Example 57
Source File: TailInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.LanguageException import org.mmadt.language.obj.Obj._ import org.mmadt.language.obj.`type`.__ import org.mmadt.language.obj.{Lst, Obj} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor2} class TailInstTest extends FunSuite with TableDrivenPropertyChecks { test("[tail] anonymous type") { assertResult("b" |)(("a" | "b") ===> __.tail()) assertResult("b" | "c")(("a" | "b" | "c") ===> __.tail()) // assertResult("b" `;`)(("a" `;` "b") ===> __.tail()) assertResult("b" `;` "c")(("a" `;` "b" `;` "c") ===> __.tail()) } test("[tail] w/ parallel poly]") { val check: TableFor2[Lst[_], Obj] = new TableFor2(("parallel", "tail"), (str("a") |, lst("|") <= (str("a") |).tail()), (str("a") | "b", str("b") |), (str("a") | "b" | "c", str("b") | str("c")), (str("d") | "b" | "c", str("b") | str("c")), ) forEvery(check) { (left, right) => { assertResult(right)(left.tail()) } } } test("[tail] exception") { assertThrows[LanguageException] { lst.tail() } } test("[tail] w/ serial poly") { val check: TableFor2[Lst[_], Obj] = new TableFor2(("serial", "tail"), //(str("a") /, /), (str("a") `;` "b", str("b") `;`), (str("a") `;` "b" `;` "c", str("b") `;` "c"), (str("d") `;` "b" `;` "c", str("b") `;` "c"), ) forEvery(check) { (left, right) => { assertResult(right)(left.tail()) } } } }
Example 58
Source File: OrInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.op.map.OrOp import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.language.obj.{Bool, Obj} import org.mmadt.storage.StorageFactory.{asType, bfalse, bool, btrue, int} import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor1, TableFor4} class OrInstTest extends FunSuite with TableDrivenPropertyChecks { test("[or] value, type, strm, anon combinations") { val starts: TableFor4[Obj, Obj, Obj, String] = new TableFor4[Obj, Obj, Obj, String](("input", "type", "result", "kind"), (bfalse, __.or(btrue), btrue, "value"), // value * value = value (bfalse, __.or(bool), bfalse, "value"), // value * type = value (bfalse, __.or(__.or(bool)), bfalse, "value"), // value * anon = value (bool, __.or(btrue), bool.or(btrue), "type"), // type * value = type (bool, __.or(bool), bool.or(bool), "type"), // type * type = type (bool(true, true, false), __.or(btrue), bool(true, true, true), "strm"), // strm * value = strm (bool(true, true, false), __.or(bool), bool(true, true, false), "strm"), // strm * type = strm (bool(true, true, false), __.or(__.or(bool)), bool(true, true, false), "strm"), // strm * anon = strm ) forEvery(starts) { (input, atype, result, kind) => { List( //new mmlangScriptEngineFactory().getScriptEngine.eval(s"${input}${atype.toString}"), OrOp(atype.trace.head._2.arg0).q(atype.trace.head._2.q).exec(input.asInstanceOf[Bool]), input.compute(asType(atype)), input ===> (input.range ===> atype), input ===> atype, input ==> asType(atype)).foreach(x => { assertResult(result)(x) kind match { case "value" => assert(x.isInstanceOf[Value[_]]) case "type" => assert(x.isInstanceOf[Type[_]]) case "strm" => assert(x.isInstanceOf[Strm[_]]) } }) } } } test("[or] testing") { def maker(x: Obj with OrOp): Obj = x.q(2).or(bfalse).q(3).or(bfalse).q(10) val starts: TableFor1[OrOp with Obj] = new TableFor1("obj", bool, btrue, bfalse) forEvery(starts) { obj => { val expr = maker(obj) obj match { case value: Value[_] => assert(value.g == expr.asInstanceOf[Value[_]].g) case _ => } assert(obj.q != expr.q) assertResult(2)(expr.trace.length) assertResult((int(60), int(60)))(expr.q) assertResult((obj.q(2), OrOp(bfalse).q(3)))(expr.trace.head) assertResult((obj.q(2).or(bfalse).q(3), OrOp(bfalse).q(10)))(expr.trace.last) } } } }
Example 59
Source File: MultInstTest.scala From vm with GNU Affero General Public License v3.0 | 5 votes |
package org.mmadt.processor.inst.map import org.mmadt.language.mmlang.mmlangScriptEngineFactory import org.mmadt.language.obj.Obj._ import org.mmadt.language.obj.`type`.{Type, __} import org.mmadt.language.obj.value.Value import org.mmadt.language.obj.value.strm.Strm import org.mmadt.language.obj.{Lst, Obj} import org.mmadt.storage.StorageFactory._ import org.scalatest.FunSuite import org.scalatest.prop.{TableDrivenPropertyChecks, TableFor3} class MultInstTest extends FunSuite with TableDrivenPropertyChecks { test("[mult] value, type, strm, anon combinations") { val starts: TableFor3[Obj, Obj, String] = new TableFor3[Obj, Obj, String](("query", "result", "type"), //////// INT (int(2).mult(2), int(4), "value"), // value * value = value (int(2).q(10).mult(2), int(4).q(10), "value"), // value * value = value (int(2).q(10).mult(2).q(20), int(4).q(200), "value"), // value * value = value (int(2).mult(int(2).q(10)), int(4), "value"), // value * value = value (int(2).mult(int), int(4), "value"), // value * type = value (int(2).mult(__.mult(int)), int(8), "value"), // value * anon = value (int.mult(int(2)), int.mult(int(2)), "type"), // type * value = type (int.q(10).mult(int(2)), int.q(10).mult(int(2)), "type"), // type * value = type (int.mult(int), int.mult(int), "type"), // type * type = type (int(1, 2, 3).mult(2), int(2, 4, 6), "strm"), // strm * value = strm (int(1, 2, 3).mult(int(2).q(10)), int(2, 4, 6), "strm"), // strm * value = strm (int(1, 2, 3).mult(int(2)).q(10), int(int(2).q(10), int(4).q(10), int(6).q(10)), "strm"), // strm * value = strm (int(1, 2, 3).mult(int), int(1, 4, 9), "strm"), // strm * type = strm (int(1, 2, 3).mult(__.mult(int)), int(1, 8, 27), "strm"), // strm * anon = strm //////// REAL (real(2.0).mult(2.0), real(4), "value"), // value * value = value (real(2.0).mult(real), real(4.0), "value"), // value * type = value (real(2.0).mult(__.mult(real)), real(8.0), "value"), // value * anon = value (real.mult(real(2.0)), real.mult(real(2.0)), "type"), // type * value = type (real.mult(real), real.mult(real), "type"), // type * type = type (real(1.0, 2.0, 3.0).mult(2.0), real(2.0, 4.0, 6.0), "strm"), // strm * value = strm (real(1.0, 2.0, 3.0).mult(real), real(1.0, 4.0, 9.0), "strm"), // strm * type = strm (real(1.0, 2.0, 3.0).mult(__.mult(real)), real(1.0, 8.0, 27.0), "strm"), // strm * anon = strm //////// POLY //(("a" |).mult(("1" /).asInstanceOf[Poly[Obj]]), "a" / "1", "value"), (("a" `;`).mult(("1" `;`).asInstanceOf[Lst[Obj]]), "a" `;` "1", "value"), (("a" `;`).mult("1" |[Obj] "2"), ("a" `;` "1") | ("a" `;` "2"), "value"), (("a" `;` "b" `;` "c").mult("1" |[Obj] "2"), ("a" `;` "b" `;` "c" `;` "1") | ("a" `;` "b" `;` "c" `;` "2"), "value"), (("a" `;` "b" `;` "c").mult("1" `;`[Obj] "2"), "a" `;` "b" `;` "c" `;` "1" `;` "2", "value"), (("a" | "b" | "c").mult("1" `;`[Obj] "2"), lst[Obj]("|", values = List(("a" `;` "1" `;` "2"), ("b" `;` "1" `;` "2"), ("c" `;` "1" `;` "2")): _*), "value"), //(("a" | "b" | "c").mult("1" |[Obj] "2"), lst[Obj]("|", values = ("a" | "1") | ("a" | "2") | ("b" | "1") | ("b" | "2") | ("c" | "1") | ("c" | "2")), "value") ) forEvery(starts) { (query, result, atype) => { //assertResult(result)(new mmlangScriptEngineFactory().getScriptEngine.eval(s"${query}")) assertResult(result)(query) atype match { case "value" => assert(query.isInstanceOf[Value[_]]) case "type" => assert(query.isInstanceOf[Type[_]]) case "strm" => assert(query.isInstanceOf[Strm[_]]) } } } } }