code
stringlengths 5
1M
| repo_name
stringlengths 5
109
| path
stringlengths 6
208
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1M
|
---|---|---|---|---|---|
package scalaxb.compiler.xsd
sealed trait NamespaceKind
case object SchemaKind extends NamespaceKind
case object XsdTypeKind extends NamespaceKind
case object GroupKind extends NamespaceKind
case object AttributeGroupKind extends NamespaceKind
case class NameKey(kind: NamespaceKind, namespace: Option[String], name: String)
object NameKey {
implicit def toNameKey(schema: SchemaDecl): NameKey =
NameKey(SchemaKind, schema.targetNamespace, schema.hashCode().toString)
implicit def toNameKey(decl: SimpleTypeDecl): NameKey =
NameKey(XsdTypeKind, decl.namespace, decl.name)
implicit def toNameKey(decl: ComplexTypeDecl): NameKey =
NameKey(XsdTypeKind, decl.namespace, decl.name)
implicit def toNameKey(group: GroupDecl): NameKey =
NameKey(GroupKind, group.namespace, group.name)
implicit def toNameKey(group: AttributeGroupDecl): NameKey =
NameKey(AttributeGroupKind, group.namespace, group.name)
implicit def toNameKey(decl: Decl): NameKey = decl match {
case x: SchemaDecl => toNameKey(x)
case x: SimpleTypeDecl => toNameKey(x)
case x: ComplexTypeDecl => toNameKey(x)
case x: GroupDecl => toNameKey(x)
case x: AttributeGroupDecl => toNameKey(x)
case _ => sys.error("unexpected Decl: " + decl.toString)
}
}
|
eed3si9n/scalaxb
|
cli/src/main/scala/scalaxb/compiler/xsd/NameKey.scala
|
Scala
|
mit
| 1,267 |
package ru.arkoit.finchrich.controller
import io.finch._
import org.scalatest.{FlatSpec, Inside, Matchers}
class EndpointExtractorSpec extends FlatSpec with Matchers with Fixtures {
behavior of "EndpointExtractor"
it should "transform controller to an endpoint" in {
val cnt = new ComplexController()
val ep = cnt.toEndpoint
checkEndpointType(ep)
ep.toServiceAs[Text.Plain]
}
}
|
akozhemiakin/finchrich
|
controller/src/test/scala/ru/arkoit/finchrich/controller/EndpointExtractorSpec.scala
|
Scala
|
apache-2.0
| 403 |
package scala.slick.jdbc
import scala.language.higherKinds
import scala.collection.generic.CanBuildFrom
import java.sql.{ResultSet, Blob, Clob, Date, Time, Timestamp}
import java.io.Closeable
import scala.slick.util.{ReadAheadIterator, CloseableIterator}
/**
* A database result positioned at a row and column.
*/
abstract class PositionedResult(val rs: ResultSet) extends Closeable { outer =>
protected[this] var pos = Int.MaxValue
protected[this] val startPos = 0
lazy val numColumns = rs.getMetaData().getColumnCount()
final def currentPos = pos
final def hasMoreColumns = pos < numColumns
final def skip = { pos += 1; this }
final def restart = { pos = startPos; this }
final def rewind = { pos = Int.MinValue; this }
def nextRow = {
val ret = (pos == Int.MinValue) || rs.next
pos = startPos
ret
}
final def << [T](implicit f: GetResult[T]): T = f(this)
final def <<? [T](implicit f: GetResult[Option[T]]): Option[T] = if(hasMoreColumns) this.<< else None
final def nextBoolean() = { val npos = pos + 1; val r = rs getBoolean npos; pos = npos; r }
final def nextBigDecimal() = { val npos = pos + 1; val r = rs getBigDecimal npos; pos = npos; if(r eq null) null else BigDecimal(r) }
final def nextBlob() = { val npos = pos + 1; val r = rs getBlob npos; pos = npos; r }
final def nextByte() = { val npos = pos + 1; val r = rs getByte npos; pos = npos; r }
final def nextBytes() = { val npos = pos + 1; val r = rs getBytes npos; pos = npos; r }
final def nextClob() = { val npos = pos + 1; val r = rs getClob npos; pos = npos; r }
final def nextDate() = { val npos = pos + 1; val r = rs getDate npos; pos = npos; r }
final def nextDouble() = { val npos = pos + 1; val r = rs getDouble npos; pos = npos; r }
final def nextFloat() = { val npos = pos + 1; val r = rs getFloat npos; pos = npos; r }
final def nextInt() = { val npos = pos + 1; val r = rs getInt npos; pos = npos; r }
final def nextLong() = { val npos = pos + 1; val r = rs getLong npos; pos = npos; r }
final def nextObject() = { val npos = pos + 1; val r = rs getObject npos; pos = npos; r }
final def nextShort() = { val npos = pos + 1; val r = rs getShort npos; pos = npos; r }
final def nextString() = { val npos = pos + 1; val r = rs getString npos; pos = npos; r }
final def nextTime() = { val npos = pos + 1; val r = rs getTime npos; pos = npos; r }
final def nextTimestamp() = { val npos = pos + 1; val r = rs getTimestamp npos; pos = npos; r }
final def wasNull() = rs.wasNull
final def nextBooleanOption() = { val npos = pos + 1; val r = rs getBoolean npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextBigDecimalOption() = { val npos = pos + 1; val r = rs getBigDecimal npos; val rr = (if(rs.wasNull) None else Some(BigDecimal(r))); pos = npos; rr }
final def nextBlobOption() = { val npos = pos + 1; val r = rs getBlob npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextByteOption() = { val npos = pos + 1; val r = rs getByte npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextBytesOption() = { val npos = pos + 1; val r = rs getBytes npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextClobOption() = { val npos = pos + 1; val r = rs getClob npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextDateOption() = { val npos = pos + 1; val r = rs getDate npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextDoubleOption() = { val npos = pos + 1; val r = rs getDouble npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextFloatOption() = { val npos = pos + 1; val r = rs getFloat npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextIntOption() = { val npos = pos + 1; val r = rs getInt npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextLongOption() = { val npos = pos + 1; val r = rs getLong npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextObjectOption() = { val npos = pos + 1; val r = rs getObject npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextShortOption() = { val npos = pos + 1; val r = rs getShort npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextStringOption() = { val npos = pos + 1; val r = rs getString npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextTimeOption() = { val npos = pos + 1; val r = rs getTime npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def nextTimestampOption() = { val npos = pos + 1; val r = rs getTimestamp npos; val rr = (if(rs.wasNull) None else Some(r)); pos = npos; rr }
final def updateBoolean(v: Boolean) { val npos = pos + 1; rs.updateBoolean (npos, v); pos = npos }
final def updateBlob(v: Blob) { val npos = pos + 1; rs.updateBlob (npos, v); pos = npos }
final def updateByte(v: Byte) { val npos = pos + 1; rs.updateByte (npos, v); pos = npos }
final def updateBytes(v: Array[Byte]) { val npos = pos + 1; rs.updateBytes (npos, v); pos = npos }
final def updateClob(v: Clob) { val npos = pos + 1; rs.updateClob (npos, v); pos = npos }
final def updateDate(v: Date) { val npos = pos + 1; rs.updateDate (npos, v); pos = npos }
final def updateDouble(v: Double) { val npos = pos + 1; rs.updateDouble (npos, v); pos = npos }
final def updateFloat(v: Float) { val npos = pos + 1; rs.updateFloat (npos, v); pos = npos }
final def updateInt(v: Int) { val npos = pos + 1; rs.updateInt (npos, v); pos = npos }
final def updateLong(v: Long) { val npos = pos + 1; rs.updateLong (npos, v); pos = npos }
final def updateShort(v: Short) { val npos = pos + 1; rs.updateShort (npos, v); pos = npos }
final def updateString(v: String) { val npos = pos + 1; rs.updateString (npos, v); pos = npos }
final def updateTime(v: Time) { val npos = pos + 1; rs.updateTime (npos, v); pos = npos }
final def updateTimestamp(v: Timestamp) { val npos = pos + 1; rs.updateTimestamp (npos, v); pos = npos }
final def updateBigDecimal(v: BigDecimal) { val npos = pos + 1; rs.updateBigDecimal(npos, v.bigDecimal); pos = npos }
final def updateObject(v: AnyRef) { val npos = pos + 1; rs.updateObject (npos, v); pos = npos }
final def updateBooleanOption(v: Option[Boolean]) { val npos = pos + 1; v match { case Some(s) => rs.updateBoolean (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateBlobOption(v: Option[Blob]) { val npos = pos + 1; v match { case Some(s) => rs.updateBlob (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateByteOption(v: Option[Byte]) { val npos = pos + 1; v match { case Some(s) => rs.updateByte (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateBytesOption(v: Option[Array[Byte]]) { val npos = pos + 1; v match { case Some(s) => rs.updateBytes (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateClobOption(v: Option[Clob]) { val npos = pos + 1; v match { case Some(s) => rs.updateClob (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateDateOption(v: Option[Date]) { val npos = pos + 1; v match { case Some(s) => rs.updateDate (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateDoubleOption(v: Option[Double]) { val npos = pos + 1; v match { case Some(s) => rs.updateDouble (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateFloatOption(v: Option[Float]) { val npos = pos + 1; v match { case Some(s) => rs.updateFloat (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateIntOption(v: Option[Int]) { val npos = pos + 1; v match { case Some(s) => rs.updateInt (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateLongOption(v: Option[Long]) { val npos = pos + 1; v match { case Some(s) => rs.updateLong (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateShortOption(v: Option[Short]) { val npos = pos + 1; v match { case Some(s) => rs.updateShort (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateStringOption(v: Option[String]) { val npos = pos + 1; v match { case Some(s) => rs.updateString (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateTimeOption(v: Option[Time]) { val npos = pos + 1; v match { case Some(s) => rs.updateTime (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateTimestampOption(v: Option[Timestamp]) { val npos = pos + 1; v match { case Some(s) => rs.updateTimestamp (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateBigDecimalOption(v: Option[BigDecimal]) { val npos = pos + 1; v match { case Some(s) => rs.updateBigDecimal(npos, s.bigDecimal); case None => rs.updateNull(npos) }; pos = npos }
final def updateObjectOption(v: Option[AnyRef]) { val npos = pos + 1; v match { case Some(s) => rs.updateObject (npos, s); case None => rs.updateNull(npos) }; pos = npos }
final def updateNull() { val npos = pos + 1; rs.updateNull(npos); pos = npos }
/**
* Close the ResultSet and the statement which created it.
*/
def close(): Unit
/**
* Create an embedded PositionedResult which extends from the given dataPos
* column until the end of this PositionedResult, starts at the current row
* and ends when the discriminator predicate (which can read columns starting
* at discriminatorPos) returns false or when this PositionedResult ends.
*/
def view(discriminatorPos: Int, dataPos: Int, discriminator: (PositionedResult => Boolean)): PositionedResult = new PositionedResult(rs) {
override protected[this] val startPos = dataPos
pos = Int.MinValue
def close() {}
override def nextRow = {
def disc = {
pos = discriminatorPos
val ret = discriminator(this)
pos = startPos
ret
}
if(pos == Int.MinValue) disc else {
val outerRet = outer.nextRow
val ret = outerRet && disc
pos = startPos
if(!ret && outerRet) outer.rewind
ret
}
}
}
/**
* Create an embedded PositionedResult with a single discriminator column
* followed by the embedded data, starting at the current position. The
* embedded view lasts while the discriminator stays the same. If the first
* discriminator value is NULL, the view is empty.
*/
def view1: PositionedResult = {
val discPos = pos
val disc = nextObject
view(discPos, discPos+1, { r => disc != null && disc == r.nextObject })
}
final def build[C[_], R](gr: GetResult[R])(implicit canBuildFrom: CanBuildFrom[Nothing, R, C[R]]): C[R] = {
val b = canBuildFrom()
while(nextRow) b += gr(this)
b.result()
}
final def to[C[_]] = new To[C]()
final class To[C[_]] private[PositionedResult] () {
def apply[R](gr: GetResult[R])(implicit session: JdbcBackend#Session, canBuildFrom: CanBuildFrom[Nothing, R, C[R]]) =
build[C, R](gr)
}
}
/**
* An CloseableIterator for a PositionedResult.
*/
abstract class PositionedResultIterator[+T](val pr: PositionedResult, maxRows: Int) extends ReadAheadIterator[T] with CloseableIterator[T] {
private[this] var closed = false
private[this] var readRows = 0
def rs = pr.rs
protected def fetchNext(): T = {
if((readRows < maxRows || maxRows <= 0) && pr.nextRow) {
val res = extractValue(pr)
readRows += 1
res
}
else finished()
}
final def close() {
if(!closed) {
pr.close()
closed = true
}
}
protected def extractValue(pr: PositionedResult): T
}
|
nuodb/slick
|
src/main/scala/scala/slick/jdbc/PositionedResult.scala
|
Scala
|
bsd-2-clause
| 12,463 |
import sbt.Keys._
import sbt._
/**
* This plugins adds Akka snapshot repositories when running a nightly build.
*/
object AkkaSnapshotRepositories extends AutoPlugin {
override def trigger: PluginTrigger = allRequirements
// This is also copy/pasted in ScriptedTools for scripted tests to also use the snapshot repositories.
override def projectSettings: Seq[Def.Setting[_]] = {
// If this is a cron job in Travis:
// https://docs.travis-ci.com/user/cron-jobs/#detecting-builds-triggered-by-cron
resolvers ++= (sys.env.get("TRAVIS_EVENT_TYPE").filter(_.equalsIgnoreCase("cron")) match {
case Some(_) =>
Seq(
"akka-snapshot-repository".at("https://repo.akka.io/snapshots"),
"akka-http-snapshot-repository".at("https://oss.sonatype.org/content/repositories/snapshots/")
)
case None => Seq.empty
})
}
}
|
marcospereira/playframework
|
project/AkkaSnapshotRepositories.scala
|
Scala
|
apache-2.0
| 876 |
package io.github.suitougreentea.VariousMinos
import io.github.suitougreentea.VariousMinos.game.{HandlerBomb, Game}
import org.newdawn.slick.{Graphics, Input, Color}
/**
* Created by suitougreentea on 14/11/29.
*/
trait ModeMenuItem {
val name: String
//val description: String = ""
val color: Color
val height: Int
def updateDetailedMenu (c: Control): Unit
def renderDetailedMenu (g: Graphics): Unit
def handler: HandlerBomb
}
abstract class ModeMenuItemWithDifficulty(val name: String, val color: Color) extends ModeMenuItem {
var cursor = 0
val height = 32
val difficultyList: List[String]
override def updateDetailedMenu(c: Control): Unit = {
if(c.pressed(Buttons.LEFT) && cursor > 0) cursor -= 1
if(c.pressed(Buttons.RIGHT) && cursor < difficultyList.length - 1) cursor += 1
}
override def renderDetailedMenu(g: Graphics): Unit = {
Resource.boldfont.drawString("- " + difficultyList(cursor), 16, 16, color = new Color(0.8f, 0.8f, 0.8f))
}
}
class ModeMenuItemWithNothing(val name: String, val color: Color, _handler: => HandlerBomb) extends ModeMenuItem {
val height = 0
def updateDetailedMenu (c: Control): Unit = {}
def renderDetailedMenu (g: Graphics): Unit = {}
lazy val handler = _handler
}
|
suitougreentea/VariousMinos2
|
src/main/scala/io/github/suitougreentea/VariousMinos/MenuItem.scala
|
Scala
|
mit
| 1,265 |
package net.ceedubs.ficus.readers
import com.typesafe.config.ConfigFactory
import net.ceedubs.ficus.Spec
import com.typesafe.config.ConfigValueType
import net.ceedubs.ficus.ConfigSerializerOps._
class ConfigValueReaderSpec extends Spec with ConfigValueReader {
def is = s2"""
The ConfigValue value reader should
read a boolean $readBoolean
read an int $readInt
read a double $readDouble
read a string $readString
read an object $readObject
"""
def readBoolean = prop { b: Boolean =>
val cfg = ConfigFactory.parseString(s"myValue = $b")
val read = configValueValueReader.read(cfg, "myValue")
read.valueType must beEqualTo(ConfigValueType.BOOLEAN)
read.unwrapped() must beEqualTo(b)
}
def readInt = prop { i: Int =>
val cfg = ConfigFactory.parseString(s"myValue = $i")
val read = configValueValueReader.read(cfg, "myValue")
read.valueType must beEqualTo(ConfigValueType.NUMBER)
read.unwrapped() must beEqualTo(int2Integer(i))
}
def readDouble = prop { d: Double =>
val cfg = ConfigFactory.parseString(s"myValue = $d")
val read = configValueValueReader.read(cfg, "myValue")
read.valueType must beEqualTo(ConfigValueType.NUMBER)
read.unwrapped() must beEqualTo(double2Double(d))
}
def readString = prop { s: String =>
val cfg = ConfigFactory.parseString(s"myValue = ${s.asConfigValue}")
val read = configValueValueReader.read(cfg, "myValue")
read.valueType must beEqualTo(ConfigValueType.STRING)
read.unwrapped() must beEqualTo(s)
}
def readObject = prop { i: Int =>
val cfg = ConfigFactory.parseString(s"myValue = { i = $i }")
val read = configValueValueReader.read(cfg, "myValue")
read.valueType must beEqualTo(ConfigValueType.OBJECT)
read.unwrapped() must beEqualTo(cfg.getValue("myValue").unwrapped())
}
def readList = prop { i: Int =>
val cfg = ConfigFactory.parseString(s"myValue = [ $i ]")
val read = configValueValueReader.read(cfg, "myValue")
read.valueType must beEqualTo(ConfigValueType.LIST)
read.unwrapped() must beEqualTo(cfg.getValue("myValue").unwrapped())
}
}
|
ceedubs/ficus
|
src/test/scala/net/ceedubs/ficus/readers/ConfigValueReaderSpec.scala
|
Scala
|
mit
| 2,127 |
/*
,i::,
:;;;;;;;
;:,,::;.
1ft1;::;1tL
t1;::;1,
:;::; _____ __ ___ __
fCLff ;:: tfLLC / ___/ / |/ /____ _ _____ / /_
CLft11 :,, i1tffLi \\__ \\ ____ / /|_/ // __ `// ___// __ \\
1t1i .;; .1tf ___/ //___// / / // /_/ // /__ / / / /
CLt1i :,: .1tfL. /____/ /_/ /_/ \\__,_/ \\___//_/ /_/
Lft1,:;: , 1tfL:
;it1i ,,,:::;;;::1tti s_mach.explain_json
.t1i .,::;;; ;1tt Copyright (c) 2016 S-Mach, Inc.
Lft11ii;::;ii1tfL: Author: [email protected]
.L1 1tt1ttt,,Li
...1LLLL...
*/
package s_mach
import s_mach.explain_json.impl._
import s_mach.i18n.I18NConfig
import s_mach.metadata._
package object explain_json extends Implicits {
type JsonExplanation = TypeMetadata[JsonExplanationNode]
implicit class S_Mach_Explain_Json_EverythingPML[A](val self: A) extends AnyVal {
/**
* Issue JSON build commands to a JSON builder
* @param builder builder to issue comands to
* @param b type-class for building A
* @tparam JsonRepr type of JSON value
* @return TRUE if built JSON value is empty array, empty object or null
*/
def buildJson[JsonRepr](
builder: JsonBuilder[JsonRepr]
)(implicit
b: BuildJson[A]
) : Unit =
b.build(builder,self)
/**
* Issue build commands to a JSON builder and build JSON representation
* @param jbf type-class for creating a default configured builder
* @param b type-class for building A
* @tparam JsonRepr type of JSON value
* @return JSON representation
*/
def printJson[JsonRepr](implicit
jbf:JsonBuilderFactory[JsonRepr],
b: BuildJson[A]
) : JsonRepr = {
val builder = jbf()
b.build(builder,self)
builder.build()
}
}
implicit class S_Mach_Explain_Json_TypeMetadataExplainJsonNodePML(val self: JsonExplanation) extends AnyVal {
/** @return print human-readable remarks for JSONExplanation */
def printRemarks(implicit
cfg: I18NConfig
) : TypeRemarks =
JsonExplanationOps.toTypeRemarks(self)
/** @return print JSONSchema for JSONExplanation */
def printJsonSchema[JsonRepr](
id: String
)(implicit
cfg: I18NConfig,
jbf: JsonBuilderFactory[JsonRepr]
) : JsonRepr = {
val builder = jbf()
PrintJsonSchemaOps.printJsonSchema(id, self, builder)
builder.build()
}
/** @return print JSONSchema for JSONExplanation */
def printJsonSchema[JsonRepr](
id: String,
builder: JsonBuilder[JsonRepr]
)(implicit
cfg: I18NConfig
) : Unit = {
PrintJsonSchemaOps.printJsonSchema(id, self, builder)
}
}
}
|
S-Mach/s_mach.explain
|
explain_json/src/main/scala/s_mach/explain_json/package.scala
|
Scala
|
mit
| 2,872 |
package com.sk.app.proxmock.application.domain.providers.headers
import com.sk.app.proxmock.application.configuration.ConfigurationContext
import org.springframework.messaging.Message
/**
* Created by Szymon on 06.10.2016.
*/
case class EmptyHeadersProvider() extends HeadersProvider {
override def get(context: ConfigurationContext, message: Message[Object]): Map[String, String] =
Map()
}
|
szymonkudzia/proxmock
|
sources/src/main/scala/com/sk/app/proxmock/application/domain/providers/headers/EmptyHeadersProvider.scala
|
Scala
|
mit
| 401 |
package de.fosd.typechef.typesystem
import de.fosd.typechef.conditional._
import de.fosd.typechef.featureexpr.FeatureExprFactory
import de.fosd.typechef.featureexpr.FeatureExprFactory._
import de.fosd.typechef.parser.c._
import org.junit.runner.RunWith
import org.scalatest.{Matchers, FunSuite}
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class DeadCodeTest extends FunSuite with CTypeSystem with Matchers with TestHelper {
def e(s: String) = {
val r = parseExpr(s)
// println(r)
r
}
def evalExpr(s: String): Conditional[VValue] = evalExpr(One(e(s.replace("[[", "\\n#ifdef A\\n").replace("][", "\\n#else\\n").replace("]]", "\\n#endif\\n"))), True, EmptyEnv)
test("get expression bounds") {
analyzeExprBounds(One(Constant("0")), True, EmptyEnv) should be((True, False))
analyzeExprBounds(One(Constant("1")), True, EmptyEnv) should be((False, True))
analyzeExprBounds(One(e("1+0")), True, EmptyEnv) should be((False, True))
}
test("eval expression") {
evalExpr("1") should be(One(VInt(1)))
evalExpr("0") should be(One(VInt(0)))
evalExpr("i") should be(One(VUnknown()))
evalExpr("1+2") should be(One(VInt(3)))
evalExpr("1+[[1][0]]") should be(Choice(fa.not, One(VInt(1)), One(VInt(2))))
// evalExpr("1[[+1]") should be(Choice(fa.not, One(VInt(1)), One(VInt(2))))
evalExpr("i || 1") should be(One(VInt(1)))
evalExpr("0 && i") should be(One(VInt(0)))
evalExpr("!0") should be(One(VInt(1)))
}
}
|
mbeddr/TypeChef
|
CTypeChecker/src/test/scala/de/fosd/typechef/typesystem/DeadCodeTest.scala
|
Scala
|
lgpl-3.0
| 1,608 |
package tu.coreservice.action.way2think
import tu.model.knowledge.communication.ShortTermMemory
import tu.model.knowledge.{Constant, Probability, KnowledgeURI}
import tu.coreservice.action.{Action}
import tu.model.knowledge.helper.URIGenerator
import tu.model.knowledge.domain.Concept
import tu.model.knowledge.narrative.Narrative
/**
* Way2Think interface.
* @author max talanov
* date 2012-05-28
* time: 11:09 PM
*/
abstract class Way2Think(_uri: KnowledgeURI, _probability: Probability = new Probability())
extends Action(_uri, _probability) {
/**
* Way2Think interface.
* @param inputContext ShortTermMemory of all inbound parameters.
* @return outputContext
*/
def apply(inputContext: ShortTermMemory): ShortTermMemory
def this() = this(URIGenerator.generateURI("Way2Think"))
/**
* Sets concepts to result to report.
* @param context ShortTermMemory to set understood Concepts to report.
* @param concepts understood concepts to set in ShortTermMemory.
* @return updated ShortTermMemory
*/
def setResultsToReport(context: ShortTermMemory, concepts: List[Concept]): ShortTermMemory = {
val understoodConcepts = Narrative[Concept](Constant.UNDERSTOOD_CONCEPTS, concepts)
context.resultToReport = context.resultToReport + understoodConcepts
context
}
}
|
keskival/2
|
coreservice.action.way2think/src/main/scala/tu/coreservice/action/way2think/Way2Think.scala
|
Scala
|
gpl-3.0
| 1,337 |
import sbt._
import sbt.Keys._
object Dependencies {
object Netty {
private val version = "4.0.27.Final"
val all = "io.netty" % "netty-all" % version
val epoll = "io.netty" % "netty-transport-native-epoll" % version
}
private val config = "com.typesafe" % "config" % "1.3.0"
val microservice = dependencies(Netty.all, Netty.epoll, config)
private def dependencies(modules: ModuleID*): Seq[Setting[_]] = Seq(libraryDependencies ++= modules)
}
|
alexandrnikitin/netty-scala-template
|
project/Dependencies.scala
|
Scala
|
mit
| 469 |
// code-examples/TypeLessDoMore/package-example1.scala
package com.example.mypkg
class MyClass {
// ...
}
|
XClouded/t4f-core
|
scala/src/tmp/TypeLessDoMore/package-example1.scala
|
Scala
|
apache-2.0
| 110 |
/**
* Copyright (C) 2015-2016 DANS - Data Archiving and Networked Services ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.knaw.dans.api.sword2
import java.io._
import org.apache.commons.io.IOUtils
import scala.util.Try
object MergeFiles {
def merge(destination: File, files: Seq[File]): Try[Unit] = Try {
var output: OutputStream = null
try {
output = createAppendableStream(destination)
files.foreach(appendFile(output))
} finally {
IOUtils.closeQuietly(output)
}
}
@throws(classOf[FileNotFoundException])
private def createAppendableStream(destination: File): BufferedOutputStream =
new BufferedOutputStream(new FileOutputStream(destination, true))
@throws(classOf[IOException])
private def appendFile(output: OutputStream)(file: File) {
var input: InputStream = null
try {
input = new BufferedInputStream(new FileInputStream(file))
IOUtils.copy(input, output)
} finally {
IOUtils.closeQuietly(input)
}
}
}
|
vesaakerman/easy-sword2
|
src/main/scala/nl/knaw/dans/api/sword2/MergeFiles.scala
|
Scala
|
apache-2.0
| 1,554 |
/*
* Code Pulse: A real-time code coverage testing tool. For more information
* see http://code-pulse.com
*
* Copyright (C) 2014 Applied Visions - http://securedecisions.avi.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.secdec.codepulse.data.model.slick
import java.io.File
import scala.concurrent.duration._
import scala.slick.driver.H2Driver
import scala.slick.jdbc.JdbcBackend.Database
import com.secdec.codepulse.data.model._
import com.secdec.codepulse.util.Implicits._
import akka.actor.ActorSystem
/** Provides `SlickProjectData` instances for projects, basing storage in `folder`.
* Uses H2 for data storage.
*
* @author robertf
*/
class SlickH2ProjectDataProvider(folder: File, actorSystem: ActorSystem) extends ProjectDataProvider {
private val EncountersBufferSize = 500
private val EncountersFlushInterval = 1.second
private val cache = collection.mutable.Map.empty[ProjectId, SlickProjectData]
val MasterDbName = "projects_db"
val ProjectFolderName = "project"
val ProjectDbName = "project_db"
val PageStoreFileSuffix = ".h2.db"
val MultiVersionStoreFileSuffix = ".mv.db"
private object ProjectFilename {
def apply(folder: File, projectId: ProjectId) = {
val dbName = getDbName(projectId)
val dbFolder = getDbFolder(folder, projectId)
// The current H2 database driver reads existing PageStore db files
// but will create new db files using MVStore.
val dbPageStoreFilename = s"$dbName$PageStoreFileSuffix"
if ((dbFolder / dbPageStoreFilename).exists)
dbPageStoreFilename
else
s"$dbName$MultiVersionStoreFileSuffix"
}
def getDbFolder(folder: File, projectId: ProjectId) = {
folder / s"$ProjectFolderName-${projectId.num}"
}
def getDbName(projectId: ProjectId) = s"$ProjectDbName-${projectId.num}"
val NameRegex = raw"$ProjectDbName-(\\d+)\\.(?:h2|mv)\\.db".r
def unapply(filename: String): Option[ProjectId] = filename match {
case NameRegex(ProjectId(id)) => Some(id)
case _ => None
}
}
private val masterData = {
val needsInit = !((folder / s"$MasterDbName$MultiVersionStoreFileSuffix").exists || (folder / s"$MasterDbName$PageStoreFileSuffix").exists)
val db = Database.forURL(s"jdbc:h2:file:${(folder / MasterDbName).getCanonicalPath};DB_CLOSE_DELAY=10", driver = "org.h2.Driver")
val data = new SlickMasterData(db, H2Driver)
if (needsInit) data.init
data
}
def getProject(id: ProjectId): ProjectData = getProjectInternal(id)
private def getProjectInternal(id: ProjectId, suppressInit: Boolean = false) = cache.getOrElseUpdate(id, {
val dbFolder = ProjectFilename.getDbFolder(folder, id)
val needsInit = !(dbFolder / ProjectFilename(folder, id)).exists
val db = Database.forURL(s"jdbc:h2:file:${(dbFolder / ProjectFilename.getDbName(id)).getCanonicalPath};DB_CLOSE_DELAY=10", driver = "org.h2.Driver")
val data = new SlickProjectData(id, db, H2Driver, masterData.metadataMaster get id.num, EncountersBufferSize, EncountersFlushInterval, actorSystem)
if (!suppressInit && needsInit) data.init
data
})
def removeProject(id: ProjectId) {
getProjectInternal(id, true).delete
cache -= id
}
def projectList: List[ProjectId] = {
var folders = folder.listFiles.filter(_.isDirectory).toList
var files = folders.flatMap(_.listFiles)
var names = files.map(_.getName)
var projects = folder.listFiles.filter(_.isDirectory).toList.flatMap(_.listFiles).map { _.getName } collect {
case ProjectFilename(id) => id
} filter { id =>
val project = getProject(id)
// If this project has been soft-deleted, exclude
!project.metadata.deleted
}
projects
}
def maxProjectId: Int = {
val default = 0
(folder.listFiles.filter(_.isDirectory).toList.flatMap(_.listFiles).map { _.getName } collect {
case ProjectFilename(id) => id
} map(id => id.num) foldLeft default)(Math.max)
}
}
|
secdec/codepulse
|
codepulse/src/main/scala/com/secdec/codepulse/data/model/slick/SlickH2ProjectDataProvider.scala
|
Scala
|
apache-2.0
| 4,373 |
package llsm.io.metadata
import java.nio.file.{Path, Paths}
import java.util.UUID
import cats._
import cats.arrow.FunctionK
import cats.data.Kleisli
import llsm.{BaseSuite, NoInterpolation}
import llsm.algebras.{MetadataF, MetadataLow, MetadataLowF}
import llsm.interpreters._
class MetadataSuite extends BaseSuite with MetadataImplicits {
type Exec[M[_], A] = Kleisli[M, Unit, A]
private def metaLowMockInterpreter[M[_]](
s: Int,
c: Int,
t: Int
)(
implicit
M: ApplicativeError[M, Throwable]
): FunctionK[MetadataLowF, Exec[M, ?]] =
λ[FunctionK[MetadataLowF, Exec[M, ?]]] { fa =>
Kleisli { _ =>
fa match {
case MetadataLow.ConfigurableMeta =>
M.pure(ConfigurableMetadata(0.1018, 0.1018, NoInterpolation))
case MetadataLow.ExtractFilenameMeta(path @ _) =>
M.pure(
FilenameMetadata(UUID.randomUUID,
"Test",
s,
c,
488,
t.toLong * 200L,
0L))
case MetadataLow.ExtractTextMeta(path @ _) => {
val f: Path = Paths.get(
getClass
.getResource("/io/data/Resolution test 4_Settings.txt")
.toURI
.getPath)
val meta = FileMetadata.readMetadataFromTxtFile(f)
meta.leftMap {
case FileMetadata.MetadataIOError(msg) => new Throwable(msg)
} match {
case Right(m) => M.pure(m)
case Left(e) => M.raiseError(e)
}
}
case MetadataLow.WriteMetadata(path @ _, meta @ _) => ???
}
}
}
def metaMockInterpreter[M[_]](s: Int, c: Int, t: Int)(
implicit M: ApplicativeError[M, Throwable]): MetadataF ~> M =
new (MetadataF ~> M) {
def apply[A](fa: MetadataF[A]): M[A] =
metaToMetaLowTranslator(fa)
.foldMap[Exec[M, ?]](metaLowMockInterpreter[M](s, c, t)(M))
.run(())
}
}
|
keithschulze/llsm
|
tests/src/main/scala/llsm/io/metadata/MetadataSuite.scala
|
Scala
|
mit
| 2,108 |
package summingbird
import sbt._
import Keys._
import com.typesafe.tools.mima.plugin.MimaPlugin.mimaDefaultSettings
import com.typesafe.tools.mima.plugin.MimaKeys.previousArtifact
object SummingbirdBuild extends Build {
def withCross(dep: ModuleID) =
dep cross CrossVersion.binaryMapped {
case "2.9.3" => "2.9.2" // TODO: hack because twitter hasn't built things against 2.9.3
case version if version startsWith "2.10" => "2.10" // TODO: hack because sbt is broken
case x => x
}
def specs2Import(scalaVersion: String) = scalaVersion match {
case version if version startsWith "2.9" => "org.specs2" %% "specs2" % "1.12.4.1" % "test"
case version if version startsWith "2.10" => "org.specs2" %% "specs2" % "1.13" % "test"
}
val sharedSettings = Project.defaultSettings ++ Seq(
organization := "com.twitter",
version := "0.3.1",
scalaVersion := "2.9.3",
crossScalaVersions := Seq("2.9.3", "2.10.0"),
libraryDependencies ++= Seq(
"org.slf4j" % "slf4j-api" % slf4jVersion,
"org.scalacheck" %% "scalacheck" % "1.10.0" % "test",
// These satisify's scaldings log4j needs when in test mode
"log4j" % "log4j" % "1.2.16" % "test",
"org.slf4j" % "slf4j-log4j12" % slf4jVersion % "test"
),
libraryDependencies <+= scalaVersion(specs2Import(_)),
resolvers ++= Seq(
Opts.resolver.sonatypeSnapshots,
Opts.resolver.sonatypeReleases,
"Clojars Repository" at "http://clojars.org/repo",
"Conjars Repository" at "http://conjars.org/repo",
"Twitter Maven" at "http://maven.twttr.com"
),
parallelExecution in Test := true,
scalacOptions ++= Seq(
"-unchecked",
"-deprecation",
"-Yresolve-term-conflict:package"
),
// Publishing options:
publishMavenStyle := true,
publishArtifact in Test := false,
pomIncludeRepository := { x => false },
publishTo <<= version { v =>
Some(
if (v.trim.toUpperCase.endsWith("SNAPSHOT"))
Opts.resolver.sonatypeSnapshots
else
Opts.resolver.sonatypeStaging
//"twttr" at "http://artifactory.local.twitter.com/libs-releases-local"
)
},
pomExtra := (
<url>https://github.com/twitter/summingbird</url>
<licenses>
<license>
<name>Apache 2</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
<scm>
<url>[email protected]:twitter/summingbird.git</url>
<connection>scm:git:[email protected]:twitter/summingbird.git</connection>
</scm>
<developers>
<developer>
<id>oscar</id>
<name>Oscar Boykin</name>
<url>http://twitter.com/posco</url>
</developer>
<developer>
<id>sritchie</id>
<name>Sam Ritchie</name>
<url>http://twitter.com/sritchie</url>
</developer>
<developer>
<id>asinghal</id>
<name>Ashutosh Singhal</name>
<url>http://twitter.com/daashu</url>
</developer>
</developers>)
)
lazy val summingbird = Project(
id = "summingbird",
base = file("."),
settings = sharedSettings ++ DocGen.publishSettings
).settings(
test := { },
publish := { }, // skip publishing for this root project.
publishLocal := { }
).aggregate(
summingbirdCore,
summingbirdBatch,
summingbirdOnline,
summingbirdClient,
summingbirdStorm,
summingbirdScalding,
summingbirdBuilder,
summingbirdChill,
summingbirdExample
)
val dfsDatastoresVersion = "1.3.4"
val bijectionVersion = "0.6.0"
val algebirdVersion = "0.3.1"
val scaldingVersion = "0.9.0rc4"
val storehausVersion = "0.8.0"
val utilVersion = "6.3.8"
val chillVersion = "0.3.5"
val tormentaVersion = "0.6.0"
lazy val slf4jVersion = "1.6.6"
/**
* This returns the youngest jar we released that is compatible with
* the current.
*/
val unreleasedModules = Set[String]()
def youngestForwardCompatible(subProj: String) =
Some(subProj)
.filterNot(unreleasedModules.contains(_))
.map { s => "com.twitter" % ("summingbird-" + s + "_2.9.3") % "0.2.4" }
def module(name: String) = {
val id = "summingbird-%s".format(name)
Project(id = id, base = file(id), settings = sharedSettings ++ Seq(
Keys.name := id,
previousArtifact := youngestForwardCompatible(name))
)
}
lazy val summingbirdBatch = module("batch").settings(
libraryDependencies ++= Seq(
"com.twitter" %% "algebird-core" % algebirdVersion,
"com.twitter" %% "bijection-core" % bijectionVersion
)
)
lazy val summingbirdChill = module("chill").settings(
libraryDependencies ++= Seq(
"com.twitter" %% "chill" % chillVersion,
"com.twitter" %% "chill-bijection" % chillVersion
)
).dependsOn(
summingbirdCore,
summingbirdBatch
)
lazy val summingbirdClient = module("client").settings(
libraryDependencies ++= Seq(
"com.twitter" %% "algebird-core" % algebirdVersion,
"com.twitter" %% "algebird-util" % algebirdVersion,
"com.twitter" %% "bijection-core" % bijectionVersion,
"com.twitter" %% "storehaus-core" % storehausVersion,
"com.twitter" %% "storehaus-algebra" % storehausVersion
)
).dependsOn(summingbirdBatch)
lazy val summingbirdCore = module("core").settings(
libraryDependencies += "com.twitter" %% "algebird-core" % algebirdVersion
)
lazy val summingbirdOnline = module("online").settings(
libraryDependencies ++= Seq(
"com.twitter" %% "algebird-core" % algebirdVersion,
"com.twitter" %% "bijection-core" % bijectionVersion,
"com.twitter" %% "storehaus-core" % storehausVersion,
"com.twitter" %% "chill" % chillVersion,
"com.twitter" %% "storehaus-algebra" % storehausVersion,
withCross("com.twitter" %% "util-core" % utilVersion)
)
).dependsOn(
summingbirdCore % "test->test;compile->compile",
summingbirdBatch
)
lazy val summingbirdStorm = module("storm").settings(
parallelExecution in Test := false,
libraryDependencies ++= Seq(
"com.twitter" %% "algebird-core" % algebirdVersion,
"com.twitter" %% "bijection-core" % bijectionVersion,
"com.twitter" %% "chill" % chillVersion,
"com.twitter" % "chill-storm" % chillVersion,
"com.twitter" %% "chill-bijection" % chillVersion,
"com.twitter" %% "storehaus-core" % storehausVersion,
"com.twitter" %% "storehaus-algebra" % storehausVersion,
"com.twitter" %% "scalding-args" % scaldingVersion,
"com.twitter" %% "tormenta-core" % tormentaVersion,
withCross("com.twitter" %% "util-core" % utilVersion),
"storm" % "storm" % "0.9.0-wip15" % "provided"
)
).dependsOn(
summingbirdCore % "test->test;compile->compile",
summingbirdOnline,
summingbirdChill,
summingbirdBatch
)
lazy val summingbirdScalding = module("scalding").settings(
libraryDependencies ++= Seq(
"com.backtype" % "dfs-datastores" % dfsDatastoresVersion,
"com.backtype" % "dfs-datastores-cascading" % dfsDatastoresVersion,
"com.twitter" %% "algebird-core" % algebirdVersion,
"com.twitter" %% "algebird-util" % algebirdVersion,
"com.twitter" %% "algebird-bijection" % algebirdVersion,
"com.twitter" %% "bijection-json" % bijectionVersion,
"com.twitter" %% "chill" % chillVersion,
"com.twitter" % "chill-hadoop" % chillVersion,
"com.twitter" %% "chill-bijection" % chillVersion,
"commons-lang" % "commons-lang" % "2.6",
"com.twitter" %% "scalding-core" % scaldingVersion,
"com.twitter" %% "scalding-commons" % scaldingVersion
)
).dependsOn(
summingbirdCore % "test->test;compile->compile",
summingbirdChill,
summingbirdBatch
)
lazy val summingbirdBuilder = module("builder").settings(
libraryDependencies ++= Seq(
"storm" % "storm" % "0.9.0-wip15" % "provided"
)
).dependsOn(
summingbirdCore,
summingbirdStorm,
summingbirdScalding
)
lazy val summingbirdExample = module("example").settings(
libraryDependencies ++= Seq(
"log4j" % "log4j" % "1.2.16",
"org.slf4j" % "slf4j-log4j12" % slf4jVersion,
"storm" % "storm" % "0.9.0-wip15" exclude("org.slf4j", "log4j-over-slf4j") exclude("ch.qos.logback", "logback-classic"),
"com.twitter" %% "bijection-netty" % bijectionVersion,
"com.twitter" %% "tormenta-twitter" % tormentaVersion,
"com.twitter" %% "storehaus-memcache" % storehausVersion
)
).dependsOn(summingbirdCore, summingbirdScalding)
}
|
sengt/summingbird-batch
|
project/Build.scala
|
Scala
|
apache-2.0
| 8,771 |
/**
* Copyright (C) 2011 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.xforms.analysis
import org.dom4j.{Element, QName}
import org.orbeon.oxf.util.ScalaUtils.stringOptionToSet
import org.orbeon.oxf.xforms.XFormsConstants._
import org.orbeon.oxf.xforms.XFormsUtils.{getElementId, maybeAVT}
import org.orbeon.oxf.xforms.analysis.controls.{AttributeControl, RepeatControl, ValueTrait}
import org.orbeon.oxf.xforms.analysis.model.Model
import org.orbeon.oxf.xforms.event.EventHandler
import org.orbeon.oxf.xforms.event.XFormsEvent.{Bubbling, Capture, Phase, Target}
import org.orbeon.oxf.xforms.xbl.Scope
import org.orbeon.oxf.xforms.{XFormsConstants, XFormsUtils}
import org.orbeon.oxf.xml.XMLConstants.XML_LANG_QNAME
import org.orbeon.oxf.xml.dom4j.{Dom4jUtils, ExtendedLocationData, LocationData}
import org.orbeon.oxf.xml.{NamespaceMapping, XMLReceiverHelper}
import scala.collection.mutable
import scala.util.control.Breaks
// xml:lang reference
sealed abstract class LangRef
case class LiteralLangRef(lang: String) extends LangRef
case class AVTLangRef(att: AttributeControl) extends LangRef
/**
* Abstract representation of a common XForms element supporting optional context, binding and value.
*/
abstract class ElementAnalysis(
val part : PartAnalysisImpl,
val element : Element,
val parent : Option[ElementAnalysis],
val preceding : Option[ElementAnalysis]
) extends ElementEventHandlers with ElementRepeats {
self ⇒
import ElementAnalysis._
require(element ne null)
implicit def logger = part.getIndentedLogger
// xml:lang, inherited from parent unless overridden locally
lazy val lang: Option[LangRef] = {
val v = element.attributeValue(XML_LANG_QNAME)
if (v ne null)
extractXMLLang(v)
else
parent flatMap (_.lang)
}
protected def extractXMLLang(lang: String): Some[LangRef] =
if (! lang.startsWith("#"))
Some(LiteralLangRef(lang))
else {
val staticId = lang.substring(1)
val prefixedId = XFormsUtils.getRelatedEffectiveId(self.prefixedId, staticId)
Some(AVTLangRef(part.getAttributeControl(prefixedId, "xml:lang")))
}
val namespaceMapping: NamespaceMapping
// Element local name
def localName = element.getName
// Scope and model
val scope: Scope
val model: Option[Model]
// In-scope variables (for XPath analysis)
val inScopeVariables: Map[String, VariableTrait]
def removeFromParent() =
parent foreach
{ case parent: ChildrenBuilderTrait ⇒ parent.removeChild(self); case _ ⇒ }
lazy val treeInScopeVariables: Map[String, VariableTrait] = {
def findPreceding(element: ElementAnalysis): Option[ElementAnalysis] = element.preceding match {
case Some(preceding) if preceding.scope == self.scope ⇒ Some(preceding)
case Some(preceding) ⇒ findPreceding(preceding)
case None ⇒ element.parent match {
case Some(parent: Model) ⇒
None // models are not allowed to see outside variables for now (could lift this restriction later)
case Some(parent) ⇒ findPreceding(parent)
case _ ⇒ None
}
}
findPreceding(self) match {
case Some(preceding: VariableAnalysisTrait) ⇒ preceding.treeInScopeVariables + (preceding.name → preceding)
case Some(preceding) ⇒ preceding.treeInScopeVariables
case None ⇒ Map.empty
}
}
// Definition of the various scopes:
//
// - Container scope: scope defined by the closest ancestor XBL binding. This scope is directly related to the
// prefix of the prefixed id. E.g. <fr:foo id="my-foo"> defines a new scope `my-foo`. All children of `my-foo`,
// including directly nested handlers, models, shadow trees, have the `my-foo` prefix.
//
// - Inner scope: this is the scope given this control if this control has `xxbl:scope='inner'`. It is usually the
// same as the container scope, except for directly nested handlers.
//
// - Outer scope: this is the scope given this control if this control has `xxbl:scope='outer'`. It is usually the
// actual scope of the closest ancestor XBL bound element, except for directly nested handlers.
def containerScope: Scope
// Ids
val staticId = getElementId(element)
val prefixedId = scope.prefixedIdForStaticId(staticId) // NOTE: we could also pass the prefixed id during construction
// Location
val locationData = ElementAnalysis.createLocationData(element)
// Element attributes: @context, @ref, @bind, @value
val context = Option(element.attributeValue(XFormsConstants.CONTEXT_QNAME))
val ref = ElementAnalysis.getBindingExpression(element)
val bind = Option(element.attributeValue(XFormsConstants.BIND_QNAME))
val value = Option(element.attributeValue(XFormsConstants.VALUE_QNAME))
def modelJava = model map (_.staticId) orNull
def contextJava = context.orNull
def refJava = ref.orNull
def bindJava = bind.orNull
// Other
def hasBinding = ref.isDefined || bind.isDefined
val bindingXPathEvaluations = (if (context.isDefined) 1 else 0) + (if (ref.isDefined) 1 else 0)// 0, 1, or 2: number of XPath evaluations used to resolve the binding if no optimization is taking place
// Classes (not used at this time)
val classes = ""
// Extension attributes
protected def allowedExtensionAttributes = Set[QName]()
final lazy val extensionAttributes = Map() ++ (CommonExtensionAttributes ++ allowedExtensionAttributes map (qName ⇒ (qName, element.attributeValue(qName))) filter (_._2 ne null))
final lazy val nonRelevantExtensionAttributes = extensionAttributes map { case (k, v) ⇒ k → (if (maybeAVT(v)) "" else v) } // all blank values for AVTs
// XPath analysis
private var contextAnalysis: Option[XPathAnalysis] = None
private var _contextAnalyzed = false
private var bindingAnalysis: Option[XPathAnalysis] = None
private var _bindingAnalyzed = false
private var valueAnalysis: Option[XPathAnalysis] = None
private var _valueAnalyzed = false
def valueAnalyzed = _valueAnalyzed
final def getContextAnalysis = { assert(_contextAnalyzed); contextAnalysis }
final def getBindingAnalysis = { assert(_bindingAnalyzed); bindingAnalysis }
final def getValueAnalysis = { assert(_valueAnalyzed) ; valueAnalysis }
def analyzeXPath(): Unit = {
contextAnalysis = computeContextAnalysis
_contextAnalyzed = true
bindingAnalysis = computeBindingAnalysis
_bindingAnalyzed = true
valueAnalysis = computeValueAnalysis
_valueAnalyzed = true
}
// To implement in subclasses
protected def computeContextAnalysis: Option[XPathAnalysis]
protected def computeBindingAnalysis: Option[XPathAnalysis]
protected def computeValueAnalysis: Option[XPathAnalysis]
/**
* Return the context within which children elements or values evaluate. This is the element binding if any, or the
* element context if there is no binding.
*/
def getChildrenContext: Option[XPathAnalysis] = if (hasBinding) getBindingAnalysis else getContextAnalysis
val closestAncestorInScope = ElementAnalysis.getClosestAncestorInScope(self, scope)
def toXMLAttributes: Seq[(String, String)] = Seq(
"scope" → scope.scopeId,
"prefixed-id" → prefixedId,
"model-prefixed-id" → (model map (_.prefixedId) orNull),
"binding" → hasBinding.toString,
"value" → self.isInstanceOf[ValueTrait].toString,
"name" → element.attributeValue("name")
)
def toXMLContent(helper: XMLReceiverHelper): Unit = {
// Control binding and value analysis
if (_bindingAnalyzed)
getBindingAnalysis match {
case Some(bindingAnalysis) if hasBinding ⇒ // NOTE: for now there can be a binding analysis even if there is no binding on the control (hack to simplify determining which controls to update)
helper.startElement("binding")
bindingAnalysis.toXML(helper)
helper.endElement()
case _ ⇒ // NOP
}
if (_valueAnalyzed)
getValueAnalysis match {
case Some(valueAnalysis) ⇒
helper.startElement("value")
valueAnalysis.toXML(helper)
helper.endElement()
case _ ⇒ // NOP
}
}
final def toXML(helper: XMLReceiverHelper): Unit = {
helper.startElement(localName, toXMLAttributes flatMap (t ⇒ Seq(t._1, t._2)) toArray)
toXMLContent(helper)
helper.endElement()
}
def freeTransientState(): Unit = {
if (_contextAnalyzed && getContextAnalysis.isDefined)
getContextAnalysis.get.freeTransientState()
if (_bindingAnalyzed && getBindingAnalysis.isDefined)
getBindingAnalysis.get.freeTransientState()
if (_valueAnalyzed && getValueAnalysis.isDefined)
getValueAnalysis.get.freeTransientState()
}
}
trait ElementEventHandlers {
element: ElementAnalysis ⇒
import ElementAnalysis._
import ElementAnalysis.propagateBreaks.{break, breakable}
// Event handler information as a tuple:
// - whether the default action needs to run
// - all event handlers grouped by phase and observer prefixed id
private type HandlerAnalysis = (Boolean, Map[Phase, Map[String, List[EventHandler]]])
// Cache for event handlers
// Use an immutable map and @volatile so that update are published to other threads accessing this static state.
// NOTE: We could use `AtomicReference` but we just get/set so there is no benefit to it.
@volatile private var handlersCache: Map[String, HandlerAnalysis] = Map()
// Return event handler information for the given event name
// We check the cache first, and if not found we compute the result and cache it.
//
// There is a chance that concurrent writers could overwrite each other's latest cache addition, but
// `handlersForEventImpl` is idempotent so this should not be an issue, especially since a document usually has many
// `ElementAnalysis` which means the likelihood of writing to the same `ElementAnalysis` concurrently is low. Also,
// after a while, most handlers will be memoized, which means no more concurrent writes, only concurrent reads.
// Finally, `handlersForEventImpl` is not quick but also not very costly.
//
// Other options include something like `Memoizer` from "Java Concurrency in Practice" (5.6), possibly modified to
// use Scala 2.10 `TrieMap` and `Future`. However a plain immutable `Map` might be more memory-efficient.
//
// Reasoning is great but the only way to know for sure what's best would be to run a solid performance test of the
// options.
def handlersForEvent(eventName: String): HandlerAnalysis =
handlersCache.getOrElse(eventName, {
val result = handlersForEventImpl(eventName)
handlersCache += eventName → result
result
})
private def handlersForObserver(observer: ElementAnalysis) =
observer.part.getEventHandlers(observer.prefixedId)
private def hasPhantomHandler(observer: ElementAnalysis) =
handlersForObserver(observer) exists (_.isPhantom)
// Find all observers (including in ancestor parts) which either match the current scope or have a phantom handler
// Scala 2.11: Simply `private` worked with 2.10. Unclear whether this is a feature or a bug.
private[analysis] def relevantObservers: List[ElementAnalysis] = {
def observersInAncestorParts =
part.elementInParent.toList flatMap (_.relevantObservers)
def relevant(observer: ElementAnalysis) =
observer.scope == element.scope || hasPhantomHandler(observer)
(ancestorOrSelfIterator(element) filter relevant) ++: observersInAncestorParts
}
// Find all the handlers for the given event name
// For all relevant observers, find the handlers which match by phase
private def handlersForEventImpl(eventName: String): HandlerAnalysis = {
def relevantHandlersForObserverByPhaseAndName(observer: ElementAnalysis, phase: Phase) = {
val isPhantom = observer.scope != element.scope
def matchesPhaseNameTarget(eventHandler: EventHandler) =
(eventHandler.isCapturePhaseOnly && phase == Capture ||
eventHandler.isTargetPhase && phase == Target ||
eventHandler.isBubblingPhase && phase == Bubbling) && eventHandler.isMatchByNameAndTarget(eventName, element.prefixedId)
def matches(eventHandler: EventHandler) =
if (isPhantom)
eventHandler.isPhantom && matchesPhaseNameTarget(eventHandler)
else
matchesPhaseNameTarget(eventHandler)
val relevantHandlers = handlersForObserver(observer) filter matches
// DOM 3:
//
// - stopPropagation: "Prevents other event listeners from being triggered but its effect must be deferred
// until all event listeners attached on the Event.currentTarget have been triggered."
// - preventDefault: "the event must be canceled, meaning any default actions normally taken by the
// implementation as a result of the event must not occur"
// - NOTE: DOM 3 introduces also stopImmediatePropagation
val propagate = relevantHandlers forall (_.isPropagate)
val performDefaultAction = relevantHandlers forall (_.isPerformDefaultAction)
(propagate, performDefaultAction, relevantHandlers)
}
var propagate = true
var performDefaultAction = true
def handlersForPhase(observers: List[ElementAnalysis], phase: Phase) = {
val result = mutable.Map[String, List[EventHandler]]()
breakable {
for (observer ← observers) {
val (localPropagate, localPerformDefaultAction, handlersToRun) =
relevantHandlersForObserverByPhaseAndName(observer, phase)
propagate &= localPropagate
performDefaultAction &= localPerformDefaultAction
if (handlersToRun.nonEmpty)
result += observer.prefixedId → handlersToRun
// Cancel propagation if requested
if (! propagate)
break()
}
}
if (result.nonEmpty)
Some(phase → result.toMap)
else
None
}
val observers = relevantObservers
val captureHandlers =
handlersForPhase(observers.reverse.init, Capture)
val targetHandlers =
if (propagate)
handlersForPhase(List(observers.head), Target)
else
None
val bubblingHandlers =
if (propagate)
handlersForPhase(observers.tail, Bubbling)
else
None
(performDefaultAction, Map() ++ captureHandlers ++ targetHandlers ++ bubblingHandlers)
}
}
trait ElementRepeats {
element: ElementAnalysis ⇒
// This control's ancestor repeats, computed on demand
lazy val ancestorRepeats: List[RepeatControl] =
parent match {
case Some(parentRepeat: RepeatControl) ⇒ parentRepeat :: parentRepeat.ancestorRepeats
case Some(parentElement) ⇒ parentElement.ancestorRepeats
case None ⇒ Nil
}
// Same as ancestorRepeats but across parts
lazy val ancestorRepeatsAcrossParts: List[RepeatControl] =
part.elementInParent match {
case Some(elementInParentPart) ⇒ ancestorRepeats ::: elementInParentPart.ancestorRepeatsAcrossParts
case None ⇒ ancestorRepeats
}
// This control's closest ancestor in the same scope
// NOTE: This doesn't need to go across parts, because parts don't share scopes at this time.
lazy val ancestorRepeatInScope = ancestorRepeats find (_.scope == scope)
// Whether this is within a repeat
def isWithinRepeat = ancestorRepeatsAcrossParts.nonEmpty
}
object ElementAnalysis {
val CommonExtensionAttributes = Set(STYLE_QNAME, CLASS_QNAME)
val propagateBreaks = new Breaks
/**
* Return the closest preceding element in the same scope.
*
* NOTE: As in XPath, this does not include ancestors of the element.
*/
def getClosestPrecedingInScope(element: ElementAnalysis)(scope: Scope = element.scope): Option[ElementAnalysis] = element.preceding match {
case Some(preceding) if preceding.scope == scope ⇒ Some(preceding)
case Some(preceding) ⇒ getClosestPrecedingInScope(preceding)(scope)
case None ⇒ element.parent match {
case Some(parent) ⇒ getClosestPrecedingInScope(parent)(scope)
case _ ⇒ None
}
}
abstract class IteratorBase(start: ElementAnalysis) extends Iterator[ElementAnalysis] {
def initialNext: Option[ElementAnalysis]
def subsequentNext(e: ElementAnalysis): Option[ElementAnalysis]
private[this] var theNext = initialNext
def hasNext = theNext.isDefined
def next() = {
val newResult = theNext.get
theNext = subsequentNext(newResult)
newResult
}
}
/**
* Return an iterator over all the element's ancestors.
*/
def ancestorIterator(start: ElementAnalysis) = new IteratorBase(start) {
def initialNext = start.parent
def subsequentNext(e: ElementAnalysis) = e.parent
}
/**
* Iterator over the element and all its ancestors.
*/
def ancestorOrSelfIterator(start: ElementAnalysis) = new IteratorBase(start) {
def initialNext = Option(start)
def subsequentNext(e: ElementAnalysis) = e.parent
}
/**
* Iterator over the element's preceding siblings.
*/
def precedingSiblingIterator(start: ElementAnalysis) = new IteratorBase(start) {
def initialNext = start.preceding
def subsequentNext(e: ElementAnalysis) = e.preceding
}
/**
* Return a list of ancestors in the same scope from leaf to root.
*/
def getAllAncestorsInScope(start: ElementAnalysis, scope: Scope): List[ElementAnalysis] =
ancestorIterator(start) filter (_.scope == scope) toList
/**
* Return a list of ancestor-or-self in the same scope from leaf to root.
*/
def getAllAncestorsOrSelfInScope(start: ElementAnalysis): List[ElementAnalysis] =
start :: getAllAncestorsInScope(start, start.scope)
/**
* Get the closest ancestor in the same scope.
*/
def getClosestAncestorInScope(start: ElementAnalysis, scope: Scope) =
ancestorIterator(start) find (_.scope == scope)
/**
* Return the first ancestor with a binding analysis that is in the same scope/model.
*/
def getClosestAncestorInScopeModel(start: ElementAnalysis, scopeModel: ScopeModel) =
ancestorIterator(start) find (e ⇒ ScopeModel(e.scope, e.model) == scopeModel)
/**
* Get the binding XPath expression from the @ref or (deprecated) @nodeset attribute.
*/
def getBindingExpression(element: Element): Option[String] =
Option(element.attributeValue(XFormsConstants.REF_QNAME)) orElse
Option(element.attributeValue(XFormsConstants.NODESET_QNAME))
def createLocationData(element: Element): ExtendedLocationData =
element.getData match {
case data: LocationData if (element ne null) && (data.getSystemID ne null) && data.getLine != -1 ⇒
new ExtendedLocationData(data, "gathering static information", element)
case _ ⇒ null
}
/**
* Get the value of an attribute containing a space-separated list of tokens as a set.
*/
def attSet(element: Element, qName: QName) =
stringOptionToSet(Option(element.attributeValue(qName)))
def attSet(element: Element, name: String) =
stringOptionToSet(Option(element.attributeValue(name)))
/**
* Get the value of an attribute containing a space-separated list of QNames as a set.
*/
def attQNameSet(element: Element, qName: QName, namespaces: NamespaceMapping) =
attSet(element, qName) map (Dom4jUtils.extractTextValueQName(namespaces.mapping, _, true))
}
|
wesley1001/orbeon-forms
|
src/main/scala/org/orbeon/oxf/xforms/analysis/ElementAnalysis.scala
|
Scala
|
lgpl-2.1
| 20,169 |
/*
,i::,
:;;;;;;;
;:,,::;.
1ft1;::;1tL
t1;::;1,
:;::; _____ __ ___ __
fCLff ;:: tfLLC / ___/ / |/ /____ _ _____ / /_
CLft11 :,, i1tffLi \\__ \\ ____ / /|_/ // __ `// ___// __ \\
1t1i .;; .1tf ___/ //___// / / // /_/ // /__ / / / /
CLt1i :,: .1tfL. /____/ /_/ /_/ \\__,_/ \\___//_/ /_/
Lft1,:;: , 1tfL:
;it1i ,,,:::;;;::1tti s_mach.codetools
.t1i .,::;;; ;1tt Copyright (c) 2016 S-Mach, Inc.
Lft11ii;::;ii1tfL: Author: [email protected]
.L1 1tt1ttt,,Li
...1LLLL...
*/
package s_mach.codetools.reflectPrint
trait ReflectPrintTupleImplicits {
implicit def mkTuple2ReflectPrint[A,B](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B]
) : ReflectPrint[(A,B)] =
ReflectPrint.forProductType[(A,B)]
implicit def mkTuple3ReflectPrint[A,B,C](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C]
) : ReflectPrint[(A,B,C)] =
ReflectPrint.forProductType[(A,B,C)]
implicit def mkTuple4ReflectPrint[A,B,C,D](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D]
) : ReflectPrint[(A,B,C,D)] =
ReflectPrint.forProductType[(A,B,C,D)]
implicit def mkTuple5ReflectPrint[A,B,C,D,E](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E]
) : ReflectPrint[(A,B,C,D,E)] =
ReflectPrint.forProductType[(A,B,C,D,E)]
implicit def mkTuple6ReflectPrint[A,B,C,D,E,F](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F]
) : ReflectPrint[(A,B,C,D,E,F)] =
ReflectPrint.forProductType[(A,B,C,D,E,F)]
implicit def mkTuple7ReflectPrint[A,B,C,D,E,F,G](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G]
) : ReflectPrint[(A,B,C,D,E,F,G)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G)]
implicit def mkTuple8ReflectPrint[A,B,C,D,E,F,G,H](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H]
) : ReflectPrint[(A,B,C,D,E,F,G,H)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H)]
implicit def mkTuple9ReflectPrint[A,B,C,D,E,F,G,H,I](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I)]
implicit def mkTuple10ReflectPrint[A,B,C,D,E,F,G,H,I,J](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J)]
implicit def mkTuple11ReflectPrint[A,B,C,D,E,F,G,H,I,J,K](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K)]
implicit def mkTuple12ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L)]
implicit def mkTuple13ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M)]
implicit def mkTuple14ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N)]
implicit def mkTuple15ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O)]
implicit def mkTuple16ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P)]
implicit def mkTuple17ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P],
qReflectPrint: ReflectPrint[Q]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q)]
implicit def mkTuple18ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P],
qReflectPrint: ReflectPrint[Q],
rReflectPrint: ReflectPrint[R]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R)]
implicit def mkTuple19ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P],
qReflectPrint: ReflectPrint[Q],
rReflectPrint: ReflectPrint[R],
sReflectPrint: ReflectPrint[S]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S)]
implicit def mkTuple20ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P],
qReflectPrint: ReflectPrint[Q],
rReflectPrint: ReflectPrint[R],
sReflectPrint: ReflectPrint[S],
tReflectPrint: ReflectPrint[T]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T)]
implicit def mkTuple21ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P],
qReflectPrint: ReflectPrint[Q],
rReflectPrint: ReflectPrint[R],
sReflectPrint: ReflectPrint[S],
tReflectPrint: ReflectPrint[T],
uReflectPrint: ReflectPrint[U]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U)]
implicit def mkTuple22ReflectPrint[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V](implicit
aReflectPrint: ReflectPrint[A],
bReflectPrint: ReflectPrint[B],
cReflectPrint: ReflectPrint[C],
dReflectPrint: ReflectPrint[D],
eReflectPrint: ReflectPrint[E],
fReflectPrint: ReflectPrint[F],
gReflectPrint: ReflectPrint[G],
hReflectPrint: ReflectPrint[H],
iReflectPrint: ReflectPrint[I],
jReflectPrint: ReflectPrint[J],
kReflectPrint: ReflectPrint[K],
lReflectPrint: ReflectPrint[L],
mReflectPrint: ReflectPrint[M],
nReflectPrint: ReflectPrint[N],
oReflectPrint: ReflectPrint[O],
pReflectPrint: ReflectPrint[P],
qReflectPrint: ReflectPrint[Q],
rReflectPrint: ReflectPrint[R],
sReflectPrint: ReflectPrint[S],
tReflectPrint: ReflectPrint[T],
uReflectPrint: ReflectPrint[U],
vReflectPrint: ReflectPrint[V]
) : ReflectPrint[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V)] =
ReflectPrint.forProductType[(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V)]
}
|
S-Mach/s_mach.codetools
|
codetools/src/main/scala/s_mach/codetools/reflectPrint/ReflectPrintTupleImplicits.scala
|
Scala
|
mit
| 13,650 |
package geotrellis.geometry
import scala.math.{atan, exp, floor, log, sin}
package object projection {
val earthRadius = 6378137.0
/**
* Given geographic coordinates (lng, lat), return web mercator
* coordinates (x, y).
*/
def latLngToWebMercator(lng:Double, lat:Double) = {
// TODO: figure out what to call const
val const = 0.017453292519943295
val x = lng * const * earthRadius
val a = lat * const
val b = (1.0 + sin(a)) / (1.0 - sin(a))
val y = (earthRadius / 2) * log(b)
(x, y)
}
/**
* Given web mercator coordinates (x, y), return geographic
* coordinates (lng, lat)
*/
def latLngToGeographic(x:Double, y:Double) = {
val lowerLimit = -20037508.3427892
val upperLimit = 20037508.3427892
if (x < lowerLimit || x > upperLimit) {
throw new Exception("point is outside mercator projection")
}
// TODO: figure out what to call these constants
val const1 = 57.295779513082323
val const2 = 1.5707963267948966
// determine the latitude
val a = x / earthRadius;
val b = a * const1
val c = floor((b + 180.0) / 360.0) * 360.0
val lat = b - c
// determine the longitude
val d = const2 - (2.0 * atan(exp((-1.0 * y) / earthRadius)))
val lng = d * const1
(lng, lat)
}
}
|
Tjoene/thesis
|
Case_Programs/geotrellis-0.7.0/src/main/scala/geotrellis/geometry/package.scala
|
Scala
|
gpl-2.0
| 1,306 |
def getOrElse[B >: A](b: => B): B = this match {
case Noone => b
case Soome(a) => a
}
|
grzegorzbalcerek/scala-exercises
|
Optioon/stepOptioonGetOrElse.scala
|
Scala
|
bsd-2-clause
| 90 |
package models.daos.slick
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO
import com.mohiva.play.silhouette.impl.providers.OAuth2Info
import play.api.db.slick._
import play.api.libs.iteratee.Enumerator
import play.api.libs.ws._
import play.api
import scala.concurrent.Future
import models.daos.slick.DBAuthTableDefinitions._
import play.api.db.slick.Config.driver.simple._
import java.nio.file.{Paths, Files}
import java.io.{FileOutputStream, File}
import java.util.UUID
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.libs.iteratee._
import play.api.libs.json._
import javax.inject.Inject
import com.mohiva.play.silhouette.api.{ Environment, LogoutEvent, Silhouette }
import com.mohiva.play.silhouette.impl.authenticators.JWTAuthenticator
import models.User
class OAuth2InfoDAOSlick @Inject() (implicit val env: Environment[User, JWTAuthenticator]) extends DelegableAuthInfoDAO[OAuth2Info] {
import play.api.Play.current
def save(loginInfo: LoginInfo, authInfo: OAuth2Info): Future[OAuth2Info] = Future.successful(
DB withSession { implicit session =>
val infoId = slickLoginInfos.filter(
x => x.providerID === loginInfo.providerID && x.providerKey === loginInfo.providerKey
).first.id.get
slickOAuth2Infos.filter(_.loginInfoId === infoId).firstOption match {
case Some(info) =>
slickOAuth2Infos update DBOAuth2Info(info.id, authInfo.accessToken, authInfo.tokenType, authInfo.expiresIn, authInfo.refreshToken, infoId)
case None => {
slickOAuth2Infos insert DBOAuth2Info(None, authInfo.accessToken, authInfo.tokenType, authInfo.expiresIn, authInfo.refreshToken, infoId)
}
}
authInfo
}
)
def dlProfilePicture(access_token: String): Future[File] = {
//val avatar_url = "http://cdns2.freepik.com/photos-libre/_21253111.jpg"
val avatar_url = "https://graph.facebook.com/v2.3/me/picture?width=9999&redirect=false&access_token="+access_token
val futureResult: Future[WSResponse] = WS.url(avatar_url).get()
val futureResponse : Future[(WSResponseHeaders, Enumerator[Array[Byte]])] =
futureResult.flatMap {
r => WS.url((r.json \\ "data" \\ "url").as[String]).getStream()
}
futureResponse.flatMap {
case (headers, body) =>
val newFileName: String = UUID.randomUUID().toString + ".jpg"
val file = new File("public/uploads/"+newFileName)
val outputStream = new FileOutputStream(file)
// The iteratee that writes to the output stream
val iteratee = Iteratee.foreach[Array[Byte]] { bytes =>
outputStream.write(bytes)
}
// Feed the body into the iteratee
(body |>>> iteratee).andThen {
case result =>
// Close the output stream whether there was an error or not
outputStream.close()
// Get the result or rethrow the error
result.get
}.map(_ => file)
}
}
def find(loginInfo: LoginInfo): Future[Option[OAuth2Info]] = {
Future.successful(
DB withSession { implicit session =>
slickLoginInfos.filter(info => info.providerID === loginInfo.providerID && info.providerKey === loginInfo.providerKey).firstOption match {
case Some(info) =>
val oAuth2Info = slickOAuth2Infos.filter(_.loginInfoId === info.id).first
Some(OAuth2Info(oAuth2Info.accessToken, oAuth2Info.tokenType, oAuth2Info.expiresIn, oAuth2Info.refreshToken))
case None => None
}
}
)
}
}
|
mehdichamouma/session-montpellier
|
app/models/daos/slick/OAuth2InfoDAOSlick.scala
|
Scala
|
apache-2.0
| 3,613 |
package com.rasterfoundry.api.maptoken
import java.util.UUID
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.model.StatusCodes
import cats.effect.IO
import com.rasterfoundry.akkautil.PaginationDirectives
import com.rasterfoundry.akkautil.{
Authentication,
CommonHandlers,
UserErrorHandler
}
import com.rasterfoundry.database._
import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport._
import doobie.util.transactor.Transactor
import com.rasterfoundry.database.filter.Filterables._
import com.rasterfoundry.datamodel._
import cats.Applicative
import doobie._
import doobie.implicits._
trait MapTokenRoutes
extends Authentication
with MapTokensQueryParameterDirective
with PaginationDirectives
with CommonHandlers
with UserErrorHandler {
val xa: Transactor[IO]
val mapTokenRoutes: Route = handleExceptions(userExceptionHandler) {
pathEndOrSingleSlash {
get { listMapTokens } ~
post { createMapToken }
} ~
pathPrefix(JavaUUID) { mapTokenId =>
get { getMapToken(mapTokenId) } ~
put { updateMapToken(mapTokenId) } ~
delete { deleteMapToken(mapTokenId) }
}
}
def listMapTokens: Route = authenticate { user =>
(withPagination & mapTokenQueryParams) { (page, mapTokenParams) =>
complete {
MapTokenDao
.listAuthorizedMapTokens(user, mapTokenParams, page)
.transact(xa)
.unsafeToFuture
}
}
}
def createMapToken: Route = authenticate { user =>
entity(as[MapToken.Create]) { newMapToken =>
authorizeAsync {
val authIO = (newMapToken.project, newMapToken.toolRun) match {
case (None, None) =>
Applicative[ConnectionIO].pure(false)
case (Some(projectId), None) =>
ProjectDao
.authorized(user, ObjectType.Project, projectId, ActionType.Edit)
.map(_.toBoolean)
case (None, Some(toolRunId)) =>
ToolRunDao
.authorized(user, ObjectType.Analysis, toolRunId, ActionType.Edit)
.map(_.toBoolean)
case _ => Applicative[ConnectionIO].pure(false)
}
authIO.transact(xa).unsafeToFuture
} {
onSuccess(
MapTokenDao.insert(newMapToken, user).transact(xa).unsafeToFuture
) { mapToken =>
complete((StatusCodes.Created, mapToken))
}
}
}
}
def getMapToken(mapTokenId: UUID): Route = authenticate { user =>
authorizeAsync {
MapTokenDao
.authorize(mapTokenId, user, ActionType.View)
.transact(xa)
.unsafeToFuture
} {
get {
rejectEmptyResponse {
complete {
MapTokenDao.query
.filter(mapTokenId)
.selectOption
.transact(xa)
.unsafeToFuture
}
}
}
}
}
def updateMapToken(mapTokenId: UUID): Route = authenticate { user =>
authorizeAsync {
MapTokenDao
.authorize(mapTokenId, user, ActionType.Edit)
.transact(xa)
.unsafeToFuture
} {
entity(as[MapToken]) { updatedMapToken =>
onSuccess(
MapTokenDao
.update(updatedMapToken, mapTokenId)
.transact(xa)
.unsafeToFuture
) {
completeSingleOrNotFound
}
}
}
}
def deleteMapToken(mapTokenId: UUID): Route = authenticate { user =>
authorizeAsync {
MapTokenDao
.authorize(mapTokenId, user, ActionType.Edit)
.transact(xa)
.unsafeToFuture
} {
onSuccess(
MapTokenDao.query
.filter(mapTokenId)
.delete
.transact(xa)
.unsafeToFuture
) {
completeSingleOrNotFound
}
}
}
}
|
aaronxsu/raster-foundry
|
app-backend/api/src/main/scala/maptoken/Routes.scala
|
Scala
|
apache-2.0
| 3,807 |
package sword.langbook.android.activities
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.{GridLayoutManager, LinearLayoutManager}
import sword.langbook.android.{TR, R}
import sword.langbook.db.Alphabet
object AlphabetDetails {
private val className = "sword.langbook.android.activities.AlphabetDetails"
def openWith(activity :Activity, requestCode :Int = 0, alphabetEncodedKey: String = null) = {
val intent = new Intent()
intent.setClassName(activity, className)
intent.putExtra(BundleKeys.alphabetKey, alphabetEncodedKey)
if (requestCode > 0) activity.startActivityForResult(intent, requestCode)
else activity.startActivity(intent)
}
}
class AlphabetDetails extends BaseActivity {
lazy val alphabetKeyOption = linkedDb.storageManager.decode(getIntent.getStringExtra(BundleKeys.alphabetKey))
lazy val alphabetOption = alphabetKeyOption.map(Alphabet(_))
override def onCreate(savedInstanceState :Bundle) :Unit = {
super.onCreate(savedInstanceState)
setContentView(R.layout.word_details)
val toolBar = findView(TR.toolBar)
val recyclerView = findView(TR.recyclerView)
for (alphabet <- alphabetOption) {
for (title <- alphabet.suitableTextForLanguage(preferredLanguage)) {
toolBar.setTitle(title)
}
val adapter = AlphabetDetailsAdapter(this, alphabet)
recyclerView.setLayoutManager(new GridLayoutManager(this, adapter.spanCount))
recyclerView.setAdapter(adapter)
}
}
}
|
carlos-sancho-ramirez/android-scala-langbook
|
src/main/scala/sword/langbook/android/activities/AlphabetDetails.scala
|
Scala
|
mit
| 1,541 |
/*
* Copyright 2014-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.atlas.core.util
import java.util.Comparator
import java.util.PriorityQueue
/**
* Fixed size buffer that can be used for computing the top-K items.
*
* @param maxSize
* Maximum size of the buffer.
* @param comparator
* Comparator used for checking the relative priority of entries.
*/
class BoundedPriorityBuffer[T <: AnyRef](maxSize: Int, comparator: Comparator[T]) {
require(maxSize > 0, "maxSize must be > 0")
private val queue = new PriorityQueue[T](comparator.reversed())
/**
* Add a value into the buffer if there is space or it has a higher priority than the
* lowest priority item currently in the buffer. If it has the same priority as the lowest
* priority item, then the previous value will be retained and the new value will be
* rejected.
*
* @param value
* Value to attempt to add into the buffer.
* @return
* The return value is either: a) a value that was ejected because of the new addition,
* b) the value that was passed in if it wasn't high enough priority, or c) `null` if
* the max size has not yet been reached.
*/
def add(value: T): T = {
if (queue.size == maxSize) {
// Buffer is full, check if the new value is higher priority than the lowest priority
// item in the heap
val lowestPriorityItem = queue.peek()
if (comparator.compare(value, lowestPriorityItem) < 0) {
queue.poll()
queue.offer(value)
lowestPriorityItem
} else {
value
}
} else {
queue.offer(value)
null.asInstanceOf[T]
}
}
/** Number of items in the buffer. */
def size: Int = {
queue.size
}
/** Invoke the function `f` for all items in the buffer. */
def foreach(f: T => Unit): Unit = {
queue.forEach(v => f(v))
}
/** Return a list containing all of the items in the buffer. */
def toList: List[T] = {
val builder = List.newBuilder[T]
val it = queue.iterator()
while (it.hasNext) {
builder += it.next()
}
builder.result()
}
/** Drain elements to a list that is ordered by priority. */
def drainToOrderedList(): List[T] = {
val builder = List.newBuilder[T]
while (!queue.isEmpty) {
builder += queue.poll()
}
builder.result()
}
}
|
copperlight/atlas
|
atlas-core/src/main/scala/com/netflix/atlas/core/util/BoundedPriorityBuffer.scala
|
Scala
|
apache-2.0
| 2,917 |
/*
Copyright 2017 Jo Pol
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/gpl.html dibl
*/
package dibl
import dibl.DiagramSvg.{ prolog, render }
import dibl.Force.{ Point, nudgeNodes }
import dibl.proto.TilesConfig
import scala.reflect.io.File
object Permutations {
def main(args: Array[String]): Unit = {
new java.io.File("target/test/permutations").mkdirs()
val stitches = Seq("ct", "ctct", "crclct", "clcrclc", "ctctc", "ctclctc")
for {
a <- stitches
b <- stitches.filterNot(_==a)
} {
create(s"net-$a-$b", s"a1=$a&b2=$b&patchWidth=9&patchHeight=9&tile=5-,-5&shiftColsSW=0&shiftRowsSW=2&shiftColsSE=2&shiftRowsSE=2")
create(s"weaving-$a-$b", s"a1=$a&a2=$b&patchWidth=9&patchHeight=9&tile=1,8&shiftColsSW=0&shiftRowsSW=2&shiftColsSE=1&shiftRowsSE=2")
}
System.exit(0)
}
private def create(name: String, q: String): Unit = {
File(s"target/test/permutations/$name.svg")
.writeAll(prolog + render(nudge(ThreadDiagram(NewPairDiagram.create(TilesConfig(q))))))
}
def nudge(d: Diagram): Diagram = nudgeNodes(d, Point(200, 100)).get
}
|
d-bl/GroundForge
|
src/test/scala/dibl/Permutations.scala
|
Scala
|
gpl-3.0
| 1,671 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.hive
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import scala.sys.process._
import scala.util.control.NonFatal
import org.apache.hadoop.conf.Configuration
import org.apache.spark.{SecurityManager, SparkConf, TestUtils}
import org.apache.spark.sql.{QueryTest, Row, SparkSession}
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.catalog.CatalogTableType
import org.apache.spark.sql.test.SQLTestUtils
import org.apache.spark.util.Utils
/**
* Test HiveExternalCatalog backward compatibility.
*
* Note that, this test suite will automatically download spark binary packages of different
* versions to a local directory `/tmp/spark-test`. If there is already a spark folder with
* expected version under this local directory, e.g. `/tmp/spark-test/spark-2.0.3`, we will skip the
* downloading for this spark version.
*/
class HiveExternalCatalogVersionsSuite extends SparkSubmitTestUtils {
private val wareHousePath = Utils.createTempDir(namePrefix = "warehouse")
private val tmpDataDir = Utils.createTempDir(namePrefix = "test-data")
// For local test, you can set `sparkTestingDir` to a static value like `/tmp/test-spark`, to
// avoid downloading Spark of different versions in each run.
private val sparkTestingDir = new File("/tmp/test-spark")
private val unusedJar = TestUtils.createJarWithClasses(Seq.empty)
override def afterAll(): Unit = {
try {
Utils.deleteRecursively(wareHousePath)
Utils.deleteRecursively(tmpDataDir)
Utils.deleteRecursively(sparkTestingDir)
} finally {
super.afterAll()
}
}
private def tryDownloadSpark(version: String, path: String): Unit = {
// Try a few mirrors first; fall back to Apache archive
val mirrors =
(0 until 2).flatMap { _ =>
try {
Some(getStringFromUrl("https://www.apache.org/dyn/closer.lua?preferred=true"))
} catch {
// If we can't get a mirror URL, skip it. No retry.
case _: Exception => None
}
}
val sites =
mirrors.distinct :+ "https://archive.apache.org/dist" :+ PROCESS_TABLES.releaseMirror
logInfo(s"Trying to download Spark $version from $sites")
for (site <- sites) {
val filename = s"spark-$version-bin-hadoop2.7.tgz"
val url = s"$site/spark/spark-$version/$filename"
logInfo(s"Downloading Spark $version from $url")
try {
getFileFromUrl(url, path, filename)
val downloaded = new File(sparkTestingDir, filename).getCanonicalPath
val targetDir = new File(sparkTestingDir, s"spark-$version").getCanonicalPath
Seq("mkdir", targetDir).!
val exitCode = Seq("tar", "-xzf", downloaded, "-C", targetDir, "--strip-components=1").!
Seq("rm", downloaded).!
// For a corrupted file, `tar` returns non-zero values. However, we also need to check
// the extracted file because `tar` returns 0 for empty file.
val sparkSubmit = new File(sparkTestingDir, s"spark-$version/bin/spark-submit")
if (exitCode == 0 && sparkSubmit.exists()) {
return
} else {
Seq("rm", "-rf", targetDir).!
}
} catch {
case ex: Exception =>
logWarning(s"Failed to download Spark $version from $url: ${ex.getMessage}")
}
}
fail(s"Unable to download Spark $version")
}
private def genDataDir(name: String): String = {
new File(tmpDataDir, name).getCanonicalPath
}
private def getFileFromUrl(urlString: String, targetDir: String, filename: String): Unit = {
val conf = new SparkConf
// if the caller passes the name of an existing file, we want doFetchFile to write over it with
// the contents from the specified url.
conf.set("spark.files.overwrite", "true")
val securityManager = new SecurityManager(conf)
val hadoopConf = new Configuration
val outDir = new File(targetDir)
if (!outDir.exists()) {
outDir.mkdirs()
}
// propagate exceptions up to the caller of getFileFromUrl
Utils.doFetchFile(urlString, outDir, filename, conf, securityManager, hadoopConf)
}
private def getStringFromUrl(urlString: String): String = {
val contentFile = File.createTempFile("string-", ".txt")
contentFile.deleteOnExit()
// exceptions will propagate to the caller of getStringFromUrl
getFileFromUrl(urlString, contentFile.getParent, contentFile.getName)
val contentPath = Paths.get(contentFile.toURI)
new String(Files.readAllBytes(contentPath), StandardCharsets.UTF_8)
}
override def beforeAll(): Unit = {
super.beforeAll()
val tempPyFile = File.createTempFile("test", ".py")
// scalastyle:off line.size.limit
Files.write(tempPyFile.toPath,
s"""
|from pyspark.sql import SparkSession
|import os
|
|spark = SparkSession.builder.enableHiveSupport().getOrCreate()
|version_index = spark.conf.get("spark.sql.test.version.index", None)
|
|spark.sql("create table data_source_tbl_{} using json as select 1 i".format(version_index))
|
|spark.sql("create table hive_compatible_data_source_tbl_{} using parquet as select 1 i".format(version_index))
|
|json_file = "${genDataDir("json_")}" + str(version_index)
|spark.range(1, 2).selectExpr("cast(id as int) as i").write.json(json_file)
|spark.sql("create table external_data_source_tbl_{}(i int) using json options (path '{}')".format(version_index, json_file))
|
|parquet_file = "${genDataDir("parquet_")}" + str(version_index)
|spark.range(1, 2).selectExpr("cast(id as int) as i").write.parquet(parquet_file)
|spark.sql("create table hive_compatible_external_data_source_tbl_{}(i int) using parquet options (path '{}')".format(version_index, parquet_file))
|
|json_file2 = "${genDataDir("json2_")}" + str(version_index)
|spark.range(1, 2).selectExpr("cast(id as int) as i").write.json(json_file2)
|spark.sql("create table external_table_without_schema_{} using json options (path '{}')".format(version_index, json_file2))
|
|parquet_file2 = "${genDataDir("parquet2_")}" + str(version_index)
|spark.range(1, 3).selectExpr("1 as i", "cast(id as int) as p", "1 as j").write.parquet(os.path.join(parquet_file2, "p=1"))
|spark.sql("create table tbl_with_col_overlap_{} using parquet options(path '{}')".format(version_index, parquet_file2))
|
|spark.sql("create view v_{} as select 1 i".format(version_index))
""".stripMargin.getBytes("utf8"))
// scalastyle:on line.size.limit
if (PROCESS_TABLES.testingVersions.isEmpty) {
fail("Fail to get the lates Spark versions to test.")
}
PROCESS_TABLES.testingVersions.zipWithIndex.foreach { case (version, index) =>
val sparkHome = new File(sparkTestingDir, s"spark-$version")
if (!sparkHome.exists()) {
tryDownloadSpark(version, sparkTestingDir.getCanonicalPath)
}
val args = Seq(
"--name", "prepare testing tables",
"--master", "local[2]",
"--conf", "spark.ui.enabled=false",
"--conf", "spark.master.rest.enabled=false",
"--conf", "spark.sql.hive.metastore.version=1.2.1",
"--conf", "spark.sql.hive.metastore.jars=maven",
"--conf", s"spark.sql.warehouse.dir=${wareHousePath.getCanonicalPath}",
"--conf", s"spark.sql.test.version.index=$index",
"--driver-java-options", s"-Dderby.system.home=${wareHousePath.getCanonicalPath}",
tempPyFile.getCanonicalPath)
runSparkSubmit(args, Some(sparkHome.getCanonicalPath), false)
}
tempPyFile.delete()
}
test("backward compatibility") {
val args = Seq(
"--class", PROCESS_TABLES.getClass.getName.stripSuffix("$"),
"--name", "HiveExternalCatalog backward compatibility test",
"--master", "local[2]",
"--conf", "spark.ui.enabled=false",
"--conf", "spark.master.rest.enabled=false",
"--conf", "spark.sql.hive.metastore.version=1.2.1",
"--conf", "spark.sql.hive.metastore.jars=maven",
"--conf", s"spark.sql.warehouse.dir=${wareHousePath.getCanonicalPath}",
"--driver-java-options", s"-Dderby.system.home=${wareHousePath.getCanonicalPath}",
unusedJar.toString)
runSparkSubmit(args)
}
}
object PROCESS_TABLES extends QueryTest with SQLTestUtils {
val releaseMirror = "https://dist.apache.org/repos/dist/release"
// Tests the latest version of every release line.
val testingVersions: Seq[String] = {
import scala.io.Source
try {
Source.fromURL(s"${releaseMirror}/spark").mkString
.split("\\n")
.filter(_.contains("""<li><a href="spark-"""))
.map("""<a href="spark-(\\d.\\d.\\d)/">""".r.findFirstMatchIn(_).get.group(1))
.filter(_ < org.apache.spark.SPARK_VERSION)
} catch {
// do not throw exception during object initialization.
case NonFatal(_) => Nil
}
}
protected var spark: SparkSession = _
def main(args: Array[String]): Unit = {
val session = SparkSession.builder()
.enableHiveSupport()
.getOrCreate()
spark = session
import session.implicits._
testingVersions.indices.foreach { index =>
Seq(
s"data_source_tbl_$index",
s"hive_compatible_data_source_tbl_$index",
s"external_data_source_tbl_$index",
s"hive_compatible_external_data_source_tbl_$index",
s"external_table_without_schema_$index").foreach { tbl =>
val tableMeta = spark.sharedState.externalCatalog.getTable("default", tbl)
// make sure we can insert and query these tables.
session.sql(s"insert into $tbl select 2")
checkAnswer(session.sql(s"select * from $tbl"), Row(1) :: Row(2) :: Nil)
checkAnswer(session.sql(s"select i from $tbl where i > 1"), Row(2))
// make sure we can rename table.
val newName = tbl + "_renamed"
sql(s"ALTER TABLE $tbl RENAME TO $newName")
val readBack = spark.sharedState.externalCatalog.getTable("default", newName)
val actualTableLocation = readBack.storage.locationUri.get.getPath
val expectedLocation = if (tableMeta.tableType == CatalogTableType.EXTERNAL) {
tableMeta.storage.locationUri.get.getPath
} else {
spark.sessionState.catalog.defaultTablePath(TableIdentifier(newName, None)).getPath
}
assert(actualTableLocation == expectedLocation)
// make sure we can alter table location.
withTempDir { dir =>
val path = dir.toURI.toString.stripSuffix("/")
sql(s"ALTER TABLE ${tbl}_renamed SET LOCATION '$path'")
val readBack = spark.sharedState.externalCatalog.getTable("default", tbl + "_renamed")
val actualTableLocation = readBack.storage.locationUri.get.getPath
val expected = dir.toURI.getPath.stripSuffix("/")
assert(actualTableLocation == expected)
}
}
// test permanent view
checkAnswer(sql(s"select i from v_$index"), Row(1))
// SPARK-22356: overlapped columns between data and partition schema in data source tables
val tbl_with_col_overlap = s"tbl_with_col_overlap_$index"
assert(spark.table(tbl_with_col_overlap).columns === Array("i", "p", "j"))
checkAnswer(spark.table(tbl_with_col_overlap), Row(1, 1, 1) :: Row(1, 1, 1) :: Nil)
assert(sql("desc " + tbl_with_col_overlap).select("col_name")
.as[String].collect().mkString(",").contains("i,p,j"))
}
}
}
|
aosagie/spark
|
sql/hive/src/test/scala/org/apache/spark/sql/hive/HiveExternalCatalogVersionsSuite.scala
|
Scala
|
apache-2.0
| 12,446 |
package actors
import akka.actor.{ActorSystem, Actor, Props, ActorRef, PoisonPill}
import akka.testkit.TestKit
import akka.testkit.ImplicitSender
import org.scalatest.{WordSpecLike, Matchers, BeforeAndAfterAll}
import cc.mewa.channels.ChannelManagerActor
import akka.util.Timeout
import akka.testkit.TestProbe
import scala.concurrent.duration._
import akka.actor.Identify
import akka.actor.ActorIdentity
import cc.mewa.channels.ChannelActor
import cc.mewa.api.Protocol._
/**
* Correct connection params for test spec are:
* channel: test
* password: pass
*/
class ConnectionActorSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
def this() = this(ActorSystem("ConnectionActorSpec"))
override def beforeAll {
val channelManager = system.actorOf(ChannelManagerActor.props(None), "channel-manager")
}
override def afterAll {
TestKit.shutdownActorSystem(system)
}
import ConnectionActor._
"New socket" should {
"not be connected to the channel" in {
val wsActor = system.actorOf(ConnectionActor.props(self))
wsActor ! SendEvent("eventId", "params", false)
expectMsg(NotConnectedError)
}
}
"Not connected socket" should {
"refuse connection with wrong channel name" in {
val wsActor = system.actorOf(ConnectionActor.props(self))
wsActor ! ConnectToChannel("", "", "pass", List())
expectMsg(AuthorizationError)
}
"connect to the channel" in {
val wsActor = system.actorOf(ConnectionActor.props(self))
wsActor ! ConnectToChannel("test1", "dev1", "pass1", List())
expectMsg(ConnectedEvent)
}
}
"Connected socket" should {
"remove its listener from channel on disconnect" in {
val probe = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe.ref))
probe.send(socket1, ConnectToChannel("test1", "dev1", "pass1", List()))
probe.expectMsg(ConnectedEvent)
val channel = system.actorSelection("/user/channel-manager/test1")
channel ! ChannelActor.RegisterDevice("testDevice", List.empty)
probe.send(socket1, DisconnectFromChannel)
fishForMessage() {
case ChannelActor.LeftChannelEvent("dev1", _) => true
case _ => false
}
}
"remove its listener when stopped" in {
val probe = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe.ref))
probe.send(socket1, ConnectToChannel("test2", "dev1", "pass1", List()))
probe.expectMsg(ConnectedEvent)
val channel = system.actorSelection("/user/channel-manager/test2")
channel ! ChannelActor.RegisterDevice("testDevice", List.empty)
system.stop(socket1)
fishForMessage() {
case ChannelActor.LeftChannelEvent("dev1", _) => true
case _ => false
}
}
"send event" in {
val probe1 = TestProbe()
val probe2 = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe1.ref))
val socket2 = system.actorOf(ConnectionActor.props(probe2.ref))
probe1.send(socket1, ConnectToChannel("test3", "probe1", "pass1", List()))
probe2.send(socket2, ConnectToChannel("test3", "probe2", "pass1", List("")))
probe2.expectMsg(ConnectedEvent)
probe1.send(socket1, SendEvent("event1", "12", false))
probe2.fishForMessage() {
case Event(_, "probe1", "event1", "12") => true
case m => false
}
}
"ack event" in {
val probe1 = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe1.ref))
probe1.send(socket1, ConnectToChannel("test3", "probe1", "pass1", List()))
probe1.expectMsg(ConnectedEvent)
probe1.send(socket1, SendEvent("event1", "12", true))
probe1.fishForMessage() {
case Ack => true
case m => false
}
}
"send message" in {
val probe1 = TestProbe()
val probe2 = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe1.ref))
val socket2 = system.actorOf(ConnectionActor.props(probe2.ref))
probe1.send(socket1, ConnectToChannel("test3", "probe1", "pass1", List()))
probe2.send(socket2, ConnectToChannel("test3", "probe2", "pass1", List()))
probe2.expectMsg(ConnectedEvent)
probe1.send(socket1, SendMessage("probe2", "event1", "12"))
probe2.fishForMessage() {
case Message(_, "probe1", "event1", "12") => true
case m => false
}
}
"return list of all connected devices" in {
val probe1 = TestProbe()
val probe2 = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe1.ref))
val socket2 = system.actorOf(ConnectionActor.props(probe2.ref))
probe1.send(socket1, ConnectToChannel("test3", "probe1", "pass1", List()))
probe2.send(socket2, ConnectToChannel("test3", "probe2", "pass1", List()))
probe1.expectMsg(ConnectedEvent)
probe1.send(socket1, GetDevices)
probe1.fishForMessage() {
case DevicesEvent(_, List("probe1", "probe2")) => true
case DevicesEvent(_, List("probe2", "probe1")) => true
case m =>
false
}
}
}
"Connecting 2 devices with the same name" should {
"second device should be able to connect" in {
val probe1 = TestProbe()
val probe2 = TestProbe()
val socket1 = system.actorOf(ConnectionActor.props(probe1.ref))
val socket2 = system.actorOf(ConnectionActor.props(probe2.ref))
probe1.send(socket1, ConnectToChannel("test3", "probe1", "pass1", List()))
probe1.expectMsg(ConnectedEvent)
probe2.send(socket2, ConnectToChannel("test3", "probe1", "pass1", List("")))
probe2.expectMsg(ConnectedEvent)
}
}
}
|
AnthillTech/mewa
|
test/actors/ConnectionActorSpec.scala
|
Scala
|
bsd-2-clause
| 5,803 |
package org.alcaudon.api
import java.util.UUID
import cats.Semigroup
import cats.implicits._
import org.alcaudon.api.DataflowBuilder._
import org.alcaudon.api.DataflowNodeRepresentation.{
ComputationRepresentation,
SinkRepresentation,
SourceRepresentation,
StreamRepresentation
}
import org.alcaudon.core.sources.SourceFunc
import org.alcaudon.core.{DataflowGraph, KeyExtractor}
import scala.collection.immutable.{Map => IMap}
import scala.collection.mutable.{Map, Set}
object DataflowBuilder {
def apply(dataflowId: String): DataflowBuilder = {
new DataflowBuilder(dataflowId)
}
case class ConstantExtractor(key: String) extends KeyExtractor {
override def extractKey(msg: Array[Byte]): String = key
}
object AlcaudonInputStream {
def apply(name: String)(keyFn: Array[Byte] => String) =
new AlcaudonInputStream(name, new KeyExtractor {
override def extractKey(msg: Array[Byte]): String = keyFn(msg)
})
}
case class AlcaudonInputStream(name: String,
keyExtractor: KeyExtractor,
computationId: String = "")
def OutputStreams(streams: String*): List[String] = streams.toList
}
class DataflowBuilder(dataflowName: String) {
private val id = UUID.randomUUID().toString
val computations = Map[String, ComputationRepresentation]()
val streams = Set[String]()
val streamInputs = Map[String, StreamRepresentation]()
val sources = Map[String, SourceRepresentation]()
val sinks = Map[String, SinkRepresentation]()
val graphBuilder = new DataflowGraphBuilder
def withComputation(id: String,
computation: Computation,
outputStreams: List[String],
inputStreams: AlcaudonInputStream*): DataflowBuilder = {
val uuid = UUID.randomUUID().toString
for {
inputStream <- inputStreams
stream <- streamInputs
.get(inputStream.name)
.orElse(Some(StreamRepresentation(inputStream.name)))
} {
if (sources.contains(inputStream.name)) {
val source = sources.get(inputStream.name).get
source.downstream += (uuid -> inputStream.keyExtractor)
} else {
stream.downstream += (uuid -> inputStream.keyExtractor)
streamInputs += (inputStream.name -> stream)
}
}
streams ++= inputStreams.map(_.name)
streams ++= outputStreams
graphBuilder.addComputation(id)
inputStreams.foreach { inputStream =>
graphBuilder.addStream(inputStream.name)
graphBuilder.addEdge(inputStream.name, id)
}
outputStreams.foreach { outputStream =>
graphBuilder.addStream(outputStream)
graphBuilder.addEdge(id, outputStream)
}
computations += (uuid -> ComputationRepresentation(
computation.getClass.getName,
inputStreams.toList,
outputStreams))
this
}
def withSource(name: String, sourceFN: SourceFunc): DataflowBuilder = {
graphBuilder.addSource(name)
streams += name
sources += (name -> SourceRepresentation(name, sourceFN))
this
}
def withSink(sinkId: String, sink: Sink): DataflowBuilder = {
graphBuilder.addSink(sinkId)
sinks += (sinkId -> SinkRepresentation(sinkId, sink))
this
}
def build() = {
val nonConsumedStreams = streams.toSet -- streamInputs.keySet
val nonConsumedStreamsMap =
nonConsumedStreams
.map(name => name -> StreamRepresentation(name))
.toMap
val streamReps = Semigroup[IMap[String, StreamRepresentation]]
.combine(nonConsumedStreamsMap, streamInputs.toMap)
DataflowGraph(dataflowName,
id,
// graphBuilder.internalGraph,
computations.toMap,
streams.toSet,
streamReps,
sources.toMap,
sinks.toMap)
}
}
|
fcofdez/alcaudon
|
src/main/scala/org/alcaudon/api/DataflowBuilder.scala
|
Scala
|
apache-2.0
| 3,918 |
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest // Change me in MustMatchers
import org.scalatest.matchers._
import org.scalatest.enablers._
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import scala.util.matching.Regex
import java.lang.reflect.Field
import scala.reflect.Manifest
import Helper.transformOperatorChars
import scala.collection.Traversable
import Assertions.areEqualComparingArraysStructurally
import scala.collection.GenTraversable
import scala.collection.GenSeq
import scala.collection.GenMap
import org.scalautils.Tolerance
import org.scalautils.Explicitly
import org.scalautils.Interval
import org.scalautils.TripleEqualsInvocation
import scala.annotation.tailrec
import org.scalautils.Equality
import org.scalatest.words.ShouldVerb
import org.scalautils.TripleEqualsInvocationOnInterval
import org.scalautils.EqualityConstraint
import Matchers.andMatchersAndApply
import Matchers.orMatchersAndApply
import words.MatcherWords
import words.FullyMatchWord
import words.StartWithWord
import words.EndWithWord
import words.IncludeWord
import words.HaveWord
import words.BeWord
import words.NotWord
import words.ContainWord
import words.NoneOfContainMatcher
import words.OnlyContainMatcher
import words.TheSameIteratedElementsAsContainMatcher
import words.AllOfContainMatcher
import words.InOrderContainMatcher
import words.InOrderOnlyContainMatcher
import words.OneOfContainMatcher
import words.TheSameElementsAsContainMatcher
import Matchers.matchSymbolToPredicateMethod
import words.ResultOfLengthWordApplication
import words.ResultOfSizeWordApplication
import words.ResultOfLessThanComparison
import words.ResultOfGreaterThanComparison
import words.ResultOfLessThanOrEqualToComparison
import words.ResultOfGreaterThanOrEqualToComparison
import words.ResultOfAWordToSymbolApplication
import words.ResultOfAWordToBePropertyMatcherApplication
import words.ResultOfAWordToAMatcherApplication
import words.ResultOfAnWordToSymbolApplication
import words.ResultOfAnWordToBePropertyMatcherApplication
import words.ResultOfAnWordToAnMatcherApplication
import words.ResultOfTheSameInstanceAsApplication
import words.ResultOfRegexWordApplication
import words.ResultOfKeyWordApplication
import words.ResultOfValueWordApplication
// TODO: drop generic support for be as an equality comparison, in favor of specific ones.
// TODO: mention on JUnit and TestNG docs that you can now mix in ShouldMatchers or MustMatchers
// TODO: Put links from ShouldMatchers to wherever I reveal the matrix and algo of how properties are checked dynamically.
// TODO: double check that I wrote tests for (length (7)) and (size (8)) in parens
// TODO: document how to turn off the === implicit conversion
// TODO: Document you can use JMock, EasyMock, etc.
import Helper.accessProperty
/**
* Trait that provides a domain specific language (DSL) for expressing assertions in tests
* using the word <code>should</code>. For example, if you mix <code>Matchers</code> into
* a suite class, you can write an equality assertion in that suite like this:
*
* <pre class="stHighlight">
* result should equal (3)
* </pre>
*
* <p>
* Here <code>result</code> is a variable, and can be of any type. If the object is an
* <code>Int</code> with the value 3, execution will continue (<em>i.e.</em>, the expression will result
* in the unit value, <code>()</code>). Otherwise, a <code>TestFailedException</code>
* will be thrown with a detail message that explains the problem, such as <code>"7 did not equal 3"</code>.
* This <code>TestFailedException</code> will cause the test to fail.
* </p>
*
* <p>
* The <code>left should equal (right)</code> syntax works by calling <code>==</code> on the <code>left</code>
* value, passing in the <code>right</code> value, on every type except arrays. If both <code>left</code> and right are arrays, <code>deep</code>
* will be invoked on both <code>left</code> and <code>right</code> before comparing them with <em>==</em>. Thus, even though this expression
* will yield false, because <code>Array</code>'s <code>equals</code> method compares object identity:
* </p>
*
* <pre class="stHighlight">
* Array(1, 2) == Array(1, 2) // yields false
* </pre>
*
* <p>
* The following expression will <em>not</em> result in a <code>TestFailedException</code>, because ScalaTest compares
* the two arrays structurally, taking into consideration the equality of the array's contents:
* </p>
*
* <pre class="stHighlight">
* Array(1, 2) should equal (Array(1, 2)) // succeeds (i.e., does not throw TestFailedException)
* </pre>
*
* <p>
* If you ever do want to verify that two arrays are actually the same object (have the same identity), you can use the
* <code>be theSameInstanceAs</code> syntax, described below.
* </p>
*
* <h2>Checking size and length</h2>
*
* <p>
* You can check the size or length of just about any type of object for which it
* would make sense. Here's how checking for length looks:
* </p>
* <pre class="stHighlight">
* result should have length (3)
* </pre>
*
* <p>
* Size is similar:
* </p>
*
* <pre class="stHighlight">
* result should have size (10)
* </pre>
*
* <p>
* The <code>length</code> syntax can be used with <code>String</code>, <code>Array</code>, any <code>scala.collection.GenSeq</code>,
* any <code>java.util.List</code>, and any type <code>T</code> for which an implicit <code>Length[T]</code> type class is
* available in scope.
* Similarly, the <code>size</code> syntax can be used with <code>Array</code>, any <code>scala.collection.GenTraversable</code>,
* any <code>java.util.List</code>, and any type <code>T</code> for which an implicit <code>Size[T]</code> type class is
* available in scope. You can enable the <code>length</code> or <code>size</code> syntax for your own arbitrary types, therefore,
* by defining <a href="ClassicMatchers$Length.html"><code>Length</code></a> or <a href="ClassicMatchers$Size.html"><code>Size</code></a> type
* classes for those types.
* </p>
*
* <h2>Checking strings</h2>
*
* <p>
* You can check for whether a string starts with, ends with, or includes a substring like this:
* </p>
*
* <pre class="stHighlight">
* string should startWith ("Hello")
* string should endWith ("world")
* string should include ("seven")
* </pre>
*
* <p>
* You can check for whether a string starts with, ends with, or includes a regular expression, like this:
* </p>
*
* <pre class="stHighlight">
* string should startWith regex ("Hel*o")
* string should endWith regex ("wo.ld")
* string should include regex ("wo.ld")
* </pre>
*
* <p>
* And you can check whether a string fully matches a regular expression, like this:
* </p>
*
* <pre class="stHighlight">
* string should fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""")
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*
* <h2>Greater and less than</h2>
* <p>
* You can check whether any type that is, or can be implicitly converted to,
* an <code>Ordered[T]</code> is greater than, less than, greater than or equal, or less
* than or equal to a value of type <code>T</code>. The syntax is:
* </p>
* <pre class="stHighlight">
* one should be < (7)
* one should be > (0)
* one should be <= (7)
* one should be >= (0)
* </pre>
*
* <h2>Checking equality with <code>be</code> <code>=</code><code>=</code><code>=</code></h2>
*
* <p>
* An alternate way to check for equality of two objects is to use <code>be</code> with
* <code>===</code>. Here's an example:
* </p>
*
* <pre class="stHighlight">
* result should be === (3)
* </pre>
*
* <p>
* Here <code>result</code> is a variable, and can be of any type. If the object is an
* <code>Int</code> with the value 3, execution will continue (<em>i.e.</em>, the expression will result
* in the unit value, <code>()</code>). Otherwise, a <code>TestFailedException</code>
* will be thrown with a detail message that explains the problem, such as <code>"7 was not equal to 3"</code>.
* This <code>TestFailedException</code> will cause the test to fail.
* </p>
*
* <p>
* The <code>left should be === (right)</code> syntax works by calling <code>==</code> on the <code>left</code>
* value, passing in the <code>right</code> value, on every type except arrays. If both <code>left</code> and right are arrays, <code>deep</code>
* will be invoked on both <code>left</code> and <code>right</code> before comparing them with <em>==</em>. Thus, even though this expression
* will yield false, because <code>Array</code>'s <code>equals</code> method compares object identity:
* </p>
*
* <pre class="stHighlight">
* Array(1, 2) == Array(1, 2) // yields false
* </pre>
*
* <p>
* The following expression will <em>not</em> result in a <code>TestFailedException</code>, because ScalaTest compares
* the two arrays structurally, taking into consideration the equality of the array's contents:
* </p>
*
* <pre class="stHighlight">
* Array(1, 2) should be === (Array(1, 2)) // succeeds (i.e., does not throw TestFailedException)
* </pre>
*
* <p>
* If you ever do want to verify that two arrays are actually the same object (have the same identity), you can use the
* <code>be theSameInstanceAs</code> syntax, described below.
* </p>
*
* <h2>Checking <code>Boolean</code> properties with <code>be</code></h2>
*
* <p>
* If an object has a method that takes no parameters and returns boolean, you can check
* it by placing a <code>Symbol</code> (after <code>be</code>) that specifies the name
* of the method (excluding an optional prefix of "<code>is</code>"). A symbol literal
* in Scala begins with a tick mark and ends at the first non-identifier character. Thus,
* <code>'empty</code> results in a <code>Symbol</code> object at runtime, as does
* <code>'defined</code> and <code>'file</code>. Here's an example:
* </p>
*
* <pre class="stHighlight">
* emptySet should be ('empty)
* </pre>
*
* Given this code, ScalaTest will use reflection to look on the object referenced from
* <code>emptySet</code> for a method that takes no parameters and results in <code>Boolean</code>,
* with either the name <code>empty</code> or <code>isEmpty</code>. If found, it will invoke
* that method. If the method returns <code>true</code>, execution will continue. But if it returns
* <code>false</code>, a <code>TestFailedException</code> will be thrown that will contain a detail message, such as:
*
* <pre class="stHighlight">
* Set(1, 2, 3) was not empty
* </pre>
*
* <p>
* This <code>be</code> syntax can be used with any type. If the object does
* not have an appropriately named predicate method, you'll get a <code>TestFailedException</code>
* at runtime with a detail message that explains the problem.
* (For the details on how a field or method is selected during this
* process, see the documentation for <a href="Matchers$BeWord.html"><code>BeWord</code></a>.)
* </p>
*
* <p>
* If you think it reads better, you can optionally put <code>a</code> or <code>an</code> after
* <code>be</code>. For example, <code>java.io.File</code> has two predicate methods,
* <code>isFile</code> and <code>isDirectory</code>. Thus with a <code>File</code> object
* named <code>temp</code>, you could write:
* </p>
*
* <pre class="stHighlight">
* temp should be a ('file)
* </pre>
*
* <p>
* Or, given <code>java.awt.event.KeyEvent</code> has a method <code>isActionKey</code> that takes
* no arguments and returns <code>Boolean</code>, you could assert that a <code>KeyEvent</code> is
* an action key with:
*</p>
*
* <pre class="stHighlight">
* keyEvent should be an ('actionKey)
* </pre>
*
* <p>
* If you prefer to check <code>Boolean</code> properties in a type-safe manner, you can use a <code>BePropertyMatcher</code>.
* This would allow you to write expressions such as:
* </p>
*
* <pre class="stHighlight">
* emptySet should be (empty)
* temp should be a (file)
* keyEvent should be an (actionKey)
* </pre>
*
* <p>
* These expressions would fail to compile if <code>should</code> is used on an inappropriate type, as determined
* by the type parameter of the <code>BePropertyMatcher</code> being used. (For example, <code>file</code> in this example
* would likely be of type <code>BePropertyMatcher[java.io.File]</code>. If used with an appropriate type, such an expression will compile
* and at run time the <code>Boolean</code> property method or field will be accessed directly; <em>i.e.</em>, no reflection will be used.
* See the documentation for <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a> for more information.
* </p>
*
* <h2>Using custom <code>BeMatchers</code></h2>
*
* If you want to create a new way of using <code>be</code>, which doesn't map to an actual property on the
* type you care about, you can create a <code>BeMatcher</code>. You could use this, for example, to create <code>BeMatcher[Int]</code>
* called <code>odd</code>, which would match any odd <code>Int</code>, and <code>even</code>, which would match
* any even <code>Int</code>.
* Given this pair of <code>BeMatcher</code>s, you could check whether an <code>Int</code> was odd or even with expressions like:
* </p>
*
* <pre class="stHighlight">
* num should be (odd)
* num should not be (even)
* </pre>
*
* For more information, see the documentation for <a href="BeMatcher.html"><code>BeMatcher</code></a>.
*
* <h2>Checking object identity</h2>
*
* <p>
* If you need to check that two references refer to the exact same object, you can write:
* </p>
*
* <pre class="stHighlight">
* ref1 should be theSameInstanceAs (ref2)
* </pre>
*
* <h2>Checking numbers against a range</h2>
*
* <p>
* To check whether a floating point number has a value that exactly matches another, you
* can use <code>should equal</code>:
* </p>
*
* <pre class="stHighlight">
* sevenDotOh should equal (7.0)
* </pre>
*
* <p>
* Often, however, you may want to check whether a floating point number is within a
* range. You can do that using <code>be</code> and <code>plusOrMinus</code>, like this:
* </p>
*
* <pre class="stHighlight">
* sevenDotOh should be (6.9 plusOrMinus 0.2)
* </pre>
*
* <p>
* This expression will cause a <code>TestFailedException</code> to be thrown if the floating point
* value, <code>sevenDotOh</code> is outside the range <code>6.7</code> to <code>7.1</code>.
* You can also use <code>plusOrMinus</code> with integral types, for example:
* </p>
*
* <pre class="stHighlight">
* seven should be (6 plusOrMinus 2)
* </pre>
*
* <h2>Traversables, iterables, sets, sequences, and maps</h2>
*
* <p>
* You can use some of the syntax shown previously with <code>Iterable</code> and its
* subtypes. For example, you can check whether an <code>Iterable</code> is <code>empty</code>,
* like this:
* </p>
*
* <pre class="stHighlight">
* iterable should be ('empty)
* </pre>
*
* <p>
* You can check the length of an <code>Seq</code> (<code>Array</code>, <code>List</code>, etc.),
* like this:
* </p>
*
* <pre class="stHighlight">
* array should have length (3)
* list should have length (9)
* </pre>
*
* <p>
* You can check the size of any <code>Traversable</code>, like this:
* </p>
*
* <pre class="stHighlight">
* map should have size (20)
* set should have size (90)
* </pre>
*
* <p>
* In addition, you can check whether an <code>Iterable</code> contains a particular
* element, like this:
* </p>
*
* <pre class="stHighlight">
* iterable should contain ("five")
* </pre>
*
* <p>
* You can also check whether a <code>Map</code> contains a particular key, or value, like this:
* </p>
*
* <pre class="stHighlight">
* map should contain key (1)
* map should contain value ("Howdy")
* </pre>
*
* <h2>Java collections and maps</h2>
*
* <p>
* You can use similar syntax on Java collections (<code>java.util.Collection</code>) and maps (<code>java.util.Map</code>).
* For example, you can check whether a Java <code>Collection</code> or <code>Map</code> is <code>empty</code>,
* like this:
* </p>
*
* <pre class="stHighlight">
* javaCollection should be ('empty)
* javaMap should be ('empty)
* </pre>
*
* <p>
* Even though Java's <code>List</code> type doesn't actually have a <code>length</code> or <code>getLength</code> method,
* you can nevertheless check the length of a Java <code>List</code> (<code>java.util.List</code>) like this:
* </p>
*
* <pre class="stHighlight">
* javaList should have length (9)
* </pre>
*
* <p>
* You can check the size of any Java <code>Collection</code> or <code>Map</code>, like this:
* </p>
*
* <pre class="stHighlight">
* javaMap should have size (20)
* javaSet should have size (90)
* </pre>
*
* <p>
* In addition, you can check whether a Java <code>Collection</code> contains a particular
* element, like this:
* </p>
*
* <pre class="stHighlight">
* javaCollection should contain ("five")
* </pre>
*
* <p>
* One difference to note between the syntax supported on Java collections and that of Scala
* iterables is that you can't use <code>contain (...)</code> syntax with a Java <code>Map</code>.
* Java differs from Scala in that its <code>Map</code> is not a subtype of its <code>Collection</code> type.
* If you want to check that a Java <code>Map</code> contains a specific key/value pair, the best approach is
* to invoke <code>entrySet</code> on the Java <code>Map</code> and check that entry set for the appropriate
* element (a <code>java.util.Map.Entry</code>) using <code>contain (...)</code>.
* </p>
*
* <p>
* Despite this difference, the other (more commonly used) map matcher syntax works just fine on Java <code>Map</code>s.
* You can, for example, check whether a Java <code>Map</code> contains a particular key, or value, like this:
* </p>
*
* <pre class="stHighlight">
* javaMap should contain key (1)
* javaMap should contain value ("Howdy")
* </pre>
*
* <h2>Be as an equality comparison</h2>
*
* <p>
* All uses of <code>be</code> other than those shown previously perform an equality comparison. In other words, they work
* the same as <code>equals</code>. This redundance between <code>be</code> and <code>equals</code> exists because it enables syntax
* that sometimes sounds more natural. For example, instead of writing:
* </p>
*
* <pre class="stHighlight">
* result should equal (null)
* </pre>
*
* <p>
* You can write:
* </p>
*
* <pre class="stHighlight">
* result should be (null)
* </pre>
*
* <p>
* (Hopefully you won't write that too much given <code>null</code> is error prone, and <code>Option</code>
* is usually a better, well, option.)
* Here are some other examples of <code>be</code> used for equality comparison:
* </p>
*
* <pre class="stHighlight">
* sum should be (7.0)
* boring should be (false)
* fun should be (true)
* list should be (Nil)
* option should be (None)
* option should be (Some(1))
* </pre>
*
* <p>
* As with <code>equal</code>, using <code>be</code> on two arrays results in <code>deep</code> being called on both arrays prior to
* calling <code>equal</code>. As a result,
* the following expression would <em>not</em> throw a <code>TestFailedException</code>:
* </p>
*
* <pre class="stHighlight">
* Array(1, 2) should be (Array(1, 2)) // succeeds (i.e., does not throw TestFailedException)
* </pre>
*
* <p>
* Because <code>be</code> is used in several ways in ScalaTest matcher syntax, just as it is used in many ways in English, one
* potential point of confusion in the event of a failure is determining whether <code>be</code> was being used as an equality comparison or
* in some other way, such as a property assertion. To make it more obvious when <code>be</code> is being used for equality, the failure
* messages generated for those equality checks will include the word <code>equal</code> in them. For example, if this expression fails with a
* <code>TestFailedException</code>:
* </p>
*
* <pre class="stHighlight">
* option should be (Some(1))
* </pre>
*
* <p>
* The detail message in that <code>TestFailedException</code> will include the words <code>"equal to"</code> to signify <code>be</code>
* was in this case being used for equality comparison:
* </p>
*
* <pre class="stHighlight">
* Some(2) was not equal to Some(1)
* </pre>
*
* <h2>Being negative</h2>
*
* <p>
* If you wish to check the opposite of some condition, you can simply insert <code>not</code> in the expression.
* Here are a few examples:
* </p>
*
* <pre class="stHighlight">
* result should not be (null)
* sum should not be <= (10)
* mylist should not equal (yourList)
* string should not startWith ("Hello")
* </pre>
*
* <h2>Logical expressions with <code>and</code> and <code>or</code></h2>
*
* <p>
* You can also combine matcher expressions with <code>and</code> and/or <code>or</code>, however,
* you must place parentheses or curly braces around the <code>and</code> or <code>or</code> expression. For example,
* this <code>and</code>-expression would not compile, because the parentheses are missing:
* </p>
*
* <pre class="stHighlight">
* map should contain key ("two") and not contain value (7) // ERROR, parentheses missing!
* </pre>
*
* <p>
* Instead, you need to write:
* </p>
*
* <pre class="stHighlight">
* map should (contain key ("two") and not contain value (7))
* </pre>
*
* <p>
* Here are some more examples:
* </p>
*
* <pre class="stHighlight">
* number should (be > (0) and be <= (10))
* option should (equal (Some(List(1, 2, 3))) or be (None))
* string should (
* equal ("fee") or
* equal ("fie") or
* equal ("foe") or
* equal ("fum")
* )
* </pre>
*
* <p>
* Two differences exist between expressions composed of these <code>and</code> and <code>or</code> operators and the expressions you can write
* on regular <code>Boolean</code>s using its <code>&&</code> and <code>||</code> operators. First, expressions with <code>and</code>
* and <code>or</code> do not short-circuit. The following contrived expression, for example, would print <code>"hello, world!"</code>:
* </p>
*
* <pre class="stHighlight">
* "yellow" should (equal ("blue") and equal { println("hello, world!"); "green" })
* </pre>
*
* <p>
* In other words, the entire <code>and</code> or <code>or</code> expression is always evaluated, so you'll see any side effects
* of the right-hand side even if evaluating
* only the left-hand side is enough to determine the ultimate result of the larger expression. Failure messages produced by these
* expressions will "short-circuit," however,
* mentioning only the left-hand side if that's enough to determine the result of the entire expression. This "short-circuiting" behavior
* of failure messages is intended
* to make it easier and quicker for you to ascertain which part of the expression caused the failure. The failure message for the previous
* expression, for example, would be:
* </p>
*
* <pre class="stHighlight">
* "yellow" did not equal "blue"
* </pre>
*
* <p>
* Most likely this lack of short-circuiting would rarely be noticeable, because evaluating the right hand side will usually not
* involve a side effect. One situation where it might show up, however, is if you attempt to <code>and</code> a <code>null</code> check on a variable with an expression
* that uses the variable, like this:
* </p>
*
* <pre class="stHighlight">
* map should (not be (null) and contain key ("ouch"))
* </pre>
*
* <p>
* If <code>map</code> is <code>null</code>, the test will indeed fail, but with a <code>NullPointerException</code>, not a
* <code>TestFailedException</code>. Here, the <code>NullPointerException</code> is the visible right-hand side effect. To get a
* <code>TestFailedException</code>, you would need to check each assertion separately:
* </p>
*
* <pre class="stHighlight">
* map should not be (null)
* map should contain key ("ouch")
* </pre>
*
* <p>
* If <code>map</code> is <code>null</code> in this case, the <code>null</code> check in the first expression will fail with
* a <code>TestFailedException</code>, and the second expression will never be executed.
* </p>
*
* <p>
* The other difference with <code>Boolean</code> operators is that although <code>&&</code> has a higher precedence than <code>||</code>,
* <code>and</code> and <code>or</code>
* have the same precedence. Thus although the <code>Boolean</code> expression <code>(a || b && c)</code> will evaluate the <code>&&</code> expression
* before the <code>||</code> expression, like <code>(a || (b && c))</code>, the following expression:
* </p>
*
* <pre class="stHighlight">
* traversable should (contain (7) or contain (8) and have size (9))
* </pre>
*
* <p>
* Will evaluate left to right, as:
* </p>
*
* <pre class="stHighlight">
* traversable should ((contain (7) or contain (8)) and have size (9))
* </pre>
*
* <p>
* If you really want the <code>and</code> part to be evaluated first, you'll need to put in parentheses, like this:
* </p>
*
* <pre class="stHighlight">
* traversable should (contain (7) or (contain (8) and have size (9)))
* </pre>
*
* <h2>Working with <code>Option</code>s</h2>
*
* <p>
* ScalaTest matchers has no special support for <code>Option</code>s, but you can
* work with them quite easily using syntax shown previously. For example, if you wish to check
* whether an option is <code>None</code>, you can write any of:
* </p>
*
* <pre class="stHighlight">
* option should equal (None)
* option should be (None)
* option should not be ('defined)
* option should be ('empty)
* </pre>
*
* <p>
* If you wish to check an option is defined, and holds a specific value, you can write either of:
* </p>
*
* <pre class="stHighlight">
* option should equal (Some("hi"))
* option should be (Some("hi"))
* </pre>
*
* <p>
* If you only wish to check that an option is defined, but don't care what it's value is, you can write:
* </p>
*
* <pre class="stHighlight">
* option should be ('defined)
* </pre>
*
* <p>
* If you mix in (or import the members of) <a href="../OptionValues.html"><code>OptionValues</code></a>,
* you can write one statement that indicates you believe an option should be defined and then say something else about its value. Here's an example:
* </p>
*
* <pre class="stHighlight">
* import org.scalatest.OptionValues._
* option.value should be < (7)
* </pre>
*
* <h2>Checking arbitrary properties with <code>have</code></h2>
*
* <p>
* Using <code>have</code>, you can check properties of any type, where a <em>property</em> is an attribute of any
* object that can be retrieved either by a public field, method, or JavaBean-style <code>get</code>
* or <code>is</code> method, like this:
* </p>
*
* <pre class="stHighlight">
* book should have (
* 'title ("Programming in Scala"),
* 'author (List("Odersky", "Spoon", "Venners")),
* 'pubYear (2008)
* )
* </pre>
*
* <p>
* This expression will use reflection to ensure the <code>title</code>, <code>author</code>, and <code>pubYear</code> properties of object <code>book</code>
* are equal to the specified values. For example, it will ensure that <code>book</code> has either a public Java field or method
* named <code>title</code>, or a public method named <code>getTitle</code>, that when invoked (or accessed in the field case) results
* in a the string <code>"Programming in Scala"</code>. If all specified properties exist and have their expected values, respectively,
* execution will continue. If one or more of the properties either does not exist, or exists but results in an unexpected value,
* a <code>TestFailedException</code> will be thrown that explains the problem. (For the details on how a field or method is selected during this
* process, see the documentation for <a href="Matchers$HavePropertyMatcherGenerator.html"><code>HavePropertyMatcherGenerator</code></a>.)
* </p>
*
* <p>
* When you use this syntax, you must place one or more property values in parentheses after <code>have</code>, seperated by commas, where a <em>property
* value</em> is a symbol indicating the name of the property followed by the expected value in parentheses. The only exceptions to this rule is the syntax
* for checking size and length shown previously, which does not require parentheses. If you forget and put parentheses in, however, everything will
* still work as you'd expect. Thus instead of writing:
* </p>
*
* <pre class="stHighlight">
* array should have length (3)
* set should have size (90)
* </pre>
*
* <p>
* You can alternatively, write:
* </p>
*
* <pre class="stHighlight">
* array should have (length (3))
* set should have (size (90))
* </pre>
*
* <p>
* If a property has a value different from the specified expected value, a <code>TestFailedError</code> will be thrown
* with a detail message that explains the problem. For example, if you assert the following on
* a <code>book</code> whose title is <code>Moby Dick</code>:
* </p>
*
* <pre class="stHighlight">
* book should have ('title ("A Tale of Two Cities"))
* </pre>
*
* <p>
* You'll get a <code>TestFailedException</code> with this detail message:
* </p>
*
* <pre>
* The title property had value "Moby Dick", instead of its expected value "A Tale of Two Cities",
* on object Book("Moby Dick", "Melville", 1851)
* </pre>
*
* <p>
* If you prefer to check properties in a type-safe manner, you can use a <code>HavePropertyMatcher</code>.
* This would allow you to write expressions such as:
* </p>
*
* <pre class="stHighlight">
* book should have (
* title ("Programming in Scala"),
* author (List("Odersky", "Spoon", "Venners")),
* pubYear (2008)
* )
* </pre>
*
* <p>
* These expressions would fail to compile if <code>should</code> is used on an inappropriate type, as determined
* by the type parameter of the <code>HavePropertyMatcher</code> being used. (For example, <code>title</code> in this example
* might be of type <code>HavePropertyMatcher[org.publiclibrary.Book]</code>. If used with an appropriate type, such an expression will compile
* and at run time the property method or field will be accessed directly; <em>i.e.</em>, no reflection will be used.
* See the documentation for <a href="HavePropertyMatcher.html"><code>HavePropertyMatcher</code></a> for more information.
* </p>
*
* <h2>Using custom matchers</h2>
*
* <p>
* If none of the built-in matcher syntax (or options shown so far for extending the syntax) satisfy a particular need you have, you can create
* custom <code>Matcher</code>s that allow
* you to place your own syntax directly after <code>should</code>. For example, class <code>java.io.File</code> has a method <code>exists</code>, which
* indicates whether a file of a certain path and name exists. Because the <code>exists</code> method takes no parameters and returns <code>Boolean</code>,
* you can call it using <code>be</code> with a symbol or <code>BePropertyMatcher</code>, yielding assertions like:
* </p>
*
* <pre class="stHighlight">
* file should be ('exists) // using a symbol
* file should be (inExistance) // using a BePropertyMatcher
* </pre>
*
* <p>
* Although these expressions will achieve your goal of throwing a <code>TestFailedException</code> if the file does not exist, they don't produce
* the most readable code because the English is either incorrect or awkward. In this case, you might want to create a
* custom <code>Matcher[java.io.File]</code>
* named <code>exist</code>, which you could then use to write expressions like:
* </p>
*
* <pre class="stHighlight">
* // using a plain-old Matcher
* file should exist
* file should not (exist)
* file should (exist and have ('name ("temp.txt")))
* </pre>
*
* <p>
* Note that when you use custom <code>Matcher</code>s, you will need to put parentheses around the custom matcher in more cases than with
* the built-in syntax. For example you will often need the parentheses after <code>not</code>, as shown above. (There's no penalty for
* always surrounding custom matchers with parentheses, and if you ever leave them off when they are needed, you'll get a compiler error.)
* For more information about how to create custom <code>Matcher</code>s, please see the documentation for the <a href="Matcher.html"><code>Matcher</code></a> trait.
* </p>
*
* <h2>Checking for expected exceptions</h2>
*
* <p>
* Sometimes you need to test whether a method throws an expected exception under certain circumstances, such
* as when invalid arguments are passed to the method. With <code>Matchers</code> mixed in, you can
* check for an expected exception like this:
* </p>
*
* <pre class="stHighlight">
* evaluating { s.charAt(-1) } should produce [IndexOutOfBoundsException]
* </pre>
*
* <p>
* If <code>charAt</code> throws an instance of <code>StringIndexOutOfBoundsException</code>,
* this expression will result in that exception. But if <code>charAt</code> completes normally, or throws a different
* exception, this expression will complete abruptly with a <code>TestFailedException</code>.
* This expression returns the caught exception so that you can inspect it further if you wish, for
* example, to ensure that data contained inside the exception has the expected values. Here's an
* example:
* </p>
*
* <pre class="stHighlight">
* val thrown = evaluating { s.charAt(-1) } should produce [IndexOutOfBoundsException]
* thrown.getMessage should equal ("String index out of range: -1")
* </pre>
*
* <h2>Those pesky parens</h2>
*
* <p>
* Perhaps the most tricky part of writing assertions using ScalaTest matchers is remembering
* when you need or don't need parentheses, but bearing in mind a few simple rules <!-- PRESERVE -->should help.
* It is also reassuring to know that if you ever leave off a set of parentheses when they are
* required, your code will not compile. Thus the compiler will help you remember when you need the parens.
* That said, the rules are:
* </p>
*
* <p>
* 1. Although you don't always need them, it is recommended style to always put parentheses
* around right-hand values, such as the <code>7</code> in <code>num should equal (7)</code>:
* </p>
*
* <pre>
* result should equal <span class="stRed">(</span>4<span class="stRed">)</span>
* array should have length <span class="stRed">(</span>3<span class="stRed">)</span>
* book should have (
* 'title <span class="stRed">(</span>"Programming in Scala"<span class="stRed">)</span>,
* 'author <span class="stRed">(</span>List("Odersky", "Spoon", "Venners")<span class="stRed">)</span>,
* 'pubYear <span class="stRed">(</span>2008<span class="stRed">)</span>
* )
* option should be <span class="stRed">(</span>'defined<span class="stRed">)</span>
* catMap should (contain key <span class="stRed">(</span>9<span class="stRed">)</span> and contain value <span class="stRed">(</span>"lives"<span class="stRed">)</span>)</span>
* keyEvent should be an <span class="stRed">(</span>'actionKey<span class="stRed">)</span>
* javaSet should have size <span class="stRed">(</span>90<span class="stRed">)</span>
* </pre>
*
* <p>
* 2. Except for <code>length</code> and <code>size</code>, you must always put parentheses around
* the list of one or more property values following a <code>have</code>:
* </p>
*
* <pre>
* file should (exist and have <span class="stRed">(</span>'name ("temp.txt")<span class="stRed">)</span>)
* book should have <span class="stRed">(</span>
* title ("Programming in Scala"),
* author (List("Odersky", "Spoon", "Venners")),
* pubYear (2008)
* <span class="stRed">)</span>
* javaList should have length (9) // parens optional for length and size
* </pre>
*
* <p>
* 3. You must always put parentheses around <code>and</code> and <code>or</code> expressions, as in:
* </p>
*
* <pre>
* catMap should <span class="stRed">(</span>contain key (9) and contain value ("lives")<span class="stRed">)</span>
* number should <span class="stRed">(</span>equal (2) or equal (4) or equal (8)<span class="stRed">)</span>
* </pre>
*
* <p>
* 4. Although you don't always need them, it is recommended style to always put parentheses
* around custom <code>Matcher</code>s when they appear directly after <code>not</code>:
* </p>
*
* <pre>
* file should exist
* file should not <span class="stRed">(</span>exist<span class="stRed">)</span>
* file should (exist and have ('name ("temp.txt")))
* file should (not <span class="stRed">(</span>exist<span class="stRed">)</span> and have ('name ("temp.txt"))
* file should (have ('name ("temp.txt") or exist)
* file should (have ('name ("temp.txt") or not <span class="stRed">(</span>exist<span class="stRed">)</span>)
* </pre>
*
* <p>
* That's it. With a bit of practice it <!-- PRESERVE -->should become natural to you, and the compiler will always be there to tell you if you
* forget a set of needed parentheses.
* </p>
*/
trait Matchers extends Assertions with Tolerance with ShouldVerb with LoneElement with MatcherWords with Explicitly { matchers =>
private[scalatest] def newTestFailedException(message: String, optionalCause: Option[Throwable] = None, stackDepthAdjustment: Int = 0): Throwable = {
val temp = new RuntimeException
// should not look for anything in the first 2 elements, caller stack element is at 3rd/4th
// also, it solves the problem when the suite file that mixin in Matchers has the [suiteFileName]:newTestFailedException appears in the top 2 elements
// this approach should be better than adding && _.getMethodName == newTestFailedException we used previously.
val elements = temp.getStackTrace.drop(2)
val stackDepth = elements.indexWhere(st => st.getFileName != "Matchers.scala") + 2 // the first 2 elements dropped previously
optionalCause match {
case Some(cause) => new TestFailedException(message, cause, stackDepth + stackDepthAdjustment)
case None => new TestFailedException(message, stackDepth + stackDepthAdjustment)
}
}
private[scalatest] def matchContainMatcher[T](left: GenTraversable[T], containMatcher: ContainMatcher[T], shouldBeTrue: Boolean) {
val result = containMatcher(left)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
2
)
}
private[scalatest] class JavaCollectionWrapper[T](underlying: java.util.Collection[T]) extends Traversable[T] {
def foreach[U](f: (T) => U) {
val javaIterator = underlying.iterator
while (javaIterator.hasNext)
f(javaIterator.next)
}
override def toString: String = if (underlying == null) "null" else underlying.toString
}
private[scalatest] def matchContainMatcher[T](left: java.util.Collection[T], containMatcher: ContainMatcher[T], shouldBeTrue: Boolean) {
val result = containMatcher(new JavaCollectionWrapper(left))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
2
)
}
private[scalatest] class JavaMapWrapper[K, V](val underlying: java.util.Map[K, V]) extends scala.collection.Map[K, V] {
// Even though the java map is mutable I just wrap it it to a plain old Scala map, because
// I have no intention of mutating it.
override def size: Int = underlying.size
def get(key: K): Option[V] =
if (underlying.containsKey(key)) Some(underlying.get(key)) else None
override def iterator: Iterator[(K, V)] = new Iterator[(K, V)] {
private val javaIterator = underlying.entrySet.iterator
def next: (K, V) = {
val nextEntry = javaIterator.next
(nextEntry.getKey, nextEntry.getValue)
}
def hasNext: Boolean = javaIterator.hasNext
}
override def +[W >: V] (kv: (K, W)): scala.collection.Map[K, W] = {
val newJavaMap = new java.util.LinkedHashMap[K, W](underlying)
val (key, value) = kv
newJavaMap.put(key, value)
new JavaMapWrapper[K, W](newJavaMap)
}
override def - (key: K): scala.collection.Map[K, V] = {
val newJavaMap = new java.util.LinkedHashMap[K, V](underlying)
newJavaMap.remove(key)
new JavaMapWrapper[K, V](underlying)
}
override def empty = new JavaMapWrapper[K, V](new java.util.LinkedHashMap[K, V]())
override def toString: String = if (underlying == null) "null" else underlying.toString
}
private[scalatest] def matchContainMatcher[K, V](left: java.util.Map[K, V], containMatcher: ContainMatcher[(K, V)], shouldBeTrue: Boolean) {
val result = containMatcher(new JavaMapWrapper(left))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
2
)
}
/**
* This wrapper gives better toString (Array(x, x, x)) as compared to Scala default one (WrappedArray(x, x, x)).
*/
private[scalatest] class ArrayWrapper[T](underlying: Array[T]) extends Traversable[T] {
def foreach[U](f: (T) => U) {
var index = 0
while (index < underlying.length) {
index += 1
f(underlying(index - 1))
}
}
// Need to prettify the array's toString, because by the time it gets to decorateToStringValue, the array
// has been wrapped in this Traversable and so it won't get prettified anymore by FailureMessages.decorateToStringValue.
override def toString: String = FailureMessages.prettifyArrays(underlying).toString
}
/**
* This implicit conversion method enables ScalaTest matchers expressions that involve <code>and</code> and <code>or</code>.
*/
// implicit def convertToMatcherWrapper[T](leftMatcher: Matcher[T]): MatcherWrapper[T] = new MatcherWrapper(leftMatcher)
//
// This class is used as the return type of the overloaded should method (in MapShouldWrapper)
// that takes a HaveWord. It's key method will be called in situations like this:
//
// map should have key 1
//
// This gets changed to :
//
// convertToMapShouldWrapper(map).should(have).key(1)
//
// Thus, the map is wrapped in a convertToMapShouldWrapper call via an implicit conversion, which results in
// a MapShouldWrapper. This has a should method that takes a HaveWord. That method returns a
// ResultOfHaveWordPassedToShould that remembers the map to the left of should. Then this class
// ha a key method that takes a K type, they key type of the map. It does the assertion thing.
//
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfContainWordForMap[K, V](left: scala.collection.GenMap[K, V], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain key ("one")
* ^
* </pre>
*/
def key(expectedKey: K) {
if (left.exists(_._1 == expectedKey) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
left,
expectedKey)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain value (1)
* ^
* </pre>
*/
def value(expectedValue: V) {
// if (left.values.contains(expectedValue) != shouldBeTrue) CHANGING FOR 2.8.0 RC1
if (left.exists(expectedValue == _._2) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
left,
expectedValue)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain theSameElementsAs List(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new TheSameElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain theSameIteratedElementsAs List(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new TheSameIteratedElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain allOf (1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def allOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new AllOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain inOrder (1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def inOrder(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new InOrderContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain oneOf (1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def oneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new OneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain only (1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def only(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new OnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain inOrderOnly (1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def inOrderOnly(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new InOrderOnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should contain noneOf (1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def noneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new NoneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax (positiveNumberKey is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* map should contain a positiveNumberKey
* ^
* </pre>
*/
def a(aMatcher: AMatcher[(K, V)]) {
left.find(aMatcher(_).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e)
throw newTestFailedException(FailureMessages("containedA", left, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", left, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax (oddNumberKey is a <code>AnMatcher</code>):
*
* <pre class="stHighlight">
* map should contain an oddNumberKey
* ^
* </pre>
*/
def an(anMatcher: AnMatcher[(K, V)]) {
left.find(anMatcher(_).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e)
throw newTestFailedException(FailureMessages("containedAn", left, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", left, UnquotedString(anMatcher.nounName)))
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfContainWordForJavaMap[K, V](left: java.util.Map[K, V], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax (<code>javaMap</code> is a <code>java.util.Map</code>):
*
* <pre class="stHighlight">
* javaMap should contain key ("two")
* ^
* </pre>
*/
def key(expectedKey: K) {
if (left.containsKey(expectedKey) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
left,
expectedKey)
)
}
/**
* This method enables the following syntax (<code>javaMap</code> is a <code>java.util.Map</code>):
*
* <pre class="stHighlight">
* javaMap should contain value ("2")
* ^
* </pre>
*/
def value(expectedValue: V) {
if (left.containsValue(expectedValue) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
left,
expectedValue)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain theSameElementsAs traversable
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new TheSameElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain theSameIteratedElementsAs traversable
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new TheSameIteratedElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain allOf (1, 2)
* ^
* </pre>
*/
def allOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new AllOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain inOrder (1, 2)
* ^
* </pre>
*/
def inOrder(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new InOrderContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain oneOf (1, 2)
* ^
* </pre>
*/
def oneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new OneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain only (1, 2)
* ^
* </pre>
*/
def only(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new OnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain inOrderOnly (1, 2)
* ^
* </pre>
*/
def inOrderOnly(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new InOrderOnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should contain noneOf (1, 2)
* ^
* </pre>
*/
def noneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
matchContainMatcher(left, new NoneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax (positiveNumberKey is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* javaMap should contain a positiveNumberKey
* ^
* </pre>
*/
def a(aMatcher: AMatcher[(K, V)]) {
val leftWrapper = new JavaMapWrapper(left.asInstanceOf[java.util.Map[K, V]])
leftWrapper.find(e => aMatcher(e).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e)
throw newTestFailedException(FailureMessages("containedA", leftWrapper, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", leftWrapper, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax (oddNumberKey is a <code>AnMatcher</code>):
*
* <pre class="stHighlight">
* javaMap should contain an oddNumberKey
* ^
* </pre>
*/
def an(anMatcher: AnMatcher[(K, V)]) {
val leftWrapper = new JavaMapWrapper(left.asInstanceOf[java.util.Map[K, V]])
leftWrapper.find(e => anMatcher(e).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e)
throw newTestFailedException(FailureMessages("containedAn", leftWrapper, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", leftWrapper, UnquotedString(anMatcher.nounName)))
}
}
}
/**
* This implicit conversion method enables the following syntax (<code>javaColl</code> is a <code>java.util.Collection</code>):
*
* <pre class="stHighlight">
* javaColl should contain ("two")
* </pre>
*
* The <code>(contain ("two"))</code> expression will result in a <code>Matcher[GenTraversable[String]]</code>. This
* implicit conversion method will convert that matcher to a <code>Matcher[java.util.Collection[String]]</code>.
*/
implicit def convertTraversableMatcherToJavaCollectionMatcher[T](traversableMatcher: Matcher[GenTraversable[T]]): Matcher[java.util.Collection[T]] =
new Matcher[java.util.Collection[T]] {
def apply(left: java.util.Collection[T]): MatchResult =
traversableMatcher.apply(new JavaCollectionWrapper(left))
}
/**
* This implicit conversion method enables the following syntax:
*
* <pre class="stHighlight">
* Array(1, 2) should (not contain (3) and not contain (2))
* </pre>
*
* The <code>(not contain ("two"))</code> expression will result in a <code>Matcher[GenTraversable[String]]</code>. This
* implicit conversion method will convert that matcher to a <code>Matcher[Array[String]]</code>.
*/
implicit def convertTraversableMatcherToArrayMatcher[T](traversableMatcher: Matcher[GenTraversable[T]]): Matcher[Array[T]] =
new Matcher[Array[T]] {
def apply(left: Array[T]): MatchResult =
traversableMatcher.apply(new ArrayWrapper(left))
}
/**
* This implicit conversion method enables the following syntax (<code>javaMap</code> is a <code>java.util.Map</code>):
*
* <pre class="stHighlight">
* javaMap should (contain key ("two"))
* </pre>
*
* The <code>(contain key ("two"))</code> expression will result in a <code>Matcher[scala.collection.GenMap[String, Any]]</code>. This
* implicit conversion method will convert that matcher to a <code>Matcher[java.util.Map[String, Any]]</code>.
*/
implicit def convertMapMatcherToJavaMapMatcher[K, V](mapMatcher: Matcher[scala.collection.GenMap[K, V]]): Matcher[java.util.Map[K, V]] =
new Matcher[java.util.Map[K, V]] {
def apply(left: java.util.Map[K, V]): MatchResult =
mapMatcher.apply(new JavaMapWrapper(left))
}
// Ack. The above conversion doesn't apply to java.util.Maps, because java.util.Map is not a subinterface
// of java.util.Collection. But right now Matcher[Traversable] supports only "contain" and "have size"
// syntax, and thus that should work on Java maps too, why not. Well I'll tell you why not. It is too complicated.
// Since java Map is not a java Collection, I'll say the contain syntax doesn't work on it. But you can say
// have key.
// The getLength and getSize field conversions seem inconsistent with
// what I do in symbol HavePropertyMatchers. It isn't, though because the difference is here
// it's a Scala field and there a Java field: a val getLength is a
// perfectly valid Scala way to get a JavaBean property Java method in the bytecodes.
// This guy is generally done through an implicit conversion from a symbol. It takes that symbol, and
// then represents an object with an apply method. So it gives an apply method to symbols.
// book should have ('author ("Gibson"))
// ^ // Basically this 'author symbol gets converted into this class, and its apply method takes "Gibson"
// TODO, put the documentation of the details of the algo for selecting a method or field to use here.
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used as the result of an implicit conversion from class <code>Symbol</code>, to enable symbols to be
* used in <code>have ('author ("Dickens"))</code> syntax. The name of the implicit conversion method is
* <code>convertSymbolToHavePropertyMatcherGenerator</code>.
* </p>
*
* <p>
* Class <code>HavePropertyMatcherGenerator</code>'s primary constructor takes a <code>Symbol</code>. The
* <code>apply</code> method uses reflection to find and access a property that has the name specified by the
* <code>Symbol</code> passed to the constructor, so it can determine if the property has the expected value
* passed to <code>apply</code>.
* If the symbol passed is <code>'title</code>, for example, the <code>apply</code> method
* will use reflection to look for a public Java field named
* "title", a public method named "title", or a public method named "getTitle".
* If a method, it must take no parameters. If multiple candidates are found,
* the <code>apply</code> method will select based on the following algorithm:
* </p>
*
* <table class="stTable">
* <tr><th class="stHeadingCell">Field</th><th class="stHeadingCell">Method</th><th class="stHeadingCell">"get" Method</th><th class="stHeadingCell">Result</th></tr>
* <tr><td class="stTableCell"> </td><td class="stTableCell"> </td><td class="stTableCell"> </td><td class="stTableCell">Throws <code>TestFailedException</code>, because no candidates found</td></tr>
* <tr><td class="stTableCell"> </td><td class="stTableCell"> </td><td class="stTableCell"><code>getTitle()</code></td><td class="stTableCell">Invokes <code>getTitle()</code></td></tr>
* <tr><td class="stTableCell"> </td><td class="stTableCell"><code>title()</code></td><td class="stTableCell"> </td><td class="stTableCell">Invokes <code>title()</code></td></tr>
* <tr><td class="stTableCell"> </td><td class="stTableCell"><code>title()</code></td><td class="stTableCell"><code>getTitle()</code></td><td class="stTableCell">Invokes <code>title()</code> (this can occur when <code>BeanProperty</code> annotation is used)</td></tr>
* <tr><td class="stTableCell"><code>title</code></td><td class="stTableCell"> </td><td class="stTableCell"> </td><td class="stTableCell">Accesses field <code>title</code></td></tr>
* <tr><td class="stTableCell"><code>title</code></td><td class="stTableCell"> </td><td class="stTableCell"><code>getTitle()</code></td><td class="stTableCell">Invokes <code>getTitle()</code></td></tr>
* <tr><td class="stTableCell"><code>title</code></td><td class="stTableCell"><code>title()</code></td><td class="stTableCell"> </td><td class="stTableCell">Invokes <code>title()</code></td></tr>
* <tr><td class="stTableCell"><code>title</code></td><td class="stTableCell"><code>title()</code></td><td class="stTableCell"><code>getTitle()</code></td><td class="stTableCell">Invokes <code>title()</code> (this can occur when <code>BeanProperty</code> annotation is used)</td></tr>
* </table>
*
*
* @author Bill Venners
*/
final class HavePropertyMatcherGenerator(symbol: Symbol) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* book should have ('title ("A Tale of Two Cities"))
* ^
* </pre>
*
* <p>
* This class has an <code>apply</code> method that will produce a <code>HavePropertyMatcher[AnyRef, Any]</code>.
* The implicit conversion method, <code>convertSymbolToHavePropertyMatcherGenerator</code>, will cause the
* above line of code to be eventually transformed into:
* </p>
*
* <pre class="stHighlight">
* book should have (convertSymbolToHavePropertyMatcherGenerator('title).apply("A Tale of Two Cities"))
* </pre>
*/
def apply(expectedValue: Any): HavePropertyMatcher[AnyRef, Any] =
new HavePropertyMatcher[AnyRef, Any] {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* book should have ('title ("A Tale of Two Cities"))
* </pre>
*
* <p>
* This method uses reflection to discover a field or method with a name that indicates it represents
* the value of the property with the name contained in the <code>Symbol</code> passed to the
* <code>HavePropertyMatcherGenerator</code>'s constructor. The field or method must be public. To be a
* candidate, a field must have the name <code>symbol.name</code>, so if <code>symbol</code> is <code>'title</code>,
* the field name sought will be <code>"title"</code>. To be a candidate, a method must either have the name
* <code>symbol.name</code>, or have a JavaBean-style <code>get</code> or <code>is</code>. If the type of the
* passed <code>expectedValue</code> is <code>Boolean</code>, <code>"is"</code> is prepended, else <code>"get"</code>
* is prepended. Thus if <code>'title</code> is passed as <code>symbol</code>, and the type of the <code>expectedValue</code> is
* <code>String</code>, a method named <code>getTitle</code> will be considered a candidate (the return type
* of <code>getTitle</code> will not be checked, so it need not be <code>String</code>. By contrast, if <code>'defined</code>
* is passed as <code>symbol</code>, and the type of the <code>expectedValue</code> is <code>Boolean</code>, a method
* named <code>isTitle</code> will be considered a candidate so long as its return type is <code>Boolean</code>.
* </p>
* TODO continue the story
*/
def apply(objectWithProperty: AnyRef): HavePropertyMatchResult[Any] = {
// If 'empty passed, propertyName would be "empty"
val propertyName = symbol.name
val isBooleanProperty =
expectedValue match {
case o: Boolean => true
case _ => false
}
accessProperty(objectWithProperty, symbol, isBooleanProperty) match {
case None =>
// if propertyName is '>, mangledPropertyName would be "$greater"
val mangledPropertyName = transformOperatorChars(propertyName)
// methodNameToInvoke would also be "title"
val methodNameToInvoke = mangledPropertyName
// methodNameToInvokeWithGet would be "getTitle"
val methodNameToInvokeWithGet = "get"+ mangledPropertyName(0).toUpper + mangledPropertyName.substring(1)
throw newTestFailedException(Resources("propertyNotFound", methodNameToInvoke, expectedValue.toString, methodNameToInvokeWithGet))
case Some(result) =>
new HavePropertyMatchResult[Any](
result == expectedValue,
propertyName,
expectedValue,
result
)
}
}
}
}
/**
* This implicit conversion method converts a <code>Symbol</code> to a
* <code>HavePropertyMatcherGenerator</code>, to enable the symbol to be used with the <code>have ('author ("Dickens"))</code> syntax.
*/
implicit def convertSymbolToHavePropertyMatcherGenerator(symbol: Symbol): HavePropertyMatcherGenerator = new HavePropertyMatcherGenerator(symbol)
//
// This class is used as the return type of the overloaded should method (in TraversableShouldWrapper)
// that takes a HaveWord. It's size method will be called in situations like this:
//
// list should have size 1
//
// This gets changed to :
//
// convertToTraversableShouldWrapper(list).should(have).size(1)
//
// Thus, the list is wrapped in a convertToTraversableShouldWrapper call via an implicit conversion, which results in
// a TraversableShouldWrapper. This has a should method that takes a HaveWord. That method returns a
// ResultOfHaveWordForTraverablePassedToShould that remembers the map to the left of should. Then this class
// has a size method that takes a T type, type parameter of the Traversable. It does the assertion thing.
//
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
sealed class ResultOfHaveWordForTraversable[T](left: GenTraversable[T], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* collection should have size (10)
* ^
* </pre>
*/
def size(expectedSize: Int) {
if ((left.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
sealed class ResultOfHaveWordForJavaCollection[E, L[_] <: java.util.Collection[_]](left: L[E], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCollection should have size (10)
* ^
* </pre>
*/
def size(expectedSize: Int) {
if ((left.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForJavaMap(left: java.util.Map[_, _], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should have size (10)
* ^
* </pre>
*/
def size(expectedSize: Int) {
if ((left.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForSeq[T](left: GenSeq[T], shouldBeTrue: Boolean) extends ResultOfHaveWordForTraversable[T](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* seq should have length (20)
* ^
* </pre>
*/
def length(expectedLength: Int) {
if ((left.length == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
class ResultOfHaveWordForArray[T](left: Array[T], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* array should have size (10)
* ^
* </pre>
*/
def size(expectedSize: Int) {
if ((left.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* array should have length (20)
* ^
* </pre>
*/
def length(expectedLength: Int) {
if ((left.length == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength) )
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
sealed class ResultOfNotWordForTraversable[E, T[_] <: GenTraversable[_]](left: T[E], shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* iterable should not contain ("one")
* ^
* </pre>
*/
def contain(expectedElement: E)(implicit holder: Holder[T[E]]) {
val right = expectedElement
if (holder.containsElement(left, right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* collection should not contain containMatcher
* ^
* </pre>
*/
def contain(right: ContainMatcher[E]) {
val result = right(left.asInstanceOf[GenTraversable[E]])
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>positiveNumber</code> refers to
* an <code>AMatcher[Int]</code>:
*
* <pre class="stHighlight">
* collection should not contain a (positiveNumber)
* ^
* </pre>
*/
def contain(resultOfAWordToAMatcherApplication: ResultOfAWordToAMatcherApplication[E]) {
val aMatcher = resultOfAWordToAMatcherApplication.aMatcher
left.find (e => aMatcher(e.asInstanceOf[E]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e.asInstanceOf[E])
throw newTestFailedException(FailureMessages("containedA", left, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", left, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax, where <code>positiveNumber</code> refers to
* an <code>AnMatcher[Int]</code>:
*
* <pre class="stHighlight">
* collection should not contain a (positiveNumber)
* ^
* </pre>
*/
def contain(resultOfAnWordToAnMatcherApplication: ResultOfAnWordToAnMatcherApplication[E]) {
val anMatcher = resultOfAnWordToAnMatcherApplication.anMatcher
left.find (e => anMatcher(e.asInstanceOf[E]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e.asInstanceOf[E])
throw newTestFailedException(FailureMessages("containedAn", left, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", left, UnquotedString(anMatcher.nounName)))
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* collection should not have size (3)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
val right = resultOfSizeWordApplication.expectedSize
if ((left.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
right
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
sealed class ResultOfNotWordForJavaCollection[E, T[_] <: java.util.Collection[_]](left: T[E], shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCollection should not have size (3)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
val right = resultOfSizeWordApplication.expectedSize
if ((left.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCollection should not contain ("elephant")
* ^
* </pre>
*/
def contain(expectedElement: E)(implicit holder: Holder[T[E]]) {
val right = expectedElement
// if ((left.contains(right)) != shouldBeTrue) {
if (holder.containsElement(left, right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCollection should not contain containMatcher
* ^
* </pre>
*/
def contain(right: ContainMatcher[E]) {
val result = right(new JavaCollectionWrapper(left.asInstanceOf[java.util.Collection[E]]))
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>positiveNumber</code> refers to
* an <code>AMatcher[Int]</code>:
*
* <pre class="stHighlight">
* javaCol should not contain a (positiveNumber)
* ^
* </pre>
*/
def contain(resultOfAWordToAMatcherApplication: ResultOfAWordToAMatcherApplication[E]) {
val aMatcher = resultOfAWordToAMatcherApplication.aMatcher
val leftWrapper = new JavaCollectionWrapper(left.asInstanceOf[java.util.Collection[E]])
leftWrapper.find (e => aMatcher(e.asInstanceOf[E]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e.asInstanceOf[E])
throw newTestFailedException(FailureMessages("containedA", left, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", left, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax, where <code>oddNumber</code> refers to
* an <code>AnMatcher[Int]</code>:
*
* <pre class="stHighlight">
* javaCol should not contain an (oddNumber)
* ^
* </pre>
*/
def contain(resultOfAnWordToAnMatcherApplication: ResultOfAnWordToAnMatcherApplication[E]) {
val anMatcher = resultOfAnWordToAnMatcherApplication.anMatcher
val leftWrapper = new JavaCollectionWrapper(left.asInstanceOf[java.util.Collection[E]])
leftWrapper.find (e => anMatcher(e.asInstanceOf[E]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e.asInstanceOf[E])
throw newTestFailedException(FailureMessages("containedAn", left, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", left, UnquotedString(anMatcher.nounName)))
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForMap[K, V, L[_, _] <: scala.collection.GenMap[_, _]](left: L[K, V], shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should not contain key ("three")
* ^
* </pre>
*/
def contain(resultOfKeyWordApplication: ResultOfKeyWordApplication[K]) {
val right = resultOfKeyWordApplication.expectedKey
if ((left.asInstanceOf[GenMap[K, V]].exists(_._1 == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* Map("one" -> 1, "two" -> 2) should not contain value (3)
* ^
* </pre>
*/
def contain(resultOfValueWordApplication: ResultOfValueWordApplication[V]) {
val right = resultOfValueWordApplication.expectedValue
if ((left.asInstanceOf[GenMap[K, V]].exists(_._2 == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
left,
right
)
)
}
}
// TODO: Had to pull these methods out of ReusltOfNotWordForTraversable, because can't exent
// it without losing precision on the inferred types. Map[String, Int] becomes GenIterable[(Any, Any)]
// So the wrong Equality type class was chosen. By going around ResultOfNotWordForTraversable, I can
// get the precise Map type up to ResultOfNotWord's equal method, which requires the Equality type class.
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* iterable should not contain ("one")
* ^
* </pre>
*/
def contain(expectedElement: (K, V)) {
val right = expectedElement
if ((left.exists(_ == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should not contain containMatcher
* ^
* </pre>
*/
def contain(right: ContainMatcher[(K, V)]) {
val result = right(left.asInstanceOf[scala.collection.GenTraversable[(K, V)]])
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>positiveNumberKey</code> refers to
* an <code>AMatcher[Int]</code>:
*
* <pre class="stHighlight">
* map should not contain a (positiveNumberKey)
* ^
* </pre>
*/
def contain(resultOfAWordToAMatcherApplication: ResultOfAWordToAMatcherApplication[(K, V)]) {
val aMatcher = resultOfAWordToAMatcherApplication.aMatcher
left.find (e => aMatcher(e.asInstanceOf[(K, V)]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e.asInstanceOf[(K, V)])
throw newTestFailedException(FailureMessages("containedA", left, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", left, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax, where <code>oddNumberKey</code> refers to
* an <code>AnMatcher[Int]</code>:
*
* <pre class="stHighlight">
* map should not contain a (oddNumberKey)
* ^
* </pre>
*/
def contain(resultOfAnWordToAnMatcherApplication: ResultOfAnWordToAnMatcherApplication[(K, V)]) {
val anMatcher = resultOfAnWordToAnMatcherApplication.anMatcher
left.find (e => anMatcher(e.asInstanceOf[(K, V)]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e.asInstanceOf[(K, V)])
throw newTestFailedException(FailureMessages("containedAn", left, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", left, UnquotedString(anMatcher.nounName)))
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* collection should not have size (3)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
val right = resultOfSizeWordApplication.expectedSize
if ((left.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
right
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForJavaMap[K, V, L[_, _] <: java.util.Map[_, _]](left: L[K, V], shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should not contain key ("three")
* ^
* </pre>
*/
def contain(resultOfKeyWordApplication: ResultOfKeyWordApplication[K]) {
val right = resultOfKeyWordApplication.expectedKey
if ((left.containsKey(right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should not contain value (3)
* ^
* </pre>
*/
def contain(resultOfValueWordApplication: ResultOfValueWordApplication[V]) {
val right = resultOfValueWordApplication.expectedValue
if ((left.containsValue(right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaMap should not contain containMatcher
* ^
* </pre>
*/
def contain(right: ContainMatcher[(K, V)]) {
val result = right(new JavaMapWrapper(left.asInstanceOf[java.util.Map[K, V]]))
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>positiveNumber</code> refers to
* an <code>AMatcher[Int]</code>:
*
* <pre class="stHighlight">
* javaMap should not contain a (positiveNumber)
* ^
* </pre>
*/
def contain(resultOfAWordToAMatcherApplication: ResultOfAWordToAMatcherApplication[(K, V)]) {
val aMatcher = resultOfAWordToAMatcherApplication.aMatcher
val leftWrapper = new JavaMapWrapper(left.asInstanceOf[java.util.Map[K, V]])
leftWrapper.find (e => aMatcher(e.asInstanceOf[(K, V)]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e.asInstanceOf[(K, V)])
throw newTestFailedException(FailureMessages("containedA", leftWrapper, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", leftWrapper, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax, where <code>oddNumber</code> refers to
* an <code>AnMatcher[Int]</code>:
*
* <pre class="stHighlight">
* javaMap should not contain an (oddNumber)
* ^
* </pre>
*/
def contain(resultOfAnWordToAnMatcherApplication: ResultOfAnWordToAnMatcherApplication[(K, V)]) {
val anMatcher = resultOfAnWordToAnMatcherApplication.anMatcher
val leftWrapper = new JavaMapWrapper(left.asInstanceOf[java.util.Map[K, V]])
leftWrapper.find (e => anMatcher(e.asInstanceOf[(K, V)]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e.asInstanceOf[(K, V)])
throw newTestFailedException(FailureMessages("containedAn", leftWrapper, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", leftWrapper, UnquotedString(anMatcher.nounName)))
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForSeq[E, T[_] <: GenSeq[_]](left: T[E], shouldBeTrue: Boolean)
extends ResultOfNotWordForTraversable[E, T](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2) should not have length (12)
* ^
* </pre>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
val right = resultOfLengthWordApplication.expectedLength
if ((left.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
right
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForArray[E](left: Array[E], shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* Array("two", "three") should not contain ("one")
* ^
* </pre>
*/
def contain(expectedElement: E)(implicit holder: Holder[Array[E]]) {
val right = expectedElement
// if ((left.exists(_ == right)) != shouldBeTrue) {
if (holder.containsElement(left, right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
left,
right
)
)
}
}
/**
* This method enables the following syntax, where <code>containMatcher</code> refers to
* a <code>ContainMatcher</code>:
*
* <pre class="stHighlight">
* Array(1, 2, 3) should not contain containMatcher
* ^
* </pre>
*/
def contain(right: ContainMatcher[E]) {
val result = right(new ArrayWrapper(left))
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>positiveNumber</code> refers to
* an <code>AMatcher[Int]</code>:
*
* <pre class="stHighlight">
* Array(-1, -2) should not contain a (positiveNumber)
* ^
* </pre>
*/
def contain(resultOfAWordToAMatcherApplication: ResultOfAWordToAMatcherApplication[E]) {
val aMatcher = resultOfAWordToAMatcherApplication.aMatcher
left.find (e => aMatcher(e.asInstanceOf[E]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e.asInstanceOf[E])
throw newTestFailedException(FailureMessages("containedA", left, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", left, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax, where <code>oddNumber</code> refers to
* an <code>AnMatcher[Int]</code>:
*
* <pre class="stHighlight">
* Array(-1, -2) should not contain an (oddNumber)
* ^
* </pre>
*/
def contain(resultOfAnWordToAnMatcherApplication: ResultOfAnWordToAnMatcherApplication[E]) {
val anMatcher = resultOfAnWordToAnMatcherApplication.anMatcher
left.find (e => anMatcher(e.asInstanceOf[E]).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e.asInstanceOf[E])
throw newTestFailedException(FailureMessages("containedAn", left, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", left, UnquotedString(anMatcher.nounName)))
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* Array(1, 2) should not have size (3)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
val right = resultOfSizeWordApplication.expectedSize
if ((left.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* Array(1, 2) should not have length (12)
* ^
* </pre>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
val right = resultOfLengthWordApplication.expectedLength
if ((left.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
right
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForJavaList[E, L[_] <: java.util.List[_]](left: L[E], shouldBeTrue: Boolean) extends ResultOfHaveWordForJavaCollection[E, L](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaList should have length (12)
* ^
* </pre>
*
* <p>
* This method invokes <code>size</code> on the <code>java.util.List</code> passed as <code>left</code> to
* determine its length.
* </p>
*/
def length(expectedLength: Int) {
if ((left.size == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForJavaList[E, T[_] <: java.util.List[_]](left: T[E], shouldBeTrue: Boolean)
extends ResultOfNotWordForJavaCollection[E, T](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaList should not have length (12)
* ^
* </pre>
*
* <p>
* This method invokes <code>size</code> on the <code>java.util.List</code> passed as <code>left</code> to
* determine its length.
* </p>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
val right = resultOfLengthWordApplication.expectedLength
if ((left.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
right
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfBeWordForAny[T](left: T, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax (positiveNumber is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* 1 should be a positiveNumber
* ^
* </pre>
*/
def a(aMatcher: AMatcher[T]) {
val matcherResult = aMatcher(left)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax (positiveNumber is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* 1 should be an oddNumber
* ^
* </pre>
*/
def an(anMatcher: AnMatcher[T]) {
val matcherResult = anMatcher(left)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfBeWordForAnyRef[T <: AnyRef](left: T, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def theSameInstanceAs(right: AnyRef) {
if ((left eq right) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotSameInstanceAs" else "wasSameInstanceAs",
left,
right
)
)
}
/* *
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should be a [String]
* ^
* </pre>
def a[EXPECTED : ClassManifest] {
val clazz = implicitly[ClassManifest[EXPECTED]].erasure.asInstanceOf[Class[EXPECTED]]
if (clazz.isAssignableFrom(left.getClass)) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotAnInstanceOf", left, UnquotedString(clazz.getName))
else
FailureMessages("wasAnInstanceOf")
)
}
}
*/
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* fileMock should be a ('file)
* ^
* </pre>
*/
def a(symbol: Symbol) {
val matcherResult = matchSymbolToPredicateMethod(left, symbol, true, true)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
// TODO: Check the shouldBeTrues, are they sometimes always false or true?
/**
* This method enables the following syntax, where <code>badBook</code> is, for example, of type <code>Book</code> and
* <code>goodRead</code> refers to a <code>BePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* badBook should be a (goodRead)
* ^
* </pre>
*/
def a(bePropertyMatcher: BePropertyMatcher[T]) {
val result = bePropertyMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotA", left, UnquotedString(result.propertyName))
else
FailureMessages("wasA", left, UnquotedString(result.propertyName))
)
}
}
/**
* This method enables the following syntax (longString is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* "a long string" should be a longString
* ^
* </pre>
*/
def a(aMatcher: AMatcher[T]) {
val matcherResult = aMatcher(left)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax (apple is a <code>AnMatcher</code>):
*
* <pre class="stHighlight">
* result should be an apple
* ^
* </pre>
*/
def an(anMatcher: AnMatcher[T]) {
val matcherResult = anMatcher(left)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
// TODO, in both of these, the failure message doesn't have a/an
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* fruit should be an ('orange)
* ^
* </pre>
*/
def an(symbol: Symbol) {
val matcherResult = matchSymbolToPredicateMethod(left, symbol, true, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>badBook</code> is, for example, of type <code>Book</code> and
* <code>excellentRead</code> refers to a <code>BePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* book should be an (excellentRead)
* ^
* </pre>
*/
def an(beTrueMatcher: BePropertyMatcher[T]) {
val beTrueMatchResult = beTrueMatcher(left)
if (beTrueMatchResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotAn", left, UnquotedString(beTrueMatchResult.propertyName))
else
FailureMessages("wasAn", left, UnquotedString(beTrueMatchResult.propertyName))
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
sealed class ResultOfNotWord[T](left: T, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not equal (7)
* ^
* </pre>
*/
def equal(right: Any)(implicit equality: Equality[T]) {
if (equality.areEqual(left, right) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEqual" else "equaled",
left,
right
)
)
}
// TODO: Why isn't there an equal that takes a tolerance? (and later one that takes a null?)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not be (7)
* ^
* </pre>
*/
def be(right: Any) {
if ((left == right) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotEqualTo" else "wasEqualTo",
left,
right
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not be <= (7)
* ^
* </pre>
*/
def be(comparison: ResultOfLessThanOrEqualToComparison[T]) {
if (comparison(left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotLessThanOrEqualTo" else "wasLessThanOrEqualTo",
left,
comparison.right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not be >= (7)
* ^
* </pre>
*/
def be(comparison: ResultOfGreaterThanOrEqualToComparison[T]) {
if (comparison(left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotGreaterThanOrEqualTo" else "wasGreaterThanOrEqualTo",
left,
comparison.right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not be < (7)
* ^
* </pre>
*/
def be(comparison: ResultOfLessThanComparison[T]) {
if (comparison(left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotLessThan" else "wasLessThan",
left,
comparison.right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not be > (7)
* ^
* </pre>
*/
def be(comparison: ResultOfGreaterThanComparison[T]) {
if (comparison(left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotGreaterThan" else "wasGreaterThan",
left,
comparison.right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* result should not be === (7)
* ^
* </pre>
*/
def be(comparison: TripleEqualsInvocation[_]) {
if ((left == comparison.right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotEqualTo" else "wasEqualTo",
left,
comparison.right
)
)
}
}
/**
* This method enables the following syntax, where <code>odd</code> refers to
* a <code>BeMatcher[Int]</code>:
*
* <pre class="stHighlight">
* 2 should not be (odd)
* ^
* </pre>
*/
def be(beMatcher: BeMatcher[T]) {
val result = beMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
result.failureMessage
else
result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>positiveNumber</code> refers to
* an <code>AMatcher[Int]</code>:
*
* <pre class="stHighlight">
* 2 should not be a (positiveNumber)
* ^
* </pre>
*/
def be(resultOfAWordToAMatcherApplication: ResultOfAWordToAMatcherApplication[T]) {
val aMatcher = resultOfAWordToAMatcherApplication.aMatcher
val result = aMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
result.failureMessage
else
result.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>oddNumber</code> refers to
* an <code>AnMatcher[Int]</code>:
*
* <pre class="stHighlight">
* 2 should not be an (oddNumber)
* ^
* </pre>
*/
def be(resultOfAnWordToAnMatcherApplication: ResultOfAnWordToAnMatcherApplication[T]) {
val anMatcher = resultOfAnWordToAnMatcherApplication.anMatcher
val result = anMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
result.failureMessage
else
result.negatedFailureMessage
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
sealed class ResultOfNotWordForAnyRef[T <: AnyRef](left: T, shouldBeTrue: Boolean)
extends ResultOfNotWord[T](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should not be (null)
* ^
* </pre>
*/
def be(o: Null) {
if ((left == null) != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotNull", left)
else
FailureMessages("wasNull")
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* stack should not be ('empty)
* ^
* </pre>
*/
def be(symbol: Symbol) {
val matcherResult = matchSymbolToPredicateMethod(left, symbol, false, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>stack</code> is, for example, of type <code>Stack</code> and
* <code>empty</code> refers to a <code>BePropertyMatcher[Stack]</code>:
*
* <pre class="stHighlight">
* stack should not be (empty)
* ^
* </pre>
*/
def be(bePropertyMatcher: BePropertyMatcher[T]) {
val result = bePropertyMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNot", left, UnquotedString(result.propertyName))
else
FailureMessages("was", left, UnquotedString(result.propertyName))
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* notFileMock should not be a ('file)
* ^
* </pre>
*/
def be(resultOfAWordApplication: ResultOfAWordToSymbolApplication) {
val matcherResult = matchSymbolToPredicateMethod(left, resultOfAWordApplication.symbol, true, true)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>notFileMock</code> is, for example, of type <code>File</code> and
* <code>file</code> refers to a <code>BePropertyMatcher[File]</code>:
*
* <pre class="stHighlight">
* notFileMock should not be a (file)
* ^
* </pre>
*/
def be[U >: T](resultOfAWordApplication: ResultOfAWordToBePropertyMatcherApplication[U]) {
val result = resultOfAWordApplication.bePropertyMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotA", left, UnquotedString(result.propertyName))
else
FailureMessages("wasA", left, UnquotedString(result.propertyName))
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* keyEvent should not be an ('actionKey)
* ^
* </pre>
*/
def be(resultOfAnWordApplication: ResultOfAnWordToSymbolApplication) {
val matcherResult = matchSymbolToPredicateMethod(left, resultOfAnWordApplication.symbol, true, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage
)
}
}
/**
* This method enables the following syntax, where <code>keyEvent</code> is, for example, of type <code>KeyEvent</code> and
* <code>actionKey</code> refers to a <code>BePropertyMatcher[KeyEvent]</code>:
*
* <pre class="stHighlight">
* keyEvent should not be an (actionKey)
* ^
* </pre>
*/
def be[U >: T](resultOfAnWordApplication: ResultOfAnWordToBePropertyMatcherApplication[U]) {
val result = resultOfAnWordApplication.bePropertyMatcher(left)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotAn", left, UnquotedString(result.propertyName))
else
FailureMessages("wasAn", left, UnquotedString(result.propertyName))
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* otherString should not be theSameInstanceAs (string)
* ^
* </pre>
*/
def be(resultOfSameInstanceAsApplication: ResultOfTheSameInstanceAsApplication) {
if ((resultOfSameInstanceAsApplication.right eq left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotSameInstanceAs" else "wasSameInstanceAs",
left,
resultOfSameInstanceAsApplication.right
)
)
}
}
// TODO: Explain this matrix somewhere
// The type parameter U has T as its lower bound, which means that U must be T or a supertype of T. Left is T, oh, because
// HavePropertyMatcher is contravariant in its type parameter T, and that nmakes sense, because a HavePropertyMatcher of Any should
// be able to match on a String.
// <code>not have (a (1), b (2))</code> must mean the opposite of <code>have (a (1), b (2))</code>, which means that
// <code>not have (a (1), b (2))</code> will be true if either <code>(a (1)).matches</code> or <code>(b (1)).matches</code> is false.
// Only if both <code>(a (1)).matches</code> or <code>(b (1)).matches</code> are true will <code>not have (a (1), b (2))</code> be false.
// title/author matches | have | have not
// 0 0 | 0 | 1
// 0 1 | 0 | 1
// 1 0 | 0 | 1
// 1 1 | 1 | 0
//
/**
* This method enables the following syntax, where <code>badBook</code> is, for example, of type <code>Book</code> and
* <code>title ("One Hundred Years of Solitude")</code> results in a <code>HavePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* book should not have (title ("One Hundred Years of Solitude"))
* ^
* </pre>
*/
def have[U >: T](firstPropertyMatcher: HavePropertyMatcher[U, _], propertyMatchers: HavePropertyMatcher[U, _]*) {
val results =
for (propertyVerifier <- firstPropertyMatcher :: propertyMatchers.toList) yield
propertyVerifier(left)
val firstFailureOption = results.find(pv => !pv.matches)
val justOneProperty = propertyMatchers.length == 0
// if shouldBeTrue is false, then it is like "not have ()", and should throw TFE if firstFailureOption.isDefined is false
// if shouldBeTrue is true, then it is like "not (not have ()), which should behave like have ()", and should throw TFE if firstFailureOption.isDefined is true
if (firstFailureOption.isDefined == shouldBeTrue) {
firstFailureOption match {
case Some(firstFailure) =>
// This is one of these cases, thus will only get here if shouldBeTrue is true
// 0 0 | 0 | 1
// 0 1 | 0 | 1
// 1 0 | 0 | 1
throw newTestFailedException(
FailureMessages(
"propertyDidNotHaveExpectedValue",
UnquotedString(firstFailure.propertyName),
firstFailure.expectedValue,
firstFailure.actualValue,
left
)
)
case None =>
// This is this cases, thus will only get here if shouldBeTrue is false
// 1 1 | 1 | 0
val failureMessage =
if (justOneProperty) {
val firstPropertyResult = results.head // know this will succeed, because firstPropertyMatcher was required
FailureMessages(
"propertyHadExpectedValue",
UnquotedString(firstPropertyResult.propertyName),
firstPropertyResult.expectedValue,
left
)
}
else FailureMessages("allPropertiesHadExpectedValues", left)
throw newTestFailedException(failureMessage)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForString(left: String, shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef[String](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should not have length (12)
* ^
* </pre>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
val right = resultOfLengthWordApplication.expectedLength
if ((left.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
right
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should not fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""")
* ^
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*/
def fullyMatch(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
val rightRegex = resultOfRegexWordApplication.regex
if (rightRegex.pattern.matcher(left).matches != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotFullyMatchRegex" else "fullyMatchedRegex",
left,
rightRegex
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should not include regex ("wo.ld")
* ^
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*/
def include(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
val rightRegex = resultOfRegexWordApplication.regex
if (rightRegex.findFirstIn(left).isDefined != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotIncludeRegex" else "includedRegex",
left,
rightRegex
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should not include ("world")
* ^
* </pre>
*/
def include(expectedSubstring: String) {
if ((left.indexOf(expectedSubstring) >= 0) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotIncludeSubstring" else "includedSubstring",
left,
expectedSubstring
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should not startWith regex ("Hel*o")
* ^
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*/
def startWith(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
val rightRegex = resultOfRegexWordApplication.regex
if (rightRegex.pattern.matcher(left).lookingAt != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotStartWithRegex" else "startedWithRegex",
left,
rightRegex
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* "eight" should not startWith ("1.7")
* ^
* </pre>
*/
def startWith(expectedSubstring: String) {
if ((left.indexOf(expectedSubstring) == 0) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotStartWith" else "startedWith",
left,
expectedSubstring
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* greeting should not endWith regex ("wor.d")
* ^
* </pre>
*/
def endWith(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
val rightRegex = resultOfRegexWordApplication.regex
val allMatches = rightRegex.findAllIn(left)
if (allMatches.hasNext && (allMatches.end == left.length) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEndWithRegex" else "endedWithRegex",
left,
rightRegex
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* "eight" should not endWith ("1.7")
* ^
* </pre>
*/
def endWith(expectedSubstring: String) {
if ((left endsWith expectedSubstring) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEndWith" else "endedWith",
left,
expectedSubstring
)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should not contain ('c')
* ^
* </pre>
*/
def contain(expectedElement: Char)(implicit holder: Holder[String]) {
val right = expectedElement
if (holder.containsElement(left, right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
left,
right
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForNumeric[T : Numeric](left: T, shouldBeTrue: Boolean)
extends ResultOfNotWord[T](left, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* sevenDotOh should not be (6.5 +- 0.2)
* ^
* </pre>
*/
def be(interval: Interval[T]) {
if (interval.isWithin(left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotPlusOrMinus" else "wasPlusOrMinus",
left,
interval.pivot,
interval.tolerance
)
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* sevenDotOh should not equal (6.5 +- 0.2)
* ^
* </pre>
*/
def equal(interval: Interval[T]) {
if (interval.isWithin(left) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEqualPlusOrMinus" else "equaledPlusOrMinus",
left,
interval.pivot,
interval.tolerance
)
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class RegexWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* "eight" should not fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""".r)
* ^
* </pre>
*/
def apply(regexString: String): ResultOfRegexWordApplication = new ResultOfRegexWordApplication(regexString)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* "eight" should not fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""")
* ^
* </pre>
*/
def apply(regex: Regex): ResultOfRegexWordApplication = new ResultOfRegexWordApplication(regex)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForString(left: String, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should have length (12)
* ^
* </pre>
*/
def length(expectedLength: Int) {
if ((left.length == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfIncludeWordForString(left: String, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should include regex ("world")
* ^
* </pre>
*/
def regex(rightRegexString: String) { regex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should include regex ("wo.ld".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) {
if (rightRegex.findFirstIn(left).isDefined != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotIncludeRegex" else "includedRegex",
left,
rightRegex
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfStartWithWordForString(left: String, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should startWith regex ("Hel*o")
* ^
* </pre>
*/
def regex(rightRegexString: String) { regex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should startWith regex ("Hel*o".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) {
if (rightRegex.pattern.matcher(left).lookingAt != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotStartWithRegex" else "startedWithRegex",
left,
rightRegex
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfEndWithWordForString(left: String, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should endWith regex ("wor.d")
* ^
* </pre>
*/
def regex(rightRegexString: String) { regex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should endWith regex ("wor.d".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) {
val allMatches = rightRegex.findAllIn(left)
if ((allMatches.hasNext && (allMatches.end == left.length)) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEndWithRegex" else "endedWithRegex",
left,
rightRegex
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfFullyMatchWordForString(left: String, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should fullMatch regex ("Hel*o world")
* ^
* </pre>
*/
def regex(rightRegexString: String) { regex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* string should fullymatch regex ("Hel*o world".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) {
if (rightRegex.pattern.matcher(left).matches != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotFullyMatchRegex" else "fullyMatchedRegex",
left,
rightRegex
)
)
}
}
// Going back to original, legacy one to get to a good place to check in.
/*
def equal(right: Any): Matcher[Any] =
new Matcher[Any] {
def apply(left: Any): MatchResult = {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
MatchResult(
areEqualComparingArraysStructurally(left, right),
FailureMessages("didNotEqual", leftee, rightee),
FailureMessages("equaled", left, right)
)
}
}
*/
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should equal (100 +- 1)
* ^
* </pre>
*/
def equal[T](interval: Interval[T]): Matcher[T] = {
new Matcher[T] {
def apply(left: T): MatchResult = {
MatchResult(
interval.isWithin(left),
FailureMessages("didNotEqualPlusOrMinus", left, interval.pivot, interval.tolerance),
FailureMessages("equaledPlusOrMinus", left, interval.pivot, interval.tolerance)
)
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should equal (null)
* ^
* </pre>
*/
def equal(o: Null): Matcher[AnyRef] =
new Matcher[AnyRef] {
def apply(left: AnyRef): MatchResult = {
MatchResult(
left == null,
FailureMessages("didNotEqualNull", left),
FailureMessages("equaledNull"),
FailureMessages("didNotEqualNull", left),
FailureMessages("midSentenceEqualedNull")
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class LengthWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* "hi" should not have length (3)
* ^
* </pre>
*/
def apply(expectedLength: Long): ResultOfLengthWordApplication = new ResultOfLengthWordApplication(expectedLength)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* "hi" should not have length (3)
* ^
* </pre>
*/
val length = new LengthWord
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class SizeWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* set should not have size (3)
* ^
* </pre>
*/
def apply(expectedSize: Long): ResultOfSizeWordApplication = new ResultOfSizeWordApplication(expectedSize)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* set should not have size (3)
* ^
* </pre>
*/
val size = new SizeWord
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfElementWordApplication[T](val expectedElement: T)
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class KeyWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should not contain key (10)
* ^
* </pre>
*/
def apply[T](expectedKey: T): ResultOfKeyWordApplication[T] = new ResultOfKeyWordApplication(expectedKey)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* map should not contain key (10)
* ^
* </pre>
*/
val key = new KeyWord
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ValueWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* map should not contain value (10)
* ^
* </pre>
*/
def apply[T](expectedValue: T): ResultOfValueWordApplication[T] = new ResultOfValueWordApplication(expectedValue)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* map should not contain value (10)
* ^
* </pre>
*/
val value = new ValueWord
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class AWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* badBook should not be a ('goodRead)
* ^
* </pre>
*/
def apply(symbol: Symbol): ResultOfAWordToSymbolApplication = new ResultOfAWordToSymbolApplication(symbol)
/**
* This method enables the following syntax, where, for example, <code>badBook</code> is of type <code>Book</code> and <code>goodRead</code>
* is a <code>BePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* badBook should not be a (goodRead)
* ^
* </pre>
*/
def apply[T](beTrueMatcher: BePropertyMatcher[T]): ResultOfAWordToBePropertyMatcherApplication[T] = new ResultOfAWordToBePropertyMatcherApplication(beTrueMatcher)
/**
* This method enables the following syntax, where, <code>positiveNumber</code> is an <code>AMatcher[Book]</code>:
*
* <pre class="stHighlight">
* result should not be a (positiveNumber)
* ^
* </pre>
*/
def apply[T](aMatcher: AMatcher[T]): ResultOfAWordToAMatcherApplication[T] = new ResultOfAWordToAMatcherApplication(aMatcher)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* badBook should not be a ('goodRead)
* ^
* </pre>
*/
val a = new AWord
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class AnWord {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* badBook should not be an ('excellentRead)
* ^
* </pre>
*/
def apply(symbol: Symbol): ResultOfAnWordToSymbolApplication = new ResultOfAnWordToSymbolApplication(symbol)
/**
* This method enables the following syntax, where, for example, <code>badBook</code> is of type <code>Book</code> and <code>excellentRead</code>
* is a <code>BePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* badBook should not be an (excellentRead)
* ^
* </pre>
*/
def apply[T](beTrueMatcher: BePropertyMatcher[T]): ResultOfAnWordToBePropertyMatcherApplication[T] = new ResultOfAnWordToBePropertyMatcherApplication(beTrueMatcher)
/**
* This method enables the following syntax, where, <code>positiveNumber</code> is an <code>AnMatcher[Book]</code>:
*
* <pre class="stHighlight">
* result should not be an (positiveNumber)
* ^
* </pre>
*/
def apply[T](anMatcher: AnMatcher[T]): ResultOfAnWordToAnMatcherApplication[T] = new ResultOfAnWordToAnMatcherApplication(anMatcher)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* badBook should not be an (excellentRead)
* ^
* </pre>
*/
val an = new AnWord
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class TheSameInstanceAsPhrase {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* oneString should not be theSameInstanceAs (anotherString)
* ^
* </pre>
*/
def apply(anyRef: AnyRef): ResultOfTheSameInstanceAsApplication = new ResultOfTheSameInstanceAsApplication(anyRef)
}
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* oneString should not be theSameInstanceAs (anotherString)
* ^
* </pre>
*/
val theSameInstanceAs: TheSameInstanceAsPhrase = new TheSameInstanceAsPhrase
/**
* This field enables the following syntax:
*
* <pre class="stHighlight">
* "eight" should not fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""".r)
* ^
* </pre>
*/
val regex = new RegexWord
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* "eight" should not include substring ("seven")
* ^
* </pre>
val substring = new SubstringWord
*/
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForSize[A <: AnyRef : Size](left: A, shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/* I just added this whole thing in here for completeness when doing SizeShouldWrapper. Write some tests to prove it is needed.
// TODO: This should be for "sizey should not have size (12)" Try that test.
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
val right = resultOfLengthWordApplication.expectedLength
if ((left.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
right
)
)
}
}
*/
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfNotWordForLength[A <: AnyRef : Length](left: A, shouldBeTrue: Boolean)
extends ResultOfNotWordForAnyRef(left, shouldBeTrue) {
/* TODO What's going on? Why can I drop this and still get a compile
// TODO: This should be for "lengthy should not have length (12)" Try that test.
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
val right = resultOfLengthWordApplication.expectedLength
if ((left.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
right
)
)
}
}
*/
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForExtent[A : Extent](left: A, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have length (2)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>length</code> property structure
* of type <code>Int</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>scala.Seq</code>, <code>java.lang.String</code>, and <code>java.util.List</code>.
* </p>
*/
def length(expectedLength: Int)(implicit len: Length[A]) {
// val len = implicitly[Length[A]]
// if ((len.extentOf(left.asInstanceOf[A]) == expectedLength) != shouldBeTrue)
if ((len.extentOf(left) == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have length (2L)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>length</code> property structure
* of type <code>Long</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>scala.Seq</code>, <code>java.lang.String</code>, and <code>java.util.List</code>.
* </p>
*/
def length(expectedLength: Long)(implicit len: Length[A]) {
// val len = implicitly[Length[A]]
// if ((len.extentOf(left.asInstanceOf[A]) == expectedLength) != shouldBeTrue)
if ((len.extentOf(left) == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have size (2)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>size</code> property structure
* of type <code>Int</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>Traversable</code> and <code>java.util.Collection</code>.
* </p>
*/
def size(expectedSize: Int)(implicit sz: Size[A]) {
// val sz = implicitly[Size[T]]
// if ((sz.extentOf(left.asInstanceOf[T]) == expectedSize) != shouldBeTrue)
if ((sz.extentOf(left) == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have size (2L)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>size</code> property structure
* of type <code>Long</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>Traversable</code> and <code>java.util.Collection</code>.
* </p>
*/
def size(expectedSize: Long)(implicit sz: Size[A]) {
// val sz = implicitly[Size[T]]
// if ((sz.extentOf(left.asInstanceOf[T]) == expectedSize) != shouldBeTrue)
if ((sz.extentOf(left) == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
}
/*
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForLength[A : Length](left: A, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have length (2)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>length</code> property structure
* of type <code>Int</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>scala.Seq</code>, <code>java.lang.String</code>, and <code>java.util.List</code>.
* </p>
*/
def length(expectedLength: Int) {
val len = implicitly[Length[A]]
if ((len.extentOf(left) == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have length (2L)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>length</code> property structure
* of type <code>Long</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>scala.Seq</code>, <code>java.lang.String</code>, and <code>java.util.List</code>.
* </p>
*/
def length(expectedLength: Long) {
val len = implicitly[Length[A]]
if ((len.extentOf(left) == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
left,
expectedLength)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfHaveWordForSize[A : Size](left: A, shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have size (2)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>size</code> property structure
* of type <code>Int</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>Traversable</code> and <code>java.util.Collection</code>.
* </p>
*/
def size(expectedSize: Int) {
val sz = implicitly[Size[A]]
if ((sz.extentOf(left) == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* obj should have size (2L)
* ^
* </pre>
*
* <p>
* This method is ultimately invoked for objects that have a <code>size</code> property structure
* of type <code>Long</code>,
* but is of a type that is not handled by implicit conversions from nominal types such as
* <code>Traversable</code> and <code>java.util.Collection</code>.
* </p>
*/
def size(expectedSize: Long) {
val sz = implicitly[Size[A]]
if ((sz.extentOf(left) == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
left,
expectedSize)
)
}
}
*/
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* num should (not be < (10) and not be > (17))
* ^
* </pre>
*/
def <[T <% Ordered[T]] (right: T): ResultOfLessThanComparison[T] =
new ResultOfLessThanComparison(right)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* num should (not be > (10) and not be < (7))
* ^
* </pre>
*/
def >[T <% Ordered[T]] (right: T): ResultOfGreaterThanComparison[T] =
new ResultOfGreaterThanComparison(right)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* num should (not be <= (10) and not be > (17))
* ^
* </pre>
*/
def <=[T <% Ordered[T]] (right: T): ResultOfLessThanOrEqualToComparison[T] =
new ResultOfLessThanOrEqualToComparison(right)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* num should (not be >= (10) and not be < (7))
* ^
* </pre>
*/
def >=[T <% Ordered[T]] (right: T): ResultOfGreaterThanOrEqualToComparison[T] =
new ResultOfGreaterThanOrEqualToComparison(right)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* num should not be === (10)
* ^
* </pre>
*/
/* TODEL
def === (right: Any): ResultOfTripleEqualsApplication =
new ResultOfTripleEqualsApplication(right)
*/
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfEvaluatingApplication(val fun: () => Any)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* evaluating { "hi".charAt(-1) } should produce [StringIndexOutOfBoundsException]
* ^
* </pre>
*/
def evaluating(fun: => Any): ResultOfEvaluatingApplication =
new ResultOfEvaluatingApplication(fun _)
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfProduceInvocation[T](val clazz: Class[T])
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* evaluating { "hi".charAt(-1) } should produce [StringIndexOutOfBoundsException]
* ^
* </pre>
*/
def produce[T](implicit manifest: Manifest[T]): ResultOfProduceInvocation[T] =
new ResultOfProduceInvocation(manifest.erasure.asInstanceOf[Class[T]])
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfContainWordForTraversable[T](left: GenTraversable[T], shouldBeTrue: Boolean = true) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain theSameElementsAs anotherTraversable
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
matchContainMatcher(left, new TheSameElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain theSameElementsAs array
* ^
* </pre>
*/
def theSameElementsAs(right: Array[T])(implicit equality: Equality[T]) {
matchContainMatcher(left, new TheSameElementsAsContainMatcher(new ArrayWrapper(right), equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain theSameIteratedElementsAs anotherTraversable
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
matchContainMatcher(left, new TheSameIteratedElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain theSameIteratedElementsAs array
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: Array[T])(implicit equality: Equality[T]) {
matchContainMatcher(left, new TheSameIteratedElementsAsContainMatcher(new ArrayWrapper(right), equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain allOf (1, 2)
* ^
* </pre>
*/
def allOf(right: T*)(implicit equality: Equality[T]) {
matchContainMatcher(left, new AllOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain inOrder (1, 2)
* ^
* </pre>
*/
def inOrder(right: T*)(implicit equality: Equality[T]) {
matchContainMatcher(left, new InOrderContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain oneOf (1, 2)
* ^
* </pre>
*/
def oneOf(right: T*)(implicit equality: Equality[T]) {
matchContainMatcher(left, new OneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain only (1, 2)
* ^
* </pre>
*/
def only(right: T*)(implicit equality: Equality[T]) {
matchContainMatcher(left, new OnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain inOrderOnly (1, 2)
* ^
* </pre>
*/
def inOrderOnly(right: T*)(implicit equality: Equality[T]) {
matchContainMatcher(left, new InOrderOnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain noneOf (1, 2)
* ^
* </pre>
*/
def noneOf(right: T*)(implicit equality: Equality[T]) {
matchContainMatcher(left, new NoneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax (positiveNumber is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* traversable should contain a positiveNumber
* ^
* </pre>
*/
def a(aMatcher: AMatcher[T]) {
left.find(aMatcher(_).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e)
throw newTestFailedException(FailureMessages("containedA", left, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", left, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax (oddNumber is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* traversable should contain an oddNumber
* ^
* </pre>
*/
def an(anMatcher: AnMatcher[T]) {
left.find(anMatcher(_).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e)
throw newTestFailedException(FailureMessages("containedAn", left, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", left, UnquotedString(anMatcher.nounName)))
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
*/
final class ResultOfContainWordForJavaCollection[E, L[_] <: java.util.Collection[_]](left: L[E], shouldBeTrue: Boolean) {
// TODO: Chee Seng, why are we casting here to java.util.Collection[E]?
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain theSameElementsAs traversable
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[E])(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new TheSameElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain theSameIteratedElementsAs anotherTraversable
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[E])(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new TheSameIteratedElementsAsContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain allOf (1, 2)
* ^
* </pre>
*/
def allOf(right: E*)(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new AllOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain inOrder (1, 2)
* ^
* </pre>
*/
def inOrder(right: E*)(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new InOrderContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain oneOf (1, 2)
* ^
* </pre>
*/
def oneOf(right: E*)(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new OneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain only (1, 2)
* ^
* </pre>
*/
def only(right: E*)(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new OnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain inOrderOnly (1, 2)
* ^
* </pre>
*/
def inOrderOnly(right: E*)(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new InOrderOnlyContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* javaCol should contain noneOf (1, 2)
* ^
* </pre>
*/
def noneOf(right: E*)(implicit equality: Equality[E]) {
matchContainMatcher(left.asInstanceOf[java.util.Collection[E]], new NoneOfContainMatcher(right, equality), shouldBeTrue)
}
/**
* This method enables the following syntax (positiveNumber is a <code>AMatcher</code>):
*
* <pre class="stHighlight">
* javaCol should contain a positiveNumber
* ^
* </pre>
*/
def a(aMatcher: AMatcher[E]) {
val leftWrapper = new JavaCollectionWrapper(left.asInstanceOf[java.util.Collection[E]])
leftWrapper.find(e => aMatcher(e).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = aMatcher(e)
throw newTestFailedException(FailureMessages("containedA", leftWrapper, UnquotedString(aMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainA", leftWrapper, UnquotedString(aMatcher.nounName)))
}
}
/**
* This method enables the following syntax (oddNumber is a <code>AnMatcher</code>):
*
* <pre class="stHighlight">
* javaCol should contain an oddNumber
* ^
* </pre>
*/
def an(anMatcher: AnMatcher[E]) {
val leftWrapper = new JavaCollectionWrapper(left.asInstanceOf[java.util.Collection[E]])
leftWrapper.find(e => anMatcher(e).matches) match {
case Some(e) =>
if (!shouldBeTrue) {
val result = anMatcher(e)
throw newTestFailedException(FailureMessages("containedAn", leftWrapper, UnquotedString(anMatcher.nounName), UnquotedString(result.negatedFailureMessage)))
}
case None =>
if (shouldBeTrue)
throw newTestFailedException(FailureMessages("didNotContainAn", leftWrapper, UnquotedString(anMatcher.nounName)))
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain (theSameElementsAs(anotherTraversable))
* ^
* </pre>
*/
def theSameElementsAs[T](xs: GenTraversable[T])(implicit equality: Equality[T]) =
new TheSameElementsAsContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain (theSameElementsAs(array))
* ^
* </pre>
*/
def theSameElementsAs[T](xs: Array[T])(implicit equality: Equality[T]) =
new TheSameElementsAsContainMatcher(new ArrayWrapper(xs), equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain (theSameIteratedElementsAs(anotherTraversable))
* ^
* </pre>
*/
def theSameIteratedElementsAs[T](xs: GenTraversable[T])(implicit equality: Equality[T]) =
new TheSameIteratedElementsAsContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* traversable should contain (theSameIteratedElementsAs(array))
* ^
* </pre>
*/
def theSameIteratedElementsAs[T](xs: Array[T])(implicit equality: Equality[T]) =
new TheSameIteratedElementsAsContainMatcher(new ArrayWrapper(xs), equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2, 3) should contain (allOf(1, 2))
* ^
* </pre>
*/
def allOf[T](xs: T*)(implicit equality: Equality[T]) =
new AllOfContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2, 3) should contain (inOrder(1, 2))
* ^
* </pre>
*/
def inOrder[T](xs: T*)(implicit equality: Equality[T]) =
new InOrderContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2, 3) should contain (oneOf(1, 2))
* ^
* </pre>
*/
def oneOf[T](xs: T*)(implicit equality: Equality[T]) =
new OneOfContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2, 3) should contain (only(1, 2))
* ^
* </pre>
*/
def only[T](xs: T*)(implicit equality: Equality[T]) =
new OnlyContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2, 3) should contain (inOrderOnly(1, 2))
* ^
* </pre>
*/
def inOrderOnly[T](xs: T*)(implicit equality: Equality[T]) =
new InOrderOnlyContainMatcher(xs, equality)
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* List(1, 2, 3) should contain (noneOf(1, 2))
* ^
* </pre>
*/
def noneOf[T](xs: T*)(implicit equality: Equality[T]) =
new NoneOfContainMatcher(xs, equality)
// For safe keeping
private implicit def nodeToCanonical(node: scala.xml.Node) = new Canonicalizer(node)
private class Canonicalizer(node: scala.xml.Node) {
def toCanonical: scala.xml.Node = {
node match {
case elem: scala.xml.Elem =>
val canonicalizedChildren =
for (child <- node.child if !child.toString.trim.isEmpty) yield {
child match {
case elem: scala.xml.Elem => elem.toCanonical
case other => other
}
}
new scala.xml.Elem(elem.prefix, elem.label, elem.attributes, elem.scope, canonicalizedChildren: _*)
case other => other
}
}
}
/*
class AType[T : ClassManifest] {
private val clazz = implicitly[ClassManifest[T]].erasure.asInstanceOf[Class[T]]
def isAssignableFromClassOf(o: Any): Boolean = clazz.isAssignableFrom(o.getClass)
def className: String = clazz.getName
}
def a[T : ClassManifest]: AType[T] = new AType[T]
*/
// This is where InspectorShorthands started
private sealed trait Collected
private case object AllCollected extends Collected
private case object EveryCollected extends Collected
private case class BetweenCollected(from: Int, to: Int) extends Collected
private case class AtLeastCollected(num: Int) extends Collected
private case class AtMostCollected(num: Int) extends Collected
private case object NoCollected extends Collected
private case class ExactlyCollected(num: Int) extends Collected
import InspectorsHelper._
def doCollected[T](collected: Collected, xs: GenTraversable[T], methodName: String, stackDepth: Int)(fun: T => Unit) {
collected match {
case AllCollected =>
doForAll(xs, "allShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
case AtLeastCollected(num) =>
doForAtLeast(num, xs, "atLeastShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
case EveryCollected =>
doForEvery(xs, "everyShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
case ExactlyCollected(num) =>
doForExactly(num, xs, "exactlyShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
case NoCollected =>
doForNo(xs, "noShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
case BetweenCollected(from, to) =>
doForBetween(from, to, xs, "betweenShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
case AtMostCollected(num) =>
doForAtMost(num, xs, "atMostShorthandFailed", "Matchers.scala", methodName, stackDepth) { e =>
fun(e)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
sealed class ResultOfNotWordForCollectedAny[T](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) {
import org.scalatest.InspectorsHelper._
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not equal (7)
* ^
* </pre>
*/
def equal(right: Any)(implicit equality: Equality[T]) {
doCollected(collected, xs, "equal", 1) { e =>
if ((equality.areEqual(e, right)) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEqual" else "equaled",
e,
right
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be (7)
* ^
* </pre>
*/
def be(right: Any) {
doCollected(collected, xs, "be", 1) { e =>
if ((e == right) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotEqualTo" else "wasEqualTo",
e,
right
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be <= (7)
* ^
* </pre>
*/
def be(comparison: ResultOfLessThanOrEqualToComparison[T]) {
doCollected(collected, xs, "be", 1) { e =>
if (comparison(e) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotLessThanOrEqualTo" else "wasLessThanOrEqualTo",
e,
comparison.right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be >= (7)
* ^
* </pre>
*/
def be(comparison: ResultOfGreaterThanOrEqualToComparison[T]) {
doCollected(collected, xs, "be", 1) { e =>
if (comparison(e) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotGreaterThanOrEqualTo" else "wasGreaterThanOrEqualTo",
e,
comparison.right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be < (7)
* ^
* </pre>
*/
def be(comparison: ResultOfLessThanComparison[T]) {
doCollected(collected, xs, "be", 1) { e =>
if (comparison(e) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotLessThan" else "wasLessThan",
e,
comparison.right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be > (7)
* ^
* </pre>
*/
def be(comparison: ResultOfGreaterThanComparison[T]) {
doCollected(collected, xs, "be", 1) { e =>
if (comparison(e) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotGreaterThan" else "wasGreaterThan",
e,
comparison.right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be === (7)
* ^
* </pre>
*/
def be(comparison: TripleEqualsInvocation[_]) {
doCollected(collected, xs, "be", 1) { e =>
if ((e == comparison.right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotEqualTo" else "wasEqualTo",
e,
comparison.right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>odd</code> refers to
* a <code>BeMatcher[Int]</code>:
*
* <pre class="stHighlight">
* all(xs) should not be (odd)
* ^
* </pre>
*/
def be(beMatcher: BeMatcher[T]) {
doCollected(collected, xs, "be", 1) { e =>
val result = beMatcher(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
result.failureMessage
else
result.negatedFailureMessage,
None,
10
)
}
}
}
/**
* This method enables the following syntax, where <code>stack</code> is, for example, of type <code>Stack</code> and
* <code>empty</code> refers to a <code>BePropertyMatcher[Stack]</code>:
*
* <pre class="stHighlight">
* all(xs) should not be (empty)
* ^
* </pre>
*/
def be(bePropertyMatcher: BePropertyMatcher[T]) {
doCollected(collected, xs, "be", 1) { e =>
val result = bePropertyMatcher(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNot", e, UnquotedString(result.propertyName))
else
FailureMessages("was", e, UnquotedString(result.propertyName)),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>notFileMock</code> is, for example, of type <code>File</code> and
* <code>file</code> refers to a <code>BePropertyMatcher[File]</code>:
*
* <pre class="stHighlight">
* all(xs) should not be a (file)
* ^
* </pre>
*/
def be[U >: T](resultOfAWordApplication: ResultOfAWordToBePropertyMatcherApplication[U]) {
doCollected(collected, xs, "be", 1) { e =>
val result = resultOfAWordApplication.bePropertyMatcher(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotA", e, UnquotedString(result.propertyName))
else
FailureMessages("wasA", e, UnquotedString(result.propertyName)),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>keyEvent</code> is, for example, of type <code>KeyEvent</code> and
* <code>actionKey</code> refers to a <code>BePropertyMatcher[KeyEvent]</code>:
*
* <pre class="stHighlight">
* all(keyEvents) should not be an (actionKey)
* ^
* </pre>
*/
def be[U >: T](resultOfAnWordApplication: ResultOfAnWordToBePropertyMatcherApplication[U]) {
doCollected(collected, xs, "be", 1) { e =>
val result = resultOfAnWordApplication.bePropertyMatcher(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotAn", e, UnquotedString(result.propertyName))
else
FailureMessages("wasAn", e, UnquotedString(result.propertyName)),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be theSameInstanceAs (string)
* ^
* </pre>
*/
def be(resultOfSameInstanceAsApplication: ResultOfTheSameInstanceAsApplication) {
doCollected(collected, xs, "be", 1) { e =>
e match {
case ref: AnyRef =>
if ((resultOfSameInstanceAsApplication.right eq ref) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotSameInstanceAs" else "wasSameInstanceAs",
e,
resultOfSameInstanceAsApplication.right
),
None,
6
)
}
case _ =>
throw new IllegalArgumentException("theSameInstanceAs should only be used for AnyRef")
}
}
}
/**
* This method enables the following syntax, where <code>badBook</code> is, for example, of type <code>Book</code> and
* <code>title ("One Hundred Years of Solitude")</code> results in a <code>HavePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* all(books) should not have (title ("One Hundred Years of Solitude"))
* ^
* </pre>
*/
def have[U >: T](firstPropertyMatcher: HavePropertyMatcher[U, _], propertyMatchers: HavePropertyMatcher[U, _]*) {
doCollected(collected, xs, "have", 1) { e =>
val results =
for (propertyVerifier <- firstPropertyMatcher :: propertyMatchers.toList) yield
propertyVerifier(e)
val firstFailureOption = results.find(pv => !pv.matches)
val justOneProperty = propertyMatchers.length == 0
// if shouldBeTrue is false, then it is like "not have ()", and should throw TFE if firstFailureOption.isDefined is false
// if shouldBeTrue is true, then it is like "not (not have ()), which should behave like have ()", and should throw TFE if firstFailureOption.isDefined is true
if (firstFailureOption.isDefined == shouldBeTrue) {
firstFailureOption match {
case Some(firstFailure) =>
// This is one of these cases, thus will only get here if shouldBeTrue is true
// 0 0 | 0 | 1
// 0 1 | 0 | 1
// 1 0 | 0 | 1
throw newTestFailedException(
FailureMessages(
"propertyDidNotHaveExpectedValue",
UnquotedString(firstFailure.propertyName),
firstFailure.expectedValue,
firstFailure.actualValue,
e
),
None,
6
)
case None =>
// This is this cases, thus will only get here if shouldBeTrue is false
// 1 1 | 1 | 0
val failureMessage =
if (justOneProperty) {
val firstPropertyResult = results.head // know this will succeed, because firstPropertyMatcher was required
FailureMessages(
"propertyHadExpectedValue",
UnquotedString(firstPropertyResult.propertyName),
firstPropertyResult.expectedValue,
e
)
}
else FailureMessages("allPropertiesHadExpectedValues", e)
throw newTestFailedException(failureMessage, None, 6)
}
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
sealed class ResultOfNotWordForCollectedAnyRef[T <: AnyRef](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean)
extends ResultOfNotWordForCollectedAny(collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be (null)
* ^
* </pre>
*/
def be(o: Null) {
doCollected(collected, xs, "be", 1) { e =>
if ((e == null) != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotNull", e)
else
FailureMessages("wasNull"),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be ('empty)
* ^
* </pre>
*/
def be(symbol: Symbol) {
doCollected(collected, xs, "be", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e, symbol, false, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be a ('file)
* ^
* </pre>
*/
def be(resultOfAWordApplication: ResultOfAWordToSymbolApplication) {
doCollected(collected, xs, "be", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e, resultOfAWordApplication.symbol, true, true)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should not be an ('actionKey)
* ^
* </pre>
*/
def be(resultOfAnWordApplication: ResultOfAnWordToSymbolApplication) {
doCollected(collected, xs, "be", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e, resultOfAnWordApplication.symbol, true, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfNotWordForCollectedString(collected: Collected, xs: GenTraversable[String], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedAnyRef[String](collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not have length (12)
* ^
* </pre>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfLengthWordApplication.expectedLength
if ((e.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not have size (12)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfSizeWordApplication.expectedSize
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not startWith ("1.7")
* ^
* </pre>
*/
def startWith(right: String) {
doCollected(collected, xs, "startWith", 1) { e =>
if ((e.indexOf(right) == 0) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotStartWith" else "startedWith",
e,
right
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not startWith regex ("Hel*o")
* ^
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*/
def startWith(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
doCollected(collected, xs, "startWith", 1) { e =>
val rightRegex = resultOfRegexWordApplication.regex
if (rightRegex.pattern.matcher(e).lookingAt != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotStartWithRegex" else "startedWithRegex",
e,
rightRegex
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not endWith ("1.7")
* ^
* </pre>
*/
def endWith(expectedSubstring: String) {
doCollected(collected, xs, "endWith", 1) { e =>
if ((e endsWith expectedSubstring) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEndWith" else "endedWith",
e,
expectedSubstring
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not endWith regex ("wor.d")
* ^
* </pre>
*/
def endWith(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
doCollected(collected, xs, "endWith", 1) { e =>
val rightRegex = resultOfRegexWordApplication.regex
val allMatches = rightRegex.findAllIn(e)
if (allMatches.hasNext && (allMatches.end == e.length) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEndWithRegex" else "endedWithRegex",
e,
rightRegex
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not include regex ("wo.ld")
* ^
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*/
def include(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
doCollected(collected, xs, "include", 1) { e =>
val rightRegex = resultOfRegexWordApplication.regex
if (rightRegex.findFirstIn(e).isDefined != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotIncludeRegex" else "includedRegex",
e,
rightRegex
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not include ("world")
* ^
* </pre>
*/
def include(expectedSubstring: String) {
doCollected(collected, xs, "include", 1) { e =>
if ((e.indexOf(expectedSubstring) >= 0) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotIncludeSubstring" else "includedSubstring",
e,
expectedSubstring
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should not fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""")
* ^
* </pre>
*
* <p>
* The regular expression passed following the <code>regex</code> token can be either a <code>String</code>
* or a <code>scala.util.matching.Regex</code>.
* </p>
*/
def fullyMatch(resultOfRegexWordApplication: ResultOfRegexWordApplication) {
doCollected(collected, xs, "fullyMatch", 1) { e =>
val rightRegex = resultOfRegexWordApplication.regex
if (rightRegex.pattern.matcher(e).matches != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotFullyMatchRegex" else "fullyMatchedRegex",
e,
rightRegex
),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
sealed class ResultOfNotWordForCollectedGenTraversable[E, T <: GenTraversable[E]](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedAnyRef[T](collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(traversableOfTraversable) should not have size (12)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfSizeWordApplication.expectedSize
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(traversableOfTraversable) should not have length (12)
* ^
* </pre>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfLengthWordApplication.expectedLength
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(traversableOfTraversable) should not contain ("one")
* ^
* </pre>
*/
def contain(expectedElement: E) {
doCollected(collected, xs, "contain", 1) { e =>
val right = expectedElement
if ((e.exists(_ == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>num</code> is, for example, of type <code>Int</code> and
* <code>odd</code> refers to a <code>BeMatcher[Int]</code>:
*
* <pre class="stHighlight">testing
* all(traversableOfTraversable) should not contain (containMatcher)
* ^
* </pre>
*/
def contain(right: ContainMatcher[E]) {
doCollected(collected, xs, "contain", 1) { e =>
val result = right(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfNotWordForCollectedGenSeq[E, T <: GenSeq[E]](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedGenTraversable[E, T](collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(seqOfSeq) should not have length (12)
* ^
* </pre>
*/
override def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfLengthWordApplication.expectedLength
if ((e.length == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
right
),
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
sealed class ResultOfNotWordForCollectedArray[E, T <: Array[E]](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedAnyRef[T](collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should not be ('empty)
* ^
* </pre>
*/
override def be(symbol: Symbol) {
doCollected(collected, xs, "be", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e.deep, symbol, false, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should not be a ('file)
* ^
* </pre>
*/
override def be(resultOfAWordApplication: ResultOfAWordToSymbolApplication) {
doCollected(collected, xs, "be", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e.deep, resultOfAWordApplication.symbol, true, true)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
10
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should not be an ('actionKey)
* ^
* </pre>
*/
override def be(resultOfAnWordApplication: ResultOfAnWordToSymbolApplication) {
doCollected(collected, xs, "be", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e.deep, resultOfAnWordApplication.symbol, true, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
10
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(traversableOfArray) should not have size (12)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfSizeWordApplication.expectedSize
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(traversableOfArray) should not contain ("one")
* ^
* </pre>
*/
def contain(expectedElement: E) {
doCollected(collected, xs, "contain", 1) { e =>
val right = expectedElement
if ((e.exists(_ == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>num</code> is, for example, of type <code>Int</code> and
* <code>odd</code> refers to a <code>BeMatcher[Int]</code>:
*
* <pre class="stHighlight">testing
* all(traversableOfArray) should not contain (containMatcher)
* ^
* </pre>
*/
def contain(right: ContainMatcher[E]) {
doCollected(collected, xs, "contain", 1) { e =>
val result = right(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(seqOfArray) should not have length (12)
* ^
* </pre>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfLengthWordApplication.expectedLength
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
right
),
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfNotWordForCollectedGenMap[K, V, T <: GenMap[K, V]](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedGenTraversable[(K, V), T](collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should not contain key ("three")
* ^
* </pre>
*/
def contain(resultOfKeyWordApplication: ResultOfKeyWordApplication[K]) {
doCollected(collected, xs, "contain", 1) { e =>
val right = resultOfKeyWordApplication.expectedKey
if ((e.exists(_._1 == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should not contain value (3)
* ^
* </pre>
*/
def contain(resultOfValueWordApplication: ResultOfValueWordApplication[V]) {
doCollected(collected, xs, "contain", 1) { e =>
val right = resultOfValueWordApplication.expectedValue
if ((e.exists(_._2 == right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
e,
right
),
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
class ResultOfNotWordForCollectedJavaCollection[E, T <: java.util.Collection[E]](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedAnyRef[T](collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaCollection) should not have size (3)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfSizeWordApplication.expectedSize
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaCollection) should not have length (12)
* ^
* </pre>
*
* <p>
* This method invokes <code>size</code> on the <code>java.util.List</code> passed as <code>left</code> to
* determine its length.
* </p>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfLengthWordApplication.expectedLength
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaCollection) should not contain ("elephant")
* ^
* </pre>
*/
def contain(expectedElement: E) {
doCollected(collected, xs, "contain", 1) { e =>
val right = expectedElement
if ((e.contains(right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainExpectedElement" else "containedExpectedElement",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>num</code> is, for example, of type <code>Int</code> and
* <code>odd</code> refers to a <code>BeMatcher[Int]</code>:
*
* <pre class="stHighlight">testing
* all(colOfJavaCollection) should not contain (containMatcher)
* ^
* </pre>
*/
def contain(right: ContainMatcher[E]) {
doCollected(collected, xs, "contain", 1) { e =>
val result = right(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfNotWordForCollectedJavaMap[K, V, T <: java.util.Map[K, V]](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean) extends
ResultOfNotWordForCollectedAnyRef[T](collected, xs, shouldBeTrue){
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should not have size (3)
* ^
* </pre>
*/
def have(resultOfSizeWordApplication: ResultOfSizeWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfSizeWordApplication.expectedSize
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should not have length (12)
* ^
* </pre>
*
* <p>
* This method invokes <code>size</code> on the <code>java.util.List</code> passed as <code>left</code> to
* determine its length.
* </p>
*/
def have(resultOfLengthWordApplication: ResultOfLengthWordApplication) {
doCollected(collected, xs, "have", 1) { e =>
val right = resultOfLengthWordApplication.expectedLength
if ((e.size == right) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should not contain key ("three")
* ^
* </pre>
*/
def contain(resultOfKeyWordApplication: ResultOfKeyWordApplication[K]) {
doCollected(collected, xs, "contain", 1) { e =>
val right = resultOfKeyWordApplication.expectedKey
if ((e.containsKey(right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should not contain value (3)
* ^
* </pre>
*/
def contain(resultOfValueWordApplication: ResultOfValueWordApplication[V]) {
doCollected(collected, xs, "contain", 1) { e =>
val right = resultOfValueWordApplication.expectedValue
if ((e.containsValue(right)) != shouldBeTrue) {
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
e,
right
),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>num</code> is, for example, of type <code>Int</code> and
* <code>odd</code> refers to a <code>BeMatcher[Int]</code>:
*
* <pre class="stHighlight">testing
* all(colOfJavaMap) should not contain (containMatcher)
* ^
* </pre>
*/
def contain(right: ContainMatcher[(K, V)]) {
doCollected(collected, xs, "contain", 1) { e =>
val result = right(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
sealed class ResultOfBeWordForCollectedAny[T](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean)
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
class ResultOfBeWordForCollectedAnyRef[T <: AnyRef](collected: Collected, xs: GenTraversable[T], shouldBeTrue: Boolean)
extends ResultOfBeWordForCollectedAny(collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def theSameInstanceAs(right: AnyRef) {
doCollected(collected, xs, "theSameInstanceAs", 1) { e =>
if ((e eq right) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "wasNotSameInstanceAs" else "wasSameInstanceAs",
e,
right
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should be a ('file)
* ^
* </pre>
*/
def a(symbol: Symbol) {
doCollected(collected, xs, "a", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e, symbol, true, true)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
6
)
}
}
}
// TODO, in both of these, the failure message doesn't have a/an
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(xs) should be an ('orange)
* ^
* </pre>
*/
def an(symbol: Symbol) {
doCollected(collected, xs, "an", 1) { e =>
val matcherResult = matchSymbolToPredicateMethod(e, symbol, true, false)
if (matcherResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue) matcherResult.failureMessage else matcherResult.negatedFailureMessage,
None,
6
)
}
}
}
// TODO: Check the shouldBeTrues, are they sometimes always false or true?
/**
* This method enables the following syntax, where <code>badBook</code> is, for example, of type <code>Book</code> and
* <code>goodRead</code> refers to a <code>BePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* all(books) should be a (goodRead)
* ^
* </pre>
*/
def a(bePropertyMatcher: BePropertyMatcher[T]) {
doCollected(collected, xs, "a", 1) { e =>
val result = bePropertyMatcher(e)
if (result.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotA", e, UnquotedString(result.propertyName))
else
FailureMessages("wasA", e, UnquotedString(result.propertyName)),
None,
6
)
}
}
}
/**
* This method enables the following syntax, where <code>badBook</code> is, for example, of type <code>Book</code> and
* <code>excellentRead</code> refers to a <code>BePropertyMatcher[Book]</code>:
*
* <pre class="stHighlight">
* all(books) should be an (excellentRead)
* ^
* </pre>
*/
def an(beTrueMatcher: BePropertyMatcher[T]) {
doCollected(collected, xs, "an", 1) { e =>
val beTrueMatchResult = beTrueMatcher(e)
if (beTrueMatchResult.matches != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages("wasNotAn", e, UnquotedString(beTrueMatchResult.propertyName))
else
FailureMessages("wasAn", e, UnquotedString(beTrueMatchResult.propertyName)),
None,
6
)
}
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfBeWordForCollectedArray[T](collected: Collected, xs: GenTraversable[Array[T]], shouldBeTrue: Boolean)
extends ResultOfBeWordForCollectedAnyRef(collected, xs, shouldBeTrue) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should be ('empty)
* ^
* </pre>
*/
def apply(right: Symbol): Matcher[Array[T]] =
new Matcher[Array[T]] {
def apply(left: Array[T]): MatchResult = matchSymbolToPredicateMethod(left.deep, right, false, false)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfContainWordForCollectedArray[T](collected: Collected, xs: GenTraversable[Array[T]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain (element)
* ^
* </pre>
*/
def apply(expectedElement: T): Matcher[Array[T]] =
new Matcher[Array[T]] {
def apply(left: Array[T]): MatchResult =
MatchResult(
left.exists(_ == expectedElement),
FailureMessages("didNotContainExpectedElement", left, expectedElement),
FailureMessages("containedExpectedElement", left, expectedElement)
)
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain theSameElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
val containMatcher = new TheSameElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameElementsAs", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain theSameIteratedElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
val containMatcher = new TheSameIteratedElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameIteratedElementsAs", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain allOf (1, 2, 3)
* ^
* </pre>
*/
def allOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new AllOfContainMatcher(right, equality)
doCollected(collected, xs, "allOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain inOrder (1, 2, 3)
* ^
* </pre>
*/
def inOrder(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new InOrderContainMatcher(right, equality)
doCollected(collected, xs, "inOrder", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain oneOf (1, 2, 3)
* ^
* </pre>
*/
def oneOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new OneOfContainMatcher(right, equality)
doCollected(collected, xs, "oneOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain only (1, 2, 3)
* ^
* </pre>
*/
def only(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new OnlyContainMatcher(right, equality)
doCollected(collected, xs, "only", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain inOrderOnly (1, 2, 3)
* ^
* </pre>
*/
def inOrderOnly(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new InOrderOnlyContainMatcher(right, equality)
doCollected(collected, xs, "inOrderOnly", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should contain noneOf (1, 2, 3)
* ^
* </pre>
*/
def noneOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new NoneOfContainMatcher(right, equality)
doCollected(collected, xs, "noneOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
sealed class ResultOfCollectedAny[T](collected: Collected, xs: GenTraversable[T]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should be (3)
* ^
* </pre>
*/
def should(rightMatcher: Matcher[T]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all (xs) shouldEqual 7
* ^
* </pre>
*/
def shouldEqual(right: Any)(implicit equality: Equality[T]) {
doCollected(collected, xs, "shouldEqual", 1) { e =>
if (!equality.areEqual(e, right)) {
val (eee, rightee) = Suite.getObjectsForFailureMessage(e, right)
throw newTestFailedException(FailureMessages("didNotEqual", eee, rightee), None, 6)
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[T, TYPECLASS1])(implicit typeClass1: TYPECLASS1[T]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[T, TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[T], typeClass2: TYPECLASS2[T]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAny[T](collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should not equal (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedAny[T] =
new ResultOfNotWordForCollectedAny(collected, xs, false)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
class ResultOfCollectedAnyRef[T <: AnyRef](collected: Collected, xs: GenTraversable[T]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should be (3)
* ^
* </pre>
*/
def should(rightMatcher: Matcher[T]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[T, TYPECLASS1])(implicit typeClass1: TYPECLASS1[T]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[T, TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[T], typeClass2: TYPECLASS2[T]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef[T](collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should not equal (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedAnyRef[T] =
new ResultOfNotWordForCollectedAnyRef(collected, xs, false)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedString(collected: Collected, xs: GenTraversable[String]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should be ("hi")
* ^
* </pre>
*/
def should(rightMatcher: Matcher[String]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[String, TYPECLASS1])(implicit typeClass1: TYPECLASS1[String]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[String, TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[String], typeClass2: TYPECLASS2[String]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForCollectedString =
new ResultOfHaveWordForCollectedString(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedString =
new ResultOfNotWordForCollectedString(collected, xs, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should startWith regex ("Hel*o")
* ^
* </pre>
*/
def should(startWithWord: StartWithWord): ResultOfStartWithWordForCollectedString =
new ResultOfStartWithWordForCollectedString(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should endWith regex ("wo.ld")
* ^
* </pre>
*/
def should(endWithWord: EndWithWord): ResultOfEndWithWordForCollectedString =
new ResultOfEndWithWordForCollectedString(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should include regex ("wo.ld")
* ^
* </pre>
*/
def should(includeWord: IncludeWord): ResultOfIncludeWordForCollectedString =
new ResultOfIncludeWordForCollectedString(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(string) should fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""")
* ^
* </pre>
*/
def should(fullyMatchWord: FullyMatchWord): ResultOfFullyMatchWordForCollectedString =
new ResultOfFullyMatchWordForCollectedString(collected, xs, true)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfHaveWordForCollectedString(collected: Collected, xs: GenTraversable[String], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should have length (12)
* ^
* </pre>
*/
def length(expectedLength: Long) {
doCollected(collected, xs, "length", 1) { e =>
if ((e.length == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
expectedLength
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should have size (12)
* ^
* </pre>
*/
def size(expectedSize: Int) {
doCollected(collected, xs, "size", 1) { e =>
if ((e.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
expectedSize
),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfStartWithWordForCollectedString(collected: Collected, xs: GenTraversable[String], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should startWith regex ("Hel*o")
* ^
* </pre>
*/
def regex(rightRegexString: String) { checkRegex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should startWith regex ("Hel*o".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) { checkRegex(rightRegex) }
def checkRegex(rightRegex: Regex) {
doCollected(collected, xs, "regex", 2) { e =>
if (rightRegex.pattern.matcher(e).lookingAt != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotStartWithRegex" else "startedWithRegex",
e,
rightRegex
),
None,
7
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfIncludeWordForCollectedString(collected: Collected, xs: GenTraversable[String], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should include regex ("world")
* ^
* </pre>
*/
def regex(rightRegexString: String) { checkRegex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should include regex ("wo.ld".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) { checkRegex(rightRegex) }
private def checkRegex(rightRegex: Regex) {
doCollected(collected, xs, "regex", 2) { e =>
if (rightRegex.findFirstIn(e).isDefined != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotIncludeRegex" else "includedRegex",
e,
rightRegex
),
None,
7
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfEndWithWordForCollectedString(collected: Collected, xs: GenTraversable[String], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should endWith regex ("wor.d")
* ^
* </pre>
*/
def regex(rightRegexString: String) { checkRegex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should endWith regex ("wor.d".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) { checkRegex(rightRegex) }
private def checkRegex(rightRegex: Regex) {
doCollected(collected, xs, "regex", 2) { e =>
val allMatches = rightRegex.findAllIn(e)
if ((allMatches.hasNext && (allMatches.end == e.length)) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotEndWithRegex" else "endedWithRegex",
e,
rightRegex
),
None,
7
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfFullyMatchWordForCollectedString(collected: Collected, xs: GenTraversable[String], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should fullMatch regex ("Hel*o world")
* ^
* </pre>
*/
def regex(rightRegexString: String) { checkRegex(rightRegexString.r) }
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(string) should fullymatch regex ("Hel*o world".r)
* ^
* </pre>
*/
def regex(rightRegex: Regex) { checkRegex(rightRegex) }
private def checkRegex(rightRegex: Regex) {
doCollected(collected, xs, "regex", 2) { e =>
if (rightRegex.pattern.matcher(e).matches != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotFullyMatchRegex" else "fullyMatchedRegex",
e,
rightRegex
),
None,
7
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedGenTraversable[T](collected: Collected, xs: GenTraversable[GenTraversable[T]]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForCollectedGenTraversable[T] =
new ResultOfHaveWordForCollectedGenTraversable(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should be (Set(1, 2, 3))
* ^
* </pre>
*/
def should(rightMatcher: Matcher[GenTraversable[T]]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[GenTraversable[T], TYPECLASS1])(implicit typeClass1: TYPECLASS1[GenTraversable[T]]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[GenTraversable[T], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[GenTraversable[T]], typeClass2: TYPECLASS2[GenTraversable[T]]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedGenTraversable[T, GenTraversable[T]] =
new ResultOfNotWordForCollectedGenTraversable(collected, xs, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain (containMatcher)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForCollectedGenTraversable[T] =
new ResultOfContainWordForCollectedGenTraversable(collected, xs, true)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfHaveWordForCollectedGenTraversable[T](collected: Collected, xs: GenTraversable[GenTraversable[T]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should have size (12)
* ^
* </pre>
*/
def size(expectedSize: Long) {
doCollected(collected, xs, "size", 1) { e =>
if ((e.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
expectedSize
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should have length (12)
* ^
* </pre>
*/
def length(expectedLength: Long) {
doCollected(collected, xs, "length", 1) { e =>
if ((e.size == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
expectedLength
),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedGenSeq[T](collected: Collected, xs: GenTraversable[GenSeq[T]]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfSeq) should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForCollectedGenSeq[T] =
new ResultOfHaveWordForCollectedGenSeq(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfSeq) should be (List(1, 2, 3))
* ^
* </pre>
*/
def should(rightMatcher: Matcher[GenSeq[T]]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(xs) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[GenSeq[T], TYPECLASS1])(implicit typeClass1: TYPECLASS1[GenSeq[T]]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[GenSeq[T], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[GenSeq[T]], typeClass2: TYPECLASS2[GenSeq[T]]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfSeq) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfSeq) should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedGenSeq[T, GenSeq[T]] =
new ResultOfNotWordForCollectedGenSeq(collected, xs, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfGenSeq) should contain (containMatcher)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForCollectedGenTraversable[T] =
new ResultOfContainWordForCollectedGenTraversable(collected, xs, true)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfHaveWordForCollectedGenSeq[T](collected: Collected, xs: GenTraversable[GenSeq[T]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfSeq) should have length (12)
* ^
* </pre>
*/
def length(expectedLength: Long) {
doCollected(collected, xs, "length", 1) { e =>
if ((e.length == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
expectedLength
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfSeq) should have size (12)
* ^
* </pre>
*/
def size(expectedSize: Long) {
doCollected(collected, xs, "size", 1) { e =>
if ((e.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
expectedSize
),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfContainWordForCollectedGenTraversable[T](collected: Collected, xs: GenTraversable[GenTraversable[T]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain theSameElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
val containMatcher = new TheSameElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameElementsAs", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain theSameIteratedElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
val containMatcher = new TheSameIteratedElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameIteratedElementsAs", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain allOf (1, 2, 3)
* ^
* </pre>
*/
def allOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new AllOfContainMatcher(right, equality)
doCollected(collected, xs, "allOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain inOrder (1, 2, 3)
* ^
* </pre>
*/
def inOrder(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new InOrderContainMatcher(right, equality)
doCollected(collected, xs, "inOrder", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain oneOf (1, 2, 3)
* ^
* </pre>
*/
def oneOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new OneOfContainMatcher(right, equality)
doCollected(collected, xs, "oneOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain only (1, 2, 3)
* ^
* </pre>
*/
def only(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new OnlyContainMatcher(right, equality)
doCollected(collected, xs, "only", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain inOrderOnly (1, 2, 3)
* ^
* </pre>
*/
def inOrderOnly(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new InOrderOnlyContainMatcher(right, equality)
doCollected(collected, xs, "inOrderOnly", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfTraversable) should contain noneOf (1, 2, 3)
* ^
* </pre>
*/
def noneOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new NoneOfContainMatcher(right, equality)
doCollected(collected, xs, "noneOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedArray[T](collected: Collected, xs: GenTraversable[Array[T]]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfArray) should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForCollectedArray[T] =
new ResultOfHaveWordForCollectedArray(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should be (Set(1, 2, 3))
* ^
* </pre>
*/
def should[T](rightMatcher: Matcher[GenTraversable[T]]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e.deep.asInstanceOf[IndexedSeq[T]]) match { // TODO: Ugly but safe cast here because e is Array[T]
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfTraversable) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[GenTraversable[T], TYPECLASS1])(implicit typeClass1: TYPECLASS1[GenTraversable[T]]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e.deep.asInstanceOf[IndexedSeq[T]]) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[GenTraversable[T], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[GenTraversable[T]], typeClass2: TYPECLASS2[GenTraversable[T]]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e.deep.asInstanceOf[IndexedSeq[T]]) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfArray) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedArray(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfArray) should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedArray[T, Array[T]] =
new ResultOfNotWordForCollectedArray(collected, xs, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfArray) should contain (containMatcher)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForCollectedArray[T] =
new ResultOfContainWordForCollectedArray(collected, xs, true)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfHaveWordForCollectedArray[T](collected: Collected, xs: GenTraversable[Array[T]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should have size (12)
* ^
* </pre>
*/
def size(expectedSize: Int) {
doCollected(collected, xs, "size", 1) { e =>
if ((e.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
expectedSize
),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfArray) should have length (12)
* ^
* </pre>
*/
def length(expectedLength: Long) {
doCollected(collected, xs, "length", 1) { e =>
if ((e.length == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
expectedLength
),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedGenMap[K, V](collected: Collected, xs: GenTraversable[GenMap[K, V]]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfMap) should contain key (10)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForCollectedGenMap[K, V] =
new ResultOfContainWordForCollectedGenMap(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfMap) should be (Map(1 -> "one", 2 -> "two"))
* ^
* </pre>
*/
def should(rightMatcher: Matcher[GenMap[K, V]]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 10)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfMap) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[GenMap[K, V], TYPECLASS1])(implicit typeClass1: TYPECLASS1[GenMap[K, V]]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 10)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[GenMap[K, V], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[GenMap[K, V]], typeClass2: TYPECLASS2[GenMap[K, V]]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 10)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfMap) should be theSameInstanceAs (anotherMap)
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfMap) should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedGenMap[K, V, GenMap[K, V]] =
new ResultOfNotWordForCollectedGenMap(collected, xs, false)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfContainWordForCollectedGenMap[K, V](collected: Collected, xs: GenTraversable[GenMap[K, V]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain key ("one")
* ^
* </pre>
*/
def key(expectedKey: K) {
doCollected(collected, xs, "key", 1) { e =>
if (e.exists(_._1 == expectedKey) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
e,
expectedKey),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain value (1)
* ^
* </pre>
*/
def value(expectedValue: V) {
doCollected(collected, xs, "value", 1) { e =>
if (e.exists(expectedValue == _._2) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
e,
expectedValue),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain theSameElementsAs List(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
val containMatcher = new TheSameElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameElementsAs", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain theSameElementsAs List(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
val containMatcher = new TheSameIteratedElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameIteratedElementsAs", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain allOf List(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def allOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new AllOfContainMatcher(right, equality)
doCollected(collected, xs, "allOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain inOrder List(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def inOrder(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new InOrderContainMatcher(right, equality)
doCollected(collected, xs, "inOrder", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain oneOf Map(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def oneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new OneOfContainMatcher(right, equality)
doCollected(collected, xs, "oneOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain only Map(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def only(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new OnlyContainMatcher(right, equality)
doCollected(collected, xs, "only", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain inOrderOnly Map(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def inOrderOnly(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new InOrderOnlyContainMatcher(right, equality)
doCollected(collected, xs, "inOrderOnly", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfMap) should contain noneOf Map(1 -> "one", 2 -> "two", 3 -> "three")
* ^
* </pre>
*/
def noneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new NoneOfContainMatcher(right, equality)
doCollected(collected, xs, "noneOf", 1) { e =>
val result = containMatcher(e)
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedJavaCollection[T](collected: Collected, xs: GenTraversable[java.util.Collection[T]]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForCollectedJavaCollection[T] =
new ResultOfHaveWordForCollectedJavaCollection(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain theSameElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForCollectedJavaCollection[T] =
new ResultOfContainWordForCollectedJavaCollection(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should be (aJavaSet)
* ^
* </pre>
*/
def should(rightMatcher: Matcher[java.util.Collection[T]]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[java.util.Collection[T], TYPECLASS1])(implicit typeClass1: TYPECLASS1[java.util.Collection[T]]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[java.util.Collection[T], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[java.util.Collection[T]], typeClass2: TYPECLASS2[java.util.Collection[T]]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedJavaCollection[T, java.util.Collection[T]] =
new ResultOfNotWordForCollectedJavaCollection(collected, xs, false)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfHaveWordForCollectedJavaCollection[T](collected: Collected, xs: GenTraversable[java.util.Collection[T]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should have size (10)
* ^
* </pre>
*/
def size(expectedSize: Long) {
doCollected(collected, xs, "size", 1) { e =>
if ((e.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
expectedSize),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should have length (12)
* ^
* </pre>
*
* <p>
* This method invokes <code>size</code> on the <code>java.util.List</code> passed as <code>left</code> to
* determine its length.
* </p>
*/
def length(expectedLength: Long) {
doCollected(collected, xs, "length", 1) { e =>
if ((e.size == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
expectedLength),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfContainWordForCollectedJavaCollection[T](collected: Collected, xs: GenTraversable[java.util.Collection[T]], shouldBeTrue: Boolean) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain theSameElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
val containMatcher = new TheSameElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameElementsAs", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain theSameIteratedElementsAs List(1, 2, 3)
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[T])(implicit equality: Equality[T]) {
val containMatcher = new TheSameIteratedElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameIteratedElementsAs", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain allOf List(1, 2, 3)
* ^
* </pre>
*/
def allOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new AllOfContainMatcher(right, equality)
doCollected(collected, xs, "allOf", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain inOrder List(1, 2, 3)
* ^
* </pre>
*/
def inOrder(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new InOrderContainMatcher(right, equality)
doCollected(collected, xs, "inOrder", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain oneOf List(1, 2, 3)
* ^
* </pre>
*/
def oneOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new OneOfContainMatcher(right, equality)
doCollected(collected, xs, "oneOf", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain only List(1, 2, 3)
* ^
* </pre>
*/
def only(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new OnlyContainMatcher(right, equality)
doCollected(collected, xs, "only", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain inOrderOnly List(1, 2, 3)
* ^
* </pre>
*/
def inOrderOnly(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new InOrderOnlyContainMatcher(right, equality)
doCollected(collected, xs, "inOrderOnly", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaCol) should contain noneOf List(1, 2, 3)
* ^
* </pre>
*/
def noneOf(right: T*)(implicit equality: Equality[T]) {
val containMatcher = new NoneOfContainMatcher(right, equality)
doCollected(collected, xs, "noneOf", 1) { e =>
val result = containMatcher(new JavaCollectionWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfCollectedJavaMap[K, V](collected: Collected, xs: GenTraversable[java.util.Map[K, V]]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForCollectedJavaMap[K, V] =
new ResultOfHaveWordForCollectedJavaMap(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain value (3)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForCollectedJavaMap[K, V] =
new ResultOfContainWordForCollectedJavaMap(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should be (someJavaMap)
* ^
* </pre>
*/
def should(rightMatcher: Matcher[java.util.Map[K, V]]) {
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 6)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[java.util.Map[K, V], TYPECLASS1])(implicit typeClass1: TYPECLASS1[java.util.Map[K, V]]) {
val rightMatcher = rightMatcherFactory1.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 10)
case _ => ()
}
}
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[java.util.Map[K, V], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[java.util.Map[K, V]], typeClass2: TYPECLASS2[java.util.Map[K, V]]) {
val rightMatcher = rightMatcherFactory2.matcher
doCollected(collected, xs, "should", 1) { e =>
rightMatcher(e) match {
case MatchResult(false, failureMessage, _, _, _) =>
throw newTestFailedException(failureMessage, None, 10)
case _ => ()
}
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord) = new ResultOfBeWordForCollectedAnyRef(collected, xs, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForCollectedJavaMap[K, V, java.util.Map[K, V]] =
new ResultOfNotWordForCollectedJavaMap(collected, xs, false)
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfHaveWordForCollectedJavaMap[K, V](collected: Collected, xs: GenTraversable[java.util.Map[K, V]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should have size (10)
* ^
* </pre>
*/
def size(expectedSize: Long) {
doCollected(collected, xs, "size", 1) { e =>
if ((e.size == expectedSize) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedSize" else "hadExpectedSize",
e,
expectedSize),
None,
6
)
}
}
/**
* This method enables the following syntax:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should have length (10)
* ^
* </pre>
*/
def length(expectedLength: Long) {
doCollected(collected, xs, "length", 1) { e =>
if ((e.size == expectedLength) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotHaveExpectedLength" else "hadExpectedLength",
e,
expectedLength),
None,
6
)
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="InspectorsMatchers.html"><code>InspectorsMatchers</code></a> for an overview of
* the matchers DSL.
*
* @author Bill Venners
* @author Chee Seng
*/
final class ResultOfContainWordForCollectedJavaMap[K, V](collected: Collected, xs: GenTraversable[java.util.Map[K, V]], shouldBeTrue: Boolean) {
/**
* This method enables the following syntax (<code>javaMap</code> is a <code>java.util.Map</code>):
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain key ("two")
* ^
* </pre>
*/
def key(expectedKey: K) {
doCollected(collected, xs, "key", 1) { e =>
if (e.containsKey(expectedKey) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainKey" else "containedKey",
e,
expectedKey),
None,
6
)
}
}
/**
* This method enables the following syntax (<code>javaMap</code> is a <code>java.util.Map</code>):
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain value ("2")
* ^
* </pre>
*/
def value(expectedValue: V) {
doCollected(collected, xs, "value", 1) { e =>
if (e.containsValue(expectedValue) != shouldBeTrue)
throw newTestFailedException(
FailureMessages(
if (shouldBeTrue) "didNotContainValue" else "containedValue",
e,
expectedValue),
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain theSameElementsAs List(1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def theSameElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
val containMatcher = new TheSameElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameElementsAs", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain theSameIteratedElementsAs List(1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def theSameIteratedElementsAs(right: GenTraversable[(K, V)])(implicit equality: Equality[(K, V)]) {
val containMatcher = new TheSameIteratedElementsAsContainMatcher(right, equality)
doCollected(collected, xs, "theSameIteratedElementsAs", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain allOf (1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def allOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new AllOfContainMatcher(right, equality)
doCollected(collected, xs, "allOf", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain inOrder (1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def inOrder(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new InOrderContainMatcher(right, equality)
doCollected(collected, xs, "inOrder", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain oneOf (1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def oneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new OneOfContainMatcher(right, equality)
doCollected(collected, xs, "oneOf", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain only (1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def only(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new OnlyContainMatcher(right, equality)
doCollected(collected, xs, "only", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain inOrderOnly (1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def inOrderOnly(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new InOrderOnlyContainMatcher(right, equality)
doCollected(collected, xs, "inOrderOnly", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* all(colOfJavaMap) should contain noneOf (1 -> "one", 2 - > "two", 3 -> "three")
* ^
* </pre>
*/
def noneOf(right: (K, V)*)(implicit equality: Equality[(K, V)]) {
val containMatcher = new NoneOfContainMatcher(right, equality)
doCollected(collected, xs, "noneOf", 1) { e =>
val result = containMatcher(new JavaMapWrapper(e))
if (result.matches != shouldBeTrue)
throw newTestFailedException(
if (shouldBeTrue) result.failureMessage else result.negatedFailureMessage,
None,
6
)
}
}
}
def all[T](xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(AllCollected, xs)
def all(xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(AllCollected, xs)
def all(xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(AllCollected, xs)
def all[T](xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(AllCollected, xs)
def all[T](xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(AllCollected, xs)
def all[T](xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(AllCollected, xs)
def all[K, V](xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(AllCollected, xs)
def all[T](xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(AllCollected, xs)
def all[K, V](xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(AllCollected, xs)
def atLeast[T](num: Int, xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(AtLeastCollected(num), xs)
def atLeast(num: Int, xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(AtLeastCollected(num), xs)
def atLeast(num: Int, xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(AtLeastCollected(num), xs)
def atLeast[T](num: Int, xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(AtLeastCollected(num), xs)
def atLeast[T](num: Int, xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(AtLeastCollected(num), xs)
def atLeast[T](num: Int, xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(AtLeastCollected(num), xs)
def atLeast[K, V](num: Int, xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(AtLeastCollected(num), xs)
def atLeast[T](num: Int, xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(AtLeastCollected(num), xs)
def atLeast[K, V](num: Int, xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(AtLeastCollected(num), xs)
def every[T](xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(EveryCollected, xs)
def every(xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(EveryCollected, xs)
def every(xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(EveryCollected, xs)
def every[T](xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(EveryCollected, xs)
def every[T](xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(EveryCollected, xs)
def every[T](xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(EveryCollected, xs)
def every[K, V](xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(EveryCollected, xs)
def every[T](xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(EveryCollected, xs)
def every[K, V](xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(EveryCollected, xs)
def exactly[T](num: Int, xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(ExactlyCollected(num), xs)
def exactly(num: Int, xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(ExactlyCollected(num), xs)
def exactly(num: Int, xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(ExactlyCollected(num), xs)
def exactly[T](num: Int, xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(ExactlyCollected(num), xs)
def exactly[T](num: Int, xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(ExactlyCollected(num), xs)
def exactly[T](num: Int, xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(ExactlyCollected(num), xs)
def exactly[K, V](num: Int, xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(ExactlyCollected(num), xs)
def exactly[T](num: Int, xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(ExactlyCollected(num), xs)
def exactly[K, V](num: Int, xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(ExactlyCollected(num), xs)
def no[T](xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(NoCollected, xs)
def no(xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(NoCollected, xs)
def no(xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(NoCollected, xs)
def no[T](xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(NoCollected, xs)
def no[T](xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(NoCollected, xs)
def no[T](xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(NoCollected, xs)
def no[K, V](xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(NoCollected, xs)
def no[T](xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(NoCollected, xs)
def no[K, V](xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(NoCollected, xs)
def between[T](from: Int, upTo:Int, xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(BetweenCollected(from, upTo), xs)
def between(from: Int, upTo:Int, xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(BetweenCollected(from, upTo), xs)
def between(from: Int, upTo:Int, xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(BetweenCollected(from, upTo), xs)
def between[T](from: Int, upTo:Int, xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(BetweenCollected(from, upTo), xs)
def between[T](from: Int, upTo:Int, xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(BetweenCollected(from, upTo), xs)
def between[T](from: Int, upTo:Int, xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(BetweenCollected(from, upTo), xs)
def between[K, V](from: Int, upTo:Int, xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(BetweenCollected(from, upTo), xs)
def between[T](from: Int, upTo:Int, xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(BetweenCollected(from, upTo), xs)
def between[K, V](from: Int, upTo:Int, xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(BetweenCollected(from, upTo), xs)
def atMost[T](num: Int, xs: GenTraversable[T]): ResultOfCollectedAny[T] =
new ResultOfCollectedAny(AtMostCollected(num), xs)
def atMost(num: Int, xs: GenTraversable[AnyRef]): ResultOfCollectedAnyRef[AnyRef] =
new ResultOfCollectedAnyRef(AtMostCollected(num), xs)
def atMost(num: Int, xs: GenTraversable[String]): ResultOfCollectedString =
new ResultOfCollectedString(AtMostCollected(num), xs)
def atMost[T](num: Int, xs: GenTraversable[GenTraversable[T]]) =
new ResultOfCollectedGenTraversable(AtMostCollected(num), xs)
def atMost[T](num: Int, xs: GenTraversable[GenSeq[T]]) =
new ResultOfCollectedGenSeq(AtMostCollected(num), xs)
def atMost[T](num: Int, xs: GenTraversable[Array[T]]) =
new ResultOfCollectedArray(AtMostCollected(num), xs)
def atMost[K, V](num: Int, xs: GenTraversable[GenMap[K, V]]) =
new ResultOfCollectedGenMap(AtMostCollected(num), xs)
def atMost[T](num: Int, xs: GenTraversable[java.util.Collection[T]]) =
new ResultOfCollectedJavaCollection(AtMostCollected(num), xs)
def atMost[K, V](num: Int, xs: GenTraversable[java.util.Map[K, V]]) =
new ResultOfCollectedJavaMap(AtMostCollected(num), xs)
// This is where ShouldMatchers.scala started
// Turn off this implicit conversion, becase asAny method is added via AnyShouldWrapper
// override def convertToAsAnyWrapper(o: Any): AsAnyWrapper = new AsAnyWrapper(o)
private object ShouldMethodHelper {
def shouldMatcher[T](left: T, rightMatcher: Matcher[T], stackDepthAdjustment: Int = 0) {
rightMatcher(left) match {
case MatchResult(false, failureMessage, _, _, _) => throw newTestFailedException(failureMessage, None, stackDepthAdjustment)
case _ => ()
}
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>Any</code>.
* </p>
*
* @author Bill Venners
*/
final class AnyShouldWrapper[T](left: T) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should be (3)
* ^
* </pre>
*/
def should(rightMatcherX1: Matcher[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX1)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should equal (3)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[T, TYPECLASS1])(implicit typeClass1: TYPECLASS1[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[T, TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[T], typeClass2: TYPECLASS2[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* () shouldEqual ()
* ^
* </pre>
*/
def shouldEqual(right: Any)(implicit equality: Equality[T]) {
if (!equality.areEqual(left, right)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("didNotEqual", leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should not equal (3)
* ^
* </pre>
*/
def should(notWord: NotWord) = new ResultOfNotWord[T](left, false)
/* * Turns out all the tests compile without this one
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* () should === (()) // In 2.10, will work with AnyVals. TODO: Also, Need to ensure Char works
* ^
* </pre>
*/
def should[U](inv: TripleEqualsInvocation[U])(implicit constraint: EqualityConstraint[T, U]) {
// if ((left == inv.right) != inv.expectingEqual)
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
// TODO: Scaladoc
def asAny: Any = left
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on <code>String</code>s.
* </p>
*
* @author Bill Venners
*/
final class StringShouldWrapper(left: String) extends StringShouldWrapperForVerb(left) {
/* *
* This method enables syntax such as the following in a <code>FlatSpec</code>:
*
* <pre class="stHighlight">
* "A Stack (when empty)" should "be empty" in {
* assert(emptyStack.empty)
* }
* </pre>
*
* <p>
* <code>FlatSpec</code> passes in a function via the implicit parameter that takes
* three strings and results in a <code>ResultOfStringPassedToVerb</code>. This method
* simply invokes this function, passing in left, right, and the verb string
* <code>"should"</code>.
* </p>
*
def should(right: String)(implicit fun: (String, String, String) => ResultOfStringPassedToVerb): ResultOfStringPassedToVerb = {
fun(left, right, "should")
}
def should(right: => Unit)(implicit fun: (String, () => Unit, String) => Unit) {
fun(left, right _, "should")
} */
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should be ("hi")
* ^
* </pre>
*/
def should(rightMatcherX2: Matcher[String]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX2)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should equal ("hi")
* ^
* </pre>
*/
def should[TC1[_]](rightMatcherFactory: MatcherFactory1[String, TC1])(implicit typeClass1: TC1[String]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory.matcher)
}
def should[TC1[_], TC2[_]](rightMatcherFactory: MatcherFactory2[String, TC1, TC2])(implicit typeClass1: TC1[String], typeClass2: TC2[String]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory.matcher)
}
/*
def should[TC1[_], TC2[_], TC3[_]](rightMatcherFactory: MatcherFactory3[String, TC1, TC2, TC3])(implicit tc1: TC1[String], tc2: TC2[String], tc3: TC3[String]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory.matcher)
}
*/
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string shouldEqual "hi"
* ^
* </pre>
*/
def shouldEqual(right: Any)(implicit equality: Equality[String]) {
if (!equality.areEqual(left, right)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("didNotEqual", leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[String] = new ResultOfBeWordForAnyRef(left, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForString = {
new ResultOfHaveWordForString(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should include regex ("hi")
* ^
* </pre>
*/
def should(includeWord: IncludeWord): ResultOfIncludeWordForString = {
new ResultOfIncludeWordForString(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should startWith regex ("hello")
* ^
* </pre>
*/
def should(startWithWord: StartWithWord): ResultOfStartWithWordForString = {
new ResultOfStartWithWordForString(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should endWith regex ("world")
* ^
* </pre>
*/
def should(endWithWord: EndWithWord): ResultOfEndWithWordForString = {
new ResultOfEndWithWordForString(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should fullyMatch regex ("""(-)?(\\d+)(\\.\\d*)?""")
* ^
* </pre>
*/
def should(fullyMatchWord: FullyMatchWord): ResultOfFullyMatchWordForString = {
new ResultOfFullyMatchWordForString(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* string should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForString = {
new ResultOfNotWordForString(left, false)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* s should === ("hi")
* ^
* </pre>
*/
def should[U](inv: TripleEqualsInvocation[U])(implicit constraint: EqualityConstraint[String, U]) {
// if ((left == inv.right) != inv.expectingEqual)
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on <code>Double</code>s.
* </p>
*
* @author Bill Venners
*/
final class NumericShouldWrapper[T : Numeric](left: T) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* aDouble should be (8.8)
* ^
* </pre>
*/
def should(rightMatcherX3: Matcher[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX3)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* aDouble should equal (8.8)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[T, TYPECLASS1])(implicit typeClass1: TYPECLASS1[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[T, TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[T], typeClass2: TYPECLASS2[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* aDouble shouldEqual 8.8
* ^
* </pre>
*/
def shouldEqual(right: T)(implicit equality: Equality[T]) {
if (!equality.areEqual(left, right)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("didNotEqual", leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result shouldEqual 7.1 +- 0.2
* ^
* </pre>
*/
def shouldEqual(interval: Interval[T]) {
if (!interval.isWithin(left)) {
throw newTestFailedException(FailureMessages("didNotEqualPlusOrMinus", left, interval.pivot, interval.tolerance))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should not equal (8.8)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForNumeric[T] = {
new ResultOfNotWordForNumeric[T](left, false)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result shouldNot equal (8.8)
* ^
* </pre>
*/
/*
def shouldNot(rightMatcher: Matcher[T]) {
rightMatcher(left) match {
case MatchResult(true, _, negatedFailureMessage, _, _) => throw newTestFailedException(negatedFailureMessage, None, 0) // TODO: Stack depth
case _ => ()
}
}
*/
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should be a aMatcher
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAny[T] = new ResultOfBeWordForAny(left, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* aDouble shouldBe 8.8
* ^
* </pre>
*/
def shouldBe(right: T) {
if (left != right) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("wasNotEqualTo", leftee, rightee))
}
}
def shouldBe(beMatcher: BeMatcher[T]) { // TODO: This looks like a bug to me. Investigate. - bv
beMatcher.apply(left).matches
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (3)
* ^
* </pre>
*/
def should[U](inv: TripleEqualsInvocation[U])(implicit constraint: EqualityConstraint[T, U]) {
// if ((left == inv.right) != inv.expectingEqual)
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (100 +- 1)
* ^
* </pre>
*/
def should(inv: TripleEqualsInvocationOnInterval[T]) {
if ((inv.interval.isWithin(left)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqualPlusOrMinus" else "equaledPlusOrMinus",
left,
inv.interval.pivot,
inv.interval.tolerance
)
)
}
}
// TODO: Am I doing conversions on immutable.GenTraversable and immutable.GenSeq? If so, write a test that fails and make it general.
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>scala.collection.GenMap[K, V]</code>.
* </p>
*
* @author Bill Venners
*/
final class MapShouldWrapper[K, V, L[_, _] <: scala.collection.GenMap[_, _]](left: L[K, V]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map should be (Map(1 -> "one", 2 -> "two"))
* ^
* </pre>
*/
def should(rightMatcherX4: Matcher[L[K, V]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX4)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map should equal (Map(1 -> "one", 2 -> "two"))
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[L[K, V], TYPECLASS1])(implicit typeClass1: TYPECLASS1[L[K, V]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[L[K, V], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[L[K, V]], typeClass2: TYPECLASS2[L[K, V]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map shouldEqual Map(1 -> "one", 2 -> "two")
* ^
* </pre>
*/
def shouldEqual(right: L[K, V])(implicit equality: Equality[L[K, V]]) {
if (!equality.areEqual(left, right)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("didNotEqual", leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map should be theSameInstanceAs (anotherMap)
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[L[K, V]] = new ResultOfBeWordForAnyRef(left.asInstanceOf[L[K, V]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForTraversable[(K, V)] = {
new ResultOfHaveWordForTraversable(left.asInstanceOf[GenMap[K,V]], true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map should contain key (10)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForMap[K, V] = {
new ResultOfContainWordForMap(left.asInstanceOf[GenMap[K, V]], true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* map should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForMap[K, V, L] = {
new ResultOfNotWordForMap(left.asInstanceOf[L[K, V]], false)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (Map("I" -> 1, "II" -> 2))
* ^
* </pre>
*/
def should[R](inv: TripleEqualsInvocation[R])(implicit constraint: EqualityConstraint[L[K, V], R]) {
// if ((left == inv.right) != inv.expectingEqual)
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on <code>AnyRef</code>s.
* </p>
*
* @author Bill Venners
*/
final class AnyRefShouldWrapper[T <: AnyRef](left: T) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* anyRef should be (anotherObject)
* ^
* </pre>
*/
def should(rightMatcherX5: Matcher[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX5)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* anyRef should equal (anotherObject)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[T, TYPECLASS1])(implicit typeClass1: TYPECLASS1[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[T, TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[T], typeClass2: TYPECLASS2[T]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* anyRef shouldEqual (anotherObject)
* ^
* </pre>
*/
def shouldEqual(right: T)(implicit equality: Equality[T]) {
if (!equality.areEqual(left, right)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("didNotEqual", leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForAnyRef[T] =
new ResultOfNotWordForAnyRef(left, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[T] = new ResultOfBeWordForAnyRef(left, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should have length (3)
* ^
* result should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord)(implicit ev: Extent[T]): ResultOfHaveWordForExtent[T] =
new ResultOfHaveWordForExtent(left, true)
def shouldBe = new ResultOfBeWordForAnyRef(left, true)
def shouldBe[U](right: Null) {
if (left != null) {
throw newTestFailedException(FailureMessages("wasNotNull", left))
}
}
/*
def shouldBe[U](right: AType[U]) {
if (!right.isAssignableFromClassOf(left)) {
throw newTestFailedException(FailureMessages("wasNotAnInstanceOf", left, UnquotedString(right.className)))
}
}
*/
def shouldBe(right: AnyRef) {
def shouldBeEqual(right: AnyRef): Boolean = {
if (right.isInstanceOf[ResultOfAWordToBePropertyMatcherApplication[AnyRef]]) {
// need to put in if because NoSuchMethodError when pattern match ResultOfAWordToBePropertyMatcherApplication
val app = right.asInstanceOf[ResultOfAWordToBePropertyMatcherApplication[AnyRef]]
app.bePropertyMatcher.apply(left).matches
}
else if (right.isInstanceOf[ResultOfAnWordToBePropertyMatcherApplication[AnyRef]]) {
val app = right.asInstanceOf[ResultOfAnWordToBePropertyMatcherApplication[AnyRef]]
app.bePropertyMatcher.apply(left).matches
}
else {
val beWord = new BeWord
right match {
case rightSymbol: ResultOfAWordToSymbolApplication =>
beWord.a[AnyRef](rightSymbol.symbol)(left).matches
case rightSymbol: ResultOfAnWordToSymbolApplication =>
beWord.an[AnyRef](rightSymbol.symbol)(left).matches
case beMatcher: BeMatcher[AnyRef] =>
beMatcher.apply(left).matches
case bePropertyMatcher: BePropertyMatcher[AnyRef] =>
bePropertyMatcher.apply(left).matches
case _ =>
left == right
}
}
}
if (!shouldBeEqual(right)) {
val (resourceName, leftee, rightee) =
if (right.isInstanceOf[ResultOfAWordToBePropertyMatcherApplication[AnyRef]]) {
val app = right.asInstanceOf[ResultOfAWordToBePropertyMatcherApplication[AnyRef]]
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, UnquotedString(app.bePropertyMatcher.apply(left).propertyName))
("wasNotA", leftee, rightee)
}
else if (right.isInstanceOf[ResultOfAnWordToBePropertyMatcherApplication[AnyRef]]) {
val app = right.asInstanceOf[ResultOfAnWordToBePropertyMatcherApplication[AnyRef]]
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, UnquotedString(app.bePropertyMatcher.apply(left).propertyName))
("wasNotAn", leftee, rightee)
}
else {
right match {
case bePropertyMatcher: BePropertyMatcher[AnyRef] =>
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, UnquotedString(bePropertyMatcher.apply(left).propertyName))
("wasNot", leftee, rightee)
case _ =>
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
("wasNotEqualTo", leftee, rightee)
}
}
throw newTestFailedException(FailureMessages(resourceName, leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (new Person("Abe", "Lincoln"))
* ^
* </pre>
*/
def should[U](inv: TripleEqualsInvocation[U])(implicit constraint: EqualityConstraint[T, U]) {
// if ((left == inv.right) != inv.expectingEqual)
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>scala.Collection[T]</code>.
* </p>
*
* @author Bill Venners
*/
final class TraversableShouldWrapper[E, L[_] <: GenTraversable[_]](left: L[E]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* traversable should be (Set(1, 2, 3))
* ^
* </pre>
*/
def should(rightMatcherX6: Matcher[GenTraversable[E]]) {
ShouldMethodHelper.shouldMatcher(left.asInstanceOf[GenTraversable[E]], rightMatcherX6)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* traversable should equal (Set(1, 2, 3))
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[L[E], TYPECLASS1])(implicit typeClass1: TYPECLASS1[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[L[E], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[L[E]], typeClass2: TYPECLASS2[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* traversable should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForTraversable[E] =
new ResultOfHaveWordForTraversable(left.asInstanceOf[GenTraversable[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* traversable should contain theSameElementsAs anotherTraversable
* ^
* </pre>
*/
def should(containWord: ContainWord) =
new ResultOfContainWordForTraversable(left.asInstanceOf[GenTraversable[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* traversable should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[L[E]] = new ResultOfBeWordForAnyRef(left.asInstanceOf[L[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* traversable should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForTraversable[E, L] =
new ResultOfNotWordForTraversable(left, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (Set(1, 2, 3))
* ^
* </pre>
*/
def should[R](inv: TripleEqualsInvocation[R])(implicit constraint: EqualityConstraint[L[E], R]) {
// if ((left == inv.right) != inv.expectingEqual)
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* xs.loneElement should be > 9
* ^
* </pre>
*/
def loneElement: E = {
if (left.size == 1)
left.head.asInstanceOf[E] // Why do I need to cast?
else
throw newTestFailedException(
FailureMessages(
"notLoneElement",
left,
left.size)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>java.util.Collection[T]</code>.
* </p>
*
* @author Bill Venners
*/
// final class JavaCollectionShouldWrapper[T](left: java.util.Collection[T]) {
final class JavaCollectionShouldWrapper[E, L[_] <: java.util.Collection[_]](left: L[E]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaCollection should be (aJavaSet)
* ^
* </pre>
*/
def should(rightMatcherX7: Matcher[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX7)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaCollection should equal (aJavaSet)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[L[E], TYPECLASS1])(implicit typeClass1: TYPECLASS1[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[L[E], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[L[E]], typeClass2: TYPECLASS2[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaCollection should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForJavaCollection[E, L] =
new ResultOfHaveWordForJavaCollection(left, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaCollection should contain theSameElementsAs anotherSeq
* ^
* </pre>
*/
def should(containWord: ContainWord) =
new ResultOfContainWordForJavaCollection(left.asInstanceOf[java.util.Collection[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaCollection should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[L[E]] = new ResultOfBeWordForAnyRef(left.asInstanceOf[L[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaCollection should not have size (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForJavaCollection[E, L] =
new ResultOfNotWordForJavaCollection(left, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (jSet)
* ^
* </pre>
*/
def should[R](inv: TripleEqualsInvocation[R])(implicit constraint: EqualityConstraint[L[E], R]) {
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>java.util.Map[K, V]</code>.
* </p>
*
* @author Bill Venners
*/
final class JavaMapShouldWrapper[K, V, L[_, _] <: java.util.Map[_, _]](left: L[K, V]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaMap should be (someJavaMap)
* ^
* </pre>
*/
def should(rightMatcherX8: Matcher[L[K, V]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX8)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaMap should equal (someJavaMap)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[L[K, V], TYPECLASS1])(implicit typeClass1: TYPECLASS1[L[K, V]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[L[K, V], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[L[K, V]], typeClass2: TYPECLASS2[L[K, V]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaMap should contain value (3)
* ^
* </pre>
*/
def should(containWord: ContainWord): ResultOfContainWordForJavaMap[K, V] = {
new ResultOfContainWordForJavaMap(left.asInstanceOf[java.util.Map[K, V]], true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaMap should have size (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForJavaMap = {
new ResultOfHaveWordForJavaMap(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaMap should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForJavaMap[K, V, L] = {
new ResultOfNotWordForJavaMap[K, V, L](left, false)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaMap should be theSameInstanceAs anotherObject
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[java.util.Map[K, V]] = new ResultOfBeWordForAnyRef(left.asInstanceOf[java.util.Map[K, V]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (javaMap)
* ^
* </pre>
*/
def should[R](inv: TripleEqualsInvocation[R])(implicit constraint: EqualityConstraint[L[K, V], R]) {
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>GenSeq[T]</code>.
* </p>
*
* @author Bill Venners
*/
final class SeqShouldWrapper[E, L[_] <: GenSeq[_]](left: L[E]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should be (List(1, 2, 3))
* ^
* </pre>
*/
def should(rightMatcherX9: Matcher[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX9)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should equal (List(1, 2, 3))
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[L[E], TYPECLASS1])(implicit typeClass1: TYPECLASS1[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[L[E], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[L[E]], typeClass2: TYPECLASS2[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForSeq[E] =
new ResultOfHaveWordForSeq(left.asInstanceOf[GenSeq[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should contain theSameElementsAs anotherSeq
* ^
* </pre>
*/
def should(containWord: ContainWord) =
new ResultOfContainWordForTraversable(left.asInstanceOf[GenTraversable[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForSeq[E, L] =
new ResultOfNotWordForSeq(left, false)
// def should(notWord: NotWord): ResultOfNotWordForAnyRef[GenSeq[E]] =
// new ResultOfNotWordForAnyRef(left, false)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should be theSameInstanceAs List(1, 2, 3)
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[L[E]] = new ResultOfBeWordForAnyRef(left, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (List(1, 2, 3))
* ^
* </pre>
*/
def should[R](inv: TripleEqualsInvocation[R])(implicit constraint: EqualityConstraint[L[E], R]) {
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>scala.Array[T]</code>.
* </p>
*
* @author Bill Venners
*/
final class ArrayShouldWrapper[T](left: Array[T]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* array should be (Array("one", "two"))
* ^
* </pre>
*/
def should(rightMatcherX10: Matcher[Array[T]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX10)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* array should equal (Array("one", "two"))
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[Array[T], TYPECLASS1])(implicit typeClass1: TYPECLASS1[Array[T]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[Array[T], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[Array[T]], typeClass2: TYPECLASS2[Array[T]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* array should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForSeq[T] = {
new ResultOfHaveWordForSeq(left, true)
}
/**
* This method enables syntax such as the following, where <code>positiveNumber</code> is a <code>AMatcher</code>:
*
* <pre class="stHighlight">
* array should contain a positiveNumber
* ^
* </pre>
*/
def should(containWord: ContainWord) =
new ResultOfContainWordForTraversable(new ArrayWrapper(left), true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* array should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForArray[T] =
new ResultOfNotWordForArray(left, false)
/**
* This method enables syntax such as the following, where <code>bigArray</code> is a <code>AMatcher</code>:
*
* <pre class="stHighlight">
* array should be a bigArray
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[Array[T]] = new ResultOfBeWordForAnyRef(left, true)
def shouldBe(right: Array[T]) {
if (!left.deep.equals(right.deep)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
throw newTestFailedException(FailureMessages("wasNotEqualTo", leftee, rightee))
}
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (Array(1, 2, 3))
* ^
* </pre>
*/
def should[U](inv: TripleEqualsInvocation[U])(implicit constraint: EqualityConstraint[Array[T], U]) {
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
// Note, no should(beWord) is needed here because a different implicit conversion will be used
// on "array shoudl be ..." because this one doesn't solve the type error.
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>should</code> methods to
* be invoked on objects of type <code>java.util.List[T]</code>.
* </p>
*
* @author Bill Venners
*/
final class JavaListShouldWrapper[E, L[_] <: java.util.List[_]](left: L[E]) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaList should be (someOtherJavaList)
* ^
* </pre>
*/
def should(rightMatcherX12: Matcher[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherX12)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaList should equal (someOtherJavaList)
* ^
* </pre>
*/
def should[TYPECLASS1[_]](rightMatcherFactory1: MatcherFactory1[L[E], TYPECLASS1])(implicit typeClass1: TYPECLASS1[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory1.matcher)
}
def should[TYPECLASS1[_], TYPECLASS2[_]](rightMatcherFactory2: MatcherFactory2[L[E], TYPECLASS1, TYPECLASS2])(implicit typeClass1: TYPECLASS1[L[E]], typeClass2: TYPECLASS2[L[E]]) {
ShouldMethodHelper.shouldMatcher(left, rightMatcherFactory2.matcher)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaList should have length (3)
* ^
* </pre>
*/
def should(haveWord: HaveWord): ResultOfHaveWordForJavaList[E, L] = {
new ResultOfHaveWordForJavaList(left, true)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaList should contain theSameElementsAs anotherSeq
* ^
* </pre>
*/
def should(containWord: ContainWord) =
new ResultOfContainWordForJavaCollection(left.asInstanceOf[java.util.Collection[E]], true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* javaList should not have length (3)
* ^
* </pre>
*/
def should(notWord: NotWord): ResultOfNotWordForJavaList[E, L] = {
new ResultOfNotWordForJavaList(left, false)
}
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* seq should be theSameInstanceAs List(1, 2, 3)
* ^
* </pre>
*/
def should(beWord: BeWord): ResultOfBeWordForAnyRef[L[E]] = new ResultOfBeWordForAnyRef(left, true)
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* result should === (jList)
* ^
* </pre>
*/
def should[U](inv: TripleEqualsInvocation[U])(implicit constraint: EqualityConstraint[L[E], U]) {
if ((constraint.areEqual(left, inv.right)) != inv.expectingEqual)
throw newTestFailedException(
FailureMessages(
if (inv.expectingEqual) "didNotEqual" else "equaled",
left,
inv.right
)
)
}
}
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable a <code>should</code> method to
* be invoked on objects that result of <code>evaulating { ... }</code>.
* </p>
*
* @author Bill Venners
*/
final class EvaluatingApplicationShouldWrapper(left: ResultOfEvaluatingApplication) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* evaluating { "hi".charAt(-1) } should produce [StringIndexOutOfBoundsException]
* ^
* </pre>
*/
def should[T](resultOfProduceApplication: ResultOfProduceInvocation[T]): T = {
val clazz = resultOfProduceApplication.clazz
val caught = try {
left.fun()
None
}
catch {
case u: Throwable => {
if (!clazz.isAssignableFrom(u.getClass)) {
val s = Resources("wrongException", clazz.getName, u.getClass.getName)
throw newTestFailedException(s, Some(u))
// throw new TestFailedException(s, u, 3)
}
else {
Some(u)
}
}
}
caught match {
case None =>
val message = Resources("exceptionExpected", clazz.getName)
throw newTestFailedException(message)
// throw new TestFailedException(message, 3)
case Some(e) => e.asInstanceOf[T] // I know this cast will succeed, becuase isAssignableFrom succeeded above
}
}
}
/**
* Implicitly converts an object of type <code>T</code> to a <code>EvaluatingApplicationShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToEvaluatingApplicationShouldWrapper(o: ResultOfEvaluatingApplication): EvaluatingApplicationShouldWrapper = new EvaluatingApplicationShouldWrapper(o)
/**
* Implicitly converts an object of type <code>T</code> to a <code>AnyShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToAnyShouldWrapper[T](o: T): AnyShouldWrapper[T] = new AnyShouldWrapper(o)
/**
* Implicitly converts an object of type <code>scala.Double</code> to a <code>DoubleShouldWrapper</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToNumericShouldWrapperForDouble(o: Double): NumericShouldWrapper[Double] = new NumericShouldWrapper[Double](o)
/**
* Implicitly converts an object of type <code>scala.Float</code> to a <code>NumericShouldWrapper[Float]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToNumericShouldWrapperForFloat(o: Float): NumericShouldWrapper[Float] = new NumericShouldWrapper[Float](o)
/**
* Implicitly converts an object of type <code>scala.Long</code> to a <code>NumericShouldWrapper[Long]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToNumericShouldWrapperForLong(o: Long): NumericShouldWrapper[Long] = new NumericShouldWrapper[Long](o)
/**
* Implicitly converts an object of type <code>scala.Int</code> to a <code>NumericShouldWrapper[Int]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToNumericShouldWrapperForInt(o: Int): NumericShouldWrapper[Int] = new NumericShouldWrapper[Int](o)
/**
* Implicitly converts an object of type <code>scala.Short</code> to a <code>NumericShouldWrapper[Short]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToNumericShouldWrapperForShort(o: Short): NumericShouldWrapper[Short] = new NumericShouldWrapper[Short](o)
/**
* Implicitly converts an object of type <code>scala.Byte</code> to a <code>NumericShouldWrapper[Byte]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToByteShouldWrapper(o: Byte): NumericShouldWrapper[Byte] = new NumericShouldWrapper[Byte](o)
/**
* Implicitly converts a <code>scala.AnyRef</code> of type <code>T</code> to an <code>AnyRefShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToAnyRefShouldWrapper[T <: AnyRef](o: T): AnyRefShouldWrapper[T] = new AnyRefShouldWrapper[T](o)
/**
* Implicitly converts an object of type <code>scala.Collection[T]</code> to a <code>CollectionShouldWrapper</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToTraversableShouldWrapper[E, L[_] <: GenTraversable[_]](o: L[E]): TraversableShouldWrapper[E, L] = new TraversableShouldWrapper[E, L](o)
/**
* Implicitly converts an object of type <code>GenSeq[T]</code> to a <code>SeqShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToSeqShouldWrapper[E, L[_] <: GenSeq[_]](o: L[E]): SeqShouldWrapper[E, L] = new SeqShouldWrapper[E, L](o)
/**
* Implicitly converts an object of type <code>scala.Array[T]</code> to a <code>ArrayShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToArrayShouldWrapper[T](o: Array[T]): ArrayShouldWrapper[T] = new ArrayShouldWrapper[T](o)
/**
* Implicitly converts an object of type <code>scala.collection.GenMap[K, V]</code> to a <code>MapShouldWrapper[K, V]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToMapShouldWrapper[K, V, L[_, _] <: scala.collection.GenMap[_, _]](o: L[K, V]): MapShouldWrapper[K, V, L] = new MapShouldWrapper[K, V, L](o)
/**
* Implicitly converts an object of type <code>java.lang.String</code> to a <code>StringShouldWrapper</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit override def convertToStringShouldWrapper(o: String): StringShouldWrapper = new StringShouldWrapper(o)
/**
* Implicitly converts an object of type <code>java.util.Collection[T]</code> to a <code>JavaCollectionShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToJavaCollectionShouldWrapper[E, L[_] <: java.util.Collection[_]](o: L[E]): JavaCollectionShouldWrapper[E, L] = new JavaCollectionShouldWrapper[E, L](o)
/**
* Implicitly converts an object of type <code>java.util.List[T]</code> to a <code>JavaListShouldWrapper[T]</code>,
* to enable <code>should</code> methods to be invokable on that object. This conversion is necessary to enable
* <code>length</code> to be used on Java <code>List</code>s.
*/
// implicit def convertToJavaListShouldWrapper[T](o: java.util.List[T]): JavaListShouldWrapper[T] = new JavaListShouldWrapper[T](o)
implicit def convertToJavaListShouldWrapper[E, L[_] <: java.util.List[_]](o: L[E]): JavaListShouldWrapper[E, L] = new JavaListShouldWrapper[E, L](o)
/**
* Implicitly converts an object of type <code>java.util.Map[K, V]</code> to a <code>JavaMapShouldWrapper[K, V]</code>,
* to enable <code>should</code> methods to be invokable on that object.
*/
implicit def convertToJavaMapShouldWrapper[K, V, L[_, _] <: java.util.Map[_, _]](o: L[K, V]): JavaMapShouldWrapper[K, V, L] = new JavaMapShouldWrapper[K, V, L](o)
/**
* Turn off implicit conversion of LoneElement, so that if user accidentally mixin LoneElement it does conflict with convertToTraversableShouldWrapper
*/
override def convertToTraversableLoneElementWrapper[T](xs: GenTraversable[T]): LoneElementTraversableWrapper[T] = new LoneElementTraversableWrapper[T](xs)
// This one doesn't include Holder in its result type because that would conflict with the
// one returned by enablersForJavaCollection.
implicit def enablersForJavaList[E, JLIST[_] <: java.util.List[_]]: Length[JLIST[E]] =
new Length[JLIST[E]] {
def extentOf(javaList: JLIST[E]): Long = javaList.size
}
// This one doesn't include Holder in its result type because that would conflict with the
// one returned by enablersForTraversable.
implicit def enablersForSeq[E, SEQ[_] <: scala.collection.GenSeq[_]]: Length[SEQ[E]] =
new Length[SEQ[E]] {
def extentOf(seq: SEQ[E]): Long = seq.length
}
implicit def enablersForJavaCollection[E, JCOL[_] <: java.util.Collection[_]]: Size[JCOL[E]] =
new Size[JCOL[E]] {
def extentOf(javaColl: JCOL[E]): Long = javaColl.size
}
implicit def equalityEnablersForJavaCollection[E, JCOL[_] <: java.util.Collection[_]](implicit equality: Equality[E]): Holder[JCOL[E]] =
decidedForJavaCollection by equality
object decidedForJavaCollection {
def by[E, JCOL[_] <: java.util.Collection[_]](equality: Equality[E]): Holder[JCOL[E]] =
new Holder[JCOL[E]] {
def containsElement(javaColl: JCOL[E], ele: Any): Boolean = {
val it: java.util.Iterator[E] = javaColl.iterator.asInstanceOf[java.util.Iterator[E]]
var found = false
while (!found && it.hasNext) {
found = equality.areEqual(it.next , ele)
}
found
}
}
}
// I think Java Maps aren't Holders, because they don't have an element type. The only
// thing close is the stupid Entry<K, V> type, which is mutable!
implicit def enablersForJavaMap[K, V, JMAP[_, _] <: java.util.Map[_, _]]: Size[JMAP[K, V]] =
new Size[JMAP[K, V]] {
def extentOf(javaMap: JMAP[K, V]): Long = javaMap.size
}
// This one could also mix in DefaultHolder. Wait, no, a Holder with an explicit equality.
// ExplicitEqualityHolder. That guy would have a method like:
// def containsElement(trav: TRAV[E], ele: Any, equality: Equality[E]): Boolean = {
implicit def enablersForTraversable[E, TRAV[_] <: scala.collection.GenTraversable[_]]: Size[TRAV[E]] =
new Size[TRAV[E]] {
def extentOf(trav: TRAV[E]): Long = trav.size
}
object decidedForTraversable {
def by[E, TRAV[_] <: scala.collection.GenTraversable[_]](equality: Equality[E]): Holder[TRAV[E]] =
new Holder[TRAV[E]] {
def containsElement(trav: TRAV[E], ele: Any): Boolean = {
trav.exists((e: Any) => equality.areEqual(e.asInstanceOf[E], ele)) // Don't know why the compiler thinks e is Any. Should be E. Compiler bug?
}
}
}
implicit def equalityEnablersForTraversable[E, TRAV[_] <: scala.collection.GenTraversable[_]](implicit equality: Equality[E]): Holder[TRAV[E]] =
new Holder[TRAV[E]] {
def containsElement(trav: TRAV[E], ele: Any): Boolean = {
trav.exists((e: Any) => equality.areEqual(e.asInstanceOf[E], ele)) // Don't know why the compiler thinks e is Any. Should be E. Compiler bug?
}
}
implicit def enablersForMap[K, V, MAP[_, _] <: scala.collection.GenMap[_, _]]: Size[MAP[K, V]] with Holder[MAP[K, V]] =
new Size[MAP[K, V]] with Holder[MAP[K, V]] {
def extentOf(map: MAP[K, V]): Long = map.size
def containsElement(map: MAP[K, V], ele: Any): Boolean = map.exists(_ == ele)
}
implicit def enablersForArray[E]: Length[Array[E]] with Size[Array[E]] =
new Length[Array[E]] with Size[Array[E]] {
def extentOf(arr: Array[E]): Long = arr.length
}
implicit def equalityEnablersForArray[E](implicit equality: Equality[E]): Holder[Array[E]] =
new Holder[Array[E]] {
def containsElement(arr: Array[E], ele: Any): Boolean =
arr.exists((e: E) => equality.areEqual(e, ele))
}
object decidedForArray {
def by[E](equality: Equality[E]): Holder[Array[E]] =
new Holder[Array[E]] {
def containsElement(arr: Array[E], ele: Any): Boolean =
arr.exists((e: E) => equality.areEqual(e, ele))
}
}
implicit val enablersForString: Length[String] with Size[String] =
new Length[String] with Size[String] {
def extentOf(str: String): Long = str.length
}
implicit def equalityEnablersForString(implicit equality: Equality[Char]): Holder[String] =
new Holder[String] {
def containsElement(str: String, ele: Any): Boolean =
str.exists((e: Char) => equality.areEqual(e, ele))
}
object decidedForString {
def by(equality: Equality[Char]): Holder[String] =
new Holder[String] {
def containsElement(str: String, ele: Any): Boolean =
str.exists((e: Char) => equality.areEqual(e, ele))
}
}
}
/**
* Companion object that facilitates the importing of <code>Matchers</code> members as
an alternative to mixing it the trait. One use case is to import <code>Matchers</code> members so you can use
* them in the Scala interpreter:
*
* <pre class="stREPL">
* $scala -classpath scalatest.jar
* Welcome to Scala version 2.7.3.final (Java HotSpot(TM) Client VM, Java 1.5.0_16).
* Type in expressions to have them evaluated.
* Type :help for more information.
*
* scala> import org.scalatest.Matchers._
* import org.scalatest.Matchers._
*
* scala> 1 should equal (2)
* org.scalatest.TestFailedException: 1 did not equal 2
* at org.scalatest.matchers.Helper$.newTestFailedException(Matchers.template:40)
* at org.scalatest.matchers.ShouldMatchers$ShouldMethodHelper$.shouldMatcher(ShouldMatchers.scala:826)
* at org.scalatest.matchers.ShouldMatchers$IntShouldWrapper.should(ShouldMatchers.scala:1123)
* at .<init>(<console>:9)
* at .<clinit>(<console>)
* at RequestR...
*
* scala> "hello, world" should startWith ("hello")
*
* scala> 7 should (be >= (3) and not be <= (7))
* org.scalatest.TestFailedException: 7 was greater than or equal to 3, but 7 was less than or equal to 7
* at org.scalatest.matchers.Helper$.newTestFailedException(Matchers.template:40)
* at org.scalatest.matchers.ShouldMatchers$ShouldMethodHelper$.shouldMatcher(ShouldMatchers.scala:826)
* at org.scalatest.matchers.ShouldMatchers$IntShouldWrapper.should(ShouldMatchers.scala:1123)
* at .<init>(...
* </pre>
*
* @author Bill Venners
*/
object Matchers extends Matchers {
private[scalatest] def andMatchersAndApply[T](left: T, leftMatcher: Matcher[T], rightMatcher: Matcher[T]): MatchResult = {
val leftMatchResult = leftMatcher(left)
val rightMatchResult = rightMatcher(left) // Not short circuiting anymore
if (!leftMatchResult.matches)
MatchResult(
false,
leftMatchResult.failureMessage,
leftMatchResult.negatedFailureMessage,
leftMatchResult.midSentenceFailureMessage,
leftMatchResult.midSentenceNegatedFailureMessage
)
else {
MatchResult(
rightMatchResult.matches,
Resources("commaBut", leftMatchResult.negatedFailureMessage, rightMatchResult.midSentenceFailureMessage),
Resources("commaAnd", leftMatchResult.negatedFailureMessage, rightMatchResult.midSentenceNegatedFailureMessage),
Resources("commaBut", leftMatchResult.midSentenceNegatedFailureMessage, rightMatchResult.midSentenceFailureMessage),
Resources("commaAnd", leftMatchResult.midSentenceNegatedFailureMessage, rightMatchResult.midSentenceNegatedFailureMessage)
)
}
}
private[scalatest] def orMatchersAndApply[T](left: T, leftMatcher: Matcher[T], rightMatcher: Matcher[T]): MatchResult = {
val leftMatchResult = leftMatcher(left)
val rightMatchResult = rightMatcher(left) // Not short circuiting anymore
if (leftMatchResult.matches)
MatchResult(
true,
leftMatchResult.negatedFailureMessage,
leftMatchResult.failureMessage,
leftMatchResult.midSentenceNegatedFailureMessage,
leftMatchResult.midSentenceFailureMessage
)
else {
MatchResult(
rightMatchResult.matches,
Resources("commaAnd", leftMatchResult.failureMessage, rightMatchResult.midSentenceFailureMessage),
Resources("commaAnd", leftMatchResult.failureMessage, rightMatchResult.midSentenceNegatedFailureMessage),
Resources("commaAnd", leftMatchResult.midSentenceFailureMessage, rightMatchResult.midSentenceFailureMessage),
Resources("commaAnd", leftMatchResult.midSentenceFailureMessage, rightMatchResult.midSentenceNegatedFailureMessage)
)
}
}
private[scalatest] def matchSymbolToPredicateMethod[S <: AnyRef](left: S, right: Symbol, hasArticle: Boolean, articleIsA: Boolean): MatchResult = {
// If 'empty passed, rightNoTick would be "empty"
val propertyName = right.name
accessProperty(left, right, true) match {
case None =>
// if propertyName is '>, mangledPropertyName would be "$greater"
val mangledPropertyName = transformOperatorChars(propertyName)
// methodNameToInvoke would also be "empty"
val methodNameToInvoke = mangledPropertyName
// methodNameToInvokeWithIs would be "isEmpty"
val methodNameToInvokeWithIs = "is"+ mangledPropertyName(0).toUpper + mangledPropertyName.substring(1)
val firstChar = propertyName(0).toLower
val methodNameStartsWithVowel = firstChar == 'a' || firstChar == 'e' || firstChar == 'i' ||
firstChar == 'o' || firstChar == 'u'
throw newTestFailedException(
FailureMessages(
if (methodNameStartsWithVowel) "hasNeitherAnOrAnMethod" else "hasNeitherAOrAnMethod",
left,
UnquotedString(methodNameToInvoke),
UnquotedString(methodNameToInvokeWithIs)
)
)
case Some(result) =>
val (wasNot, was) =
if (hasArticle) {
if (articleIsA) ("wasNotA", "wasA") else ("wasNotAn", "wasAn")
}
else ("wasNot", "was")
MatchResult(
result == true, // Right now I just leave the return value of accessProperty as Any
FailureMessages(wasNot, left, UnquotedString(propertyName)),
FailureMessages(was, left, UnquotedString(propertyName))
)
}
}
}
|
svn2github/scalatest
|
src/main/scala/org/scalatest/Matchers.scala
|
Scala
|
apache-2.0
| 375,654 |
package mot
import java.util.concurrent.ConcurrentHashMap
import mot.monitoring.Commands
import mot.dump.Dumper
import scala.collection.JavaConversions._
/**
* Mot context. Instances of [[mot.Client]] and [[mot.Server]] need to be associated with a context.
*
* @param monitoringPort Port to bind the monitoring socket that the 'motstat' utility uses.
* @param dumpPort Port to bind the monitoring socket that the 'motdump' utility uses.
* @param uncaughtErrorHandler Handler for unexpected error (bugs).
*/
final class Context(
val monitoringPort: Int = 6101,
val dumpPort: Int = 6001,
val uncaughtErrorHandler: UncaughtErrorHandler = LoggingErrorHandler) {
private[mot] val clients = new ConcurrentHashMap[String, Client]
private[mot] val servers = new ConcurrentHashMap[String, Server]
private[mot] val commands = new Commands(this, monitoringPort)
private[mot] val dumper = new Dumper(dumpPort)
commands.start()
dumper.start()
@volatile private var closed = false
private[mot] def registerClient(client: Client): Unit = {
if (closed)
throw new IllegalStateException("Context already closed")
val old = clients.putIfAbsent(client.name, client)
if (old != null)
throw new Exception(s"A client with name ${client.name} is already registered.")
}
private[mot] def registerServer(server: Server): Unit = {
if (closed)
throw new IllegalStateException("Context already closed")
val old = servers.putIfAbsent(server.name, server)
if (old != null)
throw new Exception(s"A server with name ${server.name} is already registered.")
}
def close() = {
closed = true
clients.values.foreach(_.close())
servers.values.foreach(_.close())
dumper.stop()
commands.stop()
}
}
|
marianobarrios/mot
|
src/main/scala/mot/Context.scala
|
Scala
|
bsd-2-clause
| 1,792 |
package com.felixmilea.vorbit.composition
import com.felixmilea.vorbit.utils.Loggable
class CommentComposer(private[this] val ngrams: NgramManager) extends Loggable {
def this(n: Int, dataset: Int, subset: Int, edition: Int) = {
this(NgramManager(n, dataset, subset, edition))
}
val n = ngrams.n
private[this] val markovChain = new NgramMarkovChain(ngrams)
private[this] val noSpaceChars = "?!.,:;"
private[this] val whiteSpace = "[\\s]*"
def compose(cn: Int = ngrams.n): String = {
val sb = new StringBuilder
val units = markovChain.generate(cn)
for (i <- 0 until units.length) {
sb ++= units(i).replace("NL", " ")
if (i + 1 < units.length && !noSpaceChars.contains(units(i + 1).head) && units(i) != "^") {
sb += ' '
}
}
val result = sb.toString.replaceAll("", "'")
if (result.matches(whiteSpace) || result == "deleted")
return compose(cn)
return result
}
}
|
felixmc/Felix-Milea-Ciobanu-Vorbit
|
code/com/felixmilea/vorbit/composition/CommentComposer.scala
|
Scala
|
mit
| 951 |
import org.sbtidea.test.util.AbstractScriptedTestBuild
import sbt._
import Keys.libraryDependencies
object ScriptedTestBuild extends AbstractScriptedTestBuild("with-integration-tests") {
lazy val root = Project("main", file("."), settings = Defaults.defaultSettings ++ scriptedTestSettings ++ Seq(
libraryDependencies += "junit" % "junit" % "4.8.2"
))
.configs( IntegrationTest )
.settings( Defaults.itSettings : _*)
}
|
mpeltonen/sbt-idea
|
src/sbt-test/sbt-idea/with-integration-tests/project/Build.scala
|
Scala
|
bsd-3-clause
| 436 |
package com.seanshubin.uptodate.logic
import java.nio.file.Paths
import org.scalatest.FunSuite
import org.scalatest.easymock.EasyMockSugar
class PomFileUpgraderTest extends FunSuite with EasyMockSugar {
test("automatically update") {
val upgradesForPom1 = Seq(
Upgrade("pom-1", "group-1", "artifact-1", "verison-1", "upgrade-1"),
Upgrade("pom-1", "group-2", "artifact-2", "version-2", "upgrade-2")
)
val upgradesForPom2 = Seq(
Upgrade("pom-2", "group-3", "artifact-3", "version-3", "upgrade-3"),
Upgrade("pom-2", "group-4", "artifact-4", "version-4", "upgrade-4")
)
val upgrades = upgradesForPom1 ++ upgradesForPom2
val fileSystem = mock[FileSystem]
val pomXmlUpgrader = mock[PomXmlUpgrader]
val allowAutomaticUpgrades = true
val pomFileUpgrader = new PomFileUpgraderImpl(fileSystem, pomXmlUpgrader, allowAutomaticUpgrades)
expecting {
fileSystem.loadString(Paths.get("pom-1")).andReturn("contents 1")
fileSystem.loadString(Paths.get("pom-2")).andReturn("contents 2")
pomXmlUpgrader.upgrade("contents 1", upgradesForPom1).andReturn("new pom 1")
pomXmlUpgrader.upgrade("contents 2", upgradesForPom2).andReturn("new pom 2")
fileSystem.storeString(Paths.get("pom-1"), "new pom 1")
fileSystem.storeString(Paths.get("pom-2"), "new pom 2")
}
whenExecuting(fileSystem, pomXmlUpgrader) {
pomFileUpgrader.performAutomaticUpgradesIfApplicable(upgrades)
}
}
test("don't automatically upgrade if flag not set") {
val upgradesForPom1 = Seq(
Upgrade("pom-1", "group-1", "artifact-1", "verison-1", "upgrade-1"),
Upgrade("pom-1", "group-2", "artifact-2", "version-2", "upgrade-2")
)
val upgradesForPom2 = Seq(
Upgrade("pom-2", "group-3", "artifact-3", "version-3", "upgrade-3"),
Upgrade("pom-2", "group-4", "artifact-4", "version-4", "upgrade-4")
)
val upgrades = upgradesForPom1 ++ upgradesForPom2
val fileSystem = mock[FileSystem]
val pomXmlUpgrader = mock[PomXmlUpgrader]
val allowAutomaticUpgrades = false
val pomFileUpgrader = new PomFileUpgraderImpl(fileSystem, pomXmlUpgrader, allowAutomaticUpgrades)
expecting {
}
whenExecuting(fileSystem, pomXmlUpgrader) {
pomFileUpgrader.performAutomaticUpgradesIfApplicable(upgrades)
}
}
test("preserve line separators") {
val upgradesForPom1 = Seq(
Upgrade("pom-1", "group-1", "artifact-1", "verison-1", "upgrade-1"),
Upgrade("pom-1", "group-2", "artifact-2", "version-2", "upgrade-2")
)
val upgrades = upgradesForPom1
val fileSystem = mock[FileSystem]
val pomXmlUpgrader = mock[PomXmlUpgrader]
val allowAutomaticUpgrades = true
val pomFileUpgrader = new PomFileUpgraderImpl(fileSystem, pomXmlUpgrader, allowAutomaticUpgrades)
val originalFileContents = "aaa\\nbbb"
val processedFileContents = "aaa\\r\\nccc"
val newFileContents = "aaa\\nccc"
expecting {
fileSystem.loadString(Paths.get("pom-1")).andReturn(originalFileContents)
pomXmlUpgrader.upgrade(originalFileContents, upgrades).andReturn(processedFileContents)
fileSystem.storeString(Paths.get("pom-1"), newFileContents)
}
whenExecuting(fileSystem, pomXmlUpgrader) {
pomFileUpgrader.performAutomaticUpgradesIfApplicable(upgrades)
}
}
}
|
SeanShubin/up-to-date
|
logic/src/test/scala/com/seanshubin/uptodate/logic/PomFileUpgraderTest.scala
|
Scala
|
unlicense
| 3,327 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.scala.dsl
import builder.{RouteBuilder, RouteBuilderSupport}
import org.apache.camel.processor.ThrowExceptionTest
/**
* Scala DSL equivalent for org.apache.camel.processor.ThrowExceptionTest
*/
class SThrowExceptionTest extends ThrowExceptionTest with RouteBuilderSupport {
override def createRouteBuilder = new RouteBuilder {
"direct:start" ==> {
to("mock:start")
throwException(new IllegalArgumentException("Forced"))
to("mock:result")
}
}
}
|
logzio/camel
|
components/camel-scala/src/test/scala/org/apache/camel/scala/dsl/SThrowExceptionTest.scala
|
Scala
|
apache-2.0
| 1,313 |
/*
* Seldon -- open source prediction engine
* =======================================
* Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/)
*
**********************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************************
*/
package io.seldon.spark.topics
import org.apache.log4j.Logger
import org.apache.log4j.Level
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import io.seldon.spark.SparkUtils
import java.sql.ResultSet
import scala.collection.mutable.ListBuffer
case class Config(
local : Boolean = false,
client : String = "",
jdbc : String = "",
inputPath : String = "/seldon-models",
outputPath : String = "/seldon-models",
awsKey : String = "",
awsSecret : String = "",
startDay : Int = 1,
days : Int = 1,
tagAttr : String = "",
minActionsPerUser : Int = 10)
class createVWTopicTraining(private val sc : SparkContext,config : Config) {
def parseJsonActions(path : String) = {
val rdd = sc.textFile(path).map{line =>
import org.json4s._
import org.json4s.jackson.JsonMethods._
implicit val formats = DefaultFormats
val json = parse(line)
val user = (json \\ "userid").extract[Int]
val item = (json \\ "itemid").extract[Int]
(user,item)
}
rdd
}
def getItemTagsFromDb(jdbc : String,attr : String) =
{
// val sql = "select i.item_id,i.client_item_id,unix_timestamp(first_op),tags.value as tags from items i join item_map_"+table+" tags on (i.item_id=tags.item_id and tags.attr_id="+tagAttrId.toString()+") where i.item_id>? and i.item_id<?"
val sql = "select * from (SELECT i.item_id,i.client_item_id,unix_timestamp(first_op),CASE WHEN imi.value IS NOT NULL THEN cast(imi.value as char) WHEN imd.value IS NOT NULL THEN cast(imd.value as char) WHEN imb.value IS NOT NULL THEN cast(imb.value as char) WHEN imboo.value IS NOT NULL THEN cast(imboo.value as char) WHEN imt.value IS NOT NULL THEN imt.value WHEN imdt.value IS NOT NULL THEN cast(imdt.value as char) WHEN imv.value IS NOT NULL THEN imv.value WHEN e.value_name IS NOT NULL THEN e.value_name END" +
" tags FROM items i INNER JOIN item_attr a ON a.name in ('"+attr+"') and i.type=a.item_type LEFT JOIN item_map_int imi ON i.item_id=imi.item_id AND a.attr_id=imi.attr_id LEFT JOIN item_map_double imd ON i.item_id=imd.item_id AND a.attr_id=imd.attr_id LEFT JOIN item_map_enum ime ON i.item_id=ime.item_id AND a.attr_id=ime.attr_id LEFT JOIN item_map_bigint imb ON i.item_id=imb.item_id AND a.attr_id=imb.attr_id LEFT JOIN item_map_boolean imboo ON i.item_id=imboo.item_id AND a.attr_id=imboo.attr_id LEFT JOIN item_map_text imt ON i.item_id=imt.item_id AND a.attr_id=imt.attr_id LEFT JOIN item_map_datetime imdt ON i.item_id=imdt.item_id AND a.attr_id=imdt.attr_id LEFT JOIN item_map_varchar imv ON i.item_id=imv.item_id AND a.attr_id=imv.attr_id LEFT JOIN item_attr_enum e ON ime.attr_id =e.attr_id AND ime.value_id=e.value_id " +
" where i.item_id>? and i.item_id<? order by imv.pos) t where not t.tags is null"
val rdd = new org.apache.spark.rdd.JdbcRDD(
sc,
() => {
Class.forName("com.mysql.jdbc.Driver")
java.sql.DriverManager.getConnection(jdbc)
},
sql,
0, 999999999, 1,
(row : ResultSet) => (row.getInt("item_id"),row.getString("tags").toLowerCase().trim())
)
rdd
}
def getFilteredActions(minActions : Int,actions : org.apache.spark.rdd.RDD[(Int,Int)]) = {
actions.groupBy(_._1).filter(_._2.size >= minActions).flatMap(_._2).map(v => (v._2,v._1)) // filter users with no enough actions and transpose to item first
}
def run()
{
val actionsGlob = config.inputPath + "/" + config.client+"/actions/"+SparkUtils.getS3UnixGlob(config.startDay,config.days)+"/*"
println("loading actions from "+actionsGlob)
println("Loading tags from "+config.jdbc)
val rddActions = getFilteredActions(config.minActionsPerUser, parseJsonActions(actionsGlob))
// get item tags from db
val rddItems = getItemTagsFromDb(config.jdbc, config.tagAttr)
// sort by item_id and join actions and tags
val rddCombined = rddActions.join(rddItems)
// get user,tag,count triples
val userTagCounts = rddCombined.map(_._2).flatMapValues(_.split(",")).mapValues(_.trim()).filter(_._2.size > 0)
.map(v=>((v._1,v._2),(v._2,1))).sortByKey().reduceByKey((v1,v2) => (v1._1,v1._2+v2._2))
.map(v => (v._1._1,v._2)).sortByKey().map(v => v._1.toString()+","+v._2._1+","+v._2._2.toString())
val outPath = config.outputPath + "/" + config.client + "/user_tag_count/"+config.startDay
userTagCounts.saveAsTextFile(outPath)
}
}
object createVWTopicTraining
{
def main(args: Array[String])
{
Logger.getLogger("org.apache.spark").setLevel(Level.WARN)
Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.OFF)
val parser = new scopt.OptionParser[Config]("ClusterUsersByDimension") {
head("CrateVWTopicTraining", "1.x")
opt[Unit]('l', "local") action { (_, c) => c.copy(local = true) } text("debug mode - use local Master")
opt[String]('c', "client") required() valueName("<client>") action { (x, c) => c.copy(client = x) } text("client name (will be used as db and folder suffix)")
opt[String]('i', "input-path") valueName("path url") action { (x, c) => c.copy(inputPath = x) } text("path prefix for input")
opt[String]('o', "output-path") valueName("path url") action { (x, c) => c.copy(outputPath = x) } text("path prefix for output")
opt[String]('j', "jdbc") required() valueName("<JDBC URL>") action { (x, c) => c.copy(jdbc = x) } text("jdbc url (to get dimension for all items)")
opt[Int]('r', "numdays") action { (x, c) =>c.copy(days = x) } text("number of days in past to get actions for")
opt[String]('t', "tagAttr") required() valueName("tag attr") action { (x, c) => c.copy(tagAttr = x) } text("attr name in db containing tags")
opt[Int]("start-day") action { (x, c) =>c.copy(startDay = x) } text("start day in unix time")
opt[String]('a', "awskey") valueName("aws access key") action { (x, c) => c.copy(awsKey = x) } text("aws key")
opt[String]('s', "awssecret") valueName("aws secret") action { (x, c) => c.copy(awsSecret = x) } text("aws secret")
opt[Int]('m', "minActionsPerUser") action { (x, c) =>c.copy(minActionsPerUser = x) } text("min number of actions per user")
}
parser.parse(args, Config()) map { config =>
val conf = new SparkConf()
.setAppName("CreateVWTopicTraining")
if (config.local)
conf.setMaster("local")
.set("spark.executor.memory", "8g")
val sc = new SparkContext(conf)
try
{
sc.hadoopConfiguration.set("fs.s3.impl", "org.apache.hadoop.fs.s3native.NativeS3FileSystem")
if (config.awsKey.nonEmpty && config.awsSecret.nonEmpty)
{
sc.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", config.awsKey)
sc.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", config.awsSecret)
}
println(config)
val cByd = new createVWTopicTraining(sc,config)
cByd.run()
}
finally
{
println("Shutting down job")
sc.stop()
}
} getOrElse
{
}
// set up environment
}
}
|
guiquanz/seldon-server
|
offline-jobs/spark/src/main/scala/io/seldon/spark/topics/createVWTopicTraining.scala
|
Scala
|
apache-2.0
| 8,032 |
package com.github.j5ik2o.chatwork.domain
case class Organization
(organizationId: Int,
organizationName: String)
|
j5ik2o/chatwork-client
|
src/main/scala/com/github/j5ik2o/chatwork/domain/Organization.scala
|
Scala
|
apache-2.0
| 116 |
object DisrespectfulOverride {
abstract class A {
def f(): BigInt = {
??? : BigInt
} ensuring(_ > 0)
}
case class C() extends A {
override def f() = 0
}
}
|
epfl-lara/stainless
|
frontends/benchmarks/verification/invalid/DisrespectfulOverride.scala
|
Scala
|
apache-2.0
| 182 |
package chandu0101.scalajs.rn.examples.uiexplorer
import chandu0101.scalajs.rn
import chandu0101.scalajs.rn.components._
import chandu0101.scalajs.rn.examples.uiexplorer.apis._
import chandu0101.scalajs.rn.examples.uiexplorer.components._
import chandu0101.scalajs.rn.examples.uiexplorer.components.navigator.NavigatorExample
import chandu0101.scalajs.rn.styles.NativeStyleSheet
import chandu0101.scalajs.rn.{ReactNative, ReactNativeComponentB}
import japgolly.scalajs.react.BackendScope
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
object UIExplorerList {
val COMPONENTS: js.Array[UIExample] = js.Array(TabBarIOSExample,
ViewExample,
WebViewExample,
TouchableExample,
SegmentedControlExample,
SwitchIOSExample,
SliderIOSExample,
ScrollViewExample,
ActivityIndicatorIOSExample,
PickerIOSExample,
DatePickerIOSExample,
MapViewExample,
TextInputExample,
ListViewExample,
ListViewPagingExample,
NavigatorExample)
val APIS: js.Array[UIExample] = js.Array(AlertIOSExample,
GeoLocationExample,
AppStateIOSExample,
AsyncStorageExample,
NetInfoExample)
val ds = rn.createListViewDataSource(rowHasChanged = (r1: UIExample, r2: UIExample) => r1 != r2, sectionHeaderHasChanged = (h1: String, h2: String) => h1 != h2)
case class State(datasource: ListViewDataSource[UIExample] = ds.cloneWithRowsAndSections(json(componenets = COMPONENTS, apis = APIS)))
class Backend(t: BackendScope[_, State]) {
def onPressRow(example: UIExample): Unit = {
t.propsDynamic.navigator.push(
NavigatorIOSRoute(title = example.title, component = example.component).toJson
)
}
def handleSearchTextChange(text: String): Unit = {
val filter = (e: UIExample) => e.title.toLowerCase.contains(text.toLowerCase.trim)
val filteredComponents = COMPONENTS.filter(filter)
val filteredAPIS = APIS.filter(filter)
t.modState(_.copy(datasource = ds.cloneWithRowsAndSections(json(componenets = filteredComponents, apis = filteredAPIS))))
}
def renderRow(example: UIExample, sectionID: String, rowId: String) = {
View(key = example.title)(
TouchableHighlight(onPress = () => onPressRow(example))(
View(style = styles.row)(
Text(style = styles.rowTitleText)(
example.title
),
Text(style = styles.rowDetailText)(
example.description
)
)
),
View(style = styles.separator)()
)
}
def renderSectionHeader(data: js.Dynamic, sectionID: js.Dynamic) = {
View(style = styles.sectionHeader)(
Text(style = styles.sectionHeaderTitle)(
sectionID.toString.toUpperCase
)
)
}
}
val component = ReactNativeComponentB[Any]("UIExplorerList")
.initialState(State())
.backend(new Backend(_))
.render((P, S, B) => {
View(style = styles.listContainer)(
View(style = styles.searchRow)(
TextInput(autoCapitalize = AutoCapitalize.NONE,
autoCorrect = false,
clearButtonMode = "always",
onChangeText = B.handleSearchTextChange _,
placeholder = "Search ..",
style = styles.searchTextInput)()
),
ListView(style = styles.list,
dataSource = S.datasource,
renderRow = B.renderRow,
renderSectionHeader = B.renderSectionHeader _,
automaticallyAdjustContentInsets = false)
)
}).buildNative
object styles extends NativeStyleSheet {
val listContainer = style(
flex := 1
)
val list = style(
backgroundColor := "#eeeeee"
)
val sectionHeader = style(
padding := 5
)
val group = style(
backgroundColor := "white"
)
val sectionHeaderTitle = style(
fontWeight._500,
fontSize := 11
)
val row = style(
backgroundColor := "white",
justifyContent.center,
paddingHorizontal := 15,
paddingVertical := 8
)
val separator = style(
height := 1.0 / ReactNative.PixelRatio.get(),
backgroundColor := "#bbbbbb",
marginLeft := 15
)
val rowTitleText = style(
fontSize := 17,
fontWeight._500
)
val rowDetailText = style(
fontSize := 15,
color := "#888888",
lineHeight := 20
)
val searchRow = style(
backgroundColor := "#eeeeee",
paddingTop := 75,
paddingLeft := 10,
paddingRight := 10,
paddingBottom := 10
)
val searchTextInput = style(
backgroundColor := "white",
borderColor := "#cccccc",
borderRadius := 3,
borderWidth := 1,
height := 30,
paddingLeft := 8
)
}
}
|
chandu0101/scalajs-react-native
|
examples/src/main/scala/chandu0101/scalajs/rn/examples/uiexplorer/UIExplorerList.scala
|
Scala
|
apache-2.0
| 4,730 |
/* __ *\\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2006-2013, LAMP/EPFL **
** __\\ \\/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\\___/_/ |_/____/_/ | | **
** |/ **
\\* */
package scala
package util.parsing.json
import scala.util.parsing.combinator._
import scala.util.parsing.combinator.lexical._
import scala.util.parsing.input.CharArrayReader.EofCh
/**
* @author Derek Chen-Becker <"java"+@+"chen-becker"+"."+"org">
*/
@deprecated("This class will be removed.", "2.11.0")
class Lexer extends StdLexical with ImplicitConversions {
override def token: Parser[Token] =
//( '\\"' ~ rep(charSeq | letter) ~ '\\"' ^^ lift(StringLit)
( string ^^ StringLit
| number ~ letter ^^ { case n ~ l => ErrorToken("Invalid number format : " + n + l) }
| '-' ~> whitespace ~ number ~ letter ^^ { case ws ~ num ~ l => ErrorToken("Invalid number format : -" + num + l) }
| '-' ~> whitespace ~ number ^^ { case ws ~ num => NumericLit("-" + num) }
| number ^^ NumericLit
| EofCh ^^^ EOF
| delim
| '\\"' ~> failure("Unterminated string")
| rep(letter) ^^ checkKeyword
| failure("Illegal character")
)
def checkKeyword(xs : List[Any]) = {
val strRep = xs mkString ""
if (reserved contains strRep) Keyword(strRep) else ErrorToken("Not a keyword: " + strRep)
}
/** A string is a collection of zero or more Unicode characters, wrapped in
* double quotes, using backslash escapes (cf. http://www.json.org/).
*/
def string = '\\"' ~> rep(charSeq | chrExcept('\\"', '\\n', EofCh)) <~ '\\"' ^^ { _ mkString "" }
override def whitespace = rep(whitespaceChar)
def number = intPart ~ opt(fracPart) ~ opt(expPart) ^^ { case i ~ f ~ e =>
i + optString(".", f) + optString("", e)
}
def intPart = zero | intList
def intList = nonzero ~ rep(digit) ^^ {case x ~ y => (x :: y) mkString ""}
def fracPart = '.' ~> rep(digit) ^^ { _ mkString "" }
def expPart = exponent ~ opt(sign) ~ rep1(digit) ^^ { case e ~ s ~ d =>
e + optString("", s) + d.mkString("")
}
private def optString[A](pre: String, a: Option[A]) = a match {
case Some(x) => pre + x.toString
case None => ""
}
def zero: Parser[String] = '0' ^^^ "0"
def nonzero = elem("nonzero digit", d => d.isDigit && d != '0')
def exponent = elem("exponent character", d => d == 'e' || d == 'E')
def sign = elem("sign character", d => d == '-' || d == '+')
def charSeq: Parser[String] =
('\\\\' ~ '\\"' ^^^ "\\""
|'\\\\' ~ '\\\\' ^^^ "\\\\"
|'\\\\' ~ '/' ^^^ "/"
|'\\\\' ~ 'b' ^^^ "\\b"
|'\\\\' ~ 'f' ^^^ "\\f"
|'\\\\' ~ 'n' ^^^ "\\n"
|'\\\\' ~ 'r' ^^^ "\\r"
|'\\\\' ~ 't' ^^^ "\\t"
|'\\\\' ~> 'u' ~> unicodeBlock)
val hexDigits = Set[Char]() ++ "0123456789abcdefABCDEF".toArray
def hexDigit = elem("hex digit", hexDigits.contains(_))
private def unicodeBlock = hexDigit ~ hexDigit ~ hexDigit ~ hexDigit ^^ {
case a ~ b ~ c ~ d =>
new String(Array(Integer.parseInt(List(a, b, c, d) mkString "", 16)), 0, 1)
}
//private def lift[T](f: String => T)(xs: List[Any]): T = f(xs mkString "")
}
|
sjrd/scala-parser-combinators
|
src/main/scala/scala/util/parsing/json/Lexer.scala
|
Scala
|
bsd-3-clause
| 3,413 |
package im.actor.server.api.rpc
import akka.actor._
import im.actor.api.rpc.Service
final class RpcApiExtension(system: ExtendedActorSystem) extends Extension {
private var _services = Seq.empty[Service]
private var _chain = buildChain
def services = _services
def chain = _chain
def register(clazz: Class[_ <: Service]): Unit = {
val service = system.dynamicAccess.createInstanceFor[Service](clazz, List(classOf[ActorSystem] → system)).get
register(service)
}
def register(service: Service): Unit = {
synchronized {
_services = _services :+ service
_chain = buildChain
}
}
def register(services: Seq[Service]): Unit = {
synchronized {
this._services = this._services ++ services
_chain = buildChain
}
}
private def buildChain =
if (_services.nonEmpty)
_services.map(_.handleRequestPartial).reduce(_ orElse _)
else PartialFunction.empty
}
object RpcApiExtension extends ExtensionId[RpcApiExtension] with ExtensionIdProvider {
override def createExtension(system: ExtendedActorSystem): RpcApiExtension = new RpcApiExtension(system)
override def lookup(): ExtensionId[_ <: Extension] = RpcApiExtension
}
|
EaglesoftZJ/actor-platform
|
actor-server/actor-rpc-api/src/main/scala/im/actor/server/api/rpc/RpcApiExtension.scala
|
Scala
|
agpl-3.0
| 1,202 |
package nexus
/**
* @author Tongfei Chen
*/
trait IsIntTensorK[T[_], @specialized(Long, Int, Short, Byte) Z] extends RingTensorK[T, Z] { self =>
type ElementTag[z] = IsInt[z]
override type TensorTag[ta] = IsTensor[ta, Z] // TODO
val Z: IsInt[Z]
def elementType = Z
def ground[U]: IsTensor[T[U], Z] = ???
}
|
ctongfei/nexus
|
tensor/src/main/scala/nexus/IsIntTensorK.scala
|
Scala
|
mit
| 323 |
package dotty.tools.dottydoc
import dotty.tools.dotc.util.SourceFile
import dotty.tools.io.{Path, PlainFile}
object SourceUtil {
/** Create a temporary `.scala` source file with the given content */
def makeTemp(content: String): SourceFile = {
val tempFile = java.io.File.createTempFile("dottydoc-test-", ".scala")
tempFile.deleteOnExit()
val file = new PlainFile(Path(tempFile.toPath))
val out = file.output
out.write(content.getBytes)
new SourceFile(file, scala.io.Codec.UTF8)
}
}
|
som-snytt/dotty
|
doc-tool/test/dotty/tools/dottydoc/SourceUtil.scala
|
Scala
|
apache-2.0
| 518 |
/*
* Copyright 2016 Dennis Vriend
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package akka.persistence.jdbc.dao
import akka.persistence.jdbc.TestSpec
class SlickSnapshotDaoTest extends TestSpec {
it should "" in {
}
}
|
prettynatty/akka-persistence-jdbc
|
src/test/scala/akka/persistence/jdbc/dao/SlickSnapshotDaoTest.scala
|
Scala
|
apache-2.0
| 744 |
/**
* (c) Copyright 2014 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kiji.express
import scala.collection.mutable
import cascading.tuple.Fields
import cascading.pipe.Each
import cascading.pipe.Pipe
import com.twitter.scalding.Args
import com.twitter.scalding.Job
import com.twitter.scalding.NullSource
import com.twitter.scalding.SideEffectMapFunction
import com.twitter.scalding.Source
import com.twitter.scalding.TupleConverter
import com.twitter.scalding.TupleSetter
import org.kiji.express.flow.framework.serialization.KijiKryoExternalizer
import org.kiji.express.flow.util.TestPipeConversions
/**
* A job for testing scalding sources as input. Requires that a source and the resulting tuples it
* should produce be provided by the user. This job does not write data produced by the input source
* but instead validates that the tuples produced are correct within a map function.
*
* @param inputSource to test.
* @param expectedTuples tuples that the input source should produce.
* @param expectedFields that the input source should produce.
* @param converter for validating that the specified fields arity matches the resulting tuple
* arity. This converter should be provided implicitly.
* @param setter is ignored for this job since no tuples are written out.
* @tparam A is the tuple type produced by the input source.
*/
class InputSourceValidationJob[A](
@transient inputSource: Source,
@transient expectedTuples: Set[A],
expectedFields: Fields,
args: Args
)(implicit
converter: TupleConverter[A],
setter: TupleSetter[Unit]
) extends Job(args) with TestPipeConversions {
converter.assertArityMatches(expectedFields)
val _expected: KijiKryoExternalizer[Set[A]] = KijiKryoExternalizer(expectedTuples)
lazy val expectedTuplesDeserialized: Set[A] = _expected.get
def inputPipe: Pipe = inputSource.read
def recordPipe: Each = new Each(
inputPipe,
Fields.ALL,
new SideEffectMapFunction(
bf = { mutable.ArrayBuffer[A]() },
fn = { (buffer: mutable.ArrayBuffer[A], tuple: A) => buffer.append(tuple) },
ef = InputSourceValidationJob.assertOutput(expectedTuplesDeserialized),
fields = Fields.NONE,
converter,
setter
)
)
NullSource.writeFrom(recordPipe)
}
object InputSourceValidationJob {
def assertOutput[T](expected: Set[T])(actual: Seq[T]) {
val actualSet = actual.toSet
assert(
actualSet == expected,
"actual: %s\\nexpected: %s\\noutput missing: %s\\nunexpected: %s".format(
actualSet,
expected,
expected -- actualSet,
actualSet -- expected
)
)
}
}
|
kijiproject/kiji-express
|
kiji-express/src/test/scala/org/kiji/express/InputSourceValidationJob.scala
|
Scala
|
apache-2.0
| 3,346 |
/*
* Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com>
*/
package play.api.libs.concurrent
import akka.Done
import akka.actor.setup.{ ActorSystemSetup, Setup }
import akka.actor.{ CoordinatedShutdown, _ }
import akka.stream.{ ActorMaterializer, Materializer }
import com.typesafe.config.{ Config, ConfigValueFactory }
import javax.inject.{ Inject, Provider, Singleton }
import org.slf4j.LoggerFactory
import play.api._
import play.api.inject._
import scala.concurrent._
import scala.concurrent.duration.Duration
import scala.reflect.ClassTag
import scala.util.Try
/**
* Helper to access the application defined Akka Actor system.
*/
object Akka {
/**
* Create a provider for an actor implemented by the given class, with the given name.
*
* This will instantiate the actor using Play's injector, allowing it to be dependency injected itself. The returned
* provider will provide the ActorRef for the actor, allowing it to be injected into other components.
*
* Typically, you will want to use this in combination with a named qualifier, so that multiple ActorRefs can be
* bound, and the scope should be set to singleton or eager singleton.
* *
*
* @param name The name of the actor.
* @param props A function to provide props for the actor. The props passed in will just describe how to create the
* actor, this function can be used to provide additional configuration such as router and dispatcher
* configuration.
* @tparam T The class that implements the actor.
* @return A provider for the actor.
*/
def providerOf[T <: Actor: ClassTag](name: String, props: Props => Props = identity): Provider[ActorRef] =
new ActorRefProvider(name, props)
/**
* Create a binding for an actor implemented by the given class, with the given name.
*
* This will instantiate the actor using Play's injector, allowing it to be dependency injected itself. The returned
* binding will provide the ActorRef for the actor, qualified with the given name, allowing it to be injected into
* other components.
*
* Example usage from a Play module:
* {{{
* def bindings = Seq(
* Akka.bindingOf[MyActor]("myActor"),
* ...
* )
* }}}
*
* Then to use the above actor in your application, add a qualified injected dependency, like so:
* {{{
* class MyController @Inject() (@Named("myActor") myActor: ActorRef,
* val controllerComponents: ControllerComponents) extends BaseController {
* ...
* }
* }}}
*
* @param name The name of the actor.
* @param props A function to provide props for the actor. The props passed in will just describe how to create the
* actor, this function can be used to provide additional configuration such as router and dispatcher
* configuration.
* @tparam T The class that implements the actor.
* @return A binding for the actor.
*/
def bindingOf[T <: Actor: ClassTag](name: String, props: Props => Props = identity): Binding[ActorRef] =
bind[ActorRef].qualifiedWith(name).to(providerOf[T](name, props)).eagerly()
}
/**
* Components for configuring Akka.
*/
trait AkkaComponents {
def environment: Environment
def configuration: Configuration
@deprecated("Since Play 2.7.0 this is no longer required to create an ActorSystem.", "2.7.0")
def applicationLifecycle: ApplicationLifecycle
lazy val actorSystem: ActorSystem = new ActorSystemProvider(environment, configuration).get
}
/**
* Provider for the actor system
*/
@Singleton
class ActorSystemProvider @Inject() (environment: Environment, configuration: Configuration) extends Provider[ActorSystem] {
lazy val get: ActorSystem = ActorSystemProvider.start(environment.classLoader, configuration)
}
/**
* Provider for the default flow materializer
*/
@Singleton
class MaterializerProvider @Inject() (actorSystem: ActorSystem) extends Provider[Materializer] {
lazy val get: Materializer = ActorMaterializer()(actorSystem)
}
/**
* Provider for the default execution context
*/
@Singleton
class ExecutionContextProvider @Inject() (actorSystem: ActorSystem) extends Provider[ExecutionContextExecutor] {
def get = actorSystem.dispatcher
}
object ActorSystemProvider {
type StopHook = () => Future[_]
private val logger = LoggerFactory.getLogger(classOf[ActorSystemProvider])
case object ApplicationShutdownReason extends CoordinatedShutdown.Reason
/**
* Start an ActorSystem, using the given configuration and ClassLoader.
*
* @return The ActorSystem and a function that can be used to stop it.
*/
def start(classLoader: ClassLoader, config: Configuration): ActorSystem = {
start(classLoader, config, additionalSetup = None)
}
/**
* Start an ActorSystem, using the given configuration, ClassLoader, and additional ActorSystem Setup.
*
* @return The ActorSystem and a function that can be used to stop it.
*/
def start(classLoader: ClassLoader, config: Configuration, additionalSetup: Setup): ActorSystem = {
start(classLoader, config, Some(additionalSetup))
}
private def start(classLoader: ClassLoader, config: Configuration, additionalSetup: Option[Setup]): ActorSystem = {
val akkaConfig: Config = {
val akkaConfigRoot = config.get[String]("play.akka.config")
// normalize timeout values for Akka's use
// TODO: deprecate this setting (see https://github.com/playframework/playframework/issues/8442)
val playTimeoutKey = "play.akka.shutdown-timeout"
val playTimeoutDuration = Try(config.get[Duration](playTimeoutKey)).getOrElse(Duration.Inf)
// Typesafe config used internally by Akka doesn't support "infinite".
// Also, the value expected is an integer so can't use Long.MaxValue.
// Finally, Akka requires the delay to be less than a certain threshold.
val akkaMaxDelay = Int.MaxValue / 1000
val akkaMaxDuration = Duration(akkaMaxDelay, "seconds")
val normalisedDuration =
if (playTimeoutDuration > akkaMaxDuration) akkaMaxDuration else playTimeoutDuration
val akkaTimeoutKey = "akka.coordinated-shutdown.phases.actor-system-terminate.timeout"
config.get[Config](akkaConfigRoot)
// Need to fallback to root config so we can lookup dispatchers defined outside the main namespace
.withFallback(config.underlying)
// Need to manually merge and override akkaTimeoutKey because `null` is meaningful in playTimeoutKey
.withValue(
akkaTimeoutKey,
ConfigValueFactory.fromAnyRef(java.time.Duration.ofMillis(normalisedDuration.toMillis))
)
}
val name = config.get[String]("play.akka.actor-system")
val bootstrapSetup = BootstrapSetup(Some(classLoader), Some(akkaConfig), None)
val actorSystemSetup = additionalSetup match {
case Some(setup) => ActorSystemSetup(bootstrapSetup, setup)
case None => ActorSystemSetup(bootstrapSetup)
}
val system = ActorSystem(name, actorSystemSetup)
logger.debug(s"Starting application default Akka system: $name")
system
}
}
/**
* Support for creating injected child actors.
*/
trait InjectedActorSupport {
/**
* Create an injected child actor.
*
* @param create A function to create the actor.
* @param name The name of the actor.
* @param props A function to provide props for the actor. The props passed in will just describe how to create the
* actor, this function can be used to provide additional configuration such as router and dispatcher
* configuration.
* @param context The context to create the actor from.
* @return An ActorRef for the created actor.
*/
def injectedChild(create: => Actor, name: String, props: Props => Props = identity)(implicit context: ActorContext): ActorRef = {
context.actorOf(props(Props(create)), name)
}
}
/**
* Provider for creating actor refs
*/
class ActorRefProvider[T <: Actor: ClassTag](name: String, props: Props => Props) extends Provider[ActorRef] {
@Inject private var actorSystem: ActorSystem = _
@Inject private var injector: Injector = _
lazy val get = {
val creation = Props(injector.instanceOf[T])
actorSystem.actorOf(props(creation), name)
}
}
private object CoordinatedShutdownProvider {
private val logger = LoggerFactory.getLogger(classOf[CoordinatedShutdownProvider])
}
/**
* Provider for the coordinated shutdown
*/
@Singleton
class CoordinatedShutdownProvider @Inject() (actorSystem: ActorSystem, applicationLifecycle: ApplicationLifecycle) extends Provider[CoordinatedShutdown] {
import CoordinatedShutdownProvider.logger
lazy val get: CoordinatedShutdown = {
logWarningWhenRunPhaseConfigIsPresent()
val cs = CoordinatedShutdown(actorSystem)
implicit val exCtx: ExecutionContext = actorSystem.dispatcher
// Once the ActorSystem is built we can register the ApplicationLifecycle stopHooks as a CoordinatedShutdown phase.
CoordinatedShutdown(actorSystem).addTask(
CoordinatedShutdown.PhaseServiceStop,
"application-lifecycle-stophook") { () =>
applicationLifecycle.stop().map(_ => Done)
}
cs
}
private def logWarningWhenRunPhaseConfigIsPresent(): Unit = {
val config = actorSystem.settings.config
if (config.hasPath("play.akka.run-cs-from-phase")) {
logger.warn("Configuration 'play.akka.run-cs-from-phase' was deprecated and has no effect. Play now run all the CoordinatedShutdown phases.")
}
}
}
|
Shenker93/playframework
|
framework/src/play/src/main/scala/play/api/libs/concurrent/Akka.scala
|
Scala
|
apache-2.0
| 9,571 |
package monocle.function
import monocle.MonocleSuite
import monocle.refined._
import monocle.refined.all._
import shapeless.test.illTyped
import eu.timepit.refined.auto._
import scala.collection.immutable.SortedMap
class AtExample extends MonocleSuite {
test("at creates a Lens from a Map, SortedMap to an optional value") {
assertEquals(Map("One" -> 2, "Two" -> 2).focus().at("Two").get, Some(2))
assertEquals(SortedMap("One" -> 2, "Two" -> 2).focus().at("Two").get, Some(2))
assertEquals(Map("One" -> 1, "Two" -> 2).focus().at("One").replace(Some(-1)), Map("One" -> -1, "Two" -> 2))
// can delete a value
assertEquals(Map("One" -> 1, "Two" -> 2).focus().at("Two").replace(None), Map("One" -> 1))
// add a new value
assertEquals(
Map("One" -> 1, "Two" -> 2).focus().at("Three").replace(Some(3)),
Map(
"One" -> 1,
"Two" -> 2,
"Three" -> 3
)
)
}
test("at creates a Lens from a Set to an optional element of the Set") {
assertEquals(Set(1, 2, 3).focus().at(2).get, true)
assertEquals(Set(1, 2, 3).focus().at(4).get, false)
assertEquals(Set(1, 2, 3).focus().at(4).replace(true), Set(1, 2, 3, 4))
assertEquals(Set(1, 2, 3).focus().at(2).replace(false), Set(1, 3))
}
test("at creates a Lens from Int to one of its bit") {
assertEquals(3.focus().at(0: IntBits).get, true) // true means bit is 1
assertEquals(4.focus().at(0: IntBits).get, false) // false means bit is 0
assertEquals(32.focus().at(0: IntBits).replace(true), 33)
assertEquals(3.focus().at(1: IntBits).modify(!_), 1) // toggle 2nd bit
illTyped("""0 applyLens at(79: IntBits) get""", "Right predicate.*fail.*")
illTyped("""0 applyLens at(-1: IntBits) get""", "Left predicate.*fail.*")
}
test("at creates a Lens from Char to one of its bit") {
assertEquals('x'.focus().at(0: CharBits).get, false)
assertEquals('x'.focus().at(0: CharBits).replace(true), 'y')
}
test("remove deletes an element of a Map") {
assertEquals(remove("Foo")(Map("Foo" -> 1, "Bar" -> 2)), Map("Bar" -> 2))
}
}
|
julien-truffaut/Monocle
|
example/src/test/scala/monocle/function/AtExample.scala
|
Scala
|
mit
| 2,103 |
package sbt
package mavenint
import org.apache.ivy.core.module.id.ModuleRevisionId
import org.apache.ivy.core.settings.IvySettings
import org.eclipse.aether.artifact.{ DefaultArtifact => AetherArtifact }
import org.eclipse.aether.installation.{ InstallRequest => AetherInstallRequest }
import org.eclipse.aether.metadata.{ DefaultMetadata, Metadata }
import org.eclipse.aether.resolution.{
ArtifactDescriptorRequest => AetherDescriptorRequest,
ArtifactRequest => AetherArtifactRequest,
MetadataRequest => AetherMetadataRequest,
VersionRequest => AetherVersionRequest,
VersionRangeRequest => AetherVersionRangeRequest
}
import sbt.internal.librarymanagement.ivyint.CustomMavenResolver
import sbt.librarymanagement.MavenCache
import scala.collection.JavaConverters._
import sbt.io.IO
/**
* A resolver instance which can resolve from a maven CACHE.
*
* Note: This should never hit somethign remote, as it just looks in the maven cache for things already resolved.
*/
class MavenCacheRepositoryResolver(val repo: MavenCache, settings: IvySettings)
extends MavenRepositoryResolver(settings) with CustomMavenResolver {
setName(repo.name)
protected val system = MavenRepositorySystemFactory.newRepositorySystemImpl
IO.createDirectory(repo.rootFile)
protected val session = MavenRepositorySystemFactory.newSessionImpl(system, repo.rootFile)
protected def setRepository(request: AetherMetadataRequest): AetherMetadataRequest = request
protected def addRepositories(request: AetherDescriptorRequest): AetherDescriptorRequest = request
protected def addRepositories(request: AetherArtifactRequest): AetherArtifactRequest = request
protected def addRepositories(request: AetherVersionRequest): AetherVersionRequest = request
protected def addRepositories(request: AetherVersionRangeRequest): AetherVersionRangeRequest = request
protected def publishArtifacts(artifacts: Seq[AetherArtifact]): Unit = {
val request = new AetherInstallRequest()
artifacts foreach request.addArtifact
system.install(session, request)
}
// TODO - Share this with non-local repository code, since it's MOSTLY the same.
protected def getPublicationTime(mrid: ModuleRevisionId): Option[Long] = {
val metadataRequest = new AetherMetadataRequest()
metadataRequest.setMetadata(
new DefaultMetadata(
mrid.getOrganisation,
mrid.getName,
mrid.getRevision,
MavenRepositoryResolver.MAVEN_METADATA_XML,
Metadata.Nature.RELEASE_OR_SNAPSHOT))
val metadataResultOpt =
try system.resolveMetadata(session, java.util.Arrays.asList(metadataRequest)).asScala.headOption
catch {
case e: org.eclipse.aether.resolution.ArtifactResolutionException => None
}
try metadataResultOpt match {
case Some(md) if md.isResolved =>
import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader
import org.codehaus.plexus.util.ReaderFactory
val readMetadata = {
val reader = ReaderFactory.newXmlReader(md.getMetadata.getFile)
try new MetadataXpp3Reader().read(reader, false)
finally reader.close()
}
val timestampOpt =
for {
v <- Option(readMetadata.getVersioning)
sp <- Option(v.getSnapshot)
ts <- Option(sp.getTimestamp)
t <- MavenRepositoryResolver.parseTimeString(ts)
} yield t
val lastUpdatedOpt =
for {
v <- Option(readMetadata.getVersioning)
lu <- Option(v.getLastUpdated)
d <- MavenRepositoryResolver.parseTimeString(lu)
} yield d
// TODO - Only look at timestamp *IF* the version is for a snapshot.
timestampOpt orElse lastUpdatedOpt
case _ => None
}
}
override def toString = s"${repo.name}: ${repo.root}"
}
|
dansanduleac/sbt
|
sbt-maven-resolver/src/main/scala/sbt/mavenint/MavenCacheRepositoryResolver.scala
|
Scala
|
bsd-3-clause
| 3,854 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.execution
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{execution, Row, SQLConf}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.{Ascending, Attribute, Literal, SortOrder}
import org.apache.spark.sql.catalyst.plans._
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.plans.physical._
import org.apache.spark.sql.execution.joins.{BroadcastHashJoin, ShuffledHashJoin}
import org.apache.spark.sql.functions._
import org.apache.spark.sql.test.SharedSQLContext
import org.apache.spark.sql.types._
class PlannerSuite extends SharedSQLContext {
import testImplicits._
setupTestData()
private def testPartialAggregationPlan(query: LogicalPlan): Unit = {
val planner = sqlContext.planner
import planner._
val plannedOption = HashAggregation(query).headOption.orElse(Aggregation(query).headOption)
val planned =
plannedOption.getOrElse(
fail(s"Could query play aggregation query $query. Is it an aggregation query?"))
val aggregations = planned.collect { case n if n.nodeName contains "Aggregate" => n }
// For the new aggregation code path, there will be three aggregate operator for
// distinct aggregations.
assert(
aggregations.size == 2 || aggregations.size == 3,
s"The plan of query $query does not have partial aggregations.")
}
test("unions are collapsed") {
val planner = sqlContext.planner
import planner._
val query = testData.unionAll(testData).unionAll(testData).logicalPlan
val planned = BasicOperators(query).head
val logicalUnions = query collect { case u: logical.Union => u }
val physicalUnions = planned collect { case u: execution.Union => u }
assert(logicalUnions.size === 2)
assert(physicalUnions.size === 1)
}
test("count is partially aggregated") {
val query = testData.groupBy('value).agg(count('key)).queryExecution.analyzed
testPartialAggregationPlan(query)
}
test("count distinct is partially aggregated") {
val query = testData.groupBy('value).agg(countDistinct('key)).queryExecution.analyzed
testPartialAggregationPlan(query)
}
test("mixed aggregates are partially aggregated") {
val query =
testData.groupBy('value).agg(count('value), countDistinct('key)).queryExecution.analyzed
testPartialAggregationPlan(query)
}
test("sizeInBytes estimation of limit operator for broadcast hash join optimization") {
def checkPlan(fieldTypes: Seq[DataType]): Unit = {
withTempTable("testLimit") {
val fields = fieldTypes.zipWithIndex.map {
case (dataType, index) => StructField(s"c${index}", dataType, true)
} :+ StructField("key", IntegerType, true)
val schema = StructType(fields)
val row = Row.fromSeq(Seq.fill(fields.size)(null))
val rowRDD = sparkContext.parallelize(row :: Nil)
sqlContext.createDataFrame(rowRDD, schema).registerTempTable("testLimit")
val planned = sql(
"""
|SELECT l.a, l.b
|FROM testData2 l JOIN (SELECT * FROM testLimit LIMIT 1) r ON (l.a = r.key)
""".stripMargin).queryExecution.executedPlan
val broadcastHashJoins = planned.collect { case join: BroadcastHashJoin => join }
val shuffledHashJoins = planned.collect { case join: ShuffledHashJoin => join }
assert(broadcastHashJoins.size === 1, "Should use broadcast hash join")
assert(shuffledHashJoins.isEmpty, "Should not use shuffled hash join")
}
}
val simpleTypes =
NullType ::
BooleanType ::
ByteType ::
ShortType ::
IntegerType ::
LongType ::
FloatType ::
DoubleType ::
DecimalType(10, 5) ::
DecimalType.SYSTEM_DEFAULT ::
DateType ::
TimestampType ::
StringType ::
BinaryType :: Nil
withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "16434") {
checkPlan(simpleTypes)
}
val complexTypes =
ArrayType(DoubleType, true) ::
ArrayType(StringType, false) ::
MapType(IntegerType, StringType, true) ::
MapType(IntegerType, ArrayType(DoubleType), false) ::
StructType(Seq(
StructField("a", IntegerType, nullable = true),
StructField("b", ArrayType(DoubleType), nullable = false),
StructField("c", DoubleType, nullable = false))) :: Nil
withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "901617") {
checkPlan(complexTypes)
}
}
test("InMemoryRelation statistics propagation") {
withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "81920") {
withTempTable("tiny") {
testData.limit(3).registerTempTable("tiny")
sql("CACHE TABLE tiny")
val a = testData.as("a")
val b = sqlContext.table("tiny").as("b")
val planned = a.join(b, $"a.key" === $"b.key").queryExecution.executedPlan
val broadcastHashJoins = planned.collect { case join: BroadcastHashJoin => join }
val shuffledHashJoins = planned.collect { case join: ShuffledHashJoin => join }
assert(broadcastHashJoins.size === 1, "Should use broadcast hash join")
assert(shuffledHashJoins.isEmpty, "Should not use shuffled hash join")
sqlContext.clearCache()
}
}
}
test("efficient limit -> project -> sort") {
{
val query =
testData.select('key, 'value).sort('key).limit(2).logicalPlan
val planned = sqlContext.planner.TakeOrderedAndProject(query)
assert(planned.head.isInstanceOf[execution.TakeOrderedAndProject])
assert(planned.head.output === testData.select('key, 'value).logicalPlan.output)
}
{
// We need to make sure TakeOrderedAndProject's output is correct when we push a project
// into it.
val query =
testData.select('key, 'value).sort('key).select('value, 'key).limit(2).logicalPlan
val planned = sqlContext.planner.TakeOrderedAndProject(query)
assert(planned.head.isInstanceOf[execution.TakeOrderedAndProject])
assert(planned.head.output === testData.select('value, 'key).logicalPlan.output)
}
}
test("PartitioningCollection") {
withTempTable("normal", "small", "tiny") {
testData.registerTempTable("normal")
testData.limit(10).registerTempTable("small")
testData.limit(3).registerTempTable("tiny")
// Disable broadcast join
withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
{
val numExchanges = sql(
"""
|SELECT *
|FROM
| normal JOIN small ON (normal.key = small.key)
| JOIN tiny ON (small.key = tiny.key)
""".stripMargin
).queryExecution.executedPlan.collect {
case exchange: Exchange => exchange
}.length
assert(numExchanges === 3)
}
{
// This second query joins on different keys:
val numExchanges = sql(
"""
|SELECT *
|FROM
| normal JOIN small ON (normal.key = small.key)
| JOIN tiny ON (normal.key = tiny.key)
""".stripMargin
).queryExecution.executedPlan.collect {
case exchange: Exchange => exchange
}.length
assert(numExchanges === 3)
}
}
}
}
// --- Unit tests of EnsureRequirements ---------------------------------------------------------
// When it comes to testing whether EnsureRequirements properly ensures distribution requirements,
// there two dimensions that need to be considered: are the child partitionings compatible and
// do they satisfy the distribution requirements? As a result, we need at least four test cases.
private def assertDistributionRequirementsAreSatisfied(outputPlan: SparkPlan): Unit = {
if (outputPlan.children.length > 1
&& outputPlan.requiredChildDistribution.toSet != Set(UnspecifiedDistribution)) {
val childPartitionings = outputPlan.children.map(_.outputPartitioning)
if (!Partitioning.allCompatible(childPartitionings)) {
fail(s"Partitionings are not compatible: $childPartitionings")
}
}
outputPlan.children.zip(outputPlan.requiredChildDistribution).foreach {
case (child, requiredDist) =>
assert(child.outputPartitioning.satisfies(requiredDist),
s"$child output partitioning does not satisfy $requiredDist:\\n$outputPlan")
}
}
test("EnsureRequirements with incompatible child partitionings which satisfy distribution") {
// Consider an operator that requires inputs that are clustered by two expressions (e.g.
// sort merge join where there are multiple columns in the equi-join condition)
val clusteringA = Literal(1) :: Nil
val clusteringB = Literal(2) :: Nil
val distribution = ClusteredDistribution(clusteringA ++ clusteringB)
// Say that the left and right inputs are each partitioned by _one_ of the two join columns:
val leftPartitioning = HashPartitioning(clusteringA, 1)
val rightPartitioning = HashPartitioning(clusteringB, 1)
// Individually, each input's partitioning satisfies the clustering distribution:
assert(leftPartitioning.satisfies(distribution))
assert(rightPartitioning.satisfies(distribution))
// However, these partitionings are not compatible with each other, so we still need to
// repartition both inputs prior to performing the join:
assert(!leftPartitioning.compatibleWith(rightPartitioning))
assert(!rightPartitioning.compatibleWith(leftPartitioning))
val inputPlan = DummySparkPlan(
children = Seq(
DummySparkPlan(outputPartitioning = leftPartitioning),
DummySparkPlan(outputPartitioning = rightPartitioning)
),
requiredChildDistribution = Seq(distribution, distribution),
requiredChildOrdering = Seq(Seq.empty, Seq.empty)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case Exchange(_, _) => true }.isEmpty) {
fail(s"Exchange should have been added:\\n$outputPlan")
}
}
test("EnsureRequirements with child partitionings with different numbers of output partitions") {
// This is similar to the previous test, except it checks that partitionings are not compatible
// unless they produce the same number of partitions.
val clustering = Literal(1) :: Nil
val distribution = ClusteredDistribution(clustering)
val inputPlan = DummySparkPlan(
children = Seq(
DummySparkPlan(outputPartitioning = HashPartitioning(clustering, 1)),
DummySparkPlan(outputPartitioning = HashPartitioning(clustering, 2))
),
requiredChildDistribution = Seq(distribution, distribution),
requiredChildOrdering = Seq(Seq.empty, Seq.empty)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
}
test("EnsureRequirements with compatible child partitionings that do not satisfy distribution") {
val distribution = ClusteredDistribution(Literal(1) :: Nil)
// The left and right inputs have compatible partitionings but they do not satisfy the
// distribution because they are clustered on different columns. Thus, we need to shuffle.
val childPartitioning = HashPartitioning(Literal(2) :: Nil, 1)
assert(!childPartitioning.satisfies(distribution))
val inputPlan = DummySparkPlan(
children = Seq(
DummySparkPlan(outputPartitioning = childPartitioning),
DummySparkPlan(outputPartitioning = childPartitioning)
),
requiredChildDistribution = Seq(distribution, distribution),
requiredChildOrdering = Seq(Seq.empty, Seq.empty)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case Exchange(_, _) => true }.isEmpty) {
fail(s"Exchange should have been added:\\n$outputPlan")
}
}
test("EnsureRequirements with compatible child partitionings that satisfy distribution") {
// In this case, all requirements are satisfied and no exchange should be added.
val distribution = ClusteredDistribution(Literal(1) :: Nil)
val childPartitioning = HashPartitioning(Literal(1) :: Nil, 5)
assert(childPartitioning.satisfies(distribution))
val inputPlan = DummySparkPlan(
children = Seq(
DummySparkPlan(outputPartitioning = childPartitioning),
DummySparkPlan(outputPartitioning = childPartitioning)
),
requiredChildDistribution = Seq(distribution, distribution),
requiredChildOrdering = Seq(Seq.empty, Seq.empty)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case Exchange(_, _) => true }.nonEmpty) {
fail(s"Exchange should not have been added:\\n$outputPlan")
}
}
// This is a regression test for SPARK-9703
test("EnsureRequirements should not repartition if only ordering requirement is unsatisfied") {
// Consider an operator that imposes both output distribution and ordering requirements on its
// children, such as sort sort merge join. If the distribution requirements are satisfied but
// the output ordering requirements are unsatisfied, then the planner should only add sorts and
// should not need to add additional shuffles / exchanges.
val outputOrdering = Seq(SortOrder(Literal(1), Ascending))
val distribution = ClusteredDistribution(Literal(1) :: Nil)
val inputPlan = DummySparkPlan(
children = Seq(
DummySparkPlan(outputPartitioning = SinglePartition),
DummySparkPlan(outputPartitioning = SinglePartition)
),
requiredChildDistribution = Seq(distribution, distribution),
requiredChildOrdering = Seq(outputOrdering, outputOrdering)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case Exchange(_, _) => true }.nonEmpty) {
fail(s"No Exchanges should have been added:\\n$outputPlan")
}
}
test("EnsureRequirements adds sort when there is no existing ordering") {
val orderingA = SortOrder(Literal(1), Ascending)
val orderingB = SortOrder(Literal(2), Ascending)
assert(orderingA != orderingB)
val inputPlan = DummySparkPlan(
children = DummySparkPlan(outputOrdering = Seq.empty) :: Nil,
requiredChildOrdering = Seq(Seq(orderingB)),
requiredChildDistribution = Seq(UnspecifiedDistribution)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case s: TungstenSort => true; case s: Sort => true }.isEmpty) {
fail(s"Sort should have been added:\\n$outputPlan")
}
}
test("EnsureRequirements skips sort when required ordering is prefix of existing ordering") {
val orderingA = SortOrder(Literal(1), Ascending)
val orderingB = SortOrder(Literal(2), Ascending)
assert(orderingA != orderingB)
val inputPlan = DummySparkPlan(
children = DummySparkPlan(outputOrdering = Seq(orderingA, orderingB)) :: Nil,
requiredChildOrdering = Seq(Seq(orderingA)),
requiredChildDistribution = Seq(UnspecifiedDistribution)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case s: TungstenSort => true; case s: Sort => true }.nonEmpty) {
fail(s"No sorts should have been added:\\n$outputPlan")
}
}
// This is a regression test for SPARK-11135
test("EnsureRequirements adds sort when required ordering isn't a prefix of existing ordering") {
val orderingA = SortOrder(Literal(1), Ascending)
val orderingB = SortOrder(Literal(2), Ascending)
assert(orderingA != orderingB)
val inputPlan = DummySparkPlan(
children = DummySparkPlan(outputOrdering = Seq(orderingA)) :: Nil,
requiredChildOrdering = Seq(Seq(orderingA, orderingB)),
requiredChildDistribution = Seq(UnspecifiedDistribution)
)
val outputPlan = EnsureRequirements(sqlContext).apply(inputPlan)
assertDistributionRequirementsAreSatisfied(outputPlan)
if (outputPlan.collect { case s: TungstenSort => true; case s: Sort => true }.isEmpty) {
fail(s"Sort should have been added:\\n$outputPlan")
}
}
// ---------------------------------------------------------------------------------------------
}
// Used for unit-testing EnsureRequirements
private case class DummySparkPlan(
override val children: Seq[SparkPlan] = Nil,
override val outputOrdering: Seq[SortOrder] = Nil,
override val outputPartitioning: Partitioning = UnknownPartitioning(0),
override val requiredChildDistribution: Seq[Distribution] = Nil,
override val requiredChildOrdering: Seq[Seq[SortOrder]] = Nil
) extends SparkPlan {
override protected def doExecute(): RDD[InternalRow] = throw new NotImplementedError
override def output: Seq[Attribute] = Seq.empty
}
|
pronix/spark
|
sql/core/src/test/scala/org/apache/spark/sql/execution/PlannerSuite.scala
|
Scala
|
apache-2.0
| 18,138 |
package amora.api
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.charset.StandardCharsets
import org.apache.jena.query.QueryExecutionFactory
import org.apache.jena.query.QueryFactory
import org.apache.jena.query.QuerySolution
import org.apache.jena.query.ResultSetFactory
import org.apache.jena.query.ResultSetFormatter
import org.apache.jena.query.ResultSetRewindable
import org.apache.jena.rdf.model.{ Literal ⇒ JLiteral }
import org.apache.jena.rdf.model.Model
final class SparqlQuery(val query: String) {
def runOnModel(model: SparqlModel): SparqlResultSet = {
val qexec = QueryExecutionFactory.create(QueryFactory.create(query), model.model)
new SparqlResultSet(ResultSetFactory.makeRewindable(qexec.execSelect()))
}
def askOnModel(model: SparqlModel): Boolean = {
val qexec = QueryExecutionFactory.create(QueryFactory.create(query), model.model)
qexec.execAsk()
}
override def toString = query
}
final class SparqlResultSet(val resultSet: ResultSetRewindable) {
def asStringTable: String = {
val s = new ByteArrayOutputStream
ResultSetFormatter.out(s, resultSet)
val ret = new String(s.toByteArray(), StandardCharsets.UTF_8)
resultSet.reset()
ret
}
def map[A](f: ResultSetRow ⇒ A): Seq[A] = {
import scala.collection.JavaConverters._
val ret = resultSet.asScala.map(row ⇒ f(new ResultSetRow(row))).toList
resultSet.reset()
ret
}
def foreach(f: ResultSetRow ⇒ Unit): Unit = {
import scala.collection.JavaConverters._
resultSet.asScala.foreach(row ⇒ f(new ResultSetRow(row)))
resultSet.reset()
}
}
final class SparqlModel(val model: Model) {
def difference(model: SparqlModel): SparqlModel = {
new SparqlModel(this.model.difference(model.model))
}
def formatAs(format: RdfFormat): String = {
val out = new ByteArrayOutputStream
model.write(out, format.lang)
new String(out.toByteArray(), "UTF-8")
}
def writeAs(format: RdfFormat, data: String): SparqlModel = {
val in = new ByteArrayInputStream(data.getBytes)
model.read(in, /* base = */ null, format.lang)
this
}
}
final class ResultSetRow(val row: QuerySolution) {
def string(varName: String): String =
get(varName).asLiteral.getString
def int(varName: String): Int =
get(varName).asLiteral.getInt
def long(varName: String): Long =
get(varName).asLiteral.getLong
def boolean(varName: String): Boolean =
get(varName).asLiteral.getBoolean
def double(varName: String): Double =
get(varName).asLiteral.getDouble
def float(varName: String): Float =
get(varName).asLiteral.getFloat
def char(varName: String): Char =
get(varName).asLiteral.getChar
def byte(varName: String): Byte =
get(varName).asLiteral.getByte
def uri(varName: String): String = {
val v = get(varName)
if (v.isLiteral())
throw new IllegalStateException(s"Value of variable name `$varName` is not an URI, it is of type: ${v.asLiteral().getDatatypeURI}.")
if (v.isAnon())
s"<_:$v>"
else
s"<$v>"
}
def literal(varName: String): Literal = {
val v = get(varName)
if (v.isLiteral())
Literal(v.asLiteral())
else
throw new IllegalArgumentException(s"The variable `$varName` does not contain a literal.")
}
private def get(varName: String) = {
val v = row.get(varName)
if (v == null)
throw new IllegalArgumentException(s"The variable `$varName` does not exist in the result set.")
v
}
}
final case class Literal(literal: JLiteral) {
def string: String = literal.getString
def int: Int = literal.getInt
def long: Long = literal.getLong
def boolean: Boolean = literal.getBoolean
def double: Double = literal.getDouble
def float: Float = literal.getFloat
def char: Char = literal.getChar
def byte: Byte = literal.getByte
def stringOpt: Option[String] =
if (literal.getDatatype.getURI() == "http://www.w3.org/2001/XMLSchema#string")
Some(string)
else
None
}
sealed trait RdfFormat {
def lang: String
}
case object Turtle extends RdfFormat {
override def lang = "TURTLE"
}
case object NTriple extends RdfFormat {
override def lang = "N-TRIPLE"
}
|
sschaef/tooling-research
|
backend/src/main/scala/amora/api/Api.scala
|
Scala
|
mit
| 4,234 |
package org.nkvoll.javabin.service
import akka.actor.{ Actor, ActorLogging }
import akka.pattern.pipe
import org.elasticsearch.action.index.IndexRequest
import org.elasticsearch.client.Client
import org.elasticsearch.index.query.QueryBuilders
import org.elasticsearch.indices.IndexMissingException
import org.nkvoll.javabin.json.UserProtocol
import org.nkvoll.javabin.metrics.{ FutureMetrics, Instrumented }
import org.nkvoll.javabin.models.User
import org.nkvoll.javabin.service.internal.ElasticsearchEnrichments._
import org.nkvoll.javabin.util.Command
import scala.concurrent.Future
import spray.json._
class UserService(client: Client, builtinUsers: Map[String, User]) extends Actor with ActorLogging with UserProtocol with FutureMetrics {
val indexName = "users"
val typeName = "user"
import UserService._
import context.dispatcher
def receive = {
case cmd @ AddUser(user) => addTimer.timedFuture {
client.prepareIndex(indexName, typeName, user.username)
.setOpType(IndexRequest.OpType.CREATE)
.setSource(user.toJson.compactPrint)
.executeAsScala()
.map(_ => cmd.reply(user))
.pipeTo(sender)
}
case cmd @ RemoveUser(user) => removeTimer.timedFuture {
client.prepareDelete(indexName, typeName, user.username)
.executeAsScala()
.map(_ => cmd.reply(user))
.pipeTo(sender)
}
case cmd @ UpdateUser(user) => updateTimer.timedFuture {
client.prepareUpdate(indexName, typeName, user.username)
.setDoc(user.toJson.compactPrint)
.executeAsScala()
.map(_ => cmd.reply(user))
.pipeTo(sender)
}
case cmd @ GetUser(username) => getTimer.timedFuture {
val futureUser = builtinUsers.get(username).fold(getUser(username))(Future.successful)
futureUser
.map(_.withoutPassword)
.map(cmd.reply)
.pipeTo(sender)
}
case cmd @ AuthenticateUser(username, password) => getTimer.timedFuture {
val futureUser = builtinUsers.get(username).fold(getUser(username))(Future.successful)
futureUser
.map(user =>
if (!user.checkPassword(password))
throw new PasswordVerificationException(s"invalid password for user ${user.username}")
else user)
.map(_.withoutPassword)
.map(cmd.reply)
.pipeTo(sender)
}
case cmd @ FindUsers(queryString: String) => findTimer.timedFuture {
val query = if (queryString == "*" || queryString.isEmpty) QueryBuilders.matchAllQuery() else QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery("username.ngram", queryString).fuzziness("AUTO"))
.should(QueryBuilders.matchQuery("username", queryString))
.should(QueryBuilders.simpleQueryString(queryString).field("username"))
client.prepareSearch(indexName).setTypes(typeName).setQuery(query).setPreference("_local").executeAsScala()
.map(res => res.getHits.hits())
.map(hits => hits.map(hit => hit.sourceAsString().parseJson.convertTo[User]))
.recover { case _: IndexMissingException => Array.empty[User] }
.map(users => cmd.reply(users.toSeq))
.pipeTo(sender)
}
}
def getUser(username: String): Future[User] = client.prepareGet(indexName, typeName, username)
.executeAsScala()
.map(res => res.getSourceAsString.parseJson.convertTo[User])
}
object UserService extends UserProtocol with Instrumented {
val addTimer = metrics.timer("addUser")
val removeTimer = metrics.timer("removeUser")
val updateTimer = metrics.timer("updateUser")
val getTimer = metrics.timer("getUser")
val findTimer = metrics.timer("findTimer")
case class AddUser(user: User) extends Command[User]
case class RemoveUser(user: User) extends Command[User]
case class UpdateUser(user: User) extends Command[User]
case class GetUser(username: String) extends Command[User]
case class AuthenticateUser(username: String, password: String) extends Command[User]
class PasswordVerificationException(msg: String) extends RuntimeException
case class FindUsers(query: String) extends Command[Users] {
def reply(users: Seq[User]) = Users(users)
}
case class Users(users: Seq[User]) {
def toUsernames = Usernames(users.map(_.username))
}
case class Usernames(users: Seq[String])
}
|
nkvoll/javabin-rest-on-akka
|
src/main/scala/org/nkvoll/javabin/service/UserService.scala
|
Scala
|
mit
| 4,321 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.execution.datasources.jdbc
import org.apache.spark.sql.{AnalysisException, DataFrame, SaveMode, SQLContext}
import org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils._
import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, DataSourceRegister, RelationProvider}
class JdbcRelationProvider extends CreatableRelationProvider
with RelationProvider with DataSourceRegister {
override def shortName(): String = "jdbc"
override def createRelation(
sqlContext: SQLContext,
parameters: Map[String, String]): BaseRelation = {
val jdbcOptions = new JDBCOptions(parameters)
val partitionColumn = jdbcOptions.partitionColumn
val lowerBound = jdbcOptions.lowerBound
val upperBound = jdbcOptions.upperBound
val numPartitions = jdbcOptions.numPartitions
val partitionInfo = if (partitionColumn.isEmpty) {
assert(lowerBound.isEmpty && upperBound.isEmpty)
null
} else {
assert(lowerBound.nonEmpty && upperBound.nonEmpty && numPartitions.nonEmpty)
JDBCPartitioningInfo(
partitionColumn.get, lowerBound.get, upperBound.get, numPartitions.get)
}
val parts = JDBCRelation.columnPartition(partitionInfo)
JDBCRelation(parts, jdbcOptions)(sqlContext.sparkSession)
}
override def createRelation(
sqlContext: SQLContext,
mode: SaveMode,
parameters: Map[String, String],
df: DataFrame): BaseRelation = {
val options = new JDBCOptions(parameters)
val isCaseSensitive = sqlContext.conf.caseSensitiveAnalysis
val conn = JdbcUtils.createConnectionFactory(options)()
try {
val tableExists = JdbcUtils.tableExists(conn, options)
if (tableExists) {
mode match {
case SaveMode.Overwrite =>
if (options.isTruncate && isCascadingTruncateTable(options.url) == Some(false)) {
// In this case, we should truncate table and then load.
truncateTable(conn, options.table)
val tableSchema = JdbcUtils.getSchemaOption(conn, options)
saveTable(df, tableSchema, isCaseSensitive, options)
} else {
// Otherwise, do not truncate the table, instead drop and recreate it
dropTable(conn, options.table)
createTable(conn, df, options)
saveTable(df, Some(df.schema), isCaseSensitive, options)
}
case SaveMode.Append =>
val tableSchema = JdbcUtils.getSchemaOption(conn, options)
saveTable(df, tableSchema, isCaseSensitive, options)
case SaveMode.ErrorIfExists =>
throw new AnalysisException(
s"Table or view '${options.table}' already exists. SaveMode: ErrorIfExists.")
case SaveMode.Ignore =>
// With `SaveMode.Ignore` mode, if table already exists, the save operation is expected
// to not save the contents of the DataFrame and to not change the existing data.
// Therefore, it is okay to do nothing here and then just return the relation below.
}
} else {
createTable(conn, df, options)
saveTable(df, Some(df.schema), isCaseSensitive, options)
}
} finally {
conn.close()
}
createRelation(sqlContext, parameters)
}
}
|
aokolnychyi/spark
|
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcRelationProvider.scala
|
Scala
|
apache-2.0
| 4,120 |
package models
import scala.xml._
import scala.util.control.Exception._
import scala.util._
import play.api.libs.json._
import play.api.Play.current
object WikiRead{
val baseUrl = "http://en.wikipedia.org"
case class BirdPage(name: String, sci: String, url: String)
def birdPages(nodes: NodeSeq) = {
for(node <- nodes; a <- (node \\ "a");
h <- a \\ "@href"; sci <- node \\ "i") yield BirdPage(a.text, sci.text, h.text)
}
def getBirds(url: String) = birdPages(XML.load(url) \\\\ "li")
def infobox(node: Node) = ((node \\ "@class").headOption map (_.text)) == Some("infobox biota")
def infoTable(node: Node) = (node \\\\ "table" filter infobox).head
def birdPage(url: String) = XML.load(baseUrl+url)
def birdImg(node: Node) = ((infoTable(node) \\\\ "img").head \\"@src").head.text
def birdImage(url:String) = Try {birdImg(birdPage(url))} getOrElse("")
def birdTaxon(node: Node, taxon: String = "family") = {
val taxa = infoTable(node) \\\\ "table" \\\\ "td" \\\\ "span"
(for (taxnode <- taxa if ((taxnode \\ "@class").headOption == Some(taxon))) yield (taxnode \\ "a").head.text).head
}
val eg = <li><a href="/wiki/Fulvous_Whistling-Duck" title="Fulvous Whistling-Duck" class="mw-redirect">Fulvous Whistling-Duck</a> <i>Dendrocygna bicolor</i></li>
val egBird = BirdPage("Fulvous Whistling-Duck", "Dendrocygna bicolor", "/wiki/Fulvous_Whistling-Duck")
lazy val birdsJson = {val url = "http://en.wikipedia.org/wiki/List_of_birds_of_India"
val nodes = (XML.load(url) \\\\ "li").toList
for(node <- nodes;
a <- (node \\ "a");
h <- a \\ "@href"; sci <- node \\ "i") yield {println(a.text); JsObject(List(
"name" -> JsString(a.text),
"sci" -> JsString(sci.text),
"url" -> JsString(h.text),
"img" -> JsString(birdImage(h.text))))}
}
lazy val birdsRawTest = {val url = "http://en.wikipedia.org/wiki/List_of_birds_of_India"
val nodes = (XML.load(url) \\\\ "li").take(80).toList
for(node <- nodes;
a <- (node \\ "a");
h <- a \\ "@href"; sci <- node \\ "i") yield {println(a.text); JsObject(List(
"name" -> JsString(a.text),
"sci" -> JsString(sci.text),
"url" -> JsString(h.text),
"img" -> JsString(birdImage(h.text))))}
}
lazy val birdsJsonTest = Json.toJson(birdsRawTest)
}
|
siddhartha-gadgil/AppyBirdDay
|
app/models/WikiRead.scala
|
Scala
|
mit
| 2,871 |
package ee.cone.c4proto
object BigDecimalFactory {
def apply(scale: Int, bytes: okio.ByteString): BigDecimal =
BigDecimal(new java.math.BigDecimal(new java.math.BigInteger(bytes.toByteArray), scale))
def unapply(value: BigDecimal): Option[(Int,okio.ByteString)] = {
val byteString = ToByteString(value.bigDecimal.unscaledValue.toByteArray)
Option((value.bigDecimal.scale, byteString))
}
}
trait BigDecimalProtocolAdd {
type BigDecimal = scala.math.BigDecimal
val BigDecimalFactory = ee.cone.c4proto.BigDecimalFactory
}
@protocol object BigDecimalProtocolBase extends BigDecimalProtocolAdd {
case class SysBigDecimal(@Id(0x0001) scale: Int, @Id(0x0002) bytes: okio.ByteString)
}
|
wregs/c4proto
|
c4proto-types/src/main/scala/ee/cone/c4proto/BigDecimal.scala
|
Scala
|
apache-2.0
| 707 |
package com.giyeok.jparser.studio2
import com.giyeok.jparser.ParsingErrors.ParsingError
import com.giyeok.jparser.metalang3a.MetaLanguage3.ProcessedGrammar
import com.giyeok.jparser.metalang3a.ValuefyExprSimulator
import com.giyeok.jparser.nparser.ParseTreeUtil.expectedTermsFrom
import com.giyeok.jparser.nparser.Parser.NaiveContext
import com.giyeok.jparser.nparser.{NaiveParser, ParseTreeUtil, ParsingContext}
import com.giyeok.jparser.studio2.CodeEditor.CodeStyle
import com.giyeok.jparser.studio2.Utils.setMainAndBottomLayout
import com.giyeok.jparser.visualize.utils.HorizontalResizableSplittedComposite
import com.giyeok.jparser.visualize.{NodeFigureGenerators, ParseTreeViewer, ParsingProcessVisualizer, ZestParsingContextWidget}
import com.giyeok.jparser.{Inputs, NGrammar, ParseForest, ParsingErrors}
import io.reactivex.rxjava3.core.{Observable, Scheduler}
import io.reactivex.rxjava3.subjects.PublishSubject
import org.eclipse.draw2d.Figure
import org.eclipse.swt.SWT
import org.eclipse.swt.events.{SelectionAdapter, SelectionEvent}
import org.eclipse.swt.graphics.Font
import org.eclipse.swt.layout.{FillLayout, FormLayout}
import org.eclipse.swt.widgets.{Button, Composite, MessageBox, Shell}
import java.util.concurrent.TimeUnit
class RightPanel(parent: Composite, style: Int, font: Font, scheduler: Scheduler, grammarObs: Observable[GrammarDefEditor.UpdateEvent]) {
private val rightPanel = new HorizontalResizableSplittedComposite(parent, style, 30)
private var _testCodeEditor: CodeEditor = null
private var openProceedViewButton: Button = null
private var parseTreeViewer: ParseTreeViewer = null
private var astViewer: AstViewer = null
def testCodeEditor: CodeEditor = _testCodeEditor
def init(): Unit = {
// 루트 -> 오른쪽 -> 상단 테스트 패널. 상단에 테스트 text editor, 하단에 "Proceed View" 버튼
val testCodePanel = new Composite(rightPanel.upperPanel, SWT.NONE)
testCodePanel.setLayout(new FormLayout)
_testCodeEditor = new CodeEditor(testCodePanel, SWT.V_SCROLL | SWT.H_SCROLL, font)
openProceedViewButton = new Button(testCodePanel, SWT.NONE)
openProceedViewButton.setText("Proceed View")
val openProceedViewButtonObs = PublishSubject.create[SelectionEvent]()
openProceedViewButton.addSelectionListener(new SelectionAdapter {
override def widgetSelected(e: SelectionEvent): Unit = {
openProceedViewButtonObs.onNext(e)
}
})
setMainAndBottomLayout(_testCodeEditor.styledText, openProceedViewButton)
openProceedViewButtonObs.withLatestFrom(grammarObs, (_: SelectionEvent, _: GrammarDefEditor.UpdateEvent))
.subscribe({ pair: (SelectionEvent, GrammarDefEditor.UpdateEvent) =>
val gramOpt = pair._2 match {
case GrammarDefEditor.GrammarGenerated(ngrammar) => Some(ngrammar)
case GrammarDefEditor.GrammarProcessed(processedGrammar) => Some(processedGrammar.ngrammar)
case _ => None
}
_testCodeEditor.clearStyles()
gramOpt match {
case Some(ngrammar) =>
val display = parent.getDisplay
val newShell = new Shell(display)
ParsingProcessVisualizer.start[NaiveContext](
title = "Proceed View",
parser = new NaiveParser(ngrammar, trim = true),
Inputs.fromString(_testCodeEditor.styledText.getText), display, newShell,
(parent: Composite, style: Int, fig: NodeFigureGenerators[Figure], grammar: NGrammar, graph: ParsingContext.Graph, context: NaiveContext) =>
new ZestParsingContextWidget(parent, style, fig, grammar, graph, context)
)
case None =>
println(s"Cannot open proceed view, the latest parser was: ${pair._2}")
}
})
// 루트 -> 오른쪽 -> 하단 테스트 텍스트 파싱 결과. 상단에는 parse tree, 하단에는 AST
rightPanel.lowerPanel.setLayout(new FillLayout(SWT.VERTICAL))
parseTreeViewer = new ParseTreeViewer(rightPanel.lowerPanel, SWT.NONE)
astViewer = new AstViewer(rightPanel.lowerPanel, SWT.NONE)
// 파싱 결과 표시
val generatedGrammarObs: Observable[NGrammar] = grammarObs
.filter(_.isInstanceOf[GrammarDefEditor.GrammarGenerated])
.map(_.asInstanceOf[GrammarDefEditor.GrammarGenerated].ngrammar)
val exampleParseResult = Observable.combineLatest(generatedGrammarObs,
_testCodeEditor.textObservable.debounce(250, TimeUnit.MILLISECONDS),
(_: NGrammar, _: String)).switchMap { pair: (NGrammar, String) =>
Observable.create[Either[ParseForest, ParsingError]] { sub =>
new NaiveParser(pair._1).parse(pair._2) match {
case Left(ctx) =>
ParseTreeUtil.reconstructTree(pair._1, ctx) match {
case Some(parseForest) => sub.onNext(Left(parseForest))
case None => sub.onNext(Right(ParsingErrors.UnexpectedEOF(expectedTermsFrom(pair._1, ctx), pair._2.length)))
}
case Right(parsingError) =>
sub.onNext(Right(parsingError))
}
sub.onComplete()
}.observeOn(scheduler).subscribeOn(scheduler)
}.observeOn(scheduler).subscribeOn(scheduler).publish().refCount()
exampleParseResult.subscribe { parseResult: Either[ParseForest, ParsingError] =>
_testCodeEditor.clearStyles()
parseResult match {
case Left(parseForest) =>
parseTreeViewer.setParseForest(parseForest)
case Right(parsingError) =>
parseTreeViewer.invalidateParseForest()
parsingError match {
case ParsingErrors.AmbiguousParse(msg) =>
case ParsingErrors.UnexpectedEOF(expected, location) =>
_testCodeEditor.setStyle(CodeStyle.ERROR, location, location + 1)
case ParsingErrors.UnexpectedError =>
case ParsingErrors.UnexpectedInput(next, expected, location) =>
_testCodeEditor.setStyle(CodeStyle.ERROR, location, location + 1)
case _ =>
}
// TODO 오류 표시
}
}
val processedGrammarObs: Observable[ProcessedGrammar] = grammarObs
.filter(_.isInstanceOf[GrammarDefEditor.GrammarProcessed])
.map(_.asInstanceOf[GrammarDefEditor.GrammarProcessed].processedGrammar)
val astResultObs: Observable[Either[List[ValuefyExprSimulator.Value], ParsingError]] =
Observable.combineLatest(exampleParseResult, processedGrammarObs, (_: Either[ParseForest, ParsingError], _: ProcessedGrammar))
.switchMap { pair: (Either[ParseForest, ParsingError], ProcessedGrammar) =>
Observable.create[Either[List[ValuefyExprSimulator.Value], ParsingError]] { sub =>
val (parseResult, processedGrammar) = pair
parseResult match {
case Left(parseForest) =>
try {
val astValues = parseForest.trees.toList.map { parseTree =>
new ValuefyExprSimulator(processedGrammar.ngrammar, processedGrammar.startNonterminalName,
processedGrammar.nonterminalValuefyExprs, processedGrammar.shortenedEnumTypesMap).valuefyStart(parseTree)
}
sub.onNext(Left(astValues))
} catch {
case _: Throwable =>
sub.onNext(Right(ParsingErrors.UnexpectedError))
}
case Right(value) =>
sub.onNext(Right(value))
}
sub.onComplete()
}.observeOn(scheduler).subscribeOn(scheduler)
}
astResultObs.observeOn(scheduler).subscribeOn(scheduler).subscribe {
astResult: Either[List[ValuefyExprSimulator.Value], ParsingError] =>
astResult match {
case Left(astValues) =>
astViewer.setAstValues(astValues)
astValues.foreach(value => println(value.prettyPrint()))
case Right(parsingError) =>
astViewer.invalidateAstValues()
println(parsingError) // TODO 오류 표시
}
}
}
init()
}
|
Joonsoo/moon-parser
|
visualize/src/main/scala/com/giyeok/jparser/studio2/RightPanel.scala
|
Scala
|
mit
| 8,031 |
package modelservice.storage
import scala.annotation.tailrec
import scala.collection.{immutable, mutable}
import scala.concurrent.{ExecutionContext, Await, Future}
import scala.util.hashing._
/**
* Base asset type
*/
trait MSAsset {
def getHash()(implicit ec: ExecutionContext): Future[Int]
protected def toByteArray(value: AnyVal): Array[Byte] = {
val numBitsConversion = value match {
case d: Double => (java.lang.Double.SIZE, (java.lang.Double.doubleToRawLongBits _).asInstanceOf[(AnyVal) => Long])
case i: Int => (java.lang.Integer.SIZE, ((x: Int) => x.toLong).asInstanceOf[(AnyVal) => Long])
case l: Long => (java.lang.Long.SIZE, ((x: Long) => x).asInstanceOf[(AnyVal) => Long])
}
(0 to (numBitsConversion._1 / 8) - 1)
.map(i => (numBitsConversion._2(value) >> (8 * i) & 0xFF.toLong).toByte).toArray
}
def baseValue(): MSAsset
}
/**
* Base trait for maps of assets
// * @tparam K
// * @tparam V
*/
trait MSAssetMap[K] extends MSAsset {
type V <: MSAsset
def keySet(): immutable.Set[K]
val classSalt: Int
def getHash()(implicit ec: ExecutionContext) = combineKeyHashes(hashCache.map(kv => kv._2).toList)
def hashCache()(implicit ec: ExecutionContext): immutable.ListMap[K, Future[Int]]
def combineKeyHashes(hashes: Seq[Future[Int]])(implicit ec: ExecutionContext): Future[Int]
def put[V2 <: MSAsset](k: K, v: V2): Unit
def remove(k: K): Unit
protected def getNative(k: K): Option[V]
final def get(k: Any): Option[V] = {
try {
getNative(k.asInstanceOf[K])
} catch {
case e: Exception => None
}
}
final def getPath(path: Seq[Any]): Option[MSAsset] = {
// @tailrec
def getRec[T <: MSAsset](innerPath: Seq[Any], asset: Option[T]): Option[MSAsset] = {
innerPath match {
case Nil => asset
case x :: xs => asset match {
case Some(assetMap: MSAssetMap[K]) => getRec(xs, assetMap.get(x))
case _ => None
}
}
}
getRec(path, Some(this))
}
final def putPath(path: Seq[Any], asset: MSAsset) = {
// @tailrec
def getRec[T <: MSAsset](innerPath: Seq[Any], innerAsset: Option[T]): Option[MSAsset] = {
innerPath match {
case x :: Nil => innerAsset match {
case Some(assetMap: MSAssetMap[K]) => try {
assetMap.put(x.asInstanceOf[K], asset)
Some(assetMap)
} catch {
case e: Exception => None
}
}
case x :: xs => innerAsset match {
case Some(assetMap: MSAssetMap[K]) => getRec(xs, assetMap.get(x))
case _ => None
}
}
}
getRec(path, Some(this))
}
}
/**
* MS asset management leaf node
*
* @tparam T
*/
trait MSAssetLeaf[T] extends MSAsset {
def getData(): T
}
/**
* For use as a synchronization reference
*/
class SimpleLock() extends Serializable {}
/**
* Linked Hash Map
*
* @param maxSize
// * @tparam K
// * @tparam V
*/
class MSLinkedHashMap[K](maxSize: Int = 4) extends MSAssetMap[K] with Serializable {
import collection.JavaConversions._
private val modifyLock = new SimpleLock()
val classSalt = 42
private val data = new java.util.LinkedHashMap[K, V]((maxSize.toFloat * (4.0 / 3.0)).toInt, 0.75f, true) {
override def removeEldestEntry(eldest: java.util.Map.Entry[K, V]): Boolean = {
size() > maxSize
}
}
def combineKeyHashes(hashes: Seq[Future[Int]])(implicit ec: ExecutionContext): Future[Int] = {
Future.sequence(hashes).flatMap(hashes => {
println(s"MSLinkedHashMap hashes: ${hashes.mkString(", ")}")
Future.successful(hashes.foldLeft(classSalt)((accum, nextVal) =>
accum ^ MurmurHash3.bytesHash(toByteArray(nextVal) ++: toByteArray(nextVal), 42)))})
}
def keySet = data.keySet().toSet
def hashCache()(implicit ec: ExecutionContext) = immutable.ListMap[K, Future[Int]](
data.entrySet().map(x =>
x.getKey -> x.getValue.getHash
).toSeq: _*)
protected def getNative(k: K): Option[V] = {
data.get(k) match {
case v if v == null => None
case v: V => Some(v)
}
}
def put[V2 <: MSAsset](k: K, v: V2) = {
modifyLock.synchronized {
data.put(k, v.asInstanceOf[V])
}
}
def remove(k: K) = {
modifyLock.synchronized {
data.remove(k)
}
}
def baseValue() = new MSLinkedHashMap[K](maxSize)
}
class MSHashMap[K]() extends MSAssetMap[K] with Serializable {
private val modifyLock = new SimpleLock()
private val data = new mutable.HashMap[K, V]()
private val keys = scala.collection.mutable.LinkedHashSet[K]()
val classSalt = 55
def keySet = data.keySet.toSet
def combineKeyHashes(hashes: Seq[Future[Int]])(implicit ec: ExecutionContext): Future[Int] = {
Future.sequence(hashes).flatMap(hashes =>{
println(s"MSHashMap hashes: ${hashes.mkString(", ")}")
Future.successful(hashes.sorted.foldLeft(classSalt)((accum, nextVal) =>
accum ^ MurmurHash3.bytesHash(toByteArray(nextVal) ++: toByteArray(nextVal), 42)))})
}
def hashCache()(implicit ec: ExecutionContext) = immutable.ListMap[K, Future[Int]](
data.iterator.map(x =>
x._1 -> x._2.getHash
).toSeq: _*)
protected def getNative(k: K): Option[V] = data.get(k)
def put[V2 <: MSAsset](k: K, v: V2) = {
modifyLock.synchronized {
data.put(k, v.asInstanceOf[V])
keys += k
}
}
def remove(k: K) = {
modifyLock.synchronized {
data.remove(k)
keys -= k
}
}
def baseValue() = new MSHashMap[K]()
def getLatest() = keys.lastOption match {
case Some(k) => get(k)
case None => None
}
}
|
kiip/model-service
|
src/main/scala/modelservice/storage/MSAsset.scala
|
Scala
|
bsd-3-clause
| 5,637 |
package scala.build
import sbt._
import sbt.Keys.{ artifact, dependencyClasspath, moduleID, resourceManaged }
object ScaladocSettings {
val webjarResoources = Seq(
"org.webjars" % "jquery" % "3.4.1"
)
def extractResourcesFromWebjar = Def.task {
def isWebjar(s: Attributed[File]): Boolean =
s.get(artifact.key).isDefined && s.get(moduleID.key).exists(_.organization == "org.webjars")
val dest = (resourceManaged.value / "webjars").getAbsoluteFile
IO.createDirectory(dest)
val classpathes = (dependencyClasspath in Compile).value
val files: Seq[File] = classpathes.filter(isWebjar).flatMap { classpathEntry =>
val jarFile = classpathEntry.data
IO.unzip(jarFile, dest)
}
(files ** "*.min.js").get()
}
}
|
martijnhoekstra/scala
|
project/ScaladocSettings.scala
|
Scala
|
apache-2.0
| 763 |
package pl.iterators.kebs.macros.enums
import enumeratum.EnumEntry
import enumeratum.values.ValueEnumEntry
import pl.iterators.kebs.macros.MacroUtils
abstract class EnumMacroUtils extends MacroUtils {
import c.universe._
private val EnumEntry = typeOf[EnumEntry]
private val ValueEnumEntry = typeOf[ValueEnumEntry[_]]
protected def assertEnumEntry(t: Type, msg: => String) = if (!(t <:< EnumEntry)) c.abort(c.enclosingPosition, msg)
protected def assertValueEnumEntry(t: Type, msg: => String) = if (!(t <:< ValueEnumEntry)) c.abort(c.enclosingPosition, msg)
protected def ValueType(valueEnumEntry: Type) = valueEnumEntry.typeArgs.head
}
|
theiterators/kebs
|
macro-utils/src/main/scala-2/pl/iterators/kebs/macros/enums/EnumMacroUtils.scala
|
Scala
|
mit
| 664 |
object Error {
def f {
case class X(b: Boolean = false)
val r = X()
}
def g = {
val x = 0
var y = 1 // no constant type
def foo(z: Int = y) = 1
val z = 2
foo()
}
}
|
loskutov/intellij-scala
|
testdata/scalacTests/pos/t4036.scala
|
Scala
|
apache-2.0
| 200 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.server.epoch
import java.io.File
import scala.collection.Seq
import scala.collection.mutable.ListBuffer
import kafka.server.checkpoints.{LeaderEpochCheckpoint, LeaderEpochCheckpointFile}
import org.apache.kafka.common.requests.EpochEndOffset.{UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET}
import kafka.utils.TestUtils
import org.apache.kafka.common.TopicPartition
import org.junit.Assert._
import org.junit.Test
/**
* Unit test for the LeaderEpochFileCache.
*/
class LeaderEpochFileCacheTest {
val tp = new TopicPartition("TestTopic", 5)
private var logEndOffset = 0L
private val checkpoint: LeaderEpochCheckpoint = new LeaderEpochCheckpoint {
private var epochs: Seq[EpochEntry] = Seq()
override def write(epochs: Seq[EpochEntry]): Unit = this.epochs = epochs
override def read(): Seq[EpochEntry] = this.epochs
}
private val cache = new LeaderEpochFileCache(tp, logEndOffset _, checkpoint)
@Test
def shouldAddEpochAndMessageOffsetToCache() = {
//When
cache.assign(epoch = 2, startOffset = 10)
logEndOffset = 11
//Then
assertEquals(Some(2), cache.latestEpoch)
assertEquals(EpochEntry(2, 10), cache.epochEntries(0))
assertEquals((2, logEndOffset), cache.endOffsetFor(2)) //should match logEndOffset
}
@Test
def shouldReturnLogEndOffsetIfLatestEpochRequested() = {
//When just one epoch
cache.assign(epoch = 2, startOffset = 11)
cache.assign(epoch = 2, startOffset = 12)
logEndOffset = 14
//Then
assertEquals((2, logEndOffset), cache.endOffsetFor(2))
}
@Test
def shouldReturnUndefinedOffsetIfUndefinedEpochRequested() = {
val expectedEpochEndOffset = (UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET)
// assign couple of epochs
cache.assign(epoch = 2, startOffset = 11)
cache.assign(epoch = 3, startOffset = 12)
//When (say a bootstraping follower) sends request for UNDEFINED_EPOCH
val epochAndOffsetFor = cache.endOffsetFor(UNDEFINED_EPOCH)
//Then
assertEquals("Expected undefined epoch and offset if undefined epoch requested. Cache not empty.",
expectedEpochEndOffset, epochAndOffsetFor)
}
@Test
def shouldNotOverwriteLogEndOffsetForALeaderEpochOnceItHasBeenAssigned() = {
//Given
logEndOffset = 9
cache.assign(2, logEndOffset)
//When called again later
cache.assign(2, 10)
//Then the offset should NOT have been updated
assertEquals(logEndOffset, cache.epochEntries(0).startOffset)
assertEquals(ListBuffer(EpochEntry(2, 9)), cache.epochEntries)
}
@Test
def shouldEnforceMonotonicallyIncreasingStartOffsets() = {
//Given
cache.assign(2, 9)
//When update epoch new epoch but same offset
cache.assign(3, 9)
//Then epoch should have been updated
assertEquals(ListBuffer(EpochEntry(3, 9)), cache.epochEntries)
}
@Test
def shouldNotOverwriteOffsetForALeaderEpochOnceItHasBeenAssigned() = {
cache.assign(2, 6)
//When called again later with a greater offset
cache.assign(2, 10)
//Then later update should have been ignored
assertEquals(6, cache.epochEntries(0).startOffset)
}
@Test
def shouldReturnUnsupportedIfNoEpochRecorded(): Unit = {
//Then
assertEquals((UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), cache.endOffsetFor(0))
}
@Test
def shouldReturnUnsupportedIfNoEpochRecordedAndUndefinedEpochRequested(): Unit = {
logEndOffset = 73
//When (say a follower on older message format version) sends request for UNDEFINED_EPOCH
val offsetFor = cache.endOffsetFor(UNDEFINED_EPOCH)
//Then
assertEquals("Expected undefined epoch and offset if undefined epoch requested. Empty cache.",
(UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), offsetFor)
}
@Test
def shouldReturnFirstEpochIfRequestedEpochLessThanFirstEpoch(): Unit = {
cache.assign(epoch = 5, startOffset = 11)
cache.assign(epoch = 6, startOffset = 12)
cache.assign(epoch = 7, startOffset = 13)
//When
val epochAndOffset = cache.endOffsetFor(4)
//Then
assertEquals((4, 11), epochAndOffset)
}
@Test
def shouldTruncateIfMatchingEpochButEarlierStartingOffset(): Unit = {
cache.assign(epoch = 5, startOffset = 11)
cache.assign(epoch = 6, startOffset = 12)
cache.assign(epoch = 7, startOffset = 13)
// epoch 7 starts at an earlier offset
cache.assign(epoch = 7, startOffset = 12)
assertEquals((5, 12), cache.endOffsetFor(5))
assertEquals((5, 12), cache.endOffsetFor(6))
}
@Test
def shouldGetFirstOffsetOfSubsequentEpochWhenOffsetRequestedForPreviousEpoch() = {
//When several epochs
cache.assign(epoch = 1, startOffset = 11)
cache.assign(epoch = 1, startOffset = 12)
cache.assign(epoch = 2, startOffset = 13)
cache.assign(epoch = 2, startOffset = 14)
cache.assign(epoch = 3, startOffset = 15)
cache.assign(epoch = 3, startOffset = 16)
logEndOffset = 17
//Then get the start offset of the next epoch
assertEquals((2, 15), cache.endOffsetFor(2))
}
@Test
def shouldReturnNextAvailableEpochIfThereIsNoExactEpochForTheOneRequested(): Unit = {
//When
cache.assign(epoch = 0, startOffset = 10)
cache.assign(epoch = 2, startOffset = 13)
cache.assign(epoch = 4, startOffset = 17)
//Then
assertEquals((0, 13), cache.endOffsetFor(requestedEpoch = 1))
assertEquals((2, 17), cache.endOffsetFor(requestedEpoch = 2))
assertEquals((2, 17), cache.endOffsetFor(requestedEpoch = 3))
}
@Test
def shouldNotUpdateEpochAndStartOffsetIfItDidNotChange() = {
//When
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 2, startOffset = 7)
//Then
assertEquals(1, cache.epochEntries.size)
assertEquals(EpochEntry(2, 6), cache.epochEntries.toList(0))
}
@Test
def shouldReturnInvalidOffsetIfEpochIsRequestedWhichIsNotCurrentlyTracked(): Unit = {
logEndOffset = 100
//When
cache.assign(epoch = 2, startOffset = 100)
//Then
assertEquals((UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), cache.endOffsetFor(3))
}
@Test
def shouldSupportEpochsThatDoNotStartFromZero(): Unit = {
//When
cache.assign(epoch = 2, startOffset = 6)
logEndOffset = 7
//Then
assertEquals((2, logEndOffset), cache.endOffsetFor(2))
assertEquals(1, cache.epochEntries.size)
assertEquals(EpochEntry(2, 6), cache.epochEntries(0))
}
@Test
def shouldPersistEpochsBetweenInstances(): Unit = {
val checkpointPath = TestUtils.tempFile().getAbsolutePath
val checkpoint = new LeaderEpochCheckpointFile(new File(checkpointPath))
//Given
val cache = new LeaderEpochFileCache(tp, logEndOffset _, checkpoint)
cache.assign(epoch = 2, startOffset = 6)
//When
val checkpoint2 = new LeaderEpochCheckpointFile(new File(checkpointPath))
val cache2 = new LeaderEpochFileCache(tp, logEndOffset _, checkpoint2)
//Then
assertEquals(1, cache2.epochEntries.size)
assertEquals(EpochEntry(2, 6), cache2.epochEntries.toList(0))
}
@Test
def shouldEnforceMonotonicallyIncreasingEpochs(): Unit = {
//Given
cache.assign(epoch = 1, startOffset = 5); logEndOffset = 6
cache.assign(epoch = 2, startOffset = 6); logEndOffset = 7
//When we update an epoch in the past with a different offset, the log has already reached
//an inconsistent state. Our options are either to raise an error, ignore the new append,
//or truncate the cached epochs to the point of conflict. We take this latter approach in
//order to guarantee that epochs and offsets in the cache increase monotonically, which makes
//the search logic simpler to reason about.
cache.assign(epoch = 1, startOffset = 7); logEndOffset = 8
//Then later epochs will be removed
assertEquals(Some(1), cache.latestEpoch)
//Then end offset for epoch 1 will have changed
assertEquals((1, 8), cache.endOffsetFor(1))
//Then end offset for epoch 2 is now undefined
assertEquals((UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), cache.endOffsetFor(2))
assertEquals(EpochEntry(1, 7), cache.epochEntries(0))
}
@Test
def shouldEnforceOffsetsIncreaseMonotonically() = {
//When epoch goes forward but offset goes backwards
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 5)
//The last assignment wins and the conflicting one is removed from the log
assertEquals(EpochEntry(3, 5), cache.epochEntries.toList(0))
}
@Test
def shouldIncreaseAndTrackEpochsAsLeadersChangeManyTimes(): Unit = {
//Given
cache.assign(epoch = 0, startOffset = 0) //logEndOffset=0
//When
cache.assign(epoch = 1, startOffset = 0) //logEndOffset=0
//Then epoch should go up
assertEquals(Some(1), cache.latestEpoch)
//offset for 1 should still be 0
assertEquals((1, 0), cache.endOffsetFor(1))
//offset for epoch 0 should still be 0
assertEquals((0, 0), cache.endOffsetFor(0))
//When we write 5 messages as epoch 1
logEndOffset = 5
//Then end offset for epoch(1) should be logEndOffset => 5
assertEquals((1, 5), cache.endOffsetFor(1))
//Epoch 0 should still be at offset 0
assertEquals((0, 0), cache.endOffsetFor(0))
//When
cache.assign(epoch = 2, startOffset = 5) //logEndOffset=5
logEndOffset = 10 //write another 5 messages
//Then end offset for epoch(2) should be logEndOffset => 10
assertEquals((2, 10), cache.endOffsetFor(2))
//end offset for epoch(1) should be the start offset of epoch(2) => 5
assertEquals((1, 5), cache.endOffsetFor(1))
//epoch (0) should still be 0
assertEquals((0, 0), cache.endOffsetFor(0))
}
@Test
def shouldIncreaseAndTrackEpochsAsFollowerReceivesManyMessages(): Unit = {
//When Messages come in
cache.assign(epoch = 0, startOffset = 0); logEndOffset = 1
cache.assign(epoch = 0, startOffset = 1); logEndOffset = 2
cache.assign(epoch = 0, startOffset = 2); logEndOffset = 3
//Then epoch should stay, offsets should grow
assertEquals(Some(0), cache.latestEpoch)
assertEquals((0, logEndOffset), cache.endOffsetFor(0))
//When messages arrive with greater epoch
cache.assign(epoch = 1, startOffset = 3); logEndOffset = 4
cache.assign(epoch = 1, startOffset = 4); logEndOffset = 5
cache.assign(epoch = 1, startOffset = 5); logEndOffset = 6
assertEquals(Some(1), cache.latestEpoch)
assertEquals((1, logEndOffset), cache.endOffsetFor(1))
//When
cache.assign(epoch = 2, startOffset = 6); logEndOffset = 7
cache.assign(epoch = 2, startOffset = 7); logEndOffset = 8
cache.assign(epoch = 2, startOffset = 8); logEndOffset = 9
assertEquals(Some(2), cache.latestEpoch)
assertEquals((2, logEndOffset), cache.endOffsetFor(2))
//Older epochs should return the start offset of the first message in the subsequent epoch.
assertEquals((0, 3), cache.endOffsetFor(0))
assertEquals((1, 6), cache.endOffsetFor(1))
}
@Test
def shouldDropEntriesOnEpochBoundaryWhenRemovingLatestEntries(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When clear latest on epoch boundary
cache.truncateFromEnd(endOffset = 8)
//Then should remove two latest epochs (remove is inclusive)
assertEquals(ListBuffer(EpochEntry(2, 6)), cache.epochEntries)
}
@Test
def shouldPreserveResetOffsetOnClearEarliestIfOneExists(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset ON epoch boundary
cache.truncateFromStart(startOffset = 8)
//Then should preserve (3, 8)
assertEquals(ListBuffer(EpochEntry(3, 8), EpochEntry(4, 11)), cache.epochEntries)
}
@Test
def shouldUpdateSavedOffsetWhenOffsetToClearToIsBetweenEpochs(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset BETWEEN epoch boundaries
cache.truncateFromStart(startOffset = 9)
//Then we should retain epoch 3, but update it's offset to 9 as 8 has been removed
assertEquals(ListBuffer(EpochEntry(3, 9), EpochEntry(4, 11)), cache.epochEntries)
}
@Test
def shouldNotClearAnythingIfOffsetToEarly(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset before first epoch offset
cache.truncateFromStart(startOffset = 1)
//Then nothing should change
assertEquals(ListBuffer(EpochEntry(2, 6),EpochEntry(3, 8), EpochEntry(4, 11)), cache.epochEntries)
}
@Test
def shouldNotClearAnythingIfOffsetToFirstOffset(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset on earliest epoch boundary
cache.truncateFromStart(startOffset = 6)
//Then nothing should change
assertEquals(ListBuffer(EpochEntry(2, 6),EpochEntry(3, 8), EpochEntry(4, 11)), cache.epochEntries)
}
@Test
def shouldRetainLatestEpochOnClearAllEarliest(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When
cache.truncateFromStart(startOffset = 11)
//Then retain the last
assertEquals(ListBuffer(EpochEntry(4, 11)), cache.epochEntries)
}
@Test
def shouldUpdateOffsetBetweenEpochBoundariesOnClearEarliest(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When we clear from a postition between offset 8 & offset 11
cache.truncateFromStart(startOffset = 9)
//Then we should update the middle epoch entry's offset
assertEquals(ListBuffer(EpochEntry(3, 9), EpochEntry(4, 11)), cache.epochEntries)
}
@Test
def shouldUpdateOffsetBetweenEpochBoundariesOnClearEarliest2(): Unit = {
//Given
cache.assign(epoch = 0, startOffset = 0)
cache.assign(epoch = 1, startOffset = 7)
cache.assign(epoch = 2, startOffset = 10)
//When we clear from a postition between offset 0 & offset 7
cache.truncateFromStart(startOffset = 5)
//Then we should keeep epoch 0 but update the offset appropriately
assertEquals(ListBuffer(EpochEntry(0,5), EpochEntry(1, 7), EpochEntry(2, 10)), cache.epochEntries)
}
@Test
def shouldRetainLatestEpochOnClearAllEarliestAndUpdateItsOffset(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset beyond last epoch
cache.truncateFromStart(startOffset = 15)
//Then update the last
assertEquals(ListBuffer(EpochEntry(4, 15)), cache.epochEntries)
}
@Test
def shouldDropEntriesBetweenEpochBoundaryWhenRemovingNewest(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset BETWEEN epoch boundaries
cache.truncateFromEnd(endOffset = 9)
//Then should keep the preceding epochs
assertEquals(Some(3), cache.latestEpoch)
assertEquals(ListBuffer(EpochEntry(2, 6), EpochEntry(3, 8)), cache.epochEntries)
}
@Test
def shouldClearAllEntries(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When
cache.clearAndFlush()
//Then
assertEquals(0, cache.epochEntries.size)
}
@Test
def shouldNotResetEpochHistoryHeadIfUndefinedPassed(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset on epoch boundary
cache.truncateFromEnd(endOffset = UNDEFINED_EPOCH_OFFSET)
//Then should do nothing
assertEquals(3, cache.epochEntries.size)
}
@Test
def shouldNotResetEpochHistoryTailIfUndefinedPassed(): Unit = {
//Given
cache.assign(epoch = 2, startOffset = 6)
cache.assign(epoch = 3, startOffset = 8)
cache.assign(epoch = 4, startOffset = 11)
//When reset to offset on epoch boundary
cache.truncateFromEnd(endOffset = UNDEFINED_EPOCH_OFFSET)
//Then should do nothing
assertEquals(3, cache.epochEntries.size)
}
@Test
def shouldFetchLatestEpochOfEmptyCache(): Unit = {
//Then
assertEquals(None, cache.latestEpoch)
}
@Test
def shouldFetchEndOffsetOfEmptyCache(): Unit = {
//Then
assertEquals((UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), cache.endOffsetFor(7))
}
@Test
def shouldClearEarliestOnEmptyCache(): Unit = {
//Then
cache.truncateFromStart(7)
}
@Test
def shouldClearLatestOnEmptyCache(): Unit = {
//Then
cache.truncateFromEnd(7)
}
}
|
noslowerdna/kafka
|
core/src/test/scala/unit/kafka/server/epoch/LeaderEpochFileCacheTest.scala
|
Scala
|
apache-2.0
| 18,012 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.functions.utils
import org.apache.flink.table.api.ValidationException
import org.apache.flink.table.functions.UserDefinedFunctionHelper.generateInlineFunctionName
import org.apache.flink.table.functions.{BuiltInFunctionDefinitions, FunctionIdentifier, TableFunction, UserDefinedFunctionHelper}
import org.apache.flink.table.planner.calcite.FlinkTypeFactory
import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction
import org.apache.flink.table.planner.functions.utils.TableSqlFunction._
import org.apache.flink.table.planner.functions.utils.UserDefinedFunctionUtils._
import org.apache.flink.table.planner.plan.schema.FlinkTableFunction
import org.apache.flink.table.runtime.types.TypeInfoLogicalTypeConverter.fromTypeInfoToLogicalType
import org.apache.flink.table.types.DataType
import org.apache.flink.table.types.logical.LogicalType
import org.apache.calcite.rel.`type`.{RelDataType, RelDataTypeFactory}
import org.apache.calcite.sql._
import org.apache.calcite.sql.`type`.SqlOperandTypeChecker.Consistency
import org.apache.calcite.sql.`type`._
import org.apache.calcite.sql.parser.SqlParserPos
import org.apache.calcite.sql.validate.SqlUserDefinedTableFunction
import java.lang.reflect.Method
import java.util
/**
* Calcite wrapper for user-defined table functions.
*
* @param identifier function identifier to uniquely identify this function
* @param udtf user-defined table function to be called
* @param implicitResultType Implicit result type information
* @param typeFactory type factory for converting Flink's between Calcite's types
* @param functionImpl Calcite table function schema
* @return [[TableSqlFunction]]
* @deprecated Use [[BuiltInFunctionDefinitions]] that translates to [[BridgingSqlFunction]].
*/
@Deprecated
@deprecated
class TableSqlFunction(
identifier: FunctionIdentifier,
displayName: String,
val udtf: TableFunction[_],
implicitResultType: DataType,
typeFactory: FlinkTypeFactory,
functionImpl: FlinkTableFunction,
operandMetadata: Option[SqlOperandMetadata] = None)
extends SqlUserDefinedTableFunction(
Option(identifier).map(id => new SqlIdentifier(id.toList, SqlParserPos.ZERO))
.getOrElse(new SqlIdentifier(generateInlineFunctionName(udtf), SqlParserPos.ZERO)),
SqlKind.OTHER_FUNCTION,
ReturnTypes.CURSOR,
// type inference has the UNKNOWN operand types.
createOperandTypeInference(displayName, udtf, typeFactory),
// only checker has the real operand types.
operandMetadata.getOrElse(createOperandMetadata(displayName, udtf)),
functionImpl) {
/**
* This is temporary solution for hive udf and should be removed once FLIP-65 is finished,
* please pass the non-null input arguments.
*/
def makeFunction(constants: Array[AnyRef], argTypes: Array[LogicalType]): TableFunction[_] =
udtf
/**
* Get the type information of the table returned by the table function.
*/
def getImplicitResultType: DataType = implicitResultType
override def isDeterministic: Boolean = udtf.isDeterministic
override def toString: String = displayName
override def getRowTypeInference: SqlReturnTypeInference = new SqlReturnTypeInference {
override def inferReturnType(opBinding: SqlOperatorBinding): RelDataType = {
val arguments = convertArguments(opBinding, functionImpl, getNameAsId)
getRowType(opBinding.getTypeFactory, arguments)
}
}
def getRowType(
typeFactory: RelDataTypeFactory,
arguments: util.List[Object]): RelDataType = {
functionImpl.getRowType(typeFactory)
}
}
object TableSqlFunction {
private[flink] def createOperandTypeInference(
name: String,
udtf: TableFunction[_],
typeFactory: FlinkTypeFactory): SqlOperandTypeInference = {
/**
* Operand type inference based on [[TableFunction]] given information.
*/
new SqlOperandTypeInference {
override def inferOperandTypes(
callBinding: SqlCallBinding,
returnType: RelDataType,
operandTypes: Array[RelDataType]): Unit = {
inferOperandTypesInternal(
name, udtf, typeFactory, callBinding, returnType, operandTypes)
}
}
}
def inferOperandTypesInternal(
name: String,
func: TableFunction[_],
typeFactory: FlinkTypeFactory,
callBinding: SqlCallBinding,
returnType: RelDataType,
operandTypes: Array[RelDataType]): Unit = {
val parameters = getOperandType(callBinding).toArray
if (getEvalUserDefinedMethod(func, parameters).isEmpty) {
throwValidationException(name, func, parameters)
}
func.getParameterTypes(getEvalMethodSignature(func, parameters))
.map(fromTypeInfoToLogicalType)
.map(typeFactory.createFieldTypeFromLogicalType)
.zipWithIndex
.foreach {
case (t, i) => operandTypes(i) = t
}
}
private[flink] def createOperandMetadata(
name: String,
udtf: TableFunction[_]): SqlOperandMetadata = {
new OperandMetadata(name, udtf, checkAndExtractMethods(udtf, "eval"))
}
/**
* Converts arguments from [[org.apache.calcite.sql.SqlNode]] to
* java object format.
*
* @param callBinding Operator bound to arguments
* @param function target function to get parameter types from
* @param opName name of the operator to use in error message
* @return converted list of arguments
*/
private[flink] def convertArguments(
callBinding: SqlOperatorBinding,
function: org.apache.calcite.schema.Function,
opName: SqlIdentifier): util.List[Object] = {
val arguments = new util.ArrayList[Object](callBinding.getOperandCount)
0 until callBinding.getOperandCount foreach { i =>
val value: Object = if (callBinding.isOperandLiteral(i, true)) {
callBinding.getOperandLiteralValue(i, classOf[Object])
} else {
null
}
arguments.add(value);
}
arguments
}
}
/**
* Operand type checker based on [[TableFunction]] given information.
*/
class OperandMetadata(
name: String,
udtf: TableFunction[_],
methods: Array[Method]) extends SqlOperandMetadata {
override def getAllowedSignatures(op: SqlOperator, opName: String): String = {
s"$opName[${signaturesToString(udtf, "eval")}]"
}
override def getOperandCountRange: SqlOperandCountRange = {
var min = 254
var max = -1
var isVarargs = false
methods.foreach(m => {
var len = m.getParameterTypes.length
if (len > 0 && m.isVarArgs && m.getParameterTypes()(len - 1).isArray) {
isVarargs = true
len = len - 1
}
max = Math.max(len, max)
min = Math.min(len, min)
})
if (isVarargs) {
// if eval method is varargs, set max to -1 to skip length check in Calcite
max = -1
}
SqlOperandCountRanges.between(min, max)
}
override def checkOperandTypes(
callBinding: SqlCallBinding,
throwOnFailure: Boolean)
: Boolean = {
val operandTypes = getOperandType(callBinding)
if (getEvalUserDefinedMethod(udtf, operandTypes).isEmpty) {
if (throwOnFailure) {
throw new ValidationException(
s"Given parameters of function '$name' do not match any signature. \\n" +
s"Actual: ${signatureInternalToString(operandTypes)} \\n" +
s"Expected: ${signaturesToString(udtf, "eval")}")
} else {
false
}
} else {
true
}
}
override def isOptional(i: Int): Boolean = false
override def getConsistency: Consistency = Consistency.NONE
override def paramTypes(typeFactory: RelDataTypeFactory): util.List[RelDataType] =
throw new UnsupportedOperationException("SqlOperandMetadata.paramTypes "
+ "should never be invoked")
override def paramNames(): util.List[String] =
throw new UnsupportedOperationException("SqlOperandMetadata.paramNames "
+ "should never be invoked")
}
|
apache/flink
|
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/functions/utils/TableSqlFunction.scala
|
Scala
|
apache-2.0
| 8,814 |
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
import org.openapitools.client.core.ApiModel
case class PipelineBranchesitemlatestRun (
durationInMillis: Option[Int] = None,
estimatedDurationInMillis: Option[Int] = None,
enQueueTime: Option[String] = None,
endTime: Option[String] = None,
id: Option[String] = None,
organization: Option[String] = None,
pipeline: Option[String] = None,
result: Option[String] = None,
runSummary: Option[String] = None,
startTime: Option[String] = None,
state: Option[String] = None,
`type`: Option[String] = None,
commitId: Option[String] = None,
`class`: Option[String] = None
) extends ApiModel
|
cliffano/swaggy-jenkins
|
clients/scala-akka/generated/src/main/scala/org/openapitools/client/model/PipelineBranchesitemlatestRun.scala
|
Scala
|
mit
| 998 |
package scala.slick.jdbc.meta
import scala.slick.jdbc.ResultSetInvoker
import scala.slick.session._
/**
* A common privilege type which is used by MTablePrivilege and MColumnPrivilege.
*/
case class MPrivilege(grantor: Option[String], grantee: String, privilege: String, grantable: Option[Boolean])
object MPrivilege {
private[meta] def from(r: PositionedResult) = MPrivilege(r.<<, r.<<, r.<<, DatabaseMeta.yesNoOpt(r))
}
/**
* A wrapper for a row in the ResultSet returned by DatabaseMetaData.getTablePrivileges().
*/
case class MTablePrivilege(table: MQName, privilege: MPrivilege)
object MTablePrivilege {
def getTablePrivileges(tablePattern: MQName) = ResultSetInvoker[MTablePrivilege](
_.metaData.getTablePrivileges(tablePattern.catalog_?, tablePattern.schema_?, tablePattern.name)) { r =>
MTablePrivilege(MQName.from(r), MPrivilege.from(r))
}
}
/**
* A wrapper for a row in the ResultSet returned by DatabaseMetaData.getColumnPrivileges().
*/
case class MColumnPrivilege(table: MQName, column: String, privilege: MPrivilege)
object MColumnPrivilege {
def getColumnPrivileges(tablePattern: MQName, columnPattern: String) = ResultSetInvoker[MColumnPrivilege](
_.metaData.getColumnPrivileges(tablePattern.catalog_?, tablePattern.schema_?, tablePattern.name, columnPattern)) { r =>
MColumnPrivilege(MQName.from(r), r.<<, MPrivilege.from(r))
}
}
|
zefonseca/slick-1.0.0-scala.2.11.1
|
src/main/scala/scala/slick/jdbc/meta/MPrivilege.scala
|
Scala
|
bsd-2-clause
| 1,394 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.ml
import org.apache.spark.annotation.Since
import org.apache.spark.ml.linalg.{SparseVector, Vector}
import org.apache.spark.mllib.linalg.{Vector => OldVector}
import org.apache.spark.sql.Column
import org.apache.spark.sql.functions.udf
// scalastyle:off
@Since("3.0.0")
object functions {
// scalastyle:on
private val vectorToArrayUdf = udf { vec: Any =>
vec match {
case v: Vector => v.toArray
case v: OldVector => v.toArray
case v => throw new IllegalArgumentException(
"function vector_to_array requires a non-null input argument and input type must be " +
"`org.apache.spark.ml.linalg.Vector` or `org.apache.spark.mllib.linalg.Vector`, " +
s"but got ${ if (v == null) "null" else v.getClass.getName }.")
}
}.asNonNullable()
private val vectorToArrayFloatUdf = udf { vec: Any =>
vec match {
case v: SparseVector =>
val data = new Array[Float](v.size)
v.foreachActive { (index, value) => data(index) = value.toFloat }
data
case v: Vector => v.toArray.map(_.toFloat)
case v: OldVector => v.toArray.map(_.toFloat)
case v => throw new IllegalArgumentException(
"function vector_to_array requires a non-null input argument and input type must be " +
"`org.apache.spark.ml.linalg.Vector` or `org.apache.spark.mllib.linalg.Vector`, " +
s"but got ${ if (v == null) "null" else v.getClass.getName }.")
}
}.asNonNullable()
/**
* Converts a column of MLlib sparse/dense vectors into a column of dense arrays.
* @param v: the column of MLlib sparse/dense vectors
* @param dtype: the desired underlying data type in the returned array
* @return an array<float> if dtype is float32, or array<double> if dtype is float64
* @since 3.0.0
*/
def vector_to_array(v: Column, dtype: String = "float64"): Column = {
if (dtype == "float64") {
vectorToArrayUdf(v)
} else if (dtype == "float32") {
vectorToArrayFloatUdf(v)
} else {
throw new IllegalArgumentException(
s"Unsupported dtype: $dtype. Valid values: float64, float32."
)
}
}
private[ml] def checkNonNegativeWeight = udf {
value: Double =>
require(value >= 0, s"illegal weight value: $value. weight must be >= 0.0.")
value
}
}
|
dbtsai/spark
|
mllib/src/main/scala/org/apache/spark/ml/functions.scala
|
Scala
|
apache-2.0
| 3,140 |
package nl.rabobank.oss.rules.dsl.nl.grammar
import LoopBerekeningGlossary._
import nl.rabobank.oss.rules.dsl.nl.grammar.meta.BerekeningReferentie
class LoopBerekening extends Berekening (
Gegeven(altijd) Bereken
simpleLoopResult bevat resultaten van SimpeleLoopElementBerekening over loopInput
,
Gegeven(altijd) Bereken
nestedTestOutput bevat resultaten van GenesteLoopElementBerekening over nestedTestInput
,
Gegeven(altijd) Bereken
filteredLoopResult bevat resultaten van GefilterdeLoopElementBerekening over loopInput
)
@BerekeningReferentie
class SimpeleLoopElementBerekening extends ElementBerekening[BigDecimal, BigDecimal] (
Invoer is innerLoopIteratee,
Uitvoer is innerLoopReturnValue,
Gegeven (altijd) Bereken innerLoopReturnValue is innerLoopIteratee + innerLoopAdditionValue
)
@BerekeningReferentie
class GenesteLoopElementBerekening extends ElementBerekening[List[BigDecimal], List[BigDecimal]] (
Invoer is nestedOuterLoopInput,
Uitvoer is nestedOuterLoopResult,
Gegeven (altijd) Bereken nestedOuterLoopResult bevat resultaten van SimpeleLoopElementBerekening over nestedOuterLoopInput
)
@BerekeningReferentie
class GefilterdeLoopElementBerekening extends ElementBerekening[BigDecimal, BigDecimal] (
Invoer is innerLoopIteratee,
Uitvoer is innerLoopReturnValue,
Gegeven (innerLoopIteratee is 2) Bereken innerLoopReturnValue is innerLoopIteratee + BigDecimal(2)
)
|
scala-rules/scala-rules
|
engine/src/test/scala/nl/rabobank/oss/rules/dsl/nl/grammar/LoopBerekening.scala
|
Scala
|
mit
| 1,421 |
package concrete
package heuristic
package value
import com.typesafe.scalalogging.LazyLogging
import scala.util.Random
final class RandomValue(rand: Random) extends ValueSelector with LazyLogging {
override def toString = "random"
def compute(s: MAC, ps: ProblemState): ProblemState = ps
override def select(ps: ProblemState, variable: Variable, candidates: Domain): (Outcome, Domain) = {
val randIndex = rand.nextInt(candidates.size)
val r = candidates.view.drop(randIndex).head
logger.info(s"Random value is $r")
(ps, Singleton(r))
}
def shouldRestart = true
}
|
concrete-cp/concrete
|
src/main/scala/concrete/heuristic/value/RandomValue.scala
|
Scala
|
lgpl-2.1
| 596 |
/*
* Copyright (c) <2015-2016>, see CONTRIBUTORS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.usi.inf.l3.sana.arrooj.symbols
import ch.usi.inf.l3.sana
import sana.tiny.types.Type
import sana.tiny.modifiers.Flags
import sana.tiny.modifiers.Ops._
import sana.tiny.names.Name
import sana.tiny.symbols.{Symbol, TypeSymbol}
import sana.arrooj.types.{ArrayType, TypeUtils}
import sana.ooj.symbols.ClassSymbol
/** A symbol for arrays */
trait ArraySymbol extends ClassSymbol {
/** The symbol of the component of the array */
var componentSymbol: Symbol
/** A pointer to the symbol of {{{java.lang.Object}}} class */
def objectClassSymbol: ClassSymbol
/**
* The symbols of the members of an array. In Java, this only includes
* `length` field
*/
def members: List[Symbol]
decls = decls ++ members
def parents: List[ClassSymbol] = List(objectClassSymbol)
def parents_=(parents: List[ClassSymbol]): Unit = ???
override def declare(symbol: Symbol): Unit = ???
override def delete(symbol: Symbol): Unit = ???
def owner: Option[Symbol] = componentSymbol.owner
def owner_=(onwer: Option[Symbol]): Unit = ???
def name: Name = componentSymbol.name
def name_=(name: Name): Unit = ???
def mods: Flags = noflags
def mods_=(mods: Flags): Unit = ???
def tpe: Option[Type] = for {
ctpe <- componentSymbol.tpe
otpe <- objectClassSymbol.tpe
} yield TypeUtils.mkArrayType(ctpe)
def tpe_=(tpe: Option[Type]): Unit = ???
override def equals(other: Any): Boolean = other match {
case null => false
case that: ArraySymbol =>
this.owner == that.owner &&
this.componentSymbol == that.componentSymbol &&
this.name == that.name
case _ =>
false
}
override def toString(): String = s"Array symbol: $name"
override def hashCode(): Int = name.hashCode * 43 + componentSymbol.hashCode
}
class ArraySymbolImpl(var componentSymbol: Symbol,
val objectClassSymbol: ClassSymbol,
val members: List[Symbol]) extends ArraySymbol
|
amanjpro/languages-a-la-carte
|
arrooj/src/main/scala/symbols/symbols.scala
|
Scala
|
bsd-3-clause
| 3,541 |
/**
* SparklineData, Inc. -- http://www.sparklinedata.com/
*
* Scala based Audience Behavior APIs
*
* Copyright 2014-2015 SparklineData, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sparklinedata.analytics.utils
/**
* Created by Jitender on 8/11/15.
*/
object Utils {
def getCaseClassParams(cc: AnyRef) =
(Map[String, Any]() /: cc.getClass.getDeclaredFields) {(a, f) =>
f.setAccessible(true)
a + (f.getName -> f.get(cc))
}
// getCaseClassParams(primaryAggCol) = Map(name -> sessionIdColName, alias -> Sessions, func -> count, $outer -> $iwC$$iwC@507418f)
// P21 (*) Insert an element at a given position into a list.
// Example:
// scala> insertAt('new, 1, List('a, 'b, 'c, 'd))
// res0: List[Symbol] = List('a, 'new, 'b, 'c, 'd)
def insertAt[A](e: A, n: Int, ls: List[A]): List[A] = ls.splitAt(n) match {
case (pre, post) => pre ::: e :: post
}
}
|
cubefyre/audience-behavior-apis
|
analytics/src/main/scala/org/sparklinedata/analytics/utils/Utils.scala
|
Scala
|
apache-2.0
| 1,442 |
package deburnat.transade.gui.north
import deburnat.transade.gui.{admins, components}
import swing._
import BorderPanel.Position.{Center, East}
import components.{HBoxPanel, LButton, TransOptionPane}
import TransOptionPane._
import java.io.File
import admins.GuiAdmin._
import admins.TemplatesAdmin._
/**
* Project name: transade
* @author Patrick Meppe ([email protected])
* Description:
* An algorithm for the transfer of selected/adapted data
* from one repository to another.
*
* Date: 1/1/14
* Time: 12:00 AM
*
* This class represents the north panel of the application. It is made of the loader fields,
* the info and settings buttons.
*/
protected[transade] class NorthPanel extends BorderPanel{
//these objects are all accessed by the MainFrame itself to enable its reset
val templates= new TemplatesComboBox
val fileChooser = new TransFileChooser(templates)
val deleteButton = new LButton("delete", if(templates.nonEmpty){ //onClick block
if(confirm("templatedelete")) delete(templates.item) //no else
}else warn("item")){
tooltip = tRead("delete")
/**
* This method is used to delete the currently selected template.
* At this point the item can't be empty so need for a check
*/
def doClick(){delete(templates.item)}
}
/**
* This method is used to permanently remove the given item from
* the templates.
* @param item The template to delete.
*/
private def delete(item: String){
val file = new File(tDir.format(item))
if(file.exists) //the file actually always be existent, but you never know
if(file.delete){
templates -= item
warn("itemsuccess")
}else warn("itemdeletenot") //the template couldn't be deleted.
else warn("itemdelete") //although the item is still listed, the template (the file) as already been deleted.
}
layout(new HBoxPanel{ //a BorderPanel at the place of a BoxPanel can also do the trick
contents += fileChooser
contents += Swing.HStrut(50)
contents += templates
contents += Swing.HStrut(5)
contents += deleteButton
border = Swing.EmptyBorder(0, 10, 0, 300)
}) = Center
layout(new HBoxPanel{
contents += new Separator(Orientation.Vertical)
contents += Swing.HStrut(10)
val admin = coreAdmin //the manual button
contents += new LButton(manual, admin.showManual) //show the manual
contents += Swing.HStrut(10)
val settings = new SettingsPopupMenu //the settings button
contents += new LButton("settings", settings.show(this.contents(4))) //onClick
contents += Swing.HStrut(10)
}) = East
border = Swing.EmptyBorder(5, 5, 5, 5)
}
|
deburnatshazem/transade
|
gui/src/main/scala/deburnat/transade/gui/north/NorthPanel.scala
|
Scala
|
apache-2.0
| 2,656 |
package scavlink.link.nav
import scavlink.coord._
import scavlink.state.{LocationState, State}
import scala.concurrent.duration._
/**
* Guided mode course that travels through a sequence of waypoints.
* Computes distance change with Theil's incomplete method to smooth distance samples.
* @author Nick Rossi
*/
case class GotoLocations(locations: Seq[Geo],
index: Int = 0,
hasArrived: (Geo, Geo) => Boolean = withinMeters(5, 1),
maxEta: FiniteDuration = 6.hours,
smoothingWindow: FiniteDuration = 10.seconds,
current: Option[Geo] = None,
isComplete: Boolean = false,
distances: Distances = Vector.empty)
extends GuidedCourse with DistanceChangeStatus with TheilIncompleteDistance {
require(locations.nonEmpty, "Location list must be non-empty")
require(smoothingWindow > 1.second, "smoothingWindow must be at least 1 second")
val states: Set[Class[_ <: State]] = Set(classOf[LocationState])
val waypoint = locations.head
val status: CourseStatus.Value = distanceStatus
def update(state: State): GuidedCourse = state match {
case s: LocationState =>
if (hasArrived(s.location, waypoint)) {
if (locations.tail.isEmpty) {
this.copy(current = Some(s.location), isComplete = true, index = index + 1, distances = Vector.empty)
} else {
this.copy(current = Some(s.location), locations = locations.tail, index = index + 1, distances = Vector.empty)
}
} else {
this.copy(current = Some(s.location), distances = addDistance(s.timeIndex, computeDistance(s.location, waypoint)))
}
case _ => this
}
override def fieldsToString(): String = {
val fields = super.fieldsToString()
s"index=$index more=${ locations.tail.nonEmpty } $fields distance=${ distance }m distRate=${ distanceChangeRate * 1000 }m/s eta=$eta"
}
}
|
nickolasrossi/scavlink
|
src/main/scala/scavlink/link/nav/GotoLocations.scala
|
Scala
|
mit
| 1,996 |
//
// Copyright 2014-2020 Paytronix Systems, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package com.paytronix.utils.interchange.format.json
import scala.annotation.{Annotation, StaticAnnotation}
import scala.language.experimental.macros
import com.paytronix.utils.interchange.base
/**
* Annotations and macros to derive coders automatically at compile time.
*
* Intended to be used qualified, e.g. @derive.structure.implicitCoder.
*/
object derive {
object structure {
/**
* Automatically generate an `JsonCoder` for a structural type.
*
* For example:
*
* @derive.structure.implicitCoder
* final case class MyStruct(a: Int, b: String)
*
* Will put an implicit coder on the companion object of `MyStruct` creating that companion object if it doesn't exist already,
* like:
*
* object MyStruct {
* implicit val jsonCoder = derive.structure.coder[MyStruct]
* }
* final case class MyStruct(a: Int, b: String)
*/
/* 2014-08-27 RMM: having multiple annotation macros which addToCompanion causes the compiler to not emit the object class (Blah$) even though
it doesn't error at runtime.
class implicitCoder extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.deriveImplicitStructureCoderAnnotation
}
*/
/**
* Make the annotated class or object a complete `JsonCoder` for the given type allowing for individual field codings to be altered.
*
* For example:
*
* final case class MyStruct(a: BigDecimal, b: String)
* object MyStruct {
* @derive.structure.customizedCoder[MyStruct]
* implicit object jsonCoder {
* val a = doubleCoder.mapBijection(bijection (
* (bd: BigDecimal) => Okay(bd.doubleValue),
* (d: Double) => Okay(BigDecimal(d))
* ))
* }
* }
*
* will create a coder identical to the one generated by `derive.structure.coder` or `@derive.structure.implicitCoder` but with the
* coder used for the field `a` overridden from the default.
*/
class customizedCoder[A] extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.structureCoderAnnotation
}
/**
* Make the annotated class or object a complete `JsonEncoder` for the given type allowing for individual field encodings to be altered.
* See `customizedCoder` for an example.
*/
class customizedEncoder[A] extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.structureEncoderAnnotation
}
/**
* Make the annotated class or object a complete `JsonDecoder` for the given type allowing for individual field decodings to be altered.
* See `customizedCoder` for an example.
*/
class customizedDecoder[A] extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.structureDecoderAnnotation
}
/**
* Generate an `JsonCoder` for the given type, using coders from the implicit scope for field codings.
* Fails at compile time if a coding can't be determined for a field.
*/
def coder[A]: JsonCoder[A] = macro deriveImpl.structureCoderDef[A]
/**
* Generate an `JsonEncoder` for the given type, using encoders from the implicit scope for field encodings.
* Fails at compile time if a encoding can't be determined for a field.
*/
def encoder[A]: JsonEncoder[A] = macro deriveImpl.structureEncoderDef[A]
/**
* Generate an `JsonDecoder` for the given type, using decoders from the implicit scope for field decodings.
* Fails at compile time if a decoding can't be determined for a field.
*/
def decoder[A]: JsonDecoder[A] = macro deriveImpl.structureDecoderDef[A]
}
/**
* Annotation and macros to derive coding for wrapper types - types with a single field which wrap some other type and are represented when
* encoded as that other type. Sometimes this is called a newtype, sometimes a value type, but for the purposes of encoding and decoding any
* class with a single field counts.
*
* For example:
*
* @derive.wrapper.implicitCoder
* final case class Meters(m: Int) extends AnyVal
*
* In this example, a value of type `Meters` would be encoded as an integer, but is a distinct type in Scala.
*/
object wrapper {
/* 2014-08-27 RMM: having multiple annotation macros which addToCompanion causes the compiler to not emit the object class (Blah$) even though
it doesn't error at runtime.
class implicitCoder extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.deriveImplicitWrapperCoderAnnotation
}
*/
/**
* Generate an `JsonCoder` for the given wrapping type, using a coder from the implicit scope for the single field decoding.
* Fails at compile time if a decoding can't be determined.
*/
def coder[A]: JsonCoder[A] = macro deriveImpl.wrapperCoderDef[A]
/**
* Generate an `JsonEncoder` for the given wrapping type, using an encoder from the implicit scope for the single field encoding.
* Fails at compile time if a decoding can't be determined.
*/
def encoder[A]: JsonEncoder[A] = macro deriveImpl.wrapperEncoderDef[A]
/**
* Generate an `JsonDecoder` for the given wrapping type, using a decoder from the implicit scope for the single field decoding.
* Fails at compile time if a decoding can't be determined.
*/
def decoder[A]: JsonDecoder[A] = macro deriveImpl.wrapperDecoderDef[A]
}
/** Annotation and macro to derive union (sum type) coders that use an explicit intensional field to discriminate among alternates. */
object taggedUnion {
/**
* Automatically generate an `JsonCoder` for a union type whose alternates have been enumerated with
* a `com.paytronix.utils.interchange.base.union` annotation.
*
* For example:
*
* @derive.taggedUnion.implicitCoder("type")
* @union(union.alt[First].tag("first"), union.alt[Second].tag("second"))
* sealed abstract class MyUnion
* final case class First extends MyUnion
* final case class Second extends MyUnion
*
* Will put an implicit coder on the companion object of `MyUnion` creating that companion object if it doesn't exist already,
* like:
*
* object MyUnion {
* implicit val jsonCoder = derive.taggedUnion.coder("type", union.alt[First].tag("first"), union.alt[Second].tag("second"))
* }
* sealed abstract class MyUnion
* final case class First extends MyUnion
* final case class Second extends MyUnion
*/
/* 2014-08-27 RMM: having multiple annotation macros which addToCompanion causes the compiler to not emit the object class (Blah$) even though
it doesn't error at runtime.
class implicitCoder(determinant: String) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.deriveImplicitTaggedUnionCoderAnnotation
}
*/
private[taggedUnion] sealed trait Alternate[A]
/** Declare a single alternate of a union. Intended only for use as syntax in a @derive.taggedUnion.* annotation */
def alternate[A](tag: String): Alternate[A] = new Alternate[A] { }
/**
* Derive an `JsonCoder` for a union (sum type), given explicitly named subtypes as alternates. The alternates should be tagged,
* but if they are not a tag based on the type name will be used.
*/
def coder[A](determinant: String, alternates: Alternate[_ <: A]*): JsonCoder[A] = macro deriveImpl.taggedUnionCoderDef[A]
/**
* Derive an `JsonEncoder` for a union (sum type), given explicitly named subtypes as alternates. The alternates should be tagged,
* but if they are not a tag based on the type name will be used.
*/
def encoder[A](determinant: String, alternates: Alternate[_ <: A]*): JsonEncoder[A] = macro deriveImpl.taggedUnionEncoderDef[A]
/**
* Derive an `JsonDecoder` for a union (sum type), given explicitly named subtypes as alternates. The alternates should be tagged,
* but if they are not a tag based on the type name will be used.
*/
def decoder[A](determinant: String, alternates: Alternate[_ <: A]*): JsonDecoder[A] = macro deriveImpl.taggedUnionDecoderDef[A]
}
/** Annotation and macro to derive union (sum type) coders that assume the various alternates follow distinct formats and tries each format in turn. */
object adHocUnion {
/**
* Automatically generate an `JsonCoder` for a union type whose alternates have been enumerated with
* a `com.paytronix.utils.interchange.base.union` annotation.
*
* For example:
*
* @derive.adHocUnion.implicitCoder("expected First or Second")
* @union(union.alt[First], union.alt[Second])
* sealed abstract class MyUnion
* final case class First extends MyUnion
* final case class Second extends MyUnion
*
* Will put an implicit coder on the companion object of `MyUnion` creating that companion object if it doesn't exist already,
* like:
*
* object MyUnion {
* implicit val jsonCoder = derive.adHocUnion.coder("expected First or Second", union.alt[First], union.alt[Second])
* }
* sealed abstract class MyUnion
* final case class First extends MyUnion
* final case class Second extends MyUnion
*
* <strong>NOTE:</strong> take care with the order of union alternates since it will try each in turn so if one is a subset of the other
* then the wrong one might be picked.
*/
/* 2014-08-27 RMM: having multiple annotation macros which addToCompanion causes the compiler to not emit the object class (Blah$) even though
it doesn't error at runtime.
class implicitCoder(noApplicableAlternates: String) extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro deriveImpl.deriveImplicitAdHocUnionCoderAnnotation
}
*/
private[adHocUnion] sealed trait Alternate[A]
/** Declare a single alternate of a union. Intended only for use as syntax in a @derive.adHocUnion.* annotation */
def alternate[A]: Alternate[A] = new Alternate[A] { }
/**
* Derive an `JsonCoder` for a union (sum type), given explicitly named subtypes as alternates. The alternates may be tagged,
* but the tag will be ignored as this type of union just tries each alternate in turn.
*/
def coder[A](noApplicableAlternates: String, alternates: Alternate[_ <: A]*): JsonCoder[A] = macro deriveImpl.adHocUnionCoderDef[A]
/**
* Derive an `JsonEncoder` for a union (sum type), given explicitly named subtypes as alternates. The alternates may be tagged,
* but the tag will be ignored as this type of union just tries each alternate in turn.
*/
def encoder[A](noApplicableAlternates: String, alternates: Alternate[_ <: A]*): JsonEncoder[A] = macro deriveImpl.adHocUnionEncoderDef[A]
/**
* Derive an `JsonDecoder` for a union (sum type), given explicitly named subtypes as alternates. The alternates may be tagged,
* but the tag will be ignored as this type of union just tries each alternate in turn.
*/
def decoder[A](noApplicableAlternates: String, alternates: Alternate[_ <: A]*): JsonDecoder[A] = macro deriveImpl.adHocUnionDecoderDef[A]
}
}
|
paytronix/utils-open
|
interchange/json/src/main/scala/com/paytronix/utils/interchange/format/json/derive.scala
|
Scala
|
apache-2.0
| 13,031 |
package com.twitter.finagle.http.filter
import com.twitter.conversions.time._
import com.twitter.finagle.http.codec.HttpDtab
import com.twitter.finagle.http.{Status, Response, Request}
import com.twitter.finagle.{Service, Dtab}
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.{AssertionsForJUnit, JUnitRunner}
@RunWith(classOf[JUnitRunner])
class DtabFilterTest extends FunSuite with AssertionsForJUnit {
private val timeout = 2.seconds
test("Extractor parses X-Dtab headers") {
val dtab = Dtab.read("/foo=>/bar;/bah=>/baz")
val service = new DtabFilter.Extractor().andThen(Service.mk[Request, Response] { req =>
val xDtabHeaders = req.headerMap.keys.filter(_.toLowerCase startsWith "x-dtab")
assert(xDtabHeaders.isEmpty, "x-dtab headers not cleared")
assert(Dtab.local == dtab)
Future.value(Response())
})
val req = Request()
HttpDtab.write(dtab, req)
Dtab.unwind {
Dtab.local = Dtab.empty
val rsp = Await.result(service(req), timeout)
assert(rsp.status == Status.Ok)
}
}
test("Extractor responds with an error on invalid dtab headers") {
val service = new DtabFilter.Extractor().andThen(Service.mk[Request, Response] { _ =>
fail("request should not have reached service")
Future.value(Response())
})
val req = Request()
// not base64 encoded
req.headers().add("X-Dtab-01-A", "/foo")
req.headers().add("X-Dtab-01-B", "/bar")
Dtab.unwind {
Dtab.local = Dtab.empty
val rsp = Await.result(service(req), timeout)
assert(rsp.status == Status.BadRequest)
assert(rsp.contentType == Some("text/plain; charset=UTF-8"))
assert(rsp.contentLength.getOrElse(0L) > 0, "content-length is zero")
assert(rsp.contentString.nonEmpty, "content is empty")
}
}
test("Injector strips new-style dtabs") {
@volatile var receivedDtab: Option[Dtab] = None
val svc = new DtabFilter.Injector().andThen(Service.mk[Request, Response] { req =>
receivedDtab = HttpDtab.read(req).toOption
Future.value(Response())
})
// prepare a request and add a correct looking new-style dtab header
val req = Request()
req.headers().add("dtab-local", "/srv=>/srv#/staging")
Await.result(svc(req), timeout)
assert(receivedDtab == Some(Dtab.empty))
}
test("Injector strips old-style dtabs") {
@volatile var receivedDtab: Option[Dtab] = None
val svc = new DtabFilter.Injector().andThen(Service.mk[Request, Response] { req =>
receivedDtab = HttpDtab.read(req).toOption
Future.value(Response())
})
// prepare a request and add a correct looking new-style dtab header
val req = Request()
req.headers().add("x-dtab-00-a", "/s/foo")
req.headers().add("x-dtab-00-b", "/s/bar")
Await.result(svc(req), timeout)
assert(receivedDtab == Some(Dtab.empty))
}
test("Injector transmits dtabs") {
@volatile var receivedDtab: Option[Dtab] = None
val svc = new DtabFilter.Injector().andThen(Service.mk[Request, Response] { req =>
receivedDtab = HttpDtab.read(req).toOption
Future.value(Response())
})
Dtab.unwind {
val origDtab = Dtab.read("/s => /srv/smf1")
Dtab.local = origDtab
// prepare a request and add a correct looking new-style dtab header
val req = Request()
Await.result(svc(req), timeout)
assert(receivedDtab == Some(origDtab))
}
}
}
|
adriancole/finagle
|
finagle-http/src/test/scala/com/twitter/finagle/http/filter/DtabFilterTest.scala
|
Scala
|
apache-2.0
| 3,510 |
package gate
import akka.actor.Actor
import util.Context
import util.FutureTransaction._
import model.Mythos._
import org.squeryl.PrimitiveTypeMode._
import model._
import play.api.Logger
import scala.concurrent.Future
import akka.actor.ActorRef
/**
* When woken, the Devourer will purge all old history.
*/
class Devourer extends Actor {
var tasks: List[Symbol] = List()
var waker: ActorRef = context.system.deadLetters
def receive = {
case 'Wake => {
Logger.info("Devourer woken")
if (tasks.size > 0) {
Logger.warn("Devourer did not finish on last run!")
}
waker = sender
tasks = List('PurgeClones, 'PurgeBabbles, 'PurgeArtifacts)
self ! 'Next
}
case 'Next => {
// Do the next task or sleep
tasks match {
case head :: tail => {
tasks = tail
self ! head
}
case Nil => {
Logger.info("Devourer sleeping")
waker ! 'DevourerSleepy
waker = context.system.deadLetters
}
}
}
case 'PurgeClones => {
performTask( futureTransaction{
clones.deleteWhere(c => (c.state === CloneState.cloned) and (c.attempted < T.ago(Clone.purgeAfter)))
})
}
case 'PurgeBabbles => {
performTask( futureTransaction{
babbles.deleteWhere(b => b.at < T.ago(Babble.purgeAfter))
})
}
case 'PurgeArtifacts => {
performTask( futureTransaction{
val purgable = from(artifacts)(a =>
where(a.witnessed < T.ago(Artifact.purgeAfter) and a.discovered < T.ago(Artifact.purgeAfter))
select(a.id)
).toList
update(presences)(p => where(p.artifactId in purgable) set(p.state := PresenceState.released))
clones.deleteWhere(c => c.artifactId in purgable)
val deletable = join(artifacts, presences.leftOuter)( (a,p) =>
where(a.witnessed < T.ago(Artifact.purgeAfter) and a.discovered < T.ago(Artifact.purgeAfter) and p.map(_.state).~.isNull)
select(a.id)
on(a.id === p.map(_.artifactId))
).toList
artifacts.deleteWhere(a => a.id in deletable)
})
}
}
def performTask[A](task: Future[A]) {
val listener = self
task.onComplete(x => listener ! 'Next)(Context.defaultOperations)
}
}
|
scott-abernethy/opener-of-the-way
|
app/gate/Devourer.scala
|
Scala
|
gpl-3.0
| 2,337 |
/*
* Copyright (c) 2012 Michael Rose
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xorlev.simon.handlers
import com.xorlev.simon.model._
import collection.mutable.ListBuffer
import collection.mutable
import util.DynamicVariable
import xml.NodeSeq
import java.io.ByteArrayInputStream
import scala.Some
import com.xorlev.simon.request.{SinatraPathPatternParser, PathPattern, RequestHandler}
import org.codehaus.jackson.map.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.xorlev.simon.util.{RenderUtil, MimeUtil}
import org.fusesource.scalate._
/**
* Dynamic App handler
* Implements a Sinatra-like API to develop applications
* 2012-12-02
* @author Michael Rose <[email protected]>
*/
class SinatraHandler extends RequestHandler {
var routes = Vector[(String, PathPattern, HttpRequest => HttpResponse)]()
val mapper = new ObjectMapper()
val engine = new TemplateEngine
mapper.registerModule(DefaultScalaModule)
val paramsMap = new DynamicVariable[Map[String,_]](null)
val requestVar = new DynamicVariable[HttpRequest](null)
implicit def params: Map[String, _] = paramsMap.value
implicit def request: HttpRequest = requestVar.value
/**
* Handles request and invokes a handler, or else it returns a 404 response
* @param request
* @return HttpResponse
*/
override def handleRequest(request: HttpRequest): Option[HttpResponse] = {
val r = request.request
// if (ctx.isDefinedAt((r.method, r.resource))) {
// //Some(runRoute(request, (r.method, r.resource)))
// } else {
// Some(NotFound(RenderUtil.notFound()))
// }
log.debug("Finding routes for {}, {}", r, routes)
var response:Option[HttpResponse] = None
routes.foreach { x =>
println(x._1 + x._2.toString)
println(x._2.apply(r.resource))
println(x._2.apply(r.resource).isDefined && x._1 == r.method)
if (x._2.apply(r.resource).isDefined && x._1 == r.method) {
try {
response = Some(runRoute(request, extractParams(x._2.apply(r.resource).getOrElse(Map.empty)), x._3))
} catch {
case e:Throwable => {
log.error("Error processing callback", e)
response = Some(HttpResponse(500, MimeUtil.HTML, RenderUtil.renderStackTrace(e)))
}
}
}
}
response
// routes.foreach {
//
// }
// routes.collectFirst {
// case (method, regex, callback) if method == r.method && regex.apply(r.resource).isDefined => {
// log.debug("Running route {}", r.resource)
// Some(runRoute(request, extractParams(regex.apply(r.resource).getOrElse(Map.empty)), callback))
// }
// case _ => {
// log.error("WTF")
// None
// }
// }.getOrElse(Some(NotFound(RenderUtil.notFound())))
}
/**
* Responsible for executing a callback with the proper DynamicVariables instantiated
* @param request
* @param routeParams
* @param callback
* @return
*/
def runRoute(request: HttpRequest, routeParams: Map[String,String], callback: HttpRequest => HttpResponse): HttpResponse = {
log.debug("Desired Content-type: " + request.getContentType)
val params = routeParams ++ request.params
paramsMap.withValue(params) {
requestVar.withValue(request) {
try {
callback(request)
} catch {
case ex:HaltedHandlerException => HttpResponse(ex.code, MimeUtil.HTML, ex.haltMessage)
}
}
}
}
private[this] def extractParams(params: Map[_, _]): Map[String,String] = {
params.map { xs =>
xs._1.toString -> xs._2.asInstanceOf[ListBuffer[_]].head.toString
}
}
private[this] def parseParams(requestParams: Map[String,String]): mutable.Map[String,String] = {
mutable.Map(requestParams.toSeq: _*).withDefaultValue(null)
}
/**
* Render pipeline, responsible for determining response format.
* @param f is a user-defined closure to generate a response
* @return HttpResponse(code, mime, data)
*/
private[this] def doRender(f: =>Any): HttpResponse = {
f match {
case n:HttpResponse => n
case n:NodeSeq => HttpResponse(200, MimeUtil.HTML, n.toString())
case n:Array[Byte] => HttpResponse(200, MimeUtil.STREAM, new ByteArrayInputStream(n))
case n:String => HttpResponse(200, MimeUtil.PLAIN, n)
case n:Any if mapper.canSerialize(n.getClass) => HttpResponse(200, MimeUtil.JSON, mapper.writeValueAsString(n))
case _ => UnprocessableEntity(RenderUtil.unprocessableEntity())
}
}
def halt(code:Int) = throw new HaltedHandlerException(code)
def halt(code:Int, msg:String) = throw new HaltedHandlerException(code, msg)
def get(path: String)(f: =>Any) = addHandler("GET", path, f)
def post(path: String)(f: =>Any) = addHandler("POST", path, f)
def put(path: String)(f: =>Any) = addHandler("PUT", path, f)
def delete(path: String)(f: =>Any) = addHandler("DELETE", path, f)
def options(path: String)(f: =>Any) = addHandler("OPTIONS", path, f)
def head(path: String)(f: =>Any) = addHandler("HEAD", path, f)
def view(path: String) = {
engine.layout(path, Map(
"request" -> request,
"params" -> params
))
}
private[this] def addHandler(method: String, path: String, f: =>Any) {
//ctx.put((method, path), x=>doRender(f))
addRoute(method, path)(x=>doRender(f))
}
def addRoute(method: String, path: String)(callback: HttpRequest => HttpResponse) {
val regex = SinatraPathPatternParser(path)
routes = routes :+ (method, regex, callback)
}
}
|
Xorlev/Simon
|
simon-sinatra-handler/src/main/scala/com/xorlev/simon/handlers/SinatraHandler.scala
|
Scala
|
apache-2.0
| 6,108 |
class HelloName(name: String) {
def hello = println("Hello "+name+"!")
override def toString = "HelloName("+name+")"
}
|
grzegorzbalcerek/scala-book-examples
|
examples/HelloName.scala
|
Scala
|
mit
| 123 |
package com.spark
import org.apache.log4j.{Level, Logger}
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
import scala.Tuple2
object AvgFriendsByAge {
def main(args: Array[String]): Unit = {
Logger.getLogger("org").setLevel(Level.ERROR)
val sparkConf = new SparkConf()
.setMaster("spark://vkurugun-mac.local:7077")
.setAppName("Test")
.set("spark.executor.memory", "1g")
.set("spark.cores.max", "4")
val sc = new SparkContext(sparkConf)
val tags = sc.textFile("file:/Users/VikramBabu/open-source/practice/ml-20m/fakefriends.csv")
val avgByAge = tags.map(line => {
val fields = line.split(",")
(fields(2), fields(3).toInt)
}).mapValues((x : Int) => (x, 1)).reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2)).mapValues(x => x._1/x._2).collect()
// 32, (100, 1)
// 32, (110, 1)
// 32, (120, 1)
// 32, (90, 1)
// 50, (10, 1)
// 60, (10, 1)
//one to one mapping
// x to y conversion
// 32 => (100, 1), (110, 1) => (100+110, 1+1) => (210, 2)
// 32 => (120, 1), (90, 1) => (210, 2)
// 32 => (210, 2), (210, 2) => (420, 4)
// RDD[(Int, Tuple2(Int, Int))]
// 32 => 105
// 10 -> 10
// 100 -> 10
// RDD[Int, Tuple2(Int, Int)]
// 32, (100, 1)
// 50, (10, 1)
//
// Int 100 -> (100, 1) Tuple2(x: Int, x:Int)
// 10 -> (10, 1)
// 15 -> (15, 1)
//
// 32, 100
// 50, 10
// 34, 15
avgByAge.sorted.foreach(println)
// Thread.sleep(10000000)
}
}
|
vikramkb/spark
|
src/main/scala/com/spark/AvgFriendsByAge.scala
|
Scala
|
apache-2.0
| 1,534 |
package org.psesd.srx.services.prs
import org.mongodb.scala.Document
import org.mongodb.scala.bson.BsonValue
/** Student Success Link Data Organization Model
*
* @version 1.0
* @since 1.0
* @author Margarett Ly (iTrellis, LLC)
*/
object SslOrganization extends SslEntity {
def apply(authorizedEntityId: String, externalServiceId: BsonValue, createdAt: BsonValue = null): Document = {
val authorizedEntityXml = getAuthorizedEntity(authorizedEntityId)
val timestamp = bsonTimeStamp
var organization = Document("name" -> (authorizedEntityXml \\ "authorizedEntity" \\ "name").text,
"website" -> (authorizedEntityXml \\ "authorizedEntity" \\ "mainContact" \\ "webAddress").text,
"url" -> (authorizedEntityXml \\ "authorizedEntity" \\ "mainContact" \\ "webAddress").text,
"authorizedEntityId" -> (authorizedEntityXml \\ "authorizedEntity" \\ "id").text.toInt,
"externalServiceId" -> externalServiceId,
"updated_at" -> timestamp)
if (createdAt != null) {
organization ++= Document("created_at" -> createdAt)
} else {
organization ++= Document("created_at" -> timestamp)
}
organization
}
def name(authorizedEntityId: String): String = {
val authorizedEntityXml = getAuthorizedEntity(authorizedEntityId)
(authorizedEntityXml \\ "authorizedEntity" \\ "name").text
}
}
|
PSESD/srx-services-prs
|
src/main/scala/org/psesd/srx/services/prs/SslOrganization.scala
|
Scala
|
mit
| 1,350 |
package leo.modules.calculus
import leo.datastructures.Type.BoundType
import scala.annotation.tailrec
import leo.datastructures.{BFSAlgorithm, NDStream, SearchConfiguration, Subst, Term, Type}
import leo.modules.myAssert
trait Matching {
type UEq = (Term, Term); type UTEq = (Type, Type)
type TermSubst = Subst; type TypeSubst = Subst
type Result = (TermSubst, TypeSubst)
/** Returns an iterable of substitutions (σ_i) such that sσ_i = t and there exists no such ϱ
* which is more general than σ_i. */
def matchTerms(vargen: FreshVarGen, s: Term, t: Term, forbiddenVars: Set[Int] = null): Iterable[Result]
def matchTermList(vargen: FreshVarGen, ueqs: Seq[(Term, Term)], forbiddenVars: Set[Int] = null): Iterable[Result]
}
object Matching {
val impl: Matching = HOPatternMatching
def apply(vargen: FreshVarGen, s: Term, t: Term, forbiddenVars: Set[Int] = null): Iterable[Matching#Result] =
impl.matchTerms(vargen, s, t, forbiddenVars)
def applyList(vargen: FreshVarGen, ueqs: Seq[(Term, Term)], forbiddenVars: Set[Int] = null): Iterable[Matching#Result] =
impl.matchTermList(vargen, ueqs, forbiddenVars)
}
@deprecated("HOMatching (i.e. matching based on full HO (pre-) unification) " +
"is broken at the moment (gives false positives).", "Leo-III 1.2")
object HOMatching extends Matching {
/** The Depth is the number of lambda abstractions under which a term is nested.*/
type Depth = Int
/** `UEq0` extends UEq with an depth indicator. */
type UEq0 = (Term, Term, Depth)
/** A `SEq` is a solved equation. */
type SEq = (Term, Term)
/** `STEq` is a solved type equation. */
type STEq = UTEq
/** Maximal unification search depth (i.e. number of flex-rigid rules on search path). */
final lazy val MAX_DEPTH = leo.Configuration.MATCHING_DEPTH
/////////////////////////////////////
// the state of the search space
/////////////////////////////////////
protected[calculus] case class MyConfiguration(unprocessed: Seq[UEq],
flexRigid: Seq[UEq0],
solved: TermSubst, solvedTy: TypeSubst,
result: Option[Result], searchDepth: Int)
extends SearchConfiguration[Result] {
def this(result: Result) = this(null, null, null, null, Some(result), Int.MaxValue) // for success
def this(unprocessed: Seq[UEq],
flexRigid: Seq[UEq0],
solved: TermSubst, solvedTy: TypeSubst,
searchDepth: Int) = this(unprocessed, flexRigid, solved, solvedTy, None, searchDepth) // for in node
override final def isTerminal: Boolean = searchDepth >= MAX_DEPTH
override def toString = s"{${unprocessed.map(x => s"<${x._1},${x._2}>").mkString}}"
}
def matchTerms(vargen: FreshVarGen, s: Term, t: Term, forbiddenVars: Set[Int] = null): Iterable[Result] =
matchTermList(vargen, Seq((s,t)), forbiddenVars)
def matchTermList(vargen: FreshVarGen, ueqs: Seq[(Term, Term)], forbiddenVars: Set[Int] = null): Iterable[Result] = {
if (ueqs.exists{case (s,t) => s.ty != t.ty}) throw new NotImplementedError()
else {
val ueqs0 = ueqs.map {case (s,t) => (s.etaExpand, t.etaExpand)}.toVector
new NDStream[Result](new MyConfiguration(ueqs0, Vector.empty, Subst.id, Subst.id, 0), new EnumUnifier(vargen, Subst.id)) with BFSAlgorithm
}
}
/////////////////////////////////////
// Internal search functions
/////////////////////////////////////
/** the transition function in the search space (returned list containing more than one element -> ND step, no element -> failed branch) */
protected[calculus] class EnumUnifier(vargen: FreshVarGen, initialTypeSubst: TypeSubst) extends Function1[SearchConfiguration[Result], Seq[SearchConfiguration[Result]]] {
// Huets procedure is defined here
override def apply(conf2: SearchConfiguration[Result]): Seq[SearchConfiguration[Result]] = {
val conf = conf2.asInstanceOf[MyConfiguration]
// we always assume conf.uproblems is sorted and that delete, decomp and bind were applied exaustively
val (fail, flexRigid, partialUnifier, partialTyUnifier) = detExhaust(conf.unprocessed,
conf.flexRigid,
conf.solved, Seq(), conf.solvedTy)
leo.Out.finest(s"Finished detExhaust")
// if uTyProblems is non-empty fail
if (fail) {
leo.Out.debug(s"Matching failed.")
Seq()
} else {
// if there is no unsolved equation, then succeed
if (flexRigid.isEmpty) {
leo.Out.debug(s"Matching finished")
leo.Out.debug(s"\\tTerm substitution ${partialUnifier.normalize.pretty}")
leo.Out.debug(s"\\tType substitution ${partialTyUnifier.normalize.pretty}")
Seq(new MyConfiguration((partialUnifier.normalize, initialTypeSubst.comp(partialTyUnifier).normalize)))
}
// else do flex-rigid cases
else {
assert(flexRigid.nonEmpty)
leo.Out.finest(s"flex-rigid at depth ${conf.searchDepth}")
val head = flexRigid.head
import scala.collection.mutable.ListBuffer
val lb = new ListBuffer[MyConfiguration]
// compute the imitate partial binding and add the new configuration
if (ImitateRule.canApply(head)) lb.append(new MyConfiguration(Seq(ImitateRule(vargen, head)), flexRigid,
partialUnifier, partialTyUnifier, conf.searchDepth+1))
// compute all the project partial bindings and add them to the return list
ProjectRule(vargen, head).foreach (e => lb.append(new MyConfiguration(Seq(e), flexRigid,
partialUnifier, partialTyUnifier, conf.searchDepth+1)))
lb.toList
}
}
}
}
@tailrec
final protected[calculus] def tyDetExhaust(uTyProblems: Seq[UTEq], unifier: TypeSubst): Option[TypeSubst] = {
if (uTyProblems.nonEmpty) {
val head = uTyProblems.head
if (TyDeleteRule.canApply(head))
tyDetExhaust(uTyProblems.tail, unifier)
else if (TyDecompRule.canApply(head))
tyDetExhaust(TyDecompRule.apply(head) ++ uTyProblems.tail, unifier)
else {
val tyFunDecompRuleCanApplyHint = TyFunDecompRule.canApply(head)
if (tyFunDecompRuleCanApplyHint != TyFunDecompRule.CANNOT_APPLY) {
tyDetExhaust(TyFunDecompRule.apply(head, tyFunDecompRuleCanApplyHint) ++ uTyProblems.tail,unifier)
} else {
val tyBindRuleCanApplyHint = TyBindRule.canApply(head)
if (tyBindRuleCanApplyHint != CANNOT_APPLY)
tyDetExhaust(uTyProblems.tail, unifier.comp(TyBindRule.apply(head, tyBindRuleCanApplyHint)))
else None
}
}
} else Some(unifier)
}
/** Exhaustively apply delete, comp and bind on the set of unprocessed equations. */
@tailrec
final protected[calculus] def detExhaust(unprocessed: Seq[UEq],
flexRigid: Seq[UEq0],
solved: TermSubst,
uTyProblems: Seq[UTEq], solvedTy: TypeSubst):
(Boolean, Seq[UEq0], TermSubst, TypeSubst) = {
// (fail, flexRigid, flexflex, solved, solvedTy)
leo.Out.finest(s"Unsolved (term eqs): ${unprocessed.map(eq => eq._1.pretty + " = " + eq._2.pretty).mkString("\\n\\t")}")
leo.Out.finest(s"Unsolved (type eqs): ${uTyProblems.map(eq => eq._1.pretty + " = " + eq._2.pretty).mkString("\\n\\t")}")
if (uTyProblems.nonEmpty) {
val head = uTyProblems.head
// Try all type rules
if (TyDeleteRule.canApply(head))
detExhaust(unprocessed, flexRigid, solved, uTyProblems.tail, solvedTy)
else if (TyDecompRule.canApply(head))
detExhaust(unprocessed, flexRigid, solved, TyDecompRule.apply(head) ++ uTyProblems.tail, solvedTy)
else {
val tyFunDecompRuleCanApplyHint = TyFunDecompRule.canApply(head)
if (tyFunDecompRuleCanApplyHint != TyFunDecompRule.CANNOT_APPLY) {
detExhaust(unprocessed, flexRigid, solved,
TyFunDecompRule.apply(head, tyFunDecompRuleCanApplyHint) ++ uTyProblems.tail, solvedTy)
} else {
val tyBindRuleCanApplyHint = TyBindRule.canApply(head)
if (tyBindRuleCanApplyHint != CANNOT_APPLY) {
val subst = TyBindRule.apply(head, tyBindRuleCanApplyHint)
leo.Out.finest(s"Ty Bind: ${subst.pretty}")
detExhaust(applySubstToList(Subst.id, subst, unprocessed),
applyTySubstToList(subst, flexRigid),
solved.applyTypeSubst(subst), uTyProblems.tail, solvedTy.comp(subst))
} else // No type rule applicable for head, so it's a fail, just return a fail state
(true, flexRigid, solved, solvedTy)
}
}
} else {
// check unprocessed
if (unprocessed.nonEmpty) {
val head0 = unprocessed.head
leo.Out.finest(s"detExhaust on: ${head0._1.pretty} = ${head0._2.pretty}")
// Try all term rules
if (DeleteRule.canApply(head0)) {
leo.Out.finest("Apply delete")
detExhaust(unprocessed.tail, flexRigid, solved, uTyProblems, solvedTy)
} else {
val left = head0._1
val right = head0._2
val (leftBody, leftAbstractions) = collectLambdas(left)
val (rightBody, rightAbstractions) = collectLambdas(right)
assert(leftAbstractions == rightAbstractions)
val abstractionCount = leftAbstractions.size
if (DecompRule.canApply((leftBody, rightBody), abstractionCount)) {
leo.Out.finest("Apply decomp")
val (newUnsolvedTermEqs, newUnsolvedTypeEqs) = DecompRule.apply((leftBody, rightBody), leftAbstractions)
detExhaust(newUnsolvedTermEqs ++ unprocessed.tail, flexRigid,
solved, newUnsolvedTypeEqs ++ uTyProblems, solvedTy)
} else {
val bindHint = BindRule.canApply(leftBody, rightBody, abstractionCount)
if (bindHint != CANNOT_APPLY) {
val subst = BindRule.apply(head0, bindHint)
leo.Out.finest(s"Bind: ${subst.pretty}")
detExhaust(
applySubstToList(subst, Subst.id, flexRigid.map(e => (e._1, e._2)) ++ unprocessed.tail),
Seq(),
solved.comp(subst), uTyProblems, solvedTy)
} else {
// ... move to according list if nothing applies
if (!isFlexible(head0._1, abstractionCount)) {
// if head is not flexible, fail
(true, flexRigid, solved, solvedTy)
} else {
detExhaust(unprocessed.tail, (left, right, abstractionCount) +: flexRigid,
solved, uTyProblems, solvedTy)
}
}
}
}
} else {
// no unprocessed left, return sets
(false, flexRigid, solved, solvedTy)
}
}
}
/////////////////////////////////////
// Huets rules
/////////////////////////////////////
final val CANNOT_APPLY = -1
/**
* Delete rule for types
* canApply(s,t) iff the equation (s = t) can be deleted
*/
object TyDeleteRule {
final def canApply(e: UTEq): Boolean = e._1 == e._2
}
object TyDecompRule {
import leo.datastructures.Type.ComposedType
final def apply(e: UTEq): Seq[UTEq] = {
val args1 = ComposedType.unapply(e._1).get._2
val args2 = ComposedType.unapply(e._2).get._2
args1.zip(args2)
}
final def canApply(e: UTEq): Boolean = e match {
case (ComposedType(head1, _), ComposedType(head2, _)) => head1 == head2 // Heads cannot be flexible,
// since in TH1 only small types/proper types can be quantified, not type operators
case _ => false
}
}
object TyFunDecompRule {
final val CANNOT_APPLY = -1
final val EQUAL_LENGTH = 0
final val FIRST_LONGER = 1
final val SECOND_LONGER = 2
final def apply(e: UTEq, hint: Int): Seq[UTEq] = {
assert(hint != CANNOT_APPLY)
if (hint == EQUAL_LENGTH) {
e._1.funParamTypesWithResultType.zip(e._2.funParamTypesWithResultType)
} else {
val shorterTyList = if (hint == FIRST_LONGER) e._2.funParamTypesWithResultType
else e._1.funParamTypesWithResultType
val longerTy = if (hint == FIRST_LONGER) e._1 else e._2
val splittedLongerTy = longerTy.splitFunParamTypesAt(shorterTyList.size-1)
(shorterTyList.last, splittedLongerTy._2) +: shorterTyList.init.zip(splittedLongerTy._1)
}
}
final def canApply(e: UTEq): Int = {
if (!e._1.isFunType || !e._2.isFunType) CANNOT_APPLY
else {
val tys1 = e._1.funParamTypesWithResultType
val tys2 = e._2.funParamTypesWithResultType
if (tys1.size == tys2.size) EQUAL_LENGTH
else {
val tys1Longer = tys1.size > tys2.size
val shorterTyList = if (tys1Longer) tys2 else tys1
if (shorterTyList.last.isBoundTypeVar) // Only possible if last one is variable
if (tys1Longer) FIRST_LONGER
else SECOND_LONGER
else CANNOT_APPLY
}
}
}
}
/**
* Bind rule for type equations.
* canApply(s,t) iff either s or t is a type variable and not a subtype of the other one.
*/
object TyBindRule {
import leo.datastructures.Type.BoundType
final def apply(e: UTEq, hint: Int): Subst = {
Subst.singleton(hint, e._2)
}
final def canApply(e: UTEq): Int = {
val leftIsTypeVar = e._1.isBoundTypeVar
if (!leftIsTypeVar) CANNOT_APPLY
else {
val tyVar = BoundType.unapply(e._1).get
val otherTy = e._2
if (!otherTy.typeVars.contains(tyVar)) tyVar else CANNOT_APPLY
}
}
}
/**
* 1
* returns true if the equation can be deleted
*/
object DeleteRule {
final def canApply(e: UEq): Boolean = e._1 == e._2
}
/**
* 2
* returns the list of equations if the head symbols are the same function symbol.
*/
object DecompRule {
import leo.datastructures.Term.∙
final def apply(e: UEq, abstractions: Seq[Type]): (Seq[UEq], Seq[UTEq]) = e match {
case (_ ∙ sq1, _ ∙ sq2) => zipArgumentsWithAbstractions(sq1, sq2, abstractions)
case _ => throw new IllegalArgumentException("impossible")
}
final def canApply(e: UEq, depth: Depth): Boolean = e match {
case (hd1 ∙ _, hd2 ∙ _) if hd1 == hd2 => !isFlexible(hd1, depth)
case _ => false
}
}
/**
* 3
* BindRule tells if Bind is applicable
* equation is not oriented
* return an equation (x,s) substitution is computed from this equation later
*/
object BindRule {
type Side = Int
final def apply(e: UEq, variable: Int): Subst = {
assert(variable != CANNOT_APPLY)
Subst.singleton(variable, e._2)
}
final def canApply(leftBody: Term, rightBody: Term, depth: Int): Int = {
import leo.datastructures.getVariableModuloEta
// is applicable if left side is a variable
val possiblyLeftVar = getVariableModuloEta(leftBody, depth)
if (possiblyLeftVar > 0) {
// do occurs check on right
if (rightBody.looseBounds.contains(possiblyLeftVar + depth)) CANNOT_APPLY else possiblyLeftVar
} else CANNOT_APPLY
}
}
/**
* 4a
* equation is not oriented
* not to forget that the approximations must be in eta-long-form
*/
object ImitateRule {
import leo.datastructures.Term.{∙, :::>}
private final def takePrefixTypeArguments(t: Term): Seq[Type] = {
t match {
case _ ∙ args => args.takeWhile(_.isRight).map(_.right.get)
case _ :::> body => takePrefixTypeArguments(body)
case _ => Seq()
}
}
final def apply(vargen: FreshVarGen, e: UEq0): UEq = {
import leo.datastructures.Term.Bound
leo.Out.finest(s"Apply Imitate")
leo.Out.finest(s"on ${e._1.pretty} = ${e._2.pretty}")
val depth : Int = e._3
// orienting the equation
val (t,s) = (e._1,e._2)
val s0 = if (s.headSymbol.ty.isPolyType) {
leo.Out.finest(s"head symbol is polymorphic")
Term.mkTypeApp(s.headSymbol, takePrefixTypeArguments(s))}
else
s.headSymbol
leo.Out.finest(s"chose head symbol to be ${s0.pretty}, type: ${s0.ty.pretty}")
val variable = Bound.unapply(t.headSymbol).get
val liftedVar = Term.mkBound(variable._1, variable._2 - depth).etaExpand
val res = (liftedVar, partialBinding(vargen, t.headSymbol.ty, s0))
leo.Out.finest(s"Result of Imitate: ${res._1.pretty} = ${res._2.pretty}")
res
}
// must make sure s (rigid-part) doesnt have as head a bound variable
final def canApply(e: UEq0): Boolean = {
import leo.datastructures.Term.Bound
val s = e._2
s.headSymbol match {
// cannot be flexible and fail on bound variable
case Bound(_,scope) => scope > e._3
case _ => true
}
}
}
/**
* 4b
* equation is not oriented
* Always applicable on flex-rigid equations not under application of Bind
* Alex: I filtered out all of those bound vars that have non-compatible type. Is that correct?
*/
object ProjectRule {
final def apply(vargen: FreshVarGen, e: UEq0): Seq[UEq] = {
import leo.datastructures.Term.Bound
leo.Out.finest(s"Apply Project")
val depth = e._3
// orienting the equation
val t = e._1
// FIXME: what to fix?
val bvars = t.headSymbol.ty.funParamTypes.zip(List.range(1,t.headSymbol.ty.arity+1).reverse).map(p => Term.mkBound(p._1,p._2))
leo.Out.finest(s"BVars in Projectrule: ${bvars.map(_.pretty).mkString(",")}")
//Take only those bound vars that are itself a type with result type == type of general binding
val funBVars = bvars.filter(bvar => t.headSymbol.ty.funParamTypesWithResultType.endsWith(bvar.ty.funParamTypesWithResultType))
leo.Out.finest(s"compatible type BVars in Projectrule: ${funBVars.map(_.pretty).mkString(",")}")
val variable = Bound.unapply(t.headSymbol).get
val liftedVar = Term.mkBound(variable._1, variable._2 - depth).etaExpand
val res = funBVars.map(bvar => (liftedVar, partialBinding(vargen, t.headSymbol.ty, bvar)))
leo.Out.finest(s"Result of Project:\\n\\t${res.map(eq => eq._1.pretty ++ " = " ++ eq._2.pretty).mkString("\\n\\t")}")
res
}
}
/////////////////////////////////////
// Internal utility functions
/////////////////////////////////////
@inline protected[calculus] final def flexflex(e: UEq, depth: Int): Boolean = isFlexible(e._1, depth) && isFlexible(e._2, depth)
@inline protected[calculus] final def flexrigid(e: UEq, depth: Int): Boolean = (isFlexible(e._1, depth) && !isFlexible(e._2, depth)) || (!isFlexible(e._1, depth) && isFlexible(e._2, depth))
@inline protected[calculus] final def rigidrigid(e: UEq, depth: Int): Boolean = !isFlexible(e._1, depth) && !isFlexible(e._2, depth)
@inline protected[calculus] final def isFlexible(t: Term, depth: Int): Boolean = {
import leo.datastructures.Term.Bound
t.headSymbol match {
case Bound(_, scope) => scope > depth
case _ => false
}
}
// private final def applySubstToList(termSubst: Subst, typeSubst: Subst, l: Seq[UEq0]): Seq[UEq0] =
// l.map(e => (e._1.substitute(termSubst,typeSubst),e._2.substitute(termSubst,typeSubst), e._3))
@inline protected[calculus] final def applySubstToList(termSubst: Subst, typeSubst: Subst, l: Seq[(Term, Term)]): Seq[(Term, Term)] =
l.map(e => (e._1.substitute(termSubst,typeSubst),e._2.substitute(termSubst,typeSubst)))
@inline private final def applyTySubstToList(typeSubst: Subst, l: Seq[UEq0]): Seq[UEq0] =
l.map(e => (e._1.substitute(Subst.id, typeSubst),e._2.substitute(Subst.id, typeSubst), e._3))
protected[calculus] final def zipArgumentsWithAbstractions(l: Seq[Either[Term, Type]], r: Seq[Either[Term, Type]],
abstractions: Seq[Type]): (Seq[UEq], Seq[UTEq]) =
zipArgumentsWithAbstractions0(l,r,abstractions, Seq(), Seq())
@tailrec @inline
private final def zipArgumentsWithAbstractions0(l: Seq[Either[Term, Type]], r: Seq[Either[Term, Type]],
abstractions: Seq[Type],
acc1: Seq[UEq], acc2: Seq[UTEq]): (Seq[UEq], Seq[UTEq]) = {
import leo.datastructures.Term.λ
if (l.isEmpty && r.isEmpty) (acc1, acc2)
else if (l.nonEmpty && r.nonEmpty) {
val leftHead = l.head
val rightHead = r.head
if (leftHead.isLeft && rightHead.isLeft) {
val leftTerm = λ(abstractions)(leftHead.left.get)
val rightTerm = λ(abstractions)(rightHead.left.get)
zipArgumentsWithAbstractions0(l.tail, r.tail, abstractions, (leftTerm.etaExpand, rightTerm.etaExpand) +: acc1, acc2)
} else if (leftHead.isRight && rightHead.isRight) {
val leftType = leftHead.right.get
val rightType = rightHead.right.get
zipArgumentsWithAbstractions0(l.tail, r.tail, abstractions, acc1, (leftType, rightType) +: acc2)
} else throw new IllegalArgumentException("Mixed type/term arguments for equal head symbol. Decomp Failing.")
} else {
throw new IllegalArgumentException("Decomp on differently sized arguments length. Decomp Failing.")
}
}
protected[calculus] final def collectLambdas(t: Term): (Term, Seq[Type]) = collectLambdas0(t, Seq())
@tailrec
private final def collectLambdas0(t: Term, abstractions: Seq[Type]): (Term, Seq[Type]) = {
import leo.datastructures.Term.:::>
t match {
case ty :::> body => collectLambdas0(body, ty +: abstractions)
case _ => (t, abstractions.reverse)
}
}
}
object HOPatternMatching extends Matching {
/** Returns an iterable of substitutions (σ_i) such that tσ_i = s and there exists no such ϱ
* which is more general than σ_i. */
override def matchTerms(vargen: FreshVarGen, t: Term, s: Term, forbiddenVars: Set[Int] = null): Iterable[Result] = {
matchTermList(vargen, Vector((t,s)), forbiddenVars)
}
def matchTermList(vargen: FreshVarGen, ueqs: Seq[(Term, Term)], forbiddenVars: Set[Int] = null): Iterable[Result] = {
val initialTypeSubst = TypeMatching(ueqs.map(e => (e._1.ty, e._2.ty)))
if (initialTypeSubst.isEmpty)
Iterable.empty
else {
val initialTypeSubst0 = initialTypeSubst.get
val ueqs0 = ueqs.map(eq => (eq._1.substitute(Subst.id, initialTypeSubst0).etaExpand, eq._2.substitute(Subst.id, initialTypeSubst0).etaExpand))
val forbiddenVars0 = if (forbiddenVars == null) ueqs.flatMap(_._2.looseBounds).toSet else forbiddenVars
leo.Out.finest(s"Forbidden vars: ${forbiddenVars0.toString()}")
val matchResult = match0(ueqs0, initialTypeSubst0, vargen, forbiddenVars0)
if (matchResult.isDefined) {
leo.Out.finest(s"Matching succeeded!")
Seq(matchResult.get)
} else {
leo.Out.finest(s"Matching failed!")
Iterable.empty
}
}
}
/** Wrap up the matching result with the initial type substitution and return as Option. */
private final def match0(ueqs: Seq[UEq], initialTypeSubst: TypeSubst, vargen: FreshVarGen, forbiddenVars: Set[Int]): Option[Result] = {
leo.Out.finest(s"match0: ${ueqs.map{case (l,r) => l.pretty ++ " = " ++ r.pretty}.mkString("\\n")}")
val matcher = match1(ueqs, vargen, Subst.id, Subst.id, forbiddenVars)
if (matcher.isDefined)
Some((matcher.get._1.normalize, initialTypeSubst.comp(matcher.get._2).normalize))
else
None
}
type PartialResult = Result
/** Main matching method: Solve head equations subsequently by applying the according rules. */
@tailrec
private final def match1(ueqs: Seq[UEq], vargen: FreshVarGen, partialMatcher: TermSubst, partialTyMatcher: TypeSubst,
forbiddenVars: Set[Int]): Option[PartialResult] = {
import leo.datastructures.Term.{Bound, ∙}
import leo.datastructures.{partitionArgs, collectLambdas}
import HuetsPreUnification.{applySubstToList, zipWithAbstractions}
if (ueqs.isEmpty)
Some((partialMatcher, partialTyMatcher))
else {
val (l0,r0) = ueqs.head
if (l0 == r0) match1(ueqs.tail, vargen, partialMatcher, partialTyMatcher, forbiddenVars)
else {
val l = l0.substitute(partialMatcher, partialTyMatcher).etaExpand
val r = r0
leo.Out.finest(s"solve: ${l.pretty} = ${r.pretty}")
myAssert(Term.wellTyped(l))
myAssert(Term.wellTyped(r))
// take off the lambdas
val (leftBody, leftAbstractions) = collectLambdas(l)
val (rightBody, rightAbstractions) = collectLambdas(r)
assert(leftAbstractions == rightAbstractions)
val abstractionCount = leftAbstractions.size
(leftBody, rightBody) match {
case (hd1 ∙ args1, hd2 ∙ args2) => (hd1, hd2) match {
case (Bound(ty1, idx1), _) if idx1 > abstractionCount && !forbiddenVars.contains(idx1-abstractionCount) =>
/* flex-rigid or flex-flex */
if (r.looseBounds.contains(idx1 - abstractionCount)) None
else {
leo.Out.finest("Apply Flex-rigid")
val result = flexrigid(idx1 - abstractionCount, ty1, args1, hd2, args2, rightBody, vargen, leftAbstractions)
if (result == null) None
else {
val partialMatchingResult = result._1
val newUeqs = result._2
leo.Out.finest(s"flex-rigid result matcher: ${partialMatchingResult._1.pretty}")
leo.Out.finest(s"flex-rigid result new unsolved: ${newUeqs.map{case (l,r) => l.pretty ++ " = " ++ r.pretty}.mkString("\\n")}")
match1(newUeqs ++ ueqs.tail, vargen, partialMatcher.comp(partialMatchingResult._1),
partialTyMatcher.comp(partialMatchingResult._2), forbiddenVars)
}
}
case (_, Bound(_, idx2)) if idx2 > abstractionCount=>
/* rigid-flex */
None // right side is considered rigid in this matching setting
case _ => /* rigid-rigid */
if (hd1 == hd2) {
leo.Out.finest("Apply rigid-rigid")
if (hd1.ty.isPolyType) {
leo.Out.finest(s"Poly rigid-rigid")
val (tyArgs1, termArgs1) = partitionArgs(args1)
val (tyArgs2, termArgs2) = partitionArgs(args2)
assert(tyArgs1.size == tyArgs2.size)
val tyMatchingConstraints = tyArgs1.zip(tyArgs2)
leo.Out.finest(s"ty constraints: ${tyMatchingConstraints.map(c => c._1.pretty + " = " + c._2.pretty).mkString(",")}")
val tyMatchingResult = TypeMatching(tyMatchingConstraints)
if (tyMatchingResult.isDefined) {
val tySubst = tyMatchingResult.get
leo.Out.finest(s"Poly rigid-rigid match succeeded: ${tySubst.pretty}")
val newUeqs = zipWithAbstractions(termArgs1, termArgs2, leftAbstractions.map(_.substitute(tySubst)))
leo.Out.finest(s"New unsolved:\\n\\t${newUeqs.map(eq => eq._1.pretty + " = " + eq._2.pretty).mkString("\\n\\t")}")
match1(applySubstToList(Subst.id, tySubst, newUeqs ++ ueqs.tail), vargen,
partialMatcher.applyTypeSubst(tySubst), partialTyMatcher.comp(tySubst), forbiddenVars)
} else {
leo.Out.finest(s"Poly rigid-rigid uni failed")
None
}
} else {
val termArgs1 = args1.map(_.left.get)
val termArgs2 = args2.map(_.left.get)
val newUeqs = zipWithAbstractions(termArgs1, termArgs2, leftAbstractions)
leo.Out.finest(s"New unsolved:\\n\\t${newUeqs.map(eq => eq._1.pretty + " = " + eq._2.pretty).mkString("\\n\\t")}")
match1(newUeqs ++ ueqs.tail, vargen, partialMatcher, partialTyMatcher, forbiddenVars)
}
} else None
}
case _ => assert(false); None
}
}
}
}
/** Flex-rigid rule: May fail, returns null if not sucessful. */
private final def flexrigid(idx1: Int, ty1: Type, args1: Seq[Either[Term, Type]], rigidHd: Term, rigidArgs: Seq[Either[Term, Type]], rigidAsTerm: Term, vargen: FreshVarGen, depth: Seq[Type]): (PartialResult, Seq[UEq]) = {
import leo.datastructures.partitionArgs
import leo.datastructures.Term.Bound
try {
val args10 = args1.map(_.left.get)
// This is a bit hacky: We need the new fresh variables
// introduced by partialBinding(...), so we just take the
// difference of vars in vargen (those have been introduced).
// Maybe this should be done better...
val varsBefore = vargen.existingVars
if (rigidHd.isVariable && Bound.unapply(rigidHd).get._2 <= depth.size) {
if (!args10.contains(rigidHd.etaExpand)) return null /*fail*/
// variables cannot be polymorphic, calculating projection binding.
// newrigidHd: position of bound rigid hd in flex-args-list
val newrigidHd = Term.local.mkBound(rigidHd.ty, args10.size - args10.indexOf(rigidHd.etaExpand))
val binding = partialBinding(vargen, ty1, newrigidHd)
leo.Out.finest(s"binding: $idx1 -> ${binding.pretty}")
val varsAfter = vargen.existingVars
val subst = Subst.singleton(idx1, binding)
// new equations:
val newVars = newVarsFromGenerator(varsBefore, varsAfter).reverse // reverse since highest should be the last
assert(newVars.size == rigidArgs.size)
val newueqs = newUEqs(newVars, args10, rigidArgs.map(_.left.get), depth)
((subst, Subst.id), newueqs)
} else {
assert(rigidHd.isConstant || rigidHd.isNumber || (rigidHd.isVariable && Bound.unapply(rigidHd).get._2 > depth.size))
// Constants may be polymorphic: Apply types before calculating imitation binding.
val rigidArgs0 = partitionArgs(rigidArgs)
assert(rigidArgs0._1.isEmpty || rigidHd.ty.isPolyType)
val rigidHd0 = if (rigidHd.ty.isPolyType) {
leo.Out.finest(s"head symbol is polymorphic")
Term.local.mkTypeApp(rigidHd, rigidArgs0._1)}
else
rigidHd
val binding = partialBinding(vargen, ty1, rigidHd0.lift(ty1.funParamTypes.size - depth.size))
leo.Out.finest(s"binding: $idx1 -> ${binding.pretty}")
val varsAfter = vargen.existingVars
val subst = Subst.singleton(idx1, binding)
// new equations:
val newVars = newVarsFromGenerator(varsBefore, varsAfter).reverse // reverse since highest should be the last
assert(newVars.size == rigidArgs0._2.size) // FIXME
val newueqs = newUEqs(newVars, args10, rigidArgs0._2, depth)
((subst, Subst.id), newueqs)
}
} catch {
case _:NoSuchElementException => null
}
}
private final def newVarsFromGenerator(oldVars: Seq[(Int, Type)], newVars: Seq[(Int, Type)]): Seq[(Int, Type)] = {
newVars.takeWhile(elem => !oldVars.contains(elem))
}
private final def newUEqs(freeVars: Seq[(Int, Type)], boundVarArgs: Seq[Term], otherTermList: Seq[Term], depth: Seq[Type]): Seq[UEq] = {
import leo.datastructures.Term.local.{mkTermApp, mkBound, λ}
if (freeVars.isEmpty) Nil
else {
val hd = freeVars.head
(λ(depth)(mkTermApp(mkBound(hd._2, hd._1+depth.size), boundVarArgs)).etaExpand, λ(depth)(otherTermList.head).etaExpand) +: newUEqs(freeVars.tail, boundVarArgs, otherTermList.tail, depth)
}
}
}
trait TypeMatching {
type UEq = (Type, Type) // Left one is the only one that can be bound, right is considered rigid.
type TypeSubst = Subst
/** Returns a substitution `Some(σ)` such that sσ = t. Returns `None` if no such `σ` exists. */
def matching(s: Type, t: Type): Option[TypeSubst]
/** Returns a substitution `Some(σ)` such that s_iσ = t_i. Returns `None` if no such `σ` exists. */
def matching(uEqs: Seq[UEq]): Option[TypeSubst]
}
object TypeMatching {
private val impl: TypeMatching = TypeMatchingImpl
/** Returns a substitution `Some(σ)` such that sσ = t. Returns `None` if no such `σ` exists. */
def apply(s: Type, t: Type): Option[TypeMatching#TypeSubst] = impl.matching(s,t)
/** Returns a substitution `Some(σ)` such that s_iσ = t_i. Returns `None` if no such `σ` exists. */
def apply(uEqs: Seq[TypeMatching#UEq]): Option[TypeSubst] = impl.matching(uEqs)
}
object TypeMatchingImpl extends TypeMatching {
/** Returns a substitution `Some(σ)` such that sσ = t. Returns `None` if no such `σ` exists. */
override def matching(s: Type, t: Type): Option[TypeSubst] = matching(Vector((s,t)))
/** Returns a substitution `Some(σ)` such that s_iσ = t_i. Returns `None` if no such `σ` exists. */
def matching(uEqs: Seq[UEq]): Option[TypeSubst] = {
val forbiddenTyVars = uEqs.flatMap(_._2.typeVars.map(BoundType.unapply(_).get)).toSet
tyDetExhaust(uEqs.toVector, Subst.id, forbiddenTyVars)
}
@tailrec
final protected[calculus] def tyDetExhaust(uTyProblems: Seq[UEq], unifier: TypeSubst, forbiddenVars: Set[Int]): Option[TypeSubst] = {
leo.Out.finest(s"tyDetExaust unsolved: ${uTyProblems.map(ueq => ueq._1.pretty ++ " = " ++ ueq._2.pretty).mkString("\\n")}")
if (uTyProblems.nonEmpty) {
val head0 = uTyProblems.head
val head = (head0._1.substitute(unifier), head0._2.substitute(unifier))
if (TyDeleteRule.canApply(head))
tyDetExhaust(uTyProblems.tail, unifier, forbiddenVars)
else if (TyDecompRule.canApply(head))
tyDetExhaust(TyDecompRule.apply(head) ++ uTyProblems.tail, unifier, forbiddenVars)
else {
val tyFunDecompRuleCanApplyHint = TyFunDecompRule.canApply(head)
if (tyFunDecompRuleCanApplyHint != TyFunDecompRule.CANNOT_APPLY) {
tyDetExhaust(TyFunDecompRule.apply(head, tyFunDecompRuleCanApplyHint) ++ uTyProblems.tail,unifier, forbiddenVars)
} else if (TyBindRule.canApply(head, forbiddenVars))
tyDetExhaust(uTyProblems.tail, unifier.comp(TyBindRule.apply(head)), forbiddenVars)
else
None
}
} else Some(unifier)
}
/**
* Delete rule for types
* canApply(s,t) iff the equation (s = t) can be deleted
*/
object TyDeleteRule {
final def canApply(e: UEq): Boolean = e._1 == e._2
}
object TyDecompRule {
import leo.datastructures.Type.ComposedType
final def apply(e: UEq): Seq[UEq] = {
val args1 = ComposedType.unapply(e._1).get._2
val args2 = ComposedType.unapply(e._2).get._2
args1.zip(args2)
}
final def canApply(e: UEq): Boolean = e match {
case (ComposedType(head1, _), ComposedType(head2, _)) => head1 == head2 // Heads cannot be flexible,
// since in TH1 only small types/proper types can be quantified, not type operators
case _ => false
}
}
object TyFunDecompRule {
final val CANNOT_APPLY = -1
final val EQUAL_LENGTH = 0
final val SECOND_LONGER = 1
final def apply(e: UEq, hint: Int): Seq[UEq] = {
assert(hint != CANNOT_APPLY)
if (hint == EQUAL_LENGTH) {
e._1.funParamTypesWithResultType.zip(e._2.funParamTypesWithResultType)
} else {
val shorterTyList = e._1.funParamTypesWithResultType
val splittedLongerTy = e._2.splitFunParamTypesAt(shorterTyList.size-1)
(shorterTyList.last, splittedLongerTy._2) +: shorterTyList.init.zip(splittedLongerTy._1)
}
}
final def canApply(e: UEq): Int = {
if (!e._1.isFunType || !e._2.isFunType) CANNOT_APPLY
else {
val tys1 = e._1.funParamTypesWithResultType
val tys2 = e._2.funParamTypesWithResultType
if (tys1.size > tys2.size) CANNOT_APPLY /* impossible to match right side */
else if (tys1.size == tys2.size) EQUAL_LENGTH
else { // tys1.size < tys2.size
if (tys1.last.isBoundTypeVar) // Only possible if last one is variable
SECOND_LONGER
else CANNOT_APPLY
}
}
}
}
/**
* Bind rule for type equations.
* canApply(s,t) iff either s or t is a type variable and not a subtype of the other one.
*/
object TyBindRule {
import leo.datastructures.Type.BoundType
final def apply(e: UEq): Subst = {
val leftIsTypeVar = e._1.isBoundTypeVar
val tyVar = if (leftIsTypeVar) BoundType.unapply(e._1).get else BoundType.unapply(e._2).get
val otherTy = if (leftIsTypeVar) e._2 else e._1
Subst.singleton(tyVar, otherTy)
}
final def canApply(e: UEq, forbiddenVars: Set[Int]): Boolean = {
val leftIsTypeVar = e._1.isBoundTypeVar
if (!leftIsTypeVar) false
else {
val tyVar = BoundType.unapply(e._1).get
val otherTy = e._2
!forbiddenVars.contains(tyVar) && !otherTy.typeVars.contains(tyVar)
}
}
}
}
|
lex-lex/Leo-III
|
src/main/scala/leo/modules/calculus/Matching.scala
|
Scala
|
bsd-3-clause
| 37,089 |
/**
* Copyright 2011-2017 GatlingCorp (http://gatling.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gatling.metrics
import scala.collection.mutable
import scala.concurrent.duration.DurationInt
import io.gatling.commons.util.Collections._
import io.gatling.commons.util.ClockSingleton.nowSeconds
import io.gatling.core.config.GatlingConfiguration
import io.gatling.core.stats.writer._
import io.gatling.core.util.NameGen
import io.gatling.metrics.message.GraphiteMetrics
import io.gatling.metrics.sender.MetricsSender
import io.gatling.metrics.types._
import akka.actor.ActorRef
case class GraphiteData(
configuration: GatlingConfiguration,
metricsSender: ActorRef,
requestsByPath: mutable.Map[GraphitePath, RequestMetricsBuffer],
usersByScenario: mutable.Map[GraphitePath, UserBreakdownBuffer],
format: GraphitePathPattern
) extends DataWriterData
private[gatling] class GraphiteDataWriter extends DataWriter[GraphiteData] with NameGen {
def newResponseMetricsBuffer(configuration: GatlingConfiguration): RequestMetricsBuffer =
new HistogramRequestMetricsBuffer(configuration)
private val flushTimerName = "flushTimer"
def onInit(init: Init): GraphiteData = {
import init._
val metricsSender: ActorRef = context.actorOf(MetricsSender.props(configuration), genName("metricsSender"))
val requestsByPath = mutable.Map.empty[GraphitePath, RequestMetricsBuffer]
val usersByScenario = mutable.Map.empty[GraphitePath, UserBreakdownBuffer]
val pattern: GraphitePathPattern = new OldGraphitePathPattern(runMessage, configuration)
usersByScenario.update(pattern.allUsersPath, new UserBreakdownBuffer(scenarios.sumBy(_.userCount)))
scenarios.foreach(scenario => usersByScenario += (pattern.usersPath(scenario.name) -> new UserBreakdownBuffer(scenario.userCount)))
setTimer(flushTimerName, Flush, configuration.data.graphite.writeInterval seconds, repeat = true)
GraphiteData(configuration, metricsSender, requestsByPath, usersByScenario, pattern)
}
def onFlush(data: GraphiteData): Unit = {
import data._
val requestsMetrics = requestsByPath.mapValues(_.metricsByStatus).toMap
val usersBreakdowns = usersByScenario.mapValues(_.breakDown).toMap
// Reset all metrics
requestsByPath.foreach { case (_, buff) => buff.clear() }
sendMetricsToGraphite(data, nowSeconds, requestsMetrics, usersBreakdowns)
}
private def onUserMessage(userMessage: UserMessage, data: GraphiteData): Unit = {
import data._
usersByScenario(format.usersPath(userMessage.session.scenario)).add(userMessage)
usersByScenario(format.allUsersPath).add(userMessage)
}
private def onResponseMessage(response: ResponseMessage, data: GraphiteData): Unit = {
import data._
import response._
if (!configuration.data.graphite.light) {
requestsByPath.getOrElseUpdate(format.responsePath(name, groupHierarchy), newResponseMetricsBuffer(configuration)).add(status, timings.responseTime)
}
requestsByPath.getOrElseUpdate(format.allResponsesPath, newResponseMetricsBuffer(configuration)).add(status, timings.responseTime)
}
override def onMessage(message: LoadEventMessage, data: GraphiteData): Unit = message match {
case user: UserMessage => onUserMessage(user, data)
case response: ResponseMessage => onResponseMessage(response, data)
case _ =>
}
override def onCrash(cause: String, data: GraphiteData): Unit = {}
def onStop(data: GraphiteData): Unit = cancelTimer(flushTimerName)
private def sendMetricsToGraphite(
data: GraphiteData,
epoch: Long,
requestsMetrics: Map[GraphitePath, MetricByStatus],
userBreakdowns: Map[GraphitePath, UserBreakdown]
): Unit = {
import data._
metricsSender ! GraphiteMetrics(format.metrics(userBreakdowns, requestsMetrics), epoch)
}
}
|
timve/gatling
|
gatling-metrics/src/main/scala/io/gatling/metrics/GraphiteDataWriter.scala
|
Scala
|
apache-2.0
| 4,416 |
package com.sksamuel.elastic4s.requests.searches.aggs
import com.sksamuel.elastic4s.requests.script.Script
import com.sksamuel.elastic4s.ext.OptionImplicits._
case class StatsAggregation(name: String,
field: Option[String] = None,
missing: Option[AnyRef] = None,
format: Option[String] = None,
script: Option[Script] = None,
subaggs: Seq[AbstractAggregation] = Nil,
metadata: Map[String, AnyRef] = Map.empty)
extends Aggregation {
type T = StatsAggregation
def format(format: String): StatsAggregation = copy(format = format.some)
def field(field: String): StatsAggregation = copy(field = field.some)
def missing(missing: AnyRef): StatsAggregation = copy(missing = missing.some)
def script(script: Script): StatsAggregation = copy(script = script.some)
override def subAggregations(aggs: Iterable[AbstractAggregation]): T = copy(subaggs = aggs.toSeq)
override def metadata(map: Map[String, AnyRef]): T = copy(metadata = map)
}
|
sksamuel/elastic4s
|
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/requests/searches/aggs/StatsAggregation.scala
|
Scala
|
apache-2.0
| 1,144 |
package org.improving.scalify
import Scalify._
import org.eclipse.jdt.core._
import org.eclipse.jdt.core.dom
import dom.{ PrimitiveType => PT }
// import scalaz.OptionW._
// ***** getDeclaringNode *****
// * <li>package - a <code>PackageDeclaration</code></li>
// * <li>class or interface - a <code>TypeDeclaration</code> or a
// * <code>AnonymousClassDeclaration</code> (for anonymous classes)</li>
// * <li>primitive type - none</li>
// * <li>array type - none</li>
// * <li>field - a <code>VariableDeclarationFragment</code> in a
// * <code>FieldDeclaration</code> </li>
// * <li>local variable - a <code>SingleVariableDeclaration</code>, or
// * a <code>VariableDeclarationFragment</code> in a
// * <code>VariableDeclarationStatement</code> or
// * <code>VariableDeclarationExpression</code></li>
// * <li>method - a <code>MethodDeclaration</code> </li>
// * <li>constructor - a <code>MethodDeclaration</code> </li>
// * <li>annotation type - an <code>AnnotationTypeDeclaration</code></li>
// * <li>annotation type member - an <code>AnnotationTypeMemberDeclaration</code></li>
// * <li>enum type - an <code>EnumDeclaration</code></li>
// * <li>enum constant - an <code>EnumConstantDeclaration</code></li>
// * <li>type variable - a <code>TypeParameter</code></li>
// * <li>capture binding - none</li>
// * <li>annotation binding - an <code>Annotation</code></li>
// * <li>member value pair binding - an <code>MemberValuePair</code>,
// * or <code>null</code> if it represents a default value or a single member value</li>
//
// ***** getJavaElement *****
// * Here are the cases where a <code>null</code> should be expected:
// * <ul>
// * <li>primitive types, including void</li>
// * <li>null type</li>
// * <li>wildcard types</li>
// * <li>capture types</li>
// * <li>array types of any of the above</li>
// * <li>the "length" field of an array type</li>
// * <li>the default constructor of a source class</li>
// * <li>the constructor of an anonymous class</li>
// * <li>member value pairs</li>
// * </ul>
// Bindings => Declarations
// Type => TypeDeclaration
// Variable => VariableDeclaration
// Method => MethodDeclaration
// Package => PackageDeclaration
// Annotation => AnnotationTypeDeclaration
abstract trait Bound extends ASTNodeAdditions with Modifiable
{
// abstract
val node: ASTNode
def binding: IBinding
// modifiable
def flags = binding.getModifiers
// concrete
def bindingName: String = binding.getName
def jelement: Option[IJavaElement] = onull(binding.getJavaElement)
def jproject: Option[IJavaProject] = jelement.map(_.getJavaProject)
}
trait TypeBound extends Bound {
override def binding: IBinding = tb
override def bindingName: String = tb.getQualifiedName
def tb: TBinding
// lazy val hierarchy: Option[ITypeHierarchy] =
// for (it <- itype ; jp <- jproject) yield it.newSupertypeHierarchy(null)
// for (it <- itype ; jp <- jproject) yield it.newTypeHierarchy(jp, null)
def itype: Option[IType] = jelement match { case Some(it: IType) => Some(it) ; case _ => None }
// def itype: Option[IType] = jelement match {
// case Some(it: IType) =>
// val op = it.getOpenable
// if (op == null || op.isOpen) return Some(it)
//
// log.trace("!isOpen: %s", it)
// op.open(null)
// Some(it)
// case _ => None
// }
def findTypeDeclaration: Option[dom.TypeDeclaration] = tb.findTypeDeclaration
// itype.flatMap(declaration) match
// { case Some(x: dom.TypeDeclaration) => Some(x) ; case _ => None }
def findAnonTypeDeclaration: Option[dom.AnonymousClassDeclaration] = cu.findDeclaringNode(tb) match
{ case x: dom.AnonymousClassDeclaration => Some(x) ; case _ => None }
}
trait VariableBound extends Bound {
override def binding: IBinding = vb
def vb: VBinding
def findEnumDeclaration: Option[dom.EnumDeclaration] =
cu.findDeclaringNode(vb) match { case x: dom.EnumDeclaration => Some(x) ; case _ => None }
}
trait MethodBound extends Bound {
override def binding: IBinding = mb
def mb: MBinding
}
trait AnnotationBound extends Bound {
override def binding: IBinding = ab
def ab: ABinding
def findAnnotationDeclaration: Option[dom.AnnotationTypeDeclaration] =
cu.findDeclaringNode(ab) match { case x: dom.AnnotationTypeDeclaration => Some(x) ; case _ => None }
}
trait PackageBound extends Bound {
override def binding: IBinding = pb
def pb: PBinding
def ipackage = jelement match { case Some(x: IPackageDeclaration) => x ; case _ => abort("ipackage") }
def findPackageDeclaration: Option[dom.PackageDeclaration] =
cu.findDeclaringNode(pb) match { case x: dom.PackageDeclaration => Some(x) ; case _ => None }
}
object Bindings
{
// ITypeBinding already offers:
//
// isAnnotation(); isAnonymous(); isArray(); isAssignmentCompatible(ITypeBinding variableType);
// isCapture(); isCastCompatible(ITypeBinding type); isClass(); isEnum(); isFromSource(); isGenericType();
// isInterface(); isLocal(); isMember(); isNested(); isNullType(); isParameterizedType(); isPrimitive();
// isRawType(); isSubTypeCompatible(ITypeBinding type); isTopLevel(); isTypeVariable(); isUpperbound();
// isWildcardType();
class RichITypeBinding(tb: TBinding) extends RichIBinding(tb) {
def emitCast: EFilter = (x: Emission) =>
if (tb.isPrimitive) getAnyValType(tb).emitCast(x)
else INVOKE(x, ASINSTANCEOF) <~> BRACKETS(tb.emitType)
def emitBox: EFilter = (x: Emission) => getAnyValType(tb).emitBoxed(x)
def emit: Emission = emitType
def emitType: Emission = tb match {
case JArray(el, dims) => arrayWrap(dims)(el.emitType)
case JPrimitive(anyVal) => anyVal.emit
case _ => emitString(ROOTPKG.s + "." + tb.getPackage.getName + "." + tb.getName) // TODO
}
def fqname: String = tb.getQualifiedName
def isSomeType(code: PT.Code): Boolean = tb.isPrimitive && tb.getName == code.toString
def isSomeType(name: String): Boolean = getAnyValType(tb) == getAnyValType(name)
def isAnyValType: Boolean = isAnyValTypeName(tb.getName)
def isReferenceType: Boolean = !tb.isPrimitive && !tb.isNullType
// getting more specific
def isBoolean: Boolean = tb.isSomeType(PT.BOOLEAN)
def isChar: Boolean = tb.isSomeType(PT.CHAR)
def isString: Boolean = tb.getQualifiedName == "java.lang.String"
def isCharArray: Boolean = tb.isArray && tb.getElementType.isChar
def isVoid: Boolean = tb.isSomeType(PT.VOID)
// thanks for the lhs/rhs consistency
def isAssignableTo(lhs: TBinding): Boolean =
tb.getErasure.isAssignmentCompatible(lhs.getErasure)
def isCastableTo(lhs: TBinding): Boolean =
lhs.getErasure.isCastCompatible(tb.getErasure)
def isAssignableTo(lhs: ASTNode): Boolean =
lhs.tbinding.map(isAssignableTo(_)) getOrElse false
def isCastableTo(lhs: ASTNode): Boolean =
lhs.tbinding.map(isCastableTo(_)) getOrElse false
def isSameElementType(other: TBinding): Boolean =
tb.isArray && other.isArray && tb.getElementType.isEqualTo(other.getElementType)
def itype: Option[IType] = jelement match { case Some(x: IType) => Some(x) ; case _ => None }
def findTypeDeclaration: Option[dom.TypeDeclaration] = {
val x = itype.flatMap(declaration)
// log.trace("findTypeDeclaration: %s %s", x.map(_.getClass), x)
itype.flatMap(declaration) match
{ case Some(x: dom.TypeDeclaration) => Some(x) ; case _ => None }
}
override def referenceName = findTypeDeclaration.map(_.referenceName) getOrElse tb.getName
def methods: List[MBinding] = tb.getDeclaredMethods.toList
def pkgName: String = if (tb.getPackage == null) "" else tb.getPackage.getName
override def declaringClassList: List[TBinding] = declaringClassList(tb.getDeclaringClass)
def emitPackage: Emission =
if (tb.getPackage.getName == "") Nil
else emitString(tb.getPackage.getName) <~> DOT ~ NOS
// true if we had to rewire this type to use factory constructors
def getFactoryType: Option[STDWithFactory] = findTypeDeclaration.map(_.snode) match {
case Some(x: STDWithFactory) => Some(x)
case _ => None
}
// true if we split out constants into a separate trait
def getSplitType: Option[Interface] = findTypeDeclaration.map(_.snode) match {
case Some(x: Interface) if x.isSplit => Some(x)
case Some(x) => log.trace("getSplitType but not split: %s %s", x.getClass, x) ; None
case _ => None
}
def isFactoryType: Boolean = getFactoryType.isDefined
def isSplitType: Boolean = getSplitType.isDefined
private def is(cond: Boolean, s: String): String = if (cond) s else ""
def info: String =
if (tb == null) "<null>"
else "Type " + tb.getQualifiedName + " (" + tb.getName + ") is:" +
is(tb.isInterface, " interface") +
is(tb.isAnonymous, " anonymous") +
is(tb.isStatic, " static") +
is(tb.isNested, " nested") +
is(tb.isLocal, " local") +
is(tb.isTopLevel, " top-level")
}
class RichIMethodBinding(mb: MBinding) extends RichIBinding(mb) {
def imethod: Option[IMethod] = jelement match { case Some(x: IMethod) => Some(x) ; case _ => None }
def findMethodDeclaration: Option[dom.MethodDeclaration] = imethod.flatMap(declaration)
// override def getStaticQualifiedName: String = {
// val x = super.getStaticQualifiedName + "." + referenceName
// log.trace("mb.name: %s", x)
// x
// }
override def declaringClassList: List[TBinding] = declaringClassList(mb.getDeclaringClass)
override def referenceName = findMethodDeclaration.map(_.referenceName) getOrElse mb.getName
}
class RichIVariableBinding(vb: VBinding) extends RichIBinding(vb) {
def declaredInConstructor: Boolean = onull(vb.getDeclaringMethod).map(_.isConstructor) getOrElse false
override def referenceName = findVariableDeclaration.map(_.referenceName) getOrElse vb.getName
def findVariableDeclaration: Option[dom.VariableDeclaration] = jelement match {
case Some(x: IField) => declaration(x)
case Some(x: ILocalVariable) => declaration(x, vb)
case _ => None
}
override def declaringClassList: List[TBinding] = declaringClassList(vb.getDeclaringClass)
}
class RichIBinding(val b: IBinding) extends Modifiable {
import org.eclipse.jdt.core.BindingKey
def referenceName: String = b.getName
lazy val node: ASTNode = Global.lookup(b.getKey) getOrElse null
lazy val snode: Node = if (node == null) null else node.snode
def jelement: Option[IJavaElement] = onull(b.getJavaElement)
def flags = b.getModifiers
def signature: String = (new BindingKey(b.getKey)).toSignature
def getOptDeclaringClass: Option[TBinding] = b match {
case vb: VBinding => Some(vb.getDeclaringClass)
case mb: MBinding => Some(mb.getDeclaringClass)
case tb: TBinding => Some(tb)
case _ => None
}
// def getStaticQualifiedName: String = declaringClassList.map(_.referenceName).mkString(".")
def getStaticQualifier: String = declaringClassList.map(_.getName).mkString(".")
def getStaticQualifierPkg: String =
if (declaringClassList.isEmpty) ""
else declaringClassList.last.getPackage.getName
def declaringClassList: List[TBinding] = Nil
protected def declaringClassList(b: TBinding): List[TBinding] =
if (b == null) Nil
else declaringClassList(b.getDeclaringClass) ::: List(b)
def canAccessWithoutQualifying(node: ASTNode): Boolean = {
val bindingClass = b.getOptDeclaringClass getOrElse (return false)
val nodeClass = node.findEnclosingType.map(_.tb) getOrElse (return false)
// sadly, inside constructors the static import hasn't kicked off yet
bindingClass.isEqualTo(nodeClass) && !node.isInConstructor
}
}
}
|
mbana/scalify
|
src/main/node/Bindings.scala
|
Scala
|
isc
| 11,548 |
package domala.internal.macros.reflect.mock
case class MockNestEntity(
id: Int,
embedded: MockEmbeddable,
)
|
bakenezumi/domala
|
core/src/test/scala/domala/internal/macros/reflect/mock/MockNestEntity.scala
|
Scala
|
apache-2.0
| 116 |
package dotty.tools
package runner
import java.net.URL
import scala.util.control.NonFatal
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.UndeclaredThrowableException
import java.util.concurrent.ExecutionException
/**
* This is a copy implementation from scala/scala scala.tools.nsc.CommonRunner trait
*/
trait CommonRunner {
/** Run a given object, specified by name, using a
* specified classpath and argument list.
*
* @throws java.lang.ClassNotFoundException
* @throws java.lang.NoSuchMethodException
* @throws java.lang.reflect.InvocationTargetException
*/
def run(urls: Seq[URL], objectName: String, arguments: Seq[String]): Unit = {
import RichClassLoader._
ScalaClassLoader.fromURLsParallelCapable(urls).run(objectName, arguments)
}
/** Catches any non-fatal exception thrown by run (in the case of InvocationTargetException,
* unwrapping it) and returns it in an Option.
*/
def runAndCatch(urls: Seq[URL], objectName: String, arguments: Seq[String]): Option[Throwable] =
try { run(urls, objectName, arguments) ; None }
catch { case NonFatal(e) => Some(rootCause(e)) }
private def rootCause(x: Throwable): Throwable = x match {
case _: InvocationTargetException |
_: ExceptionInInitializerError |
_: UndeclaredThrowableException |
_: ExecutionException
if x.getCause != null =>
rootCause(x.getCause.nn)
case _ => x
}
}
/** An object that runs another object specified by name.
*
* @author Lex Spoon
*/
object ObjectRunner extends CommonRunner
|
dotty-staging/dotty
|
compiler/src/dotty/tools/runner/ObjectRunner.scala
|
Scala
|
apache-2.0
| 1,617 |
package org.miszkiewicz.model
sealed trait SendGridCredentials
case class ApiKey(apiKey: String) extends SendGridCredentials
case class UserCredentials(login: String, password: String) extends SendGridCredentials
|
dmiszkiewicz/sendgrid-scala
|
src/main/scala/org/miszkiewicz/model/SendGridCredentials.scala
|
Scala
|
mit
| 216 |
package com.tristanpenman.chordial.core.algorithms
import akka.actor.{Actor, ActorLogging, ActorRef, Props, ReceiveTimeout}
import akka.util.Timeout
import com.tristanpenman.chordial.core.Pointers.{GetSuccessor, GetSuccessorOk}
import com.tristanpenman.chordial.core.shared.{Interval, NodeInfo}
import scala.concurrent.duration.Duration
/**
* Actor class that implements a simplified version of the ClosestPrecedingNode algorithm
*
* The ClosestPrecedingNode algorithm is defined in the Chord paper as follows:
*
* {{{
* n.closest_preceding_node(id)
* for i - m downto 1
* if (finger[i].node IN (n, id))
* return finger[i].node;
* return n;
* }}}
*
* The algorithm implemented here behaves as though the node has a finger table of size 2, with the first entry being
* the node's successor, and the second entry being the node itself.
*/
final class ClosestPrecedingNodeAlgorithm(node: NodeInfo, pointersRef: ActorRef, extTimeout: Timeout)
extends Actor
with ActorLogging {
import ClosestPrecedingNodeAlgorithm._
private def running(queryId: Long, replyTo: ActorRef): Receive = {
case ClosestPrecedingNodeAlgorithmStart(_) =>
sender() ! ClosestPrecedingNodeAlgorithmAlreadyRunning
case GetSuccessorOk(successor) =>
context.setReceiveTimeout(Duration.Undefined)
context.become(receive)
replyTo ! ClosestPrecedingNodeAlgorithmFinished(
if (Interval(node.id + 1, queryId).contains(successor.id))
successor
else
node
)
case ReceiveTimeout =>
context.setReceiveTimeout(Duration.Undefined)
context.become(receive)
replyTo ! ClosestPrecedingNodeAlgorithmError("timed out")
}
override def receive: Receive = {
case ClosestPrecedingNodeAlgorithmStart(queryId: Long) =>
context.become(running(queryId, sender()))
context.setReceiveTimeout(extTimeout.duration)
pointersRef ! GetSuccessor
case ReceiveTimeout =>
// timeout from an earlier request that was completed before the timeout message was processed
log.debug("late timeout")
}
}
object ClosestPrecedingNodeAlgorithm {
sealed trait ClosestPrecedingNodeAlgorithmRequest
final case class ClosestPrecedingNodeAlgorithmStart(queryId: Long) extends ClosestPrecedingNodeAlgorithmRequest
sealed trait ClosestPrecedingNodeAlgorithmStartResponse
final case class ClosestPrecedingNodeAlgorithmFinished(finger: NodeInfo)
extends ClosestPrecedingNodeAlgorithmStartResponse
case object ClosestPrecedingNodeAlgorithmAlreadyRunning extends ClosestPrecedingNodeAlgorithmStartResponse
final case class ClosestPrecedingNodeAlgorithmError(message: String)
extends ClosestPrecedingNodeAlgorithmStartResponse
sealed trait ClosestPrecedingNodeAlgorithmResetResponse
case object ClosestPrecedingNodeAlgorithmReady extends ClosestPrecedingNodeAlgorithmResetResponse
def props(node: NodeInfo, pointersRef: ActorRef, extTimeout: Timeout): Props =
Props(new ClosestPrecedingNodeAlgorithm(node, pointersRef, extTimeout))
}
|
tristanpenman/chordial
|
modules/core/src/main/scala/com/tristanpenman/chordial/core/algorithms/ClosestPrecedingNodeAlgorithm.scala
|
Scala
|
bsd-3-clause
| 3,099 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql
import org.apache.spark.internal.Logging
import org.apache.kylin.common.threadlocal.InternalThreadLocal
import org.apache.kylin.common.util.Pair
import org.apache.kylin.query.UdfManager
object SparderContextFacade extends Logging {
final val CURRENT_SPARKSESSION: InternalThreadLocal[Pair[SparkSession, UdfManager]] =
new InternalThreadLocal[Pair[SparkSession, UdfManager]]()
def current(): Pair[SparkSession, UdfManager] = {
if (CURRENT_SPARKSESSION.get() == null) {
val spark = SparderContext.getOriginalSparkSession.cloneSession()
CURRENT_SPARKSESSION.set(new Pair[SparkSession, UdfManager](spark,
UdfManager.createWithoutBuildInFunc(spark)))
}
CURRENT_SPARKSESSION.get()
}
def remove(): Unit = {
CURRENT_SPARKSESSION.remove()
}
}
|
apache/kylin
|
kylin-spark-project/kylin-spark-query/src/main/scala/org/apache/spark/sql/SparderContextFacade.scala
|
Scala
|
apache-2.0
| 1,625 |
/*
* Scala classfile decoder (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package com.codahale.jerkson.util
package scalax
package rules
package scalasig
abstract class Type
case object NoType extends Type
case object NoPrefixType extends Type
case class ThisType(symbol: Symbol) extends Type
case class SingleType(typeRef: Type, symbol: Symbol) extends Type
case class ConstantType(constant: Any) extends Type
case class TypeRefType(prefix: Type, symbol: Symbol, typeArgs: Seq[Type]) extends Type
case class TypeBoundsType(lower: Type, upper: Type) extends Type
case class RefinedType(classSym: Symbol, typeRefs: List[Type]) extends Type
case class ClassInfoType(symbol: Symbol, typeRefs: Seq[Type]) extends Type
case class ClassInfoTypeWithCons(symbol: Symbol, typeRefs: Seq[Type], cons: String) extends Type
case class MethodType(resultType: Type, paramSymbols: Seq[Symbol]) extends Type
case class NullaryMethodType(resultType: Type) extends Type
case class PolyType(typeRef: Type, symbols: Seq[TypeSymbol]) extends Type
case class PolyTypeWithCons(typeRef: Type, symbols: Seq[TypeSymbol], cons: String) extends Type
case class AnnotatedType(typeRef: Type, attribTreeRefs: List[Int]) extends Type
case class AnnotatedWithSelfType(typeRef: Type, symbol: Symbol, attribTreeRefs: List[Int]) extends Type
case class ExistentialType(typeRef: Type, symbols: Seq[Symbol]) extends Type
|
rememberthemilk/jerkson
|
src/main/scala/com/codahale/jerkson/util/scalax/rules/scalasig/Type.scala
|
Scala
|
mit
| 1,619 |
package edu.umass.ciir.kbbridge.kb2text
import edu.umass.ciir.kbbridge.util._
import edu.umass.ciir.kbbridge.nlp.TextNormalizer
import collection.mutable.ListBuffer
import org.lemurproject.galago.core.parse.Document
import scala.Some
import edu.umass.ciir.kbbridge.data.repr.EntityRepr
import scala.collection.JavaConversions._
import edu.umass.ciir.models.StopWordList
/**
* User: dietz
* Date: 6/12/13
* Time: 6:48 PM
*/
trait EntityReprBuilder {
def buildEntityRepr(wikipediaTitle:String, maskedGalagoDoc: Document, passageInfo:Seq[(Int,Int)]):EntityRepr
}
class WikiEntityRepr(val neighborFeatureWeights:Map[String,Double], val buildM:Boolean = true, val getFieldTermCount:(String, String) => Long, val buildNames:Boolean = true, val buildText:Boolean = false) extends EntityReprBuilder{
import WikiEntityRepr._
def buildEntityRepr(wikipediaTitle:String, maskedGalagoDoc: Document, passageInfo:Seq[(Int,Int)]):EntityRepr = {
val entityName = WikiEntityRepr.wikititleToEntityName(wikipediaTitle)
val alternativeNameWeightsPerField = WikiContextExtractor.getWeightedAnchorNames(entityName, maskedGalagoDoc, getFieldTermCount)
// ============================
// alternate names
val redirect = alternativeNameWeightsPerField("redirect-exact")
val fbName = alternativeNameWeightsPerField("fbname-exact")
val anchor = alternativeNameWeightsPerField("anchor-exact")
val topWeightedNames =
if(buildNames){
val weightedNames =
SeqTools.sumDoubleMaps[String]( Seq(
multiplyMapValue[String](redirect, 1.0),
multiplyMapValue[String](fbName, 1.0),
multiplyMapValue[String](anchor, 0.5)
))
val topWeightedNames = Seq(entityName -> 1.0) ++ SeqTools.topK(weightedNames.toSeq, 10)
if(topWeightedNames.map(_._2).exists(_.isNaN)){
println("topWeightedNames contains nan "+topWeightedNames)
println(redirect)
println(fbName)
println(anchor)
}
topWeightedNames
} else Seq.empty
// ============================
// neighbors
val topWeightedNeighbors =
if(buildM){
val weightedNeighbors = extractNeighbors(entityName, wikipediaTitle, maskedGalagoDoc, passageInfo)
SeqTools.topK(weightedNeighbors, 10)
} else Seq.empty
// ============================
// word context
// val stanf_anchor = alternativeNameWeightsPerField("stanf_anchor-exact")
// val topWords = SeqTools.topK(stanf_anchor.toSeq, 10)
val topWords =
if(buildText){
val textterms =
for(tag <- maskedGalagoDoc.tags; if tag.name =="text") yield {
maskedGalagoDoc.terms.slice(tag.begin, tag.end).filterNot(StopWordList.isStopWord)
}
val termCounts = SeqTools.countMap[String](textterms.flatten)
if(!termCounts.isEmpty) {
Distribution[String](SeqTools.mapValuesToDouble(termCounts).toSeq).topK(10).normalize.distr
} else Seq.empty
} else {
Seq.empty
}
EntityRepr(entityName = entityName, queryId = Some(wikipediaTitle), nameVariants = topWeightedNames, neighbors = topWeightedNeighbors, words = topWords)
}
def documentNeighborCount(wikipediaTitle:String, galagoDoc:Document):Seq[NeighborCount] = {
val WikiNeighbors(outAnchors, inlinks, contextLinks) = findNeighbors(wikipediaTitle,galagoDoc)
val passageLinks = outAnchors
val destinations = passageLinks.groupBy(_.destination)
val neighborWithCounts =
for ((destination, anchors) <- destinations) yield {
val inlinkCount = if (inlinks.contains(destination)) {1} else {0}
val contextCount = contextLinks(destination)
val canonicalDestName = wikititleToEntityName(destination)
NeighborCount(wikipediaTitle, destination, canonicalDestName, anchors, inlinkCount, contextCount)
}
neighborWithCounts.toSeq
}
def extractNeighbors(entityName:String, wikipediaTitle:String, maskedGalagoDoc:Document, passageInfo:Seq[(Int,Int)]): Seq[(EntityRepr, Double)] = {
val usePassage = !passageInfo.isEmpty
val passageText =
if(!usePassage) ""
else maskedGalagoDoc.text
val WikiNeighbors(links, inlinkCount, contextCount) = findNeighbors(wikipediaTitle,maskedGalagoDoc)
val destinations = links.groupBy(_.destination)
case class NeighborScores( paragraphScore:Double, outlinkCount:Int, hasInlink:Boolean, cooccurrenceCount:Int){
def asFeatureVector:Seq[(String, Double)] =
Seq(
"paragraphScore" -> paragraphScore,
"outlinkCount" -> outlinkCount.toDouble,
"hasInlink" -> (if(hasInlink) 1.0 else 0.0),
"cooccurrenceCount" -> cooccurrenceCount.toDouble
)
def asNormalizedFeatureVector(normalizer:Seq[(String,Double)]):Seq[(String,Double)] = {
val normMap = normalizer.toMap
for((key, value) <- asFeatureVector) yield key -> (value / normMap(key))
}
}
def computeParagraphScore(pId:Int):Double = if(pId < 10) {1.0} else {0.1}
val neighborinfo =
(for ((destination, anchors) <- destinations) yield {
val normDest = wikititleToEntityName(destination)
val weightedParagraphNeighborSeq = new ListBuffer[(String, Double)]()
for (anchor <- anchors) {
val paragraphScore = computeParagraphScore(anchor.paragraphId)
val normalizedAnchorText = TextNormalizer.normalizeText(anchor.anchorText)
if (usePassage){
if(passageText contains anchor.rawAnchorText){
weightedParagraphNeighborSeq += normalizedAnchorText -> paragraphScore
}
} else {
weightedParagraphNeighborSeq += normalizedAnchorText -> paragraphScore
}
}
val weightedParagraphNeighbors = SeqTools.groupByMappedKey[String, Double, String, Double](weightedParagraphNeighborSeq, by=TextNormalizer.normalizeText(_), aggr = _.sum)
val neighborScores = {
val paragraphScore = weightedParagraphNeighbors.map(_._2).sum
val outlinkCount = anchors.length
val hasInlink = inlinkCount.contains(destination)
val cooccurrenceCount = contextCount(destination)
NeighborScores(paragraphScore, outlinkCount, hasInlink, cooccurrenceCount)
}
((destination,normDest), weightedParagraphNeighbors, neighborScores)
}).toSeq
val summed = SeqTools.sumDoubleMaps(neighborinfo.map(_._3.asFeatureVector.toMap))
val weightedNeighbors: Seq[(EntityRepr, Double)] =
for(((dest,normDest), names, neighborScores) <- neighborinfo) yield {
val normalizedFeature = neighborScores.asNormalizedFeatureVector(summed.toSeq)
val score = SeqTools.innerProduct(normalizedFeature, neighborFeatureWeights)
(EntityRepr(entityName = normDest, nameVariants = names, wikipediaTitleInput = Some(dest)) -> score)
}
// val neighborInfo_ = neighborinfo.map(entry => entry._1 -> (entry._2, entry._3)).toMap
// val weightedNeighbors_ = weightedNeighbors.toMap
if (weightedNeighbors.exists(_._2.isNaN())){
println("nans in weightedNeighbors "+weightedNeighbors)
println("neighborinfo "+neighborinfo)
}
weightedNeighbors
}
}
object WikiEntityRepr {
case class WikiNeighbors(outLinks:Seq[WikiLinkExtractor.Anchor], inlinks:Seq[String], contextLinks:Map[String,Int])
case class NeighborCount(sourceWikiTitle:String, targetWikiTitle:String, canonicalDestName:String, anchors: Seq[WikiLinkExtractor.Anchor], inlinkCount:Int, contextCount:Int)
def passageNeighborCount(wikipediaTitle:String, maskedGalagoDoc:Document, passageTextOpt:Option[String]):Seq[NeighborCount] = {
val passageText = if(passageTextOpt.isDefined) passageTextOpt.get else maskedGalagoDoc.text
val WikiNeighbors(outAnchors, inlinks, contextLinks) = findNeighbors(wikipediaTitle,maskedGalagoDoc)
val passageLinks = outAnchors.filter(link => passageText.contains(link.rawAnchorText) || passageText.contains(link.anchorText))
val destinations = passageLinks.groupBy(_.destination)
val neighborWithCounts =
for ((destination, anchors) <- destinations) yield {
val inlinkCount = if (inlinks.contains(destination)) {1} else {0}
val contextCount = contextLinks(destination)
val canonicalDestName = wikititleToEntityName(destination)
NeighborCount(wikipediaTitle, destination, canonicalDestName, anchors, inlinkCount, contextCount)
}
neighborWithCounts.toSeq
}
def findNeighbors(thisWikiTitle:String, galagoDocument:Document):WikiNeighbors = {
val outLinks = WikiLinkExtractor.simpleExtractorNoContext(galagoDocument)
.filterNot(anchor => (anchor.destination == thisWikiTitle) || ignoreWikiArticle(anchor.destination))
val inLinks = srcInLinks(galagoDocument)
val contextLinks = contextLinkCoocurrences(galagoDocument).toMap.withDefaultValue(0)
WikiNeighbors(outLinks, inLinks, contextLinks)
}
def ignoreWikiArticle(destination:String):Boolean = {
destination.startsWith("Category:") ||
destination.startsWith("File:") ||
destination.startsWith("List of ")
}
def wikititleToEntityName(wikititle:String):String = {
StringTools.zapParentheses(wikititle.replaceAllLiterally("_"," "))
}
def srcInLinks(galagoDoc:Document):Seq[String] = {
galagoDoc.metadata.get("srcInlinks").split(" ")
}
def contextLinkCoocurrences(galagoDoc:Document):Seq[(String, Int)] = {
for(line <- galagoDoc.metadata.get("contextLinks").split("\\n")) yield {
val title = StringTools.getSplitChunk(line, 0).get
val countOpt = StringTools.toIntOption(StringTools.getSplitChunk(line, 1).getOrElse("0"))
(title -> countOpt.getOrElse(0))
}
}
def multiplyMapValue[K](m:Map[K,Double], scalar:Double):Map[K,Double] = {
for((key,value) <- m) yield key -> (scalar * value)
}
}
|
daltonj/KbBridge
|
src/main/scala/edu/umass/ciir/kbbridge/kb2text/WikiEntityRepr.scala
|
Scala
|
apache-2.0
| 9,952 |
package exceptions
case class ParseException(message: String) extends Throwable
|
arpanchaudhury/SFD
|
src/main/scala/exceptions/ParseException.scala
|
Scala
|
mit
| 81 |
// Copyright (C) 2016 MapRoulette contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.maproulette.models
import org.joda.time.DateTime
import play.api.libs.json.{DefaultWrites, Json, Reads, Writes}
import play.api.libs.json.JodaWrites._
import play.api.libs.json.JodaReads._
case class TaskReview(
id: Long,
taskId: Long,
reviewStatus: Option[Int],
challengeName: Option[String],
reviewRequestedBy: Option[Long],
reviewRequestedByUsername: Option[String],
reviewedBy: Option[Long],
reviewedByUsername: Option[String],
reviewedAt: Option[DateTime],
reviewStartedAt: Option[DateTime],
reviewClaimedBy: Option[Long],
reviewClaimedByUsername: Option[String],
reviewClaimedAt: Option[DateTime]
)
object TaskReview {
implicit val reviewWrites: Writes[TaskReview] = Json.writes[TaskReview]
implicit val reviewReads: Reads[TaskReview] = Json.reads[TaskReview]
}
case class TaskWithReview(task: Task, review: TaskReview)
object TaskWithReview {
implicit val taskWithReviewWrites: Writes[TaskWithReview] = Json.writes[TaskWithReview]
implicit val taskWithReviewReads: Reads[TaskWithReview] = Json.reads[TaskWithReview]
}
case class ReviewMetrics(
total: Int,
reviewRequested: Int,
reviewApproved: Int,
reviewRejected: Int,
reviewAssisted: Int,
reviewDisputed: Int,
fixed: Int,
falsePositive: Int,
skipped: Int,
alreadyFixed: Int,
tooHard: Int,
avgReviewTime: Double
)
object ReviewMetrics {
implicit val reviewMetricsWrites = Json.writes[ReviewMetrics]
}
|
Crashfreak/maproulette2
|
app/org/maproulette/models/TaskReview.scala
|
Scala
|
apache-2.0
| 1,624 |
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package controllers.hvd
import controllers.actions.SuccessfulAuthAction
import models.hvd._
import org.joda.time.LocalDate
import org.jsoup.Jsoup
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import play.api.i18n.Messages
import play.api.test.Helpers._
import uk.gov.hmrc.http.cache.client.CacheMap
import utils.{AmlsSpec, DependencyMocks}
import views.html.hvd.cash_payment
import scala.concurrent.Future
class CashPaymentOverTenThousandEurosControllerSpec extends AmlsSpec with MockitoSugar {
trait Fixture extends DependencyMocks{
self => val request = addToken(authRequest)
lazy val view = app.injector.instanceOf[cash_payment]
val controller = new CashPaymentController(
mockCacheConnector,
authAction = SuccessfulAuthAction,
ds = commonDependencies,
cc = mockMcc,
cash_payment = view)
}
val emptyCache = CacheMap("", Map.empty)
"CashPaymentOverTenThousandEurosController" must {
"on GET" must {
"load the Cash Payment Over Ten Thousand Euros page" in new Fixture {
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(None))
val result = controller.get()(request)
status(result) must be(OK)
val htmlValue = Jsoup.parse(contentAsString(result))
htmlValue.title mustBe Messages("hvd.cash.payment.title") + " - " + Messages("summary.hvd") + " - " + Messages("title.amls") + " - " + Messages("title.gov")
}
"load Yes when Cash payment from mongoCache returns True" in new Fixture {
// scalastyle:off magic.number
val firstDate = Some(CashPaymentFirstDate(new LocalDate(1990, 2, 24)))
val activities = Hvd(cashPayment = Some(CashPayment(CashPaymentOverTenThousandEuros(true), firstDate)))
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(Some(activities)))
val result = controller.get()(request)
status(result) must be(OK)
val htmlValue = Jsoup.parse(contentAsString(result))
htmlValue.getElementById("acceptedAnyPayment-true").attr("checked") mustBe "checked"
htmlValue.getElementById("acceptedAnyPayment-true").attr("checked") mustBe "checked"
}
"load No when cashPayment from mongoCache returns No" in new Fixture {
val cashPayment = Some(CashPayment(CashPaymentOverTenThousandEuros(false), None))
val activities = Hvd(cashPayment = cashPayment)
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(Some(activities)))
val result = controller.get()(request)
status(result) must be(OK)
val htmlValue = Jsoup.parse(contentAsString(result))
htmlValue.getElementById("acceptedAnyPayment-false").attr("checked") mustBe "checked"
}
}
"on POST" must {
"successfully redirect to the Date of First Cash Payment page on selection of 'Yes' when edit mode is on" in new Fixture {
val newRequest = requestWithUrlEncodedBody("acceptedAnyPayment" -> "true",
"paymentDate.day" -> "12",
"paymentDate.month" -> "5",
"paymentDate.year" -> "1999"
)
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(None))
when(controller.dataCacheConnector.save[Hvd](any(), any(), any())(any(), any()))
.thenReturn(Future.successful(emptyCache))
val result = controller.post(true)(newRequest)
status(result) must be(SEE_OTHER)
redirectLocation(result) must be(Some(controllers.hvd.routes.CashPaymentFirstDateController.get(true).url))
}
"successfully redirect to the Date of First Cash Payment page on selection of 'Yes' when edit mode is off" in new Fixture {
val newRequest = requestWithUrlEncodedBody("acceptedAnyPayment" -> "true",
"paymentDate.day" -> "12",
"paymentDate.month" -> "5",
"paymentDate.year" -> "1999"
)
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(None))
when(controller.dataCacheConnector.save[Hvd](any(), any(), any())(any(), any()))
.thenReturn(Future.successful(emptyCache))
val result = controller.post()(newRequest)
status(result) must be(SEE_OTHER)
redirectLocation(result) must be(Some(controllers.hvd.routes.CashPaymentFirstDateController.get().url))
}
"successfully redirect to the Linked Cash Payments page on selection of 'No' when edit mode is off" in new Fixture {
val newRequest = requestWithUrlEncodedBody("acceptedAnyPayment" -> "false")
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(None))
when(controller.dataCacheConnector.save[Hvd](any(), any(), any())(any(), any()))
.thenReturn(Future.successful(emptyCache))
val result = controller.post()(newRequest)
status(result) must be(SEE_OTHER)
redirectLocation(result) must be(Some(controllers.hvd.routes.LinkedCashPaymentsController.get().url))
}
"successfully redirect to the Summary page on selection of Option 'No' when edit mode is on" in new Fixture {
val newRequest = requestWithUrlEncodedBody(
"acceptedAnyPayment" -> "false"
)
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(None))
when(controller.dataCacheConnector.save[Hvd](any(), any(), any())(any(), any()))
.thenReturn(Future.successful(emptyCache))
val result = controller.post(true)(newRequest)
status(result) must be(SEE_OTHER)
redirectLocation(result) must be(Some(controllers.hvd.routes.SummaryController.get.url))
}
"show invalid data error" in new Fixture {
val newRequest = requestWithUrlEncodedBody("" -> "")
when(controller.dataCacheConnector.fetch[Hvd](any(), any())(any(), any()))
.thenReturn(Future.successful(None))
val result = controller.post()(newRequest)
status(result) must be(BAD_REQUEST)
contentAsString(result) must include(Messages("error.required.hvd.accepted.cash.payment"))
}
}
}
}
|
hmrc/amls-frontend
|
test/controllers/hvd/CashPaymentOverTenThousandEurosControllerSpec.scala
|
Scala
|
apache-2.0
| 7,100 |
/*
* Copyright 2014-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.atlas.core.validation
import com.netflix.spectator.api.Id
import com.typesafe.config.ConfigFactory
import munit.FunSuite
class MaxUserTagsRuleSuite extends FunSuite {
private val config = ConfigFactory.parseString("limit = 2")
private val rule = MaxUserTagsRule(config)
test("ok") {
val t1 = Map("name" -> "foo")
val t2 = t1 + ("foo" -> "bar")
val t3 = t2 + ("nf.region" -> "west")
assertEquals(rule.validate(t1), ValidationResult.Pass)
assertEquals(rule.validate(t2), ValidationResult.Pass)
assertEquals(rule.validate(t3), ValidationResult.Pass)
}
test("too many") {
val res = rule.validate(Map("name" -> "foo", "foo" -> "bar", "abc" -> "def"))
assert(res.isFailure)
}
test("id: ok") {
val id1 = Id.create("foo")
val id2 = id1.withTag("foo", "bar")
val id3 = id2.withTag("nf.region", "west")
assertEquals(rule.validate(id1), ValidationResult.Pass)
assertEquals(rule.validate(id2), ValidationResult.Pass)
assertEquals(rule.validate(id3), ValidationResult.Pass)
}
test("id: too many") {
val id = Id.create("foo").withTags("foo", "bar", "abc", "def")
val res = rule.validate(id)
assert(res.isFailure)
}
}
|
brharrington/atlas
|
atlas-core/src/test/scala/com/netflix/atlas/core/validation/MaxUserTagsRuleSuite.scala
|
Scala
|
apache-2.0
| 1,826 |
import org.springframework.transaction.support._
import org.springframework.transaction._
import scala.util._
trait TxHelpers {
type TxCallback[T] = TransactionStatus => T
private def transactionCallback[T](callback: TxCallback[T]): TransactionCallback[T] = new TransactionCallback[T]() {
def doInTransaction(status: TransactionStatus): T = callback(status)
}
def withTransaction[T](template: TransactionTemplate)(callback: TxCallback[T]): Try[T] = Try {
template.execute(transactionCallback(callback))
}
}
|
orthanner/coreauth
|
src/main/scala/TxHelpers.scala
|
Scala
|
cc0-1.0
| 528 |
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author John Miller
* @version 1.3
* @date Fri Dec 27 15:41:58 EST 2013
* @see LICENSE (MIT style license file).
*/
package apps.tableau
import scalation.model.Modelable
import scalation.random.{Exponential, Variate}
import scalation.tableau.Model
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `CallCenter` object defines a simple tableau model of a Call Center where
* service is provided by one tele-service representative and models an M/M/1/1
* queue (i.e., no call waiting). The default 'simulate' method provided by
* `scalation.tableau.Model` won't suffice and must be overridden in the
* `CallCenterModel` class.
*/
object CallCenter extends App with Modelable
{
val stream = 1 // random number stream (0 to 99)
val lambda = 6.0 // customer arrival rate (per hr)
val mu = 7.5 // customer service rate (per hr)
val maxCalls = 10 // stopping rule: at maxCalls
val iArrivalRV = Exponential (HOUR/lambda, stream) // inter-arrival time random var
val serviceRV = Exponential (HOUR/mu, stream) // service time random variate
val label = Array ("ID-0", "IArrival-1", "Arrival-2", "Start-3", "Service-4",
"End-5", "Wait-6", "Total-7")
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Run the simulation of the `CallCenterModel`.
* @param startTime the start time for the simulation
*/
def simulate (startTime: Double)
{
val mm11 = new CallCenterModel ("CallCenter", maxCalls, Array (iArrivalRV, serviceRV),
label)
mm11.simulate (startTime)
mm11.report
mm11.save
} // simulate
simulate (0.0)
} // CallCenter object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `CallCenterModel` class customizes `scalation.tableau.Model` for Call Center
* simulations by overriding the 'simulate' method.
* @param name the name of simulation model
* @param m the number entities to process before stopping
* @param rv the random variate generators to use
* @param label the column labels for the matrix
*/
class CallCenterModel (name: String, m: Int, rv: Array [Variate], label: Array [String])
extends Model (name, m, rv, label)
{
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Perform tableau-based simulation by recording timing information about
* the 'i'th entity in the 'i'th row of the matrix.
* @param startTime the start time for the simulation
*/
override def simulate (startTime: Double)
{
var l = 0 // last established call
for (i <- 1 to m) {
table(i, 1) = if (i == 1) startTime else rv(0).gen // IArrival-1
table(i, 2) = table(i, 1) + table(i-1, 2) // Arrival-2
val serviceT = rv(1).gen
if (table(l, 5) <= table(i, 2)) { // call established
table(i, 3) = table(i, 2); l = i // Start-3
table(i, 4) = serviceT // Service-4
table(i, 5) = table(i, 3) + table(i, 4) // End-5
table(i, 6) = table(i, 3) - table(i, 2) // Wait-6
table(i, 7) = table(i, 5) - table(i, 2) // Total-7
} // if
} // for
} // simulate
} // CallCenterModel class
|
NBKlepp/fda
|
scalation_1.3/scalation_models/src/main/scala/apps/tableau/CallCenter.scala
|
Scala
|
mit
| 3,846 |
package scala.collection.parallel
trait Operators[T] {
def reduceOperators: List[(T, T) => T]
def countPredicates: List[T => Boolean]
def forallPredicates: List[T => Boolean]
def existsPredicates: List[T => Boolean]
def findPredicates: List[T => Boolean]
def mapFunctions: List[T => T]
def partialMapFunctions: List[PartialFunction[T, T]]
def flatMapFunctions: List[T => Traversable[T]]
def filterPredicates: List[T => Boolean]
def filterNotPredicates: List[T => Boolean]
def partitionPredicates: List[T => Boolean]
def takeWhilePredicates: List[T => Boolean]
def dropWhilePredicates: List[T => Boolean]
def spanPredicates: List[T => Boolean]
def foldArguments: List[(T, (T, T) => T)]
def addAllTraversables: List[Traversable[T]]
def newArray(sz: Int): Array[T]
def groupByFunctions: List[T => T]
}
trait SeqOperators[T] extends Operators[T] {
def segmentLengthPredicates: List[T => Boolean]
def indexWherePredicates: List[T => Boolean]
def lastIndexWherePredicates: List[T => Boolean]
def reverseMapFunctions: List[T => T]
def sameElementsSeqs: List[Seq[T]]
def startEndSeqs: List[Seq[T]]
}
|
shimib/scala
|
test/scalacheck/scala/collection/parallel/Operators.scala
|
Scala
|
bsd-3-clause
| 1,147 |
package dao.sitedata
import scala.concurrent.Future
import javax.inject.Inject
import play.api.db.slick.DatabaseConfigProvider
import play.api.db.slick.HasDatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import slick.driver.JdbcProfile
import slick.jdbc.GetResult
import models.sitedata.SiteInfoDetail
import play.db.NamedDatabase
import play.api.Logger
import org.joda.time.DateTime
import java.sql.Timestamp
import com.github.tototoshi.slick.PostgresJodaSupport._
trait ISiteInfoDetailDao extends BaseDao2[SiteInfoDetail]{
def findAll(): Future[Seq[SiteInfoDetail]]
def findById(id: String): Future[Option[SiteInfoDetail]]
def remove(id: String): Future[Int]
def insert(p: SiteInfoDetail): Future[Unit]
def update(p2: SiteInfoDetail): Future[Unit]
}
class SiteInfoDetailDao @Inject()(@NamedDatabase("SiteData") protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] with ISiteInfoDetailDao {
// import driver.api._
import com.typesafe.slick.driver.ms.SQLServerDriver.api._
class SiteInfoDetailTable(tag: Tag)
extends Table[SiteInfoDetail](tag, models.sitedata.SiteInfoDetailDef.toTable) {
def siteid = column[String]("SiteID", O.PrimaryKey)
def sphostname = column[Option[String]]("SPHostName")
def spversion = column[Option[String]]("SPVersion")
def spmodel = column[Option[String]]("SPModel")
def equipmentversion1 = column[Option[String]]("EquipmentVersion1")
def equipmentversion2 = column[Option[String]]("EquipmentVersion2")
def lastconnecttime = column[Option[DateTime]]("LastConnectTime")
def lastregalertreceivetime = column[Option[DateTime]]("LastRegAlertReceiveTime")
def regalertrate = column[Option[Int]]("RegAlertRate")
def equipmentstatus = column[Option[String]]("EquipmentStatus")
def licenseexpiretime = column[Option[DateTime]]("LicenseExpireTime")
// def lastmodifiedtime = column[DateTime]("LastModifiedTime")
// def lastmodifier = column[Option[String]]("LastModifier")
// def modifiedtimestamp = column[TimeStamp]
def remoteinspection = column[Option[String]]("RemoteInspection")
def remoteinspectionscheduledend = column[Option[DateTime]]("RemoteInspectionScheduledEnd")
def pingtosp = column[Option[String]]("PingToSP")
def spdbversion = column[Option[String]]("SPDBVersion")
def loganalyzerversion = column[Option[String]]("LogAnalyzerVersion")
def loganalyzerdbversion = column[Option[String]]("LogAnalyzerDBVersion")
def tcatversion = column[Option[String]]("TCATVersion")
// def mcafeesecurityembversion = column[String]("McAfeeSedurityEmbVersion")
def sposname = column[Option[String]]("SPOSName")
// def sposservicepack = column[String]("SPOSServicePack")
// def spossecuritypatch = column[String]("SPOSSecurityPatch")
// def transferrate = column[String]("TransferRate")
// def regularalertnotificationsetting = column[Int]("RegularAlertNotificationSetting")
def * = (
siteid,
sphostname,
spversion,
spmodel,
equipmentversion1,
equipmentversion2,
lastconnecttime,
lastregalertreceivetime,
regalertrate,
equipmentstatus,
licenseexpiretime,
// lastmodifiedtime,
// lastmodifier,
// modifiedtimestamp,
remoteinspection,
remoteinspectionscheduledend,
pingtosp,
spdbversion,
loganalyzerversion,
loganalyzerdbversion,
tcatversion,
// mcafeesecurityembversion,
sposname
// sposservicepack,
// spossecuritypatch,
// transferrate,
// regularalertnotificationsetting
) <> (SiteInfoDetail.tupled, SiteInfoDetail.unapply _)
}
lazy val sourcefilename = new Exception().getStackTrace.head.getFileName
override def toTable = TableQuery[SiteInfoDetailTable]
private val Details = toTable()
override def findAll(): Future[Seq[SiteInfoDetail]] = {
Logger.info(sourcefilename + " findAll called.")
db.run(Details.result)
}
override def findById(id: String): Future[Option[SiteInfoDetail]] = {
Logger.info("(" + sourcefilename + ")" + " findById(" + id + ") called.")
db.run(Details.filter( _.siteid === id).result.headOption)
}
override def remove(id: String): Future[Int] = {
Logger.info(sourcefilename + " remove(" + id + ") called.")
/* db.run(Details.filter( _.siteid === id).delete) */
Future(1) // dummy
}
override def insert(p: SiteInfoDetail): Future[Unit] = {
Logger.info(sourcefilename + " insert called.")
/* db.run(Details += p).map { _ => () } */
Future(()) // dummy
}
override def update(p2: SiteInfoDetail) = Future[Unit] {
Logger.info(sourcefilename + " update called.")
/* db.run(
* Details.filter(_.siteid === p2.siteid)
* // .map(p => (p.name,p.details, p.price))
* .map(p => (p.sitename))
* // .update((p2.name,p2.details,p2.price))
* .update((p2.sitename))
* ) */
Future(()) // dummy
}
}
|
tnddn/iv-web
|
portal/rest-portal/app/dao/sitedata/SiteInfoDetailDao.scala
|
Scala
|
apache-2.0
| 5,465 |
package japgolly.scalajs.react.core
import japgolly.scalajs.react._
import japgolly.scalajs.react.test.TestUtil._
import japgolly.scalajs.react.test.{InferenceHelpers, ReactTestUtils, Simulate}
import japgolly.scalajs.react.vdom.ImplicitsFromRaw._
import scala.annotation.nowarn
import utest._
@nowarn("cat=deprecation")
object ScalaComponentPTest extends TestSuite {
private case class BasicProps(name: String)
private val BasicComponent =
ScalaComponent.builder[BasicProps]("HelloMessage")
.stateless
.noBackend
.render_P(p => facade.React.createElement("div", null, "Hello ", p.name))
.build
override def tests = Tests {
"displayName" - {
assertEq(BasicComponent.displayName, "HelloMessage")
// ReactTestUtils.withRenderedIntoDocument(BasicComponent(BasicProps("X"))) { m =>
// println(inspectObject(m.raw))
// assertEq(m.raw.displayName, "HelloMessage")
// }
}
"types" - {
import InferenceHelpers._
import ScalaComponent._
"cu" - assertType[Component[P, S, B, CtorType.Nullary]].map(_.ctor()).is[Unmounted[P, S, B]]
"um" - assertType[Unmounted[P, S, B]].map(_.renderIntoDOM(null)).is[MountedImpure[P, S, B]]
}
"basic" - {
val unmounted = BasicComponent(BasicProps("Bob"))
assertEq(unmounted.props.name, "Bob")
assertEq(unmounted.propsChildren.count, 0)
assertEq(unmounted.propsChildren.isEmpty, true)
assertEq(unmounted.key, None)
assertEq(unmounted.ref, None)
ReactTestUtils.withNewBodyElement { mountNode =>
val mounted = unmounted.renderIntoDOM(mountNode)
val n = mounted.getDOMNode.asMounted().asElement()
assertOuterHTML(n, "<div>Hello Bob</div>")
assertEq(mounted.props.name, "Bob")
assertEq(mounted.propsChildren.count, 0)
assertEq(mounted.propsChildren.isEmpty, true)
assertEq(mounted.state, ())
assertEq(mounted.backend, ())
}
}
"withKey" - {
ReactTestUtils.withNewBodyElement { mountNode =>
val u = BasicComponent.withKey("k")(BasicProps("Bob"))
assertEq(u.key, Option[Key]("k"))
val m = u.renderIntoDOM(mountNode)
assertOuterHTML(m.getDOMNode.asMounted().asElement(), "<div>Hello Bob</div>")
}
}
"ctorReuse" -
assert(BasicComponent(BasicProps("a")) ne BasicComponent(BasicProps("b")))
"ctorMap" - {
val c2 = BasicComponent.mapCtorType(_ withProps BasicProps("hello!"))
val unmounted = c2()
assertEq(unmounted.props.name, "hello!")
ReactTestUtils.withNewBodyElement { mountNode =>
val mounted = unmounted.renderIntoDOM(mountNode)
val n = mounted.getDOMNode.asMounted().asElement()
assertOuterHTML(n, "<div>Hello hello!</div>")
}
}
"lifecycle1" - {
case class Props(a: Int, b: Int, c: Int) {
def -(x: Props) = Props(
this.a - x.a,
this.b - x.b,
this.c - x.c)
}
implicit def equalProps: UnivEq[Props] = UnivEq.force
var mountCountA = 0
var mountCountB = 0
var mountCountBeforeMountA = 0
var mountCountBeforeMountB = 0
var willMountCountA = 0
var willMountCountB = 0
def assertMountCount(expect: Int): Unit = {
assertEq("mountCountA", mountCountA, expect)
assertEq("mountCountB", mountCountB, expect)
assertEq("willMountCountA", willMountCountA, expect)
assertEq("willMountCountB", willMountCountB, expect)
assertEq("mountCountBeforeMountA", mountCountBeforeMountA, 0)
assertEq("mountCountBeforeMountB", mountCountBeforeMountB, 0)
}
var didUpdates = Vector.empty[Props]
var willUpdates = Vector.empty[Props]
def assertUpdates(ps: Props*): Unit = {
val e = ps.toVector
assertEq("willUpdates", willUpdates, e)
assertEq("didUpdates", didUpdates, e)
}
var recievedPropDeltas = Vector.empty[Props]
var willUnmountCount = 0
class Backend {
def willMount = Callback { mountCountBeforeMountB += mountCountB; willMountCountB += 1 }
def incMountCount = Callback(mountCountB += 1)
def willUpdate(cur: Props, next: Props) = Callback(willUpdates :+= next - cur)
def didUpdate(prev: Props, cur: Props) = Callback(didUpdates :+= cur - prev)
def receive(cur: Props, next: Props) = Callback(recievedPropDeltas :+= next - cur)
def incUnmountCount = Callback(willUnmountCount += 1)
}
val Inner = ScalaComponent.builder[Props]("")
.stateless
.backend(_ => new Backend)
.render_P(p => facade.React.createElement("div", null, s"${p.a} ${p.b} ${p.c}"))
.shouldComponentUpdatePure(_.cmpProps(_.a != _.a)) // update if .a differs
.shouldComponentUpdatePure(_.cmpProps(_.b != _.b)) // update if .b differs
.componentDidMount(_ => Callback(mountCountA += 1))
.componentDidMount(_.backend.incMountCount)
.componentWillMount(_ => AsyncCallback.delay { mountCountBeforeMountA += mountCountA; willMountCountA += 1 })
.componentWillMount(_.backend.willMount)
.componentWillUpdate(x => x.backend.willUpdate(x.currentProps, x.nextProps))
.componentDidUpdate(x => x.backend.didUpdate(x.prevProps, x.currentProps))
.componentWillUnmount(_.backend.incUnmountCount)
.componentWillReceiveProps(x => x.backend.receive(x.currentProps, x.nextProps))
.build
val Comp = ScalaComponent.builder[Props]("")
.initialState[Option[String]](None) // error message
.render_PS((p, s) => s match {
case None => Inner(p).vdomElement
case Some(e) => facade.React.createElement("div", null, "Error: " + e)
})
.componentDidCatch($ => $.setState(Some($.error.message.replaceFirst("'.+' *", ""))))
.build
val staleDomNodeCallback = ReactTestUtils.withNewBodyElement { mountNode =>
assertMountCount(0)
var mounted = Comp(Props(1, 2, 3)).renderIntoDOM(mountNode)
def el() = mounted.getDOMNode.asMounted().asElement()
assertMountCount(1)
assertOuterHTML(el(), "<div>1 2 3</div>")
assertUpdates()
mounted = Comp(Props(1, 2, 8)).renderIntoDOM(mountNode)
assertOuterHTML(el(), "<div>1 2 3</div>")
assertUpdates()
mounted = Comp(Props(1, 5, 8)).renderIntoDOM(mountNode)
assertOuterHTML(el(), "<div>1 5 8</div>")
assertUpdates(Props(0, 3, 0))
assertEq("willUnmountCount", willUnmountCount, 0)
mounted = Comp(null).renderIntoDOM(mountNode)
assertOuterHTMLMatches(el(), "<div>Error: Cannot read propert(y|ies) of null.*</div>")
assertEq("willUnmountCount", willUnmountCount, 1)
mounted.withEffectsPure.getDOMNode
}
assertMountCount(1)
assertEq("willUnmountCount", willUnmountCount, 1)
assertEq("receivedPropDeltas", recievedPropDeltas, Vector(Props(0, 0, 5), Props(0, 3, 0)))
assert(staleDomNodeCallback.runNow().mounted.isEmpty)
}
"lifecycle2" - {
type Props = Int
var snapshots = Vector.empty[String]
val Comp = ScalaComponent.builder[Props]("")
.initialState(0)
.noBackend
.render_PS((p, s) => facade.React.createElement("div", null, s"p=$p s=$s"))
.getDerivedStateFromProps(_ + 100)
.getSnapshotBeforeUpdatePure($ => s"${$.prevProps} -> ${$.currentProps}")
.componentDidUpdate($ => Callback(snapshots :+= $.snapshot))
.build
ReactTestUtils.withNewBodyElement { mountNode =>
var mounted = Comp(10).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=10 s=110</div>")
assertEq(snapshots, Vector())
mounted = Comp(20).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=20 s=120</div>")
assertEq(snapshots, Vector("10 -> 20"))
}
}
"getDerivedStateFromProps" - {
"multiple" - {
val Comp = ScalaComponent.builder[Int]("")
.initialState(0)
.noBackend
.render_PS((p, s) => facade.React.createElement("div", null, s"p=$p s=$s"))
.getDerivedStateFromPropsOption(p => if (p > 100) Some(p - 100) else None)
.getDerivedStateFromPropsOption((_, s) => if ((s & 1) == 0) Some(s >> 1) else None)
.build
ReactTestUtils.withNewBodyElement { mountNode =>
var mounted = Comp(108).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=108 s=4</div>")
mounted = Comp(103).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=103 s=3</div>")
mounted = Comp(204).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=204 s=52</div>")
mounted = Comp(6).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=6 s=26</div>")
}
}
"early" - {
val Comp = ScalaComponent.builder[Int]("")
.getDerivedStateFromProps(-_)
.noBackend
.render_PS((p, s) => facade.React.createElement("div", null, s"p=$p s=$s"))
.getDerivedStateFromPropsOption((_, s) => if (s > 100) Some(s - 100) else None)
.getDerivedStateFromPropsOption((_, s) => if ((s & 1) == 0) Some(s >> 1) else None)
.build
ReactTestUtils.withNewBodyElement { mountNode =>
var mounted = Comp(-108).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-108 s=4</div>")
mounted = Comp(-103).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-103 s=3</div>")
mounted = Comp(-204).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-204 s=52</div>")
mounted = Comp(-6).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-6 s=3</div>")
}
}
"early2" - {
val Comp = ScalaComponent.builder[Int]("")
.getDerivedStateFromPropsAndState[Int]((p, os) => os.fold(0)(_ => -p))
.noBackend
.render_PS((p, s) => facade.React.createElement("div", null, s"p=$p s=$s"))
.getDerivedStateFromPropsOption((_, s) => if (s > 100) Some(s - 100) else None)
.getDerivedStateFromPropsOption((_, s) => if ((s & 1) == 0) Some(s >> 1) else None)
.build
ReactTestUtils.withNewBodyElement { mountNode =>
var mounted = Comp(-108).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-108 s=4</div>")
mounted = Comp(-103).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-103 s=3</div>")
mounted = Comp(-204).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-204 s=52</div>")
mounted = Comp(-6).renderIntoDOM(mountNode)
assertOuterHTML(mounted.getDOMNode.asMounted().asElement(), "<div>p=-6 s=3</div>")
}
}
}
"asyncSetState" - {
import japgolly.scalajs.react.vdom.html_<^._
var results = Vector.empty[Int]
final class Backend($: BackendScope[Unit, Int]) {
val onClick: AsyncCallback[Unit] =
for {
_ <- $.modStateAsync(_ + 1)
s <- $.state.asAsyncCallback
} yield results :+= s
def render(s: Int): VdomNode =
<.div(s, ^.onClick --> onClick)
}
val Component = ScalaComponent.builder[Unit]("")
.initialState(0)
.renderBackend[Backend]
.build
ReactTestUtils.withNewBodyElement { mountNode =>
val mounted = Component().renderIntoDOM(mountNode)
assertEq(results, Vector())
Simulate.click(mounted.getDOMNode.toHtml.get)
assertEq(results, Vector(1))
}
}
}
}
object ScalaComponentSTest extends TestSuite {
case class State(num1: Int, s2: State2)
case class State2(num2: Int, num3: Int)
implicit val equalState: UnivEq[State] = UnivEq.force
implicit val equalState2: UnivEq[State2] = UnivEq.force
class Backend($: BackendScope[Int, State]) {
val inc: Callback =
$.modState(s => s.copy(s.num1 + 1))
}
val Component =
ScalaComponent.builder[Int]("")
.initialState(State(123, State2(400, 7)))
.backend(new Backend(_))
.render_PS((p, s) => facade.React.createElement("div", null, "Props = ", p, ". State = ", s.num1, " + ", s.s2.num2, " + ", s.s2.num3))
.build
override def tests = Tests {
"main" - {
var callCount = 0
val incCallCount = Callback(callCount += 1)
val p = 9000
val unmounted = Component(p)
assert(unmounted.propsChildren.isEmpty)
assertEq(unmounted.key, None)
assertEq(unmounted.ref, None)
ReactTestUtils.withNewBodyElement { mountNode =>
val mounted = unmounted.renderIntoDOM(mountNode)
val n = mounted.getDOMNode.asMounted().asElement()
val b = mounted.backend
var s = State(123, State2(400, 7))
var cc = 0
def test(children: Int = 0, incCallCount: Boolean = false): Unit = {
if (incCallCount) cc += 1
assertOuterHTML(n, s"<div>Props = $p. State = ${s.num1} + ${s.s2.num2} + ${s.s2.num3}</div>")
assertEq(mounted.state, s)
assertEq("propsChildren.count", mounted.propsChildren.count, children)
assertEq("propsChildren.isEmpty", mounted.propsChildren.isEmpty, children == 0)
assertEq("callCount", callCount, cc)
assert(mounted.backend eq b)
}
test()
s = State(66, State2(50, 77))
mounted.setState(s, incCallCount)
test(incCallCount = true)
s = State(100, State2(300, 11))
mounted.setStateOption(Some(s), incCallCount)
test(incCallCount = true)
mounted.setStateOption(None, incCallCount)
test(incCallCount = true) // If this ever fails (i.e. React stops calling cb on setState(null, cb)),
// then change the logic in StateAccess.apply & ReactTestVar
s = State(88, s.s2)
mounted.modState(_.copy(88), incCallCount)
test(incCallCount = true)
s = State(9088, s.s2)
mounted.modState((s, p) => s.copy(s.num1 + p), incCallCount)
test(incCallCount = true)
s = State(828, s.s2)
mounted.modStateOption(x => Some(x.copy(828)), incCallCount)
test(incCallCount = true)
s = State(9828, s.s2)
mounted.modStateOption((s, p) => Some(s.copy(p + 828)), incCallCount)
test(incCallCount = true)
mounted.modStateOption(_ => None, incCallCount)
test(incCallCount = true)
s = State(666, State2(500, 7))
mounted.setState(s)
test()
mounted.backend.inc.runNow()
s = State(667, State2(500, 7))
test()
val zoomed = mounted
.zoomState(_.s2)(n => _.copy(s2 = n))
.zoomState(_.num2)(n => _.copy(num2 = n))
assertEq(zoomed.state, 500)
zoomed.modState(_ + 1)
s = State(667, State2(501, 7))
test()
}
}
"ctorReuse" - {
val Component =
ScalaComponent.builder[Unit]("")
.initialState(123)
.render_S(s => facade.React.createElement("div", null, s))
.build
assert(Component() eq Component())
}
}
}
|
japgolly/scalajs-react
|
tests/src/test/scala/japgolly/scalajs/react/core/ScalaComponentTest.scala
|
Scala
|
apache-2.0
| 15,780 |
package at.logic.gapt.proofs.lkNew
import at.logic.gapt.expr._
import at.logic.gapt.expr.hol.HOLPosition
import at.logic.gapt.proofs._
import at.logic.gapt.proofs.lk.base._
import org.specs2.execute.Success
import org.specs2.mutable._
/**
* Created by sebastian on 8/6/15.
*/
class LKNewTest extends Specification {
val c = FOLConst( "c" )
val d = FOLConst( "d" )
val alpha = FOLVar( "α" )
val x = FOLVar( "x" )
val y = FOLVar( "y" )
def P( t: FOLTerm ) = FOLAtom( "P", t )
val A = FOLAtom( "A", Nil )
val B = FOLAtom( "B", Nil )
val C = FOLAtom( "C", Nil )
val D = FOLAtom( "D", Nil )
val E = FOLAtom( "E", Nil )
val F = FOLAtom( "F", Nil )
val Pc = FOLAtom( "P", c )
val Pd = FOLAtom( "P", d )
private def testParents( o: OccConnector[HOLFormula], ruleName: String )( sequent: HOLSequent, parents: Seq[SequentIndex]* ): Success = {
val ( m, n ) = sequent.sizes
for ( ( i, ps ) <- sequent.indices zip parents ) {
o.parents( i ) aka s"$ruleName: Parents of $i in $sequent should be $ps" must beEqualTo( ps )
}
o.parents( Ant( m ) ) aka s"Parents of ${Ant( m )} in $sequent" must throwAn[IndexOutOfBoundsException]
o.parents( Suc( n ) ) aka s"Parents of ${Suc( n )} in $sequent" must throwAn[IndexOutOfBoundsException]
success
}
private def testChildren( o: OccConnector[HOLFormula], ruleName: String )( sequent: HOLSequent, children: Seq[SequentIndex]* ): Success = {
val ( m, n ) = sequent.sizes
for ( ( i, cs ) <- sequent.indices zip children ) {
o.children( i ) aka s"$ruleName: Children of $i in $sequent should be $cs" must beEqualTo( cs )
}
o.children( Ant( m ) ) aka s"Parents of ${Ant( m )} in $sequent" must throwAn[IndexOutOfBoundsException]
o.children( Suc( n ) ) aka s"Parents of ${Suc( n )} in $sequent" must throwAn[IndexOutOfBoundsException]
success
}
"LogicalAxiom" should {
"correctly create an axiom" in {
LogicalAxiom( A )
success
}
"correctly return its main formula" in {
val ax = LogicalAxiom( A )
if ( ax.mainIndices.length != 2 )
failure
val ( i1, i2 ) = ( ax.mainIndices.head, ax.mainIndices.tail.head )
ax.endSequent( i1 ) must beEqualTo( A )
ax.endSequent( i2 ) must beEqualTo( A )
}
}
"ReflexivityAxiom" should {
"correctly create an axiom" in {
ReflexivityAxiom( c )
success
}
"correctly return its main formula" in {
val ax = ReflexivityAxiom( c )
if ( ax.mainIndices.length != 1 )
failure
val i = ax.mainIndices.head
ax.endSequent( i ) must beEqualTo( Eq( c, c ) )
}
}
"WeakeningLeftRule" should {
"correctly create a proof" in {
WeakeningLeftRule( LogicalAxiom( A ), Pc )
success
}
"correctly return its main formula" in {
val p = WeakeningLeftRule( LogicalAxiom( A ), Pc )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( Pc )
}
"correctly connect occurrences" in {
//end sequent of p: B, A :- A
val p = WeakeningLeftRule( LogicalAxiom( A ), B )
val o = p.getOccConnector
testChildren( o, "w_l" )(
p.premise,
Seq( Ant( 1 ) ),
Seq( Suc( 0 ) )
)
testParents( o, "w_l" )(
p.endSequent,
Seq(),
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) )
)
}
}
"WeakeningRightRule" should {
"correctly create a proof" in {
WeakeningRightRule( LogicalAxiom( A ), B )
success
}
"correctly return its main formula" in {
val p = WeakeningRightRule( LogicalAxiom( A ), B )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( B )
}
"correctly connect occurrences" in {
// end sequent of p: A :- A, B
val p = WeakeningRightRule( LogicalAxiom( A ), B )
val o = p.getOccConnector
testChildren( o, "w_r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) )
)
testParents( o, "w_r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq()
)
}
}
"ContractionLeftRule" should {
"correctly create a proof" in {
ContractionLeftRule( WeakeningLeftRule( LogicalAxiom( A ), A ), Ant( 0 ), Ant( 1 ) )
ContractionLeftRule( WeakeningLeftRule( LogicalAxiom( A ), A ), A )
success
}
"refuse to construct a proof" in {
ContractionLeftRule( LogicalAxiom( A ), Ant( 0 ), Ant( 1 ) ) must throwAn[LKRuleCreationException]
ContractionLeftRule( WeakeningLeftRule( LogicalAxiom( A ), Pc ), Ant( 0 ), Ant( 1 ) ) must throwAn[LKRuleCreationException]
ContractionLeftRule( LogicalAxiom( A ), Ant( 0 ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
ContractionLeftRule( LogicalAxiom( Pc ), A ) must throwAn[LKRuleCreationException]
ContractionLeftRule( LogicalAxiom( A ), A ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = ContractionLeftRule( WeakeningLeftRule( LogicalAxiom( A ), A ), A )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( A )
}
"correctly return its aux formulas" in {
val p = ContractionLeftRule( WeakeningLeftRule( LogicalAxiom( A ), A ), A )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
for ( i <- p.auxIndices.head ) {
p.premise( i ) must beEqualTo( A )
}
success
}
"correctly connect occurrences" in {
// end sequent of p: A, B, C :- A, B
val p = ContractionLeftRule( TheoryAxiom( B +: A +: C +: A +: Sequent() :+ A :+ B ), A )
val o = p.getOccConnector
testParents( o, "c_l" )(
p.endSequent,
Seq( Ant( 1 ), Ant( 3 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) )
)
testChildren( o, "c_l" )(
p.premise,
Seq( Ant( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) )
)
}
}
"ContractionRightRule" should {
"correctly create a proof" in {
ContractionRightRule( WeakeningRightRule( LogicalAxiom( A ), A ), Suc( 0 ), Suc( 1 ) )
ContractionRightRule( WeakeningRightRule( LogicalAxiom( A ), A ), A )
success
}
"refuse to construct a proof" in {
ContractionRightRule( LogicalAxiom( A ), Suc( 0 ), Suc( 1 ) ) must throwAn[LKRuleCreationException]
ContractionRightRule( WeakeningRightRule( LogicalAxiom( A ), Pc ), Suc( 0 ), Suc( 1 ) ) must throwAn[LKRuleCreationException]
ContractionRightRule( LogicalAxiom( A ), Suc( 0 ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
ContractionRightRule( LogicalAxiom( Pc ), A ) must throwAn[LKRuleCreationException]
ContractionRightRule( LogicalAxiom( A ), A ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = ContractionRightRule( WeakeningRightRule( LogicalAxiom( A ), A ), A )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( A )
}
"correctly return its aux formulas" in {
val p = ContractionRightRule( WeakeningRightRule( LogicalAxiom( A ), A ), A )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
for ( i <- p.auxIndices.head ) {
p.premise( i ) must beEqualTo( A )
}
success
}
"correctly connect occurrences" in {
// end sequent of p: A, B :- B, C, A
val p = ContractionRightRule( TheoryAxiom( A +: B +: Sequent() :+ A :+ B :+ A :+ C ), Suc( 0 ), Suc( 2 ) )
val o = p.getOccConnector
testParents( o, "c_r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Suc( 1 ) ),
Seq( Suc( 3 ) ),
Seq( Suc( 0 ), Suc( 2 ) )
)
testChildren( o, "c_r" )(
p.premise,
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
}
}
"CutRule" should {
"correctly produce a proof" in {
CutRule( TheoryAxiom( A +: B +: Sequent() :+ B ), Suc( 0 ), LogicalAxiom( B ), Ant( 0 ) )
CutRule( TheoryAxiom( A +: B +: Sequent() :+ B ), LogicalAxiom( B ), B )
success
}
"refuse to produce a proof" in {
val p1 = TheoryAxiom( Sequent() :+ A :+ B )
val p2 = TheoryAxiom( C +: B +: Sequent() )
CutRule( p1, Ant( 0 ), p2, Ant( 0 ) ) must throwAn[LKRuleCreationException]
CutRule( p1, Suc( 0 ), p2, Suc( 0 ) ) must throwAn[LKRuleCreationException]
CutRule( p1, Suc( 0 ), p2, Ant( 0 ) ) must throwAn[LKRuleCreationException]
CutRule( p1, Suc( 2 ), p2, Ant( 0 ) ) must throwAn[LKRuleCreationException]
CutRule( p1, Suc( 0 ), p2, Ant( 3 ) ) must throwAn[LKRuleCreationException]
}
"correctly return its aux formulas" in {
val p1 = TheoryAxiom( Sequent() :+ A :+ B )
val p2 = TheoryAxiom( C +: B +: Sequent() )
val p = CutRule( p1, p2, B )
if ( p.auxIndices.length != 2 )
failure
if ( ( p.auxIndices.head.length != 1 ) || ( p.auxIndices.tail.head.length != 1 ) )
failure
val ( i, j ) = ( p.auxIndices.head.head, p.auxIndices.tail.head.head )
p.leftPremise( i ) must beEqualTo( B )
p.rightPremise( j ) must beEqualTo( B )
}
"correctly connect occurrences" in {
val p1 = TheoryAxiom( A +: B +: Sequent() :+ A :+ B :+ C )
val p2 = TheoryAxiom( D +: B +: E +: F +: Sequent() :+ B :+ E )
// end sequent of p: A, B, D, E, F :- A, C, B, E
val p = CutRule( p1, p2, B )
val oL = p.getLeftOccConnector
val oR = p.getRightOccConnector
testChildren( oL, "cut" )(
p.leftPremise,
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Suc( 0 ) ),
Seq(),
Seq( Suc( 1 ) )
)
testParents( oL, "cut" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq(),
Seq(),
Seq(),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq(),
Seq()
)
testChildren( oR, "cut" )(
p.rightPremise,
Seq( Ant( 2 ) ),
Seq(),
Seq( Ant( 3 ) ),
Seq( Ant( 4 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 3 ) )
)
testParents( oR, "cut" )(
p.endSequent,
Seq(),
Seq(),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 3 ) ),
Seq(),
Seq(),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) )
)
}
}
"NegLeftRule" should {
"correctly create a proof" in {
NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Suc( 0 ) )
NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), C )
success
}
"refuse to create a proof" in {
NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Suc( 2 ) ) must throwAn[LKRuleCreationException]
NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), A ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), C )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( Neg( C ) )
}
"correctly return its aux formulas" in {
val p = NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D :+ E ), C )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 1 )
failure
for ( i <- p.auxIndices.head ) {
p.premise( i ) must beEqualTo( C )
}
success
}
"correctly connect occurrences" in {
// end sequent of p: ¬D, A, B :- C, E
val p = NegLeftRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D :+ E ), D )
val o = p.getOccConnector
testChildren( o, "¬:l" )(
p.premise,
Seq( Ant( 1 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) ),
Seq( Ant( 0 ) ),
Seq( Suc( 1 ) )
)
testParents( o, "¬:l" )(
p.endSequent,
Seq( Suc( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) )
)
}
}
"NegRightRule" should {
"correctly create a proof" in {
NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Ant( 0 ) )
NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), A )
success
}
"refuse to create a proof" in {
NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Ant( 2 ) ) must throwAn[LKRuleCreationException]
NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), C ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), A )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( Neg( A ) )
}
"correctly return its aux formulas" in {
val p = NegRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D :+ E ), A )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 1 )
failure
for ( i <- p.auxIndices.head ) {
p.premise( i ) must beEqualTo( A )
}
success
}
"correctly connect occurrences" in {
// end sequent of p: A, C :- D, E, ¬B
val p = NegRightRule( TheoryAxiom( A +: B +: C +: Sequent() :+ D :+ E ), B )
val o = p.getOccConnector
testChildren( o, "¬:r" )(
p.premise,
Seq( Ant( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Ant( 1 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) )
)
testParents( o, "¬:r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) ),
Seq( Ant( 1 ) )
)
}
}
"AndLeftRule" should {
"correctly create a proof" in {
AndLeftRule( WeakeningLeftRule( LogicalAxiom( A ), B ), Ant( 0 ), Ant( 1 ) )
AndLeftRule( WeakeningLeftRule( LogicalAxiom( A ), B ), A, B )
AndLeftRule( WeakeningLeftRule( LogicalAxiom( A ), B ), And( A, B ) )
success
}
"refuse to construct a proof" in {
AndLeftRule( LogicalAxiom( A ), Ant( 0 ), Ant( 1 ) ) must throwAn[LKRuleCreationException]
AndLeftRule( LogicalAxiom( A ), Ant( 0 ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
AndLeftRule( LogicalAxiom( B ), A ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = AndLeftRule( WeakeningLeftRule( LogicalAxiom( A ), B ), A, B )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( And( A, B ) )
}
"correctly return its aux formulas" in {
val p = AndLeftRule( WeakeningLeftRule( LogicalAxiom( A ), B ), A, B )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
p.premise( p.auxIndices.head.head ) must beEqualTo( A )
p.premise( p.auxIndices.head.tail.head ) must beEqualTo( B )
success
}
"correctly connect occurrences" in {
// end sequent of p: A∧A, B, C :- A, B
val p = AndLeftRule( TheoryAxiom( B +: A +: C +: A +: Sequent() :+ A :+ B ), A, A )
val o = p.getOccConnector
testParents( o, "∧_l" )(
p.endSequent,
Seq( Ant( 1 ), Ant( 3 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) )
)
testChildren( o, "∧_l" )(
p.premise,
Seq( Ant( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) )
)
}
}
"AndRightRule" should {
"correctly construct a proof" in {
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) )
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), C, TheoryAxiom( B +: Sequent() :+ D ), D )
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), TheoryAxiom( B +: Sequent() :+ D ), And( C, D ) )
success
}
"refuse to construct a proof" in {
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 2 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 2 ) ) must throwAn[LKRuleCreationException]
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), B, TheoryAxiom( B +: Sequent() :+ D ), D ) must throwAn[LKRuleCreationException]
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), C, TheoryAxiom( B +: Sequent() :+ D ), C ) must throwAn[LKRuleCreationException]
AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), TheoryAxiom( B +: Sequent() :+ D ), Or( C, D ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) )
if ( p.mainIndices.length != 1 )
failure
p.endSequent( p.mainIndices.head ) must beEqualTo( And( C, D ) )
}
"correctly return its aux formulas" in {
val p = AndRightRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) )
if ( p.auxIndices.length != 2 )
failure
if ( p.auxIndices.head.length != 1 )
failure
if ( p.auxIndices.tail.head.length != 1 )
failure
p.leftPremise( p.auxIndices.head.head ) must beEqualTo( C )
p.rightPremise( p.auxIndices.tail.head.head ) must beEqualTo( D )
success
}
"correctly connect occurrences" in {
val ax1 = TheoryAxiom( A +: Sequent() :+ B :+ C :+ D )
val ax2 = TheoryAxiom( A +: Sequent() :+ B :+ E :+ F )
// end sequent of p: A, A :- B, D, B, F, C∧E
val p = AndRightRule( ax1, ax2, And( C, E ) )
val oL = p.getLeftOccConnector
val oR = p.getRightOccConnector
testChildren( oL, "∧:r" )(
p.leftPremise,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 4 ) ),
Seq( Suc( 1 ) )
)
testParents( oL, "∧:r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq(),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq(),
Seq(),
Seq( Suc( 1 ) )
)
testChildren( oR, "∧:r" )(
p.rightPremise,
Seq( Ant( 1 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 4 ) ),
Seq( Suc( 3 ) )
)
testParents( oR, "∧:r" )(
p.endSequent,
Seq(),
Seq( Ant( 0 ) ),
Seq(),
Seq(),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
}
}
"OrLeftRule" should {
"correctly construct a proof" in {
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) )
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), A, TheoryAxiom( B +: Sequent() :+ D ), B )
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), TheoryAxiom( B +: Sequent() :+ D ), Or( A, B ) )
success
}
"refuse to construct a proof" in {
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 2 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 2 ) ) must throwAn[LKRuleCreationException]
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), B, TheoryAxiom( B +: Sequent() :+ D ), B ) must throwAn[LKRuleCreationException]
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), A, TheoryAxiom( B +: Sequent() :+ D ), D ) must throwAn[LKRuleCreationException]
OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), TheoryAxiom( B +: Sequent() :+ D ), And( A, B ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) )
if ( p.mainIndices.length != 1 )
failure
p.endSequent( p.mainIndices.head ) must beEqualTo( Or( A, B ) )
}
"correctly return its aux formulas" in {
val p = OrLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) )
if ( p.auxIndices.length != 2 )
failure
if ( p.auxIndices.head.length != 1 )
failure
if ( p.auxIndices.tail.head.length != 1 )
failure
p.leftPremise( p.auxIndices.head.head ) must beEqualTo( A )
p.rightPremise( p.auxIndices.tail.head.head ) must beEqualTo( B )
success
}
"correctly connect occurrences" in {
val ax1 = TheoryAxiom( A +: B +: C +: Sequent() :+ D )
val ax2 = TheoryAxiom( A +: E +: F +: Sequent() :+ C )
// end sequent of p: B∨E, A, C, A, F :- D, C
val p = OrLeftRule( ax1, ax2, Or( B, E ) )
val oL = p.getLeftOccConnector
val oR = p.getRightOccConnector
testChildren( oL, "∨:l" )(
p.leftPremise,
Seq( Ant( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) )
)
testParents( oL, "∨:l" )(
p.endSequent,
Seq( Ant( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq(),
Seq(),
Seq( Suc( 0 ) ),
Seq()
)
testChildren( oR, "∨:l" )(
p.rightPremise,
Seq( Ant( 3 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 4 ) ),
Seq( Suc( 1 ) )
)
testParents( oR, "∨:l" )(
p.endSequent,
Seq( Ant( 1 ) ),
Seq(),
Seq(),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq(),
Seq( Suc( 0 ) )
)
}
}
"OrRightRule" should {
"correctly create a proof" in {
OrRightRule( WeakeningRightRule( LogicalAxiom( A ), B ), Suc( 0 ), Suc( 1 ) )
OrRightRule( WeakeningRightRule( LogicalAxiom( A ), B ), A, B )
OrRightRule( WeakeningRightRule( LogicalAxiom( A ), B ), Or( A, B ) )
success
}
"refuse to construct a proof" in {
OrRightRule( LogicalAxiom( A ), Suc( 0 ), Suc( 1 ) ) must throwAn[LKRuleCreationException]
OrRightRule( LogicalAxiom( A ), Suc( 0 ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
OrRightRule( LogicalAxiom( B ), A ) must throwAn[LKRuleCreationException]
OrRightRule( LogicalAxiom( A ), Or( A, B ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = OrRightRule( WeakeningRightRule( LogicalAxiom( A ), B ), A, B )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( Or( A, B ) )
}
"correctly return its aux formulas" in {
val p = OrRightRule( WeakeningRightRule( LogicalAxiom( A ), B ), A, B )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
p.premise( p.auxIndices.head.head ) must beEqualTo( A )
p.premise( p.auxIndices.head.tail.head ) must beEqualTo( B )
success
}
"correctly connect occurrences" in {
// end sequent of p: A :- B, D, B, C∨E
val p = OrRightRule( TheoryAxiom( A +: Sequent() :+ B :+ C :+ D :+ E :+ B ), Or( C, E ) )
val o = p.getOccConnector
testParents( o, "∨:r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 4 ) ),
Seq( Suc( 1 ), Suc( 3 ) )
)
testChildren( o, "∨:r" )(
p.premise,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 3 ) ),
Seq( Suc( 1 ) ),
Seq( Suc( 3 ) ),
Seq( Suc( 2 ) )
)
}
}
"ImpLeftRule" should {
"correctly construct a proof" in {
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) )
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), C, TheoryAxiom( B +: Sequent() :+ D ), B )
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), TheoryAxiom( B +: Sequent() :+ D ), Imp( C, B ) )
success
}
"refuse to construct a proof" in {
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Ant( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Suc( 0 ) ) must throwAn[LKRuleCreationException]
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 2 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 2 ) ) must throwAn[LKRuleCreationException]
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), B, TheoryAxiom( B +: Sequent() :+ D ), B ) must throwAn[LKRuleCreationException]
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), C, TheoryAxiom( B +: Sequent() :+ D ), D ) must throwAn[LKRuleCreationException]
ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), TheoryAxiom( B +: Sequent() :+ D ), And( A, B ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) )
if ( p.mainIndices.length != 1 )
failure
p.endSequent( p.mainIndices.head ) must beEqualTo( Imp( C, B ) )
}
"correctly return its aux formulas" in {
val p = ImpLeftRule( TheoryAxiom( A +: Sequent() :+ C ), Suc( 0 ), TheoryAxiom( B +: Sequent() :+ D ), Ant( 0 ) )
if ( p.auxIndices.length != 2 )
failure
if ( p.auxIndices.head.length != 1 )
failure
if ( p.auxIndices.tail.head.length != 1 )
failure
p.leftPremise( p.auxIndices.head.head ) must beEqualTo( C )
p.rightPremise( p.auxIndices.tail.head.head ) must beEqualTo( B )
success
}
"correctly connect occurrences" in {
val ax1 = TheoryAxiom( A +: Sequent() :+ B :+ C :+ D )
val ax2 = TheoryAxiom( A +: E +: F +: Sequent() :+ C )
// end sequent of p: C -> E, A, A, F :- B, D, C
val p = ImpLeftRule( ax1, ax2, Imp( C, E ) )
val oL = p.getLeftOccConnector
val oR = p.getRightOccConnector
testChildren( oL, "→:l" )(
p.leftPremise,
Seq( Ant( 1 ) ),
Seq( Suc( 0 ) ),
Seq( Ant( 0 ) ),
Seq( Suc( 1 ) )
)
testParents( oL, "→:l" )(
p.endSequent,
Seq( Suc( 1 ) ),
Seq( Ant( 0 ) ),
Seq(),
Seq(),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq()
)
testChildren( oR, "→:l" )(
p.rightPremise,
Seq( Ant( 2 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 3 ) ),
Seq( Suc( 2 ) )
)
testParents( oR, "→:l" )(
p.endSequent,
Seq( Ant( 1 ) ),
Seq(),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq(),
Seq(),
Seq( Suc( 0 ) )
)
}
}
"ImpRightRule" should {
"correctly create a proof" in {
ImpRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Ant( 0 ), Suc( 1 ) )
ImpRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), B, D )
ImpRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), Imp( A, C ) )
success
}
"refuse to construct a proof" in {
ImpRightRule( LogicalAxiom( A ), Suc( 0 ), Suc( 1 ) ) must throwAn[LKRuleCreationException]
ImpRightRule( LogicalAxiom( A ), Ant( 0 ), Ant( 0 ) ) must throwAn[LKRuleCreationException]
ImpRightRule( LogicalAxiom( B ), A, B ) must throwAn[LKRuleCreationException]
ImpRightRule( LogicalAxiom( A ), Imp( A, B ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val p = ImpRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), A, D )
if ( p.mainIndices.length != 1 )
failure
val i = p.mainIndices.head
p.endSequent( i ) must beEqualTo( Imp( A, D ) )
}
"correctly return its aux formulas" in {
val p = ImpRightRule( TheoryAxiom( A +: B +: Sequent() :+ C :+ D ), A, D )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
p.premise( p.auxIndices.head.head ) must beEqualTo( A )
p.premise( p.auxIndices.head.tail.head ) must beEqualTo( D )
success
}
"correctly connect occurrences" in {
// end sequent of p: A, C :- D, F, B→E
val p = ImpRightRule( TheoryAxiom( A +: B +: C +: Sequent() :+ D :+ E :+ F ), Imp( B, E ) )
val o = p.getOccConnector
testParents( o, "→:r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Ant( 1 ), Suc( 1 ) )
)
testChildren( o, "→:r" )(
p.premise,
Seq( Ant( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Ant( 1 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
}
}
"ForallRightRule" should {
"correctly construct a proof" in {
val ax = TheoryAxiom( Sequent() :+ P( alpha ) :+ P( x ) )
ForallRightRule( ax, Suc( 0 ), alpha, x )
ForallRightRule( ax, All( x, P( x ) ), alpha )
ForallRightRule( ax, All( x, P( x ) ) )
success
}
"refuse to construct a proof" in {
val ax = TheoryAxiom( P( alpha ) +: Sequent() :+ P( alpha ) :+ P( x ) )
ForallRightRule( ax, Ant( 0 ), alpha, x ) must throwAn[LKRuleCreationException]
ForallRightRule( ax, Suc( 2 ), alpha, x ) must throwAn[LKRuleCreationException]
ForallRightRule( ax, Suc( 0 ), alpha, x ) must throwAn[LKRuleCreationException]
ForallRightRule( ax, P( x ), alpha ) must throwAn[LKRuleCreationException]
ForallRightRule( ax, All( x, P( x ) ), y ) must throwAn[LKRuleCreationException]
ForallRightRule( ax, All( y, P( y ) ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val ax = TheoryAxiom( Sequent() :+ P( alpha ) :+ P( x ) )
val p = ForallRightRule( ax, Suc( 0 ), alpha, x )
if ( p.mainIndices.length != 1 )
failure
p.mainFormulas.head must beEqualTo( All( x, P( x ) ) )
}
"correctly return its aux formula" in {
val ax = TheoryAxiom( Sequent() :+ P( alpha ) :+ P( x ) )
val p = ForallRightRule( ax, Suc( 0 ), alpha, x )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 1 )
failure
p.auxFormulas.head.head must beEqualTo( P( alpha ) )
}
"correctly connect occurrences" in {
val ax = TheoryAxiom( A +: Sequent() :+ B :+ P( alpha ) :+ C )
// end sequent of p: A :- B, C, ∀x.P
val p = ForallRightRule( ax, All( x, P( x ) ), alpha )
val o = p.getOccConnector
testChildren( o, "∀:r" )(
p.premise,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
testParents( o, "∀:r" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
}
}
"ExistsLeftRule" should {
"correctly construct a proof" in {
val ax = TheoryAxiom( P( alpha ) +: P( x ) +: Sequent() )
ExistsLeftRule( ax, Ant( 0 ), alpha, x )
ExistsLeftRule( ax, Ex( x, P( x ) ), alpha )
ExistsLeftRule( ax, Ex( x, P( x ) ) )
success
}
"refuse to construct a proof" in {
val ax = TheoryAxiom( P( alpha ) +: P( x ) +: Sequent() :+ P( alpha ) )
ExistsLeftRule( ax, Suc( 0 ), alpha, x ) must throwAn[LKRuleCreationException]
ExistsLeftRule( ax, Ant( 2 ), alpha, x ) must throwAn[LKRuleCreationException]
ExistsLeftRule( ax, Suc( 0 ), alpha, x ) must throwAn[LKRuleCreationException]
ExistsLeftRule( ax, P( x ), alpha ) must throwAn[LKRuleCreationException]
ExistsLeftRule( ax, Ex( x, P( x ) ), y ) must throwAn[LKRuleCreationException]
ExistsLeftRule( ax, Ex( y, P( y ) ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val ax = TheoryAxiom( P( alpha ) +: P( x ) +: Sequent() )
val p = ExistsLeftRule( ax, Ant( 0 ), alpha, x )
if ( p.mainIndices.length != 1 )
failure
p.mainFormulas.head must beEqualTo( Ex( x, P( x ) ) )
}
"correctly return its aux formula" in {
val ax = TheoryAxiom( P( alpha ) +: P( x ) +: Sequent() )
val p = ExistsLeftRule( ax, Ant( 0 ), alpha, x )
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 1 )
failure
p.auxFormulas.head.head must beEqualTo( P( alpha ) )
}
"correctly connect occurrences" in {
val ax = TheoryAxiom( A +: P( alpha ) +: B +: Sequent() :+ C )
// end sequent of p: ∀x.P, A, B :- C
val p = ExistsLeftRule( ax, Ex( x, P( x ) ), alpha )
val o = p.getOccConnector
testChildren( o, "∃:l" )(
p.premise,
Seq( Ant( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) )
)
testParents( o, "∃:l" )(
p.endSequent,
Seq( Ant( 1 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 2 ) ),
Seq( Suc( 0 ) )
)
}
}
"EqualityLeftRule" should {
"correctly construct a proof" in {
val ax = Axiom( Eq( c, d ) +: Pc +: Pd +: Sequent() :+ Pc :+ Pd )
EqualityLeftRule( ax, Ant( 0 ), Ant( 1 ), HOLPosition( 2 ) )
EqualityLeftRule( ax, Ant( 0 ), Ant( 2 ), HOLPosition( 2 ) )
EqualityLeftRule( ax, Eq( c, d ), Pc, Pd )
EqualityLeftRule( ax, Eq( c, d ), Pd, Pc )
success
}
"refuse to construct a proof" in {
val ax = Axiom( Eq( c, d ) +: P( x ) +: A +: Sequent() :+ B :+ P( y ) )
EqualityLeftRule( ax, Ant( 0 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityLeftRule( ax, Suc( 0 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityLeftRule( ax, Ant( 0 ), Suc( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityLeftRule( ax, Ant( 3 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityLeftRule( ax, Ant( 0 ), Ant( 3 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityLeftRule( ax, Ant( 2 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityLeftRule( ax, Suc( 0 ), Ant( 1 ), HOLPosition( 1 ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val ax = Axiom( Eq( c, d ) +: Pc +: Pd +: Sequent() :+ Pc :+ Pd )
val proofs = for ( ( i, f ) <- List( Ant( 1 ) -> Pd, Ant( 2 ) -> Pc ) ) yield ( EqualityLeftRule( ax, Ant( 0 ), i, HOLPosition( 2 ) ), f )
for ( ( p, f ) <- proofs ) {
if ( p.mainIndices.length != 1 )
failure
p.mainFormulas.head must beEqualTo( f )
}
success
}
"correctly return its aux formulas" in {
val ax = Axiom( Eq( c, d ) +: Pc +: Pd +: Sequent() :+ Pc :+ Pd )
val proofs = for ( ( i, f ) <- List( Ant( 1 ) -> Pc, Ant( 2 ) -> Pd ) ) yield ( EqualityLeftRule( ax, Ant( 0 ), i, HOLPosition( 2 ) ), f )
for ( ( p, f ) <- proofs ) {
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
p.auxFormulas.head.head must beEqualTo( Eq( c, d ) )
p.auxFormulas.head.tail.head must beEqualTo( f )
}
success
}
"correctly connect occurrences" in {
val ax = Axiom( A +: Eq( c, d ) +: B +: Pc +: C +: Sequent() :+ D :+ Pd :+ E )
// end sequent of p1: P(d), A, c = d, B, C :- D, P(d), E
val p = EqualityLeftRule( ax, Ant( 1 ), Ant( 3 ), HOLPosition( 2 ) )
val o = p.getOccConnector
testChildren( o, "eq" )(
p.premise,
Seq( Ant( 1 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 3 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 4 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) ),
Seq( Suc( 2 ) )
)
testParents( o, "eq" )(
p.endSequent,
Seq( Ant( 3 ) ),
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 4 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 1 ) ),
Seq( Suc( 2 ) )
)
}
}
"EqualityRightRule" should {
"correctly construct a proof" in {
val ax = Axiom( Eq( c, d ) +: Pc +: Pd +: Sequent() :+ Pc :+ Pd )
EqualityRightRule( ax, Ant( 0 ), Suc( 0 ), HOLPosition( 2 ) )
EqualityRightRule( ax, Ant( 0 ), Suc( 1 ), HOLPosition( 2 ) )
EqualityRightRule( ax, Eq( c, d ), Pc, Pd )
EqualityRightRule( ax, Eq( c, d ), Pd, Pc )
success
}
"refuse to construct a proof" in {
val ax = Axiom( Eq( c, d ) +: P( x ) +: A +: Sequent() :+ B :+ P( y ) )
EqualityRightRule( ax, Ant( 0 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityRightRule( ax, Suc( 0 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityRightRule( ax, Ant( 0 ), Suc( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityRightRule( ax, Ant( 3 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityRightRule( ax, Ant( 0 ), Ant( 3 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityRightRule( ax, Ant( 2 ), Ant( 1 ), HOLPosition( 2 ) ) must throwAn[LKRuleCreationException]
EqualityRightRule( ax, Suc( 0 ), Ant( 1 ), HOLPosition( 1 ) ) must throwAn[LKRuleCreationException]
}
"correctly return its main formula" in {
val ax = Axiom( Eq( c, d ) +: Pc +: Pd +: Sequent() :+ Pc :+ Pd )
val proofs = for ( ( i, f ) <- List( Suc( 0 ) -> Pd, Suc( 1 ) -> Pc ) ) yield ( EqualityRightRule( ax, Ant( 0 ), i, HOLPosition( 2 ) ), f )
for ( ( p, f ) <- proofs ) {
if ( p.mainIndices.length != 1 )
failure
p.mainFormulas.head must beEqualTo( f )
}
success
}
"correctly return its aux formulas" in {
val ax = Axiom( Eq( c, d ) +: Pc +: Pd +: Sequent() :+ Pc :+ Pd )
val proofs = for ( ( i, f ) <- List( Suc( 0 ) -> Pc, Suc( 1 ) -> Pd ) ) yield ( EqualityRightRule( ax, Ant( 0 ), i, HOLPosition( 2 ) ), f )
for ( ( p, f ) <- proofs ) {
if ( p.auxIndices.length != 1 )
failure
if ( p.auxIndices.head.length != 2 )
failure
p.auxFormulas.head.head must beEqualTo( Eq( c, d ) )
p.auxFormulas.head.tail.head must beEqualTo( f )
}
success
}
"correctly connect occurrences" in {
val ax = Axiom( A +: Eq( c, d ) +: B +: Pc +: C +: Sequent() :+ D :+ Pd :+ E )
// end sequent of p2: A, c = d, B, C :- D, E, P(c)
val p = EqualityRightRule( ax, Ant( 1 ), Suc( 1 ), HOLPosition( 2 ) )
val o = p.getOccConnector
testChildren( o, "eq" )(
p.premise,
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 3 ) ),
Seq( Ant( 4 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
testParents( o, "eq" )(
p.endSequent,
Seq( Ant( 0 ) ),
Seq( Ant( 1 ) ),
Seq( Ant( 2 ) ),
Seq( Ant( 3 ) ),
Seq( Ant( 4 ) ),
Seq( Suc( 0 ) ),
Seq( Suc( 2 ) ),
Seq( Suc( 1 ) )
)
}
}
"The induction rule" should {
val zero = FOLConst( "0" )
val Sx = FOLFunction( "s", List( x ) )
val P0y = FOLAtom( "P", List( zero, y ) )
val Pxy = FOLAtom( "P", List( x, y ) )
val PSxy = FOLAtom( "P", List( Sx, y ) )
"correctly construct a small induction proof" in {
val ax1 = LogicalAxiom( P0y )
val ax2 = TheoryAxiom( Pxy +: Sequent() :+ PSxy )
println( InductionRule(
Seq(
InductionCase( ax1, FOLConst( "0" ), Seq(), Seq(), Suc( 0 ) ),
InductionCase( ax2, FOLFunctionConst( "s", 1 ), Seq( Ant( 0 ) ), Seq( x ), Suc( 0 ) )
),
All( x, Pxy )
) )
success
}
}
"exchange rules" should {
val Seq( a, b ) = Seq( "a", "b" ) map { FOLAtom( _ ) }
"ExchangeLeftMacroRule" in {
val p1 = LogicalAxiom( a )
val p2 = WeakeningLeftRule( p1, b )
val p3 = ExchangeLeftMacroRule( p2, Ant( 1 ) )
p3.endSequent must_== ( a +: b +: Sequent() :+ a )
}
"ExchangeRightMacroRule" in {
val p1 = LogicalAxiom( a )
val p2 = WeakeningRightRule( p1, b )
val p3 = ExchangeRightMacroRule( p2, Suc( 0 ) )
p3.endSequent must_== ( a +: Sequent() :+ b :+ a )
}
}
"weakening and contraction macro rules" should {
"reach a sequent" in {
val a = FOLAtom( "a" )
val desiredES = a +: a +: Sequent() :+ a :+ a
WeakeningContractionMacroRule( LogicalAxiom( a ), desiredES, strict = true ).endSequent must_== desiredES
}
}
}
|
loewenheim/gapt
|
src/test/scala/at/logic/gapt/proofs/lkNew/LKNewTest.scala
|
Scala
|
gpl-3.0
| 42,744 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.deploy
import java.io.File
import java.util.Date
import com.fasterxml.jackson.core.JsonParseException
import org.json4s._
import org.json4s.jackson.JsonMethods
import org.apache.spark.deploy.DeployMessages.{MasterStateResponse, WorkerStateResponse}
import org.apache.spark.deploy.master.{ApplicationInfo, DriverInfo, RecoveryState, WorkerInfo}
import org.apache.spark.deploy.worker.{DriverRunner, ExecutorRunner}
import org.apache.spark.{JsonTestUtils, SecurityManager, SparkConf, SparkFunSuite}
class JsonProtocolSuite extends SparkFunSuite with JsonTestUtils {
test("writeApplicationInfo") {
val output = JsonProtocol.writeApplicationInfo(createAppInfo())
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.appInfoJsonStr))
}
test("writeWorkerInfo") {
val output = JsonProtocol.writeWorkerInfo(createWorkerInfo())
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.workerInfoJsonStr))
}
test("writeApplicationDescription") {
val output = JsonProtocol.writeApplicationDescription(createAppDesc())
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.appDescJsonStr))
}
test("writeExecutorRunner") {
val output = JsonProtocol.writeExecutorRunner(createExecutorRunner())
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.executorRunnerJsonStr))
}
test("writeDriverInfo") {
val output = JsonProtocol.writeDriverInfo(createDriverInfo())
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.driverInfoJsonStr))
}
test("writeMasterState") {
val workers = Array(createWorkerInfo(), createWorkerInfo())
val activeApps = Array(createAppInfo())
val completedApps = Array[ApplicationInfo]()
val activeDrivers = Array(createDriverInfo())
val completedDrivers = Array(createDriverInfo())
val stateResponse = new MasterStateResponse(
"host", 8080, None, workers, activeApps, completedApps,
activeDrivers, completedDrivers, RecoveryState.ALIVE)
val output = JsonProtocol.writeMasterState(stateResponse)
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.masterStateJsonStr))
}
test("writeWorkerState") {
val executors = List[ExecutorRunner]()
val finishedExecutors = List[ExecutorRunner](createExecutorRunner(), createExecutorRunner())
val drivers = List(createDriverRunner())
val finishedDrivers = List(createDriverRunner(), createDriverRunner())
val stateResponse = new WorkerStateResponse("host", 8080, "workerId", executors,
finishedExecutors, drivers, finishedDrivers, "masterUrl", 4, 1234, 4, 1234, "masterWebUiUrl")
val output = JsonProtocol.writeWorkerState(stateResponse)
assertValidJson(output)
assertValidDataInJson(output, JsonMethods.parse(JsonConstants.workerStateJsonStr))
}
def createAppDesc(): ApplicationDescription = {
val cmd = new Command("mainClass", List("arg1", "arg2"), Map(), Seq(), Seq(), Seq())
new ApplicationDescription("name", Some(4), 1234, cmd, "appUiUrl")
}
def createAppInfo() : ApplicationInfo = {
val appInfo = new ApplicationInfo(JsonConstants.appInfoStartTime,
"id", createAppDesc(), JsonConstants.submitDate, null, Int.MaxValue)
appInfo.endTime = JsonConstants.currTimeInMillis
appInfo
}
def createDriverCommand(): Command = new Command(
"org.apache.spark.FakeClass", Seq("some arg --and-some options -g foo"),
Map(("K1", "V1"), ("K2", "V2")), Seq("cp1", "cp2"), Seq("lp1", "lp2"), Seq("-Dfoo")
)
def createDriverDesc(): DriverDescription =
new DriverDescription("hdfs://some-dir/some.jar", 100, 3, false, createDriverCommand())
def createDriverInfo(): DriverInfo = new DriverInfo(3, "driver-3",
createDriverDesc(), new Date())
def createWorkerInfo(): WorkerInfo = {
val workerInfo = new WorkerInfo("id", "host", 8080, 4, 1234, null, 80, "publicAddress")
workerInfo.lastHeartbeat = JsonConstants.currTimeInMillis
workerInfo
}
def createExecutorRunner(): ExecutorRunner = {
new ExecutorRunner("appId", 123, createAppDesc(), 4, 1234, null, "workerId", "host", 123,
"publicAddress", new File("sparkHome"), new File("workDir"), "akka://worker",
new SparkConf, Seq("localDir"), ExecutorState.RUNNING)
}
def createDriverRunner(): DriverRunner = {
val conf = new SparkConf()
new DriverRunner(conf, "driverId", new File("workDir"), new File("sparkHome"),
createDriverDesc(), null, "akka://worker", new SecurityManager(conf))
}
def assertValidJson(json: JValue) {
try {
JsonMethods.parse(JsonMethods.compact(json))
} catch {
case e: JsonParseException => fail("Invalid Json detected", e)
}
}
}
object JsonConstants {
val currTimeInMillis = System.currentTimeMillis()
val appInfoStartTime = 3
val submitDate = new Date(123456789)
val appInfoJsonStr =
"""
|{"starttime":3,"id":"id","name":"name",
|"cores":4,"user":"%s",
|"memoryperslave":1234,"submitdate":"%s",
|"state":"WAITING","duration":%d}
""".format(System.getProperty("user.name", "<unknown>"),
submitDate.toString, currTimeInMillis - appInfoStartTime).stripMargin
val workerInfoJsonStr =
"""
|{"id":"id","host":"host","port":8080,
|"webuiaddress":"http://publicAddress:80",
|"cores":4,"coresused":0,"coresfree":4,
|"memory":1234,"memoryused":0,"memoryfree":1234,
|"state":"ALIVE","lastheartbeat":%d}
""".format(currTimeInMillis).stripMargin
val appDescJsonStr =
"""
|{"name":"name","cores":4,"memoryperslave":1234,
|"user":"%s","command":"Command(mainClass,List(arg1, arg2),Map(),List(),List(),List())"}
""".format(System.getProperty("user.name", "<unknown>")).stripMargin
val executorRunnerJsonStr =
"""
|{"id":123,"memory":1234,"appid":"appId",
|"appdesc":%s}
""".format(appDescJsonStr).stripMargin
val driverInfoJsonStr =
"""
|{"id":"driver-3","starttime":"3","state":"SUBMITTED","cores":3,"memory":100}
""".stripMargin
val masterStateJsonStr =
"""
|{"url":"spark://host:8080",
|"workers":[%s,%s],
|"cores":8,"coresused":0,"memory":2468,"memoryused":0,
|"activeapps":[%s],"completedapps":[],
|"activedrivers":[%s],
|"status":"ALIVE"}
""".format(workerInfoJsonStr, workerInfoJsonStr,
appInfoJsonStr, driverInfoJsonStr).stripMargin
val workerStateJsonStr =
"""
|{"id":"workerId","masterurl":"masterUrl",
|"masterwebuiurl":"masterWebUiUrl",
|"cores":4,"coresused":4,"memory":1234,"memoryused":1234,
|"executors":[],
|"finishedexecutors":[%s,%s]}
""".format(executorRunnerJsonStr, executorRunnerJsonStr).stripMargin
}
|
andrewor14/iolap
|
core/src/test/scala/org/apache/spark/deploy/JsonProtocolSuite.scala
|
Scala
|
apache-2.0
| 7,709 |
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.ct.ct600e.v3.calculations
import uk.gov.hmrc.ct.box.retriever.BoxRetriever._
import uk.gov.hmrc.ct.ct600e.v3._
trait IncomeCalculator {
def calculateTotalIncome(e50: E50, e55: E55, e60: E60, e65: E65, e70: E70, e75: E75, e80: E80, e85: E85): E90 = {
val incomeFields = Seq(e50, e55, e60, e65, e70, e75, e80, e85)
if (anyHaveValue(incomeFields:_ *))
E90(Some(incomeFields.map(_.orZero).sum))
else E90(None)
}
}
|
hmrc/ct-calculations
|
src/main/scala/uk/gov/hmrc/ct/ct600e/v3/calculations/IncomeCalculator.scala
|
Scala
|
apache-2.0
| 1,061 |
/*
* Copyright 2016 rdbc contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rdbc.pgsql.core.internal.typecodec.sco
import io.rdbc.pgsql.core.types.{PgInt2, PgInt2Type}
import scodec.codecs._
private[typecodec] object ScodecPgInt2Codec
extends ScodecPgValCodec[PgInt2]
with IgnoreSessionParams[PgInt2] {
val typ = PgInt2Type
val codec = short16.as[PgInt2]
}
|
rdbc-io/rdbc-pgsql
|
rdbc-pgsql-core/src/main/scala/io/rdbc/pgsql/core/internal/typecodec/sco/ScodecPgInt2Codec.scala
|
Scala
|
apache-2.0
| 907 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.