repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ccellado/ergo
src/test/scala/org/ergoplatform/utils/ErgoTestConstants.scala
package org.ergoplatform.utils import akka.util.Timeout import org.ergoplatform.mining.difficulty.LinearDifficultyControl import org.ergoplatform.mining.emission.EmissionRules import org.ergoplatform.mining.{AutolykosPowScheme, DefaultFakePowScheme} import org.ergoplatform.modifiers.history.extension.ExtensionCandidate import org.ergoplatform.modifiers.history.popow.NipopowAlgos import org.ergoplatform.nodeView.state.{ErgoState, ErgoStateContext, StateConstants, StateType, UpcomingStateContext} import org.ergoplatform.settings.Constants.HashLength import org.ergoplatform.settings.Parameters.{MaxBlockCostIncrease, MinValuePerByteIncrease} import org.ergoplatform.settings.ValidationRules._ import org.ergoplatform.settings._ import org.ergoplatform.wallet.interface4j.SecretString import org.ergoplatform.wallet.interpreter.{ErgoInterpreter, ErgoProvingInterpreter} import org.ergoplatform.wallet.mnemonic.Mnemonic import org.ergoplatform.wallet.secrets.ExtendedSecretKey import org.ergoplatform.{DataInput, ErgoBox, ErgoScriptPredef} import scorex.core.app.Version import scorex.core.network.PeerSpec import scorex.core.utils.NetworkTimeProvider import scorex.crypto.authds.ADDigest import scorex.crypto.hash.Digest32 import scorex.util.ScorexLogging import sigmastate.Values.ErgoTree import sigmastate.basics.DLogProtocol.{DLogProverInput, ProveDlog} import sigmastate.interpreter.CryptoConstants.EcPointType import sigmastate.interpreter.{ContextExtension, ProverResult} import scala.concurrent.duration._ trait ErgoTestConstants extends ScorexLogging { implicit val votingSettings: VotingSettings = VotingSettings(1024, 32, 128, 32 * 1024, "01") val validationSettings: ErgoValidationSettings = ErgoValidationSettings.initial implicit val validationSettingsNoIl: ErgoValidationSettings = validationSettings .updated(ErgoValidationSettingsUpdate(Seq(exIlUnableToValidate, exIlEncoding, exIlStructure, exEmpty), Seq())) val parameters: Parameters = LaunchParameters val extendedParameters: Parameters = { // Randomness in tests is causing occasional cost overflow in the state context and insufficient box value val extension = Map( MaxBlockCostIncrease -> Math.ceil(parameters.parametersTable(MaxBlockCostIncrease) * 1.3).toInt, MinValuePerByteIncrease -> (parameters.parametersTable(MinValuePerByteIncrease) - 30) ) Parameters(0, Parameters.DefaultParameters ++ extension, ErgoValidationSettingsUpdate.empty) } val timeProvider: NetworkTimeProvider = ErgoTestHelpers.defaultTimeProvider val initSettings: ErgoSettings = ErgoSettings.read(Args(Some("src/test/resources/application.conf"), None)) implicit val settings: ErgoSettings = initSettings val nipopowAlgos = new NipopowAlgos(powScheme) val lightModeSettings: ErgoSettings = initSettings.copy( nodeSettings = initSettings.nodeSettings.copy(stateType = StateType.Digest) ) val emission: EmissionRules = settings.chainSettings.emissionRules val coinsTotal: Long = emission.coinsTotal val stateConstants: StateConstants = StateConstants(settings) val genesisStateDigest: ADDigest = settings.chainSettings.genesisStateDigest val feeProp: ErgoTree = ErgoScriptPredef.feeProposition(emission.settings.minerRewardDelay) val emptyProverResult: ProverResult = ProverResult(Array.emptyByteArray, ContextExtension.empty) lazy val defaultSeed: Array[Byte] = Mnemonic.toSeed(settings.walletSettings.testMnemonic.fold[SecretString](SecretString.empty())(SecretString.create(_))) val defaultRootSecret: ExtendedSecretKey = ExtendedSecretKey.deriveMasterKey(defaultSeed) val defaultChildSecrets: IndexedSeq[ExtendedSecretKey] = settings.walletSettings.testKeysQty .toIndexedSeq .flatMap(x => (0 until x).map(defaultRootSecret.child)) val genesisBoxes: Seq[ErgoBox] = ErgoState.genesisBoxes(settings.chainSettings) val genesisEmissionBox: ErgoBox = ErgoState.genesisBoxes(settings.chainSettings).head val defaultProver: ErgoProvingInterpreter = ErgoProvingInterpreter( defaultRootSecret +: defaultChildSecrets, parameters) val defaultMinerSecret: DLogProverInput = defaultProver.hdKeys.head.privateInput val defaultMinerSecretNumber: BigInt = defaultProver.hdKeys.head.privateInput.w val defaultMinerPk: ProveDlog = defaultMinerSecret.publicImage val defaultMinerPkPoint: EcPointType = defaultMinerPk.h val defaultTimestamp: Long = 1552217190000L val defaultNBits: Long = settings.chainSettings.initialNBits val defaultVotes: Array[Byte] = Array.fill(3)(0.toByte) val defaultVersion: Byte = 0 lazy val powScheme: AutolykosPowScheme = settings.chainSettings.powScheme.ensuring(_.isInstanceOf[DefaultFakePowScheme]) val emptyVSUpdate = ErgoValidationSettingsUpdate.empty val emptyStateContext: UpcomingStateContext = ErgoStateContext.empty(genesisStateDigest, settings, parameters) .upcoming(defaultMinerPkPoint, defaultTimestamp, defaultNBits, defaultVotes, emptyVSUpdate, defaultVersion) def stateContextWith(parameters: Parameters): UpcomingStateContext = ErgoStateContext.empty(genesisStateDigest, settings, parameters) .upcoming(defaultMinerPkPoint, defaultTimestamp, defaultNBits, defaultVotes, emptyVSUpdate, defaultVersion) val startHeight: Int = emptyStateContext.currentHeight val startDigest: ADDigest = emptyStateContext.genesisStateDigest val EmptyStateRoot: ADDigest = ADDigest @@ Array.fill(HashLength + 1)(0.toByte) val EmptyDigest32: Digest32 = Digest32 @@ Array.fill(HashLength)(0.toByte) val defaultDifficultyControl = new LinearDifficultyControl(settings.chainSettings) val defaultExtension: ExtensionCandidate = ExtensionCandidate(Seq(Array(0: Byte, 8: Byte) -> EmptyDigest32)) val emptyExtension: ExtensionCandidate = ExtensionCandidate(Seq()) val emptyDataInputs: IndexedSeq[DataInput] = IndexedSeq() val emptyDataBoxes: IndexedSeq[ErgoBox] = IndexedSeq() def emptyVerifier: ErgoInterpreter = ErgoInterpreter(emptyStateContext.currentParameters) val defaultTimeout: Timeout = Timeout(14.seconds) val defaultAwaitDuration: FiniteDuration = defaultTimeout.duration + 1.second val defaultPeerSpec = PeerSpec( settings.scorexSettings.network.agentName, Version(settings.scorexSettings.network.appVersion), settings.scorexSettings.network.nodeName, None, Seq.empty ) }
ccellado/ergo
src/main/scala/org/ergoplatform/settings/Parameters.scala
package org.ergoplatform.settings import com.google.common.primitives.Ints import io.circe.Encoder import io.circe.syntax._ import org.ergoplatform.nodeView.history.ErgoHistory.Height import scorex.core.serialization.ScorexSerializer import scorex.util.serialization.{Reader, Writer} import scorex.util.Extensions._ import scala.util.Try import org.ergoplatform.http.api.ApiCodecs import org.ergoplatform.modifiers.history.extension.{Extension, ExtensionCandidate} import org.ergoplatform.wallet.protocol.context.ErgoLikeParameters import Extension.SystemParametersPrefix /** * System parameters which could be readjusted via collective miners decision. */ class Parameters(val height: Height, val parametersTable: Map[Byte, Int], val proposedUpdate: ErgoValidationSettingsUpdate) extends ErgoLikeParameters { import Parameters._ /** * Cost of storing 1 byte per Constants.StoragePeriod blocks, in nanoErgs. */ lazy val storageFeeFactor: Int = parametersTable(StorageFeeFactorIncrease) /** To prevent creation of dust which is not profitable to charge storage fee from, we have this min-value per-byte * parameter. */ lazy val minValuePerByte: Int = parametersTable(MinValuePerByteIncrease) /** * Max size of transactions section of a block. */ lazy val maxBlockSize: Int = parametersTable(MaxBlockSizeIncrease) /** * Validation cost of accessing a single token. */ lazy val tokenAccessCost: Int = parametersTable(TokenAccessCostIncrease) /** * Validation cost per one transaction input. */ lazy val inputCost: Int = parametersTable(InputCostIncrease) /** * Validation cost per one data input. */ lazy val dataInputCost: Int = parametersTable(DataInputCostIncrease) /** * Validation cost per one transaction output. */ lazy val outputCost: Int = parametersTable(OutputCostIncrease) /** * Max total computation cost of a block. */ lazy val maxBlockCost: Int = parametersTable(MaxBlockCostIncrease) lazy val softForkStartingHeight: Option[Height] = parametersTable.get(SoftForkStartingHeight) lazy val softForkVotesCollected: Option[Int] = parametersTable.get(SoftForkVotesCollected) lazy val blockVersion: Byte = parametersTable(BlockVersion).toByte def update(height: Height, forkVote: Boolean, epochVotes: Seq[(Byte, Int)], proposedUpdate: ErgoValidationSettingsUpdate, votingSettings: VotingSettings): (Parameters, ErgoValidationSettingsUpdate) = { val (table1, activatedUpdate) = updateFork(height, parametersTable, forkVote, epochVotes, proposedUpdate, votingSettings) val table2 = updateParams(table1, epochVotes, votingSettings) (Parameters(height, table2, proposedUpdate), activatedUpdate) } def updateFork(height: Height, parametersTable: Map[Byte, Int], forkVote: Boolean, epochVotes: Seq[(Byte, Int)], proposedUpdate: ErgoValidationSettingsUpdate, votingSettings: VotingSettings): (Map[Byte, Int], ErgoValidationSettingsUpdate) = { import votingSettings.{activationEpochs, softForkApproved, softForkEpochs => votingEpochs, votingLength => votingEpochLength} lazy val votesInPrevEpoch = epochVotes.find(_._1 == SoftFork).map(_._2).getOrElse(0) lazy val votes = votesInPrevEpoch + parametersTable(SoftForkVotesCollected) var table = parametersTable var activatedUpdate = ErgoValidationSettingsUpdate.empty //successful voting - cleaning after activation if (softForkStartingHeight.nonEmpty && height == softForkStartingHeight.get + votingEpochLength * (votingEpochs + activationEpochs + 1) && softForkApproved(votes)) { table = table.-(SoftForkStartingHeight).-(SoftForkVotesCollected) } //unsuccessful voting - cleaning if (softForkStartingHeight.nonEmpty && height == softForkStartingHeight.get + votingEpochLength * (votingEpochs + 1) && !softForkApproved(votes)) { table = table.-(SoftForkStartingHeight).-(SoftForkVotesCollected) } //new voting if (forkVote && ((softForkStartingHeight.isEmpty && height % votingEpochLength == 0) || (softForkStartingHeight.nonEmpty && height == softForkStartingHeight.get + (votingEpochLength * (votingEpochs + activationEpochs + 1))) || (softForkStartingHeight.nonEmpty && height == softForkStartingHeight.get + (votingEpochLength * (votingEpochs + 1)) && !softForkApproved(votes)))) { table = table.updated(SoftForkStartingHeight, height).updated(SoftForkVotesCollected, 0) } //new epoch in voting if (softForkStartingHeight.nonEmpty && height <= softForkStartingHeight.get + votingEpochLength * votingEpochs) { table = table.updated(SoftForkVotesCollected, votes) } //successful voting - activation if (softForkStartingHeight.nonEmpty && height == softForkStartingHeight.get + votingEpochLength * (votingEpochs + activationEpochs) && softForkApproved(votes)) { table = table.updated(BlockVersion, table(BlockVersion) + 1) activatedUpdate = proposedUpdate } // Forced version update to version 2 at height provided in settings if (height == votingSettings.version2ActivationHeight) { // Forced update should happen, but some soft-fork update happened before. // Node should fail at this point, as the situation is unclear require(table(BlockVersion) == 1, "Protocol version is not 1 on the hard-fork") table = table.updated(BlockVersion, table(BlockVersion) + 1) } (table, activatedUpdate) } //Update non-fork parameters def updateParams(parametersTable: Map[Byte, Int], epochVotes: Seq[(Byte, Int)], votingSettings: VotingSettings): Map[Byte, Int] = { epochVotes.filter(_._1 < Parameters.SoftFork).foldLeft(parametersTable) { case (table, (paramId, count)) => val paramIdAbs = if (paramId < 0) (-paramId).toByte else paramId if (votingSettings.changeApproved(count)) { val currentValue = parametersTable(paramIdAbs) val maxValue = maxValues.getOrElse(paramIdAbs, Int.MaxValue / 2) val minValue = minValues.getOrElse(paramIdAbs, 0) val step = stepsTable.getOrElse(paramIdAbs, Math.max(1, currentValue / 100)) val newValue = paramId match { case b: Byte if b > 0 => if (currentValue < maxValue) currentValue + step else currentValue case b: Byte if b < 0 => if (currentValue > minValue) currentValue - step else currentValue } table.updated(paramIdAbs, newValue) } else { table } } } private def padVotes(vs: Array[Byte]): Array[Byte] = { val maxVotes = ParamVotesCount + 1 if (vs.length < maxVotes) vs ++ Array.fill(maxVotes - vs.length)(0: Byte) else vs } def vote(ownTargets: Map[Byte, Int], epochVotes: Array[(Byte, Int)], voteForFork: Boolean): Array[Byte] = { val vs = epochVotes.filter { case (paramId, _) => if (paramId == Parameters.SoftFork) { voteForFork } else if (paramId > 0) { ownTargets.get(paramId).exists(_ > parametersTable(paramId)) } else if (paramId < 0) { ownTargets.get((-paramId).toByte).exists(_ < parametersTable((-paramId).toByte)) } else { false } }.map(_._1) padVotes(vs) } def suggestVotes(ownTargets: Map[Byte, Int], voteForFork: Boolean): Array[Byte] = { val vs = ownTargets.flatMap { case (paramId, value) => if (paramId == SoftFork) { None } else if (value > parametersTable(paramId)) { Some(paramId) } else if (value < parametersTable(paramId)) { Some((-paramId).toByte) } else { None } }.take(ParamVotesCount).toArray padVotes(if (voteForFork) vs :+ SoftFork else vs) } def toExtensionCandidate: ExtensionCandidate = { val paramFields = parametersTable.toSeq.map { case (k, v) => Array(SystemParametersPrefix, k) -> Ints.toByteArray(v) } val rulesToDisableFields: Seq[(Array[Byte], Array[Byte])] = { Seq(SoftForkDisablingRulesKey -> ErgoValidationSettingsUpdateSerializer.toBytes(proposedUpdate)) } ExtensionCandidate(paramFields ++ rulesToDisableFields) } def withBlockCost(cost: Int): Parameters = { Parameters(height, parametersTable.updated(MaxBlockCostIncrease, cost), proposedUpdate) } override def toString: String = s"Parameters(height: $height; ${parametersTable.mkString("; ")}; $proposedUpdate)" def canEqual(o: Any): Boolean = o.isInstanceOf[Parameters] override def equals(obj: Any): Boolean = obj match { case p: Parameters => matchParameters(this, p).isSuccess case _ => false } override def hashCode(): Height = height.hashCode() + parametersTable.hashCode() } object Parameters { val SoftFork: Byte = 120 val SoftForkVotesCollected: Byte = 121 val SoftForkStartingHeight: Byte = 122 val BlockVersion: Byte = 123 val SoftForkDisablingRules: Byte = 124 val SoftForkDisablingRulesKey: Array[Byte] = Array(Extension.SystemParametersPrefix, SoftForkDisablingRules) //A vote for nothing val NoParameter: Byte = 0 //Parameter identifiers val StorageFeeFactorIncrease: Byte = 1 val StorageFeeFactorDecrease: Byte = (-StorageFeeFactorIncrease).toByte val MinValuePerByteIncrease: Byte = 2 val MinValuePerByteDecrease: Byte = (-MinValuePerByteIncrease).toByte val MaxBlockSizeIncrease: Byte = 3 val MaxBlockSizeDecrease: Byte = (-MaxBlockSizeIncrease).toByte val MaxBlockCostIncrease: Byte = 4 val MaxBlockCostDecrease: Byte = (-MaxBlockCostIncrease).toByte val TokenAccessCostIncrease: Byte = 5 val TokenAccessCostDecrease: Byte = (-TokenAccessCostIncrease).toByte val InputCostIncrease: Byte = 6 val InputCostDecrease: Byte = (-InputCostIncrease).toByte val DataInputCostIncrease: Byte = 7 val DataInputCostDecrease: Byte = (-DataInputCostIncrease).toByte val OutputCostIncrease: Byte = 8 val OutputCostDecrease: Byte = (-OutputCostIncrease).toByte val StorageFeeFactorDefault: Int = 1250000 val StorageFeeFactorMax: Int = 2500000 val StorageFeeFactorMin: Int = 0 val StorageFeeFactorStep: Int = 25000 val MinValuePerByteDefault: Int = 30 * 12 val MinValueStep: Int = 10 val MinValueMin: Int = 0 val MinValueMax: Int = 10000 //0.00001 Erg val TokenAccessCostDefault: Int = 100 val InputCostDefault: Int = 2000 val DataInputCostDefault: Int = 100 val OutputCostDefault: Int = 100 val MaxBlockSizeDefault: Int = 512 * 1024 val MaxBlockSizeMax: Int = 1024 * 1024 val MaxBlockSizeMin: Int = 16 * 1024 val MaxBlockCostDefault: Int = 1000000 val DefaultParameters: Map[Byte, Int] = Map( StorageFeeFactorIncrease -> StorageFeeFactorDefault, MinValuePerByteIncrease -> MinValuePerByteDefault, TokenAccessCostIncrease -> TokenAccessCostDefault, InputCostIncrease -> InputCostDefault, DataInputCostIncrease -> DataInputCostDefault, OutputCostIncrease -> OutputCostDefault, MaxBlockSizeIncrease -> MaxBlockSizeDefault, MaxBlockCostIncrease -> MaxBlockCostDefault, BlockVersion -> 1 ) val parametersDescs: Map[Byte, String] = Map( StorageFeeFactorIncrease -> "Storage fee factor (per byte per storage period)", MinValuePerByteIncrease -> "Minimum monetary value of a box", MaxBlockSizeIncrease -> "Maximum block size", MaxBlockCostIncrease -> "Maximum cumulative computational cost of a block", SoftFork -> "Soft-fork (increasing version of a block)", TokenAccessCostIncrease -> "Token access cost", InputCostIncrease -> "Cost per one transaction input", DataInputCostIncrease -> "Cost per one data input", OutputCostIncrease -> "Cost per one transaction output" ) val stepsTable: Map[Byte, Int] = Map( StorageFeeFactorIncrease -> StorageFeeFactorStep, MinValuePerByteIncrease -> MinValueStep ) val minValues: Map[Byte, Int] = Map( StorageFeeFactorIncrease -> StorageFeeFactorMin, MinValuePerByteIncrease -> MinValueMin, MaxBlockSizeIncrease -> MaxBlockSizeMin, MaxBlockCostIncrease -> 16 * 1024 ) val maxValues: Map[Byte, Int] = Map( StorageFeeFactorIncrease -> StorageFeeFactorMax, MinValuePerByteIncrease -> MinValueMax ) val ParamVotesCount = 2 def apply(h: Height, paramsTable: Map[Byte, Int], update: ErgoValidationSettingsUpdate): Parameters = { new Parameters(h, paramsTable, update) } def parseExtension(h: Height, extension: Extension): Try[Parameters] = Try { val paramsTable = extension.fields.flatMap { case (k, v) => require(k.length == 2, s"Wrong key during parameters parsing in extension: $extension") if (k(0) == Extension.SystemParametersPrefix && k(1) != SoftForkDisablingRules) { require(v.length == 4, s"Wrong value during parameters parsing in extension: $extension") Some(k(1) -> Ints.fromByteArray(v)) } else { None } }.toMap val proposedUpdate = extension .fields .find(k => java.util.Arrays.equals(k._1, SoftForkDisablingRulesKey)) .flatMap(b => ErgoValidationSettingsUpdateSerializer.parseBytesTry(b._2).toOption) .getOrElse(ErgoValidationSettingsUpdate.empty) require(paramsTable.nonEmpty, s"Parameters table is empty in extension: $extension") Parameters(h, paramsTable, proposedUpdate) } /** * Check that two sets of parameters are the same (contain the same records). * * @param p1 - parameters set * @param p2 - parameters set * @return Success(p1), if parameters match, Failure(_) otherwise */ def matchParameters(p1: Parameters, p2: Parameters): Try[Unit] = Try { if (p1.height != p2.height) { throw new Exception(s"Different height in parameters, p1 = $p1, p2 = $p2") } if (p1.parametersTable.size != p2.parametersTable.size) { throw new Exception(s"Parameters differ in size, p1 = $p1, p2 = $p2") } if (p1.proposedUpdate != p2.proposedUpdate) { throw new Exception(s"Parameters proposedUpdate differs, p1 = ${p1.proposedUpdate}, p2 = ${p2.proposedUpdate}") } p1.parametersTable.foreach { case (k, v) => val v2 = p2.parametersTable(k) if (v2 != v) throw new Exception(s"Calculated and received parameters differ in parameter $k ($v != $v2)") } } } object ParametersSerializer extends ScorexSerializer[Parameters] with ApiCodecs { override def serialize(params: Parameters, w: Writer): Unit = { require(params.parametersTable.nonEmpty, s"$params is empty") w.putUInt(params.height) val paramsSize = params.parametersTable.size w.putUInt(paramsSize) params.parametersTable.foreach { case (k, v) => w.put(k) w.putInt(v) } ErgoValidationSettingsUpdateSerializer.serialize(params.proposedUpdate, w) } override def parse(r: Reader): Parameters = { val height = r.getUInt().toIntExact val tableLength = r.getUInt().toIntExact val table = (0 until tableLength).map { _ => r.getByte() -> r.getInt() } val proposedUpdate = ErgoValidationSettingsUpdateSerializer.parse(r) Parameters(height, table.toMap, proposedUpdate) } implicit val jsonEncoder: Encoder[Parameters] = { p: Parameters => Map( "height" -> p.height.asJson, "blockVersion" -> p.blockVersion.asJson, "storageFeeFactor" -> p.storageFeeFactor.asJson, "minValuePerByte" -> p.minValuePerByte.asJson, "maxBlockSize" -> p.maxBlockSize.asJson, "maxBlockCost" -> p.maxBlockCost.asJson, "tokenAccessCost" -> p.tokenAccessCost.asJson, "inputCost" -> p.inputCost.asJson, "dataInputCost" -> p.dataInputCost.asJson, "outputCost" -> p.outputCost.asJson ).asJson } }
ccellado/ergo
src/main/scala/org/ergoplatform/http/api/NipopowApiRoute.scala
<filename>src/main/scala/org/ergoplatform/http/api/NipopowApiRoute.scala<gh_stars>0 package org.ergoplatform.http.api import akka.pattern.ask import akka.actor.{ActorRef, ActorRefFactory} import akka.http.scaladsl.server.Route import io.circe.Encoder import io.circe.syntax._ import org.ergoplatform.modifiers.history.popow.{PoPowHeader, NipopowProof} import org.ergoplatform.nodeView.ErgoReadersHolder.GetDataFromHistory import org.ergoplatform.nodeView.history.ErgoHistoryReader import org.ergoplatform.settings.ErgoSettings import scorex.core.api.http.ApiError.BadRequest import scorex.core.api.http.ApiResponse import scorex.core.settings.RESTApiSettings import scorex.util.ModifierId import scala.concurrent.Future import scala.util.Try case class NipopowApiRoute(viewHolderRef: ActorRef, readersHolder: ActorRef, ergoSettings: ErgoSettings) (implicit val context: ActorRefFactory) extends ErgoBaseApiRoute with ApiCodecs { override val settings: RESTApiSettings = ergoSettings.scorexSettings.restApi private implicit val popowProofEncoder: Encoder[NipopowProof] = NipopowProof.nipopowProofEncoder override val route: Route = pathPrefix("nipopow") { getPopowHeaderByHeaderIdR ~ getPopowHeaderByHeightR ~ getPopowProofR ~ getPopowProofByHeaderIdR } private def getHistory: Future[ErgoHistoryReader] = (readersHolder ? GetDataFromHistory[ErgoHistoryReader](r => r)).mapTo[ErgoHistoryReader] private def getPopowHeaderById(headerId: ModifierId): Future[Option[PoPowHeader]] = getHistory.map { history => history.popowHeader(headerId) } private def getPopowHeaderByHeight(height: Int): Future[Option[PoPowHeader]] = getHistory.map { history => history.popowHeader(height) } private def getPopowProof(m: Int, k: Int, headerIdOpt: Option[ModifierId]): Future[Try[NipopowProof]] = getHistory.map { history => history.popowProof(m, k, headerIdOpt) } /** * Get header along with interlink vector for given header identifier */ def getPopowHeaderByHeaderIdR: Route = (pathPrefix("popowHeaderById") & modifierId & get) { headerId => ApiResponse(getPopowHeaderById(headerId)) } /** * Get best chain header along with its interlink vector for given height */ def getPopowHeaderByHeightR: Route = (pathPrefix("popowHeaderByHeight" / IntNumber) & get) { headerId => ApiResponse(getPopowHeaderByHeight(headerId)) } /** * Get NiPoPow proof for current moment of time (for header from k blocks ago) */ def getPopowProofR: Route = (pathPrefix("proof" / IntNumber / IntNumber) & pathEndOrSingleSlash & get) { case (m, k) => onSuccess(getPopowProof(m, k, None)) { _.fold( e => BadRequest(e.getMessage), proof => ApiResponse(proof.asJson) ) } } /** * Get NiPoPow proof for given block id */ def getPopowProofByHeaderIdR: Route = (pathPrefix("proof" / IntNumber / IntNumber) & modifierId & get) { case (m, k, headerId) => onSuccess(getPopowProof(m, k, Some(headerId))) { _.fold( e => BadRequest(e.getMessage), proof => ApiResponse(proof.asJson) ) } } }
ccellado/ergo
ergo-wallet/src/main/scala/org/ergoplatform/contracts/ReemissionContracts.scala
<gh_stars>0 package org.ergoplatform.contracts import org.ergoplatform.ErgoBox.{R2, STokensRegType} import org.ergoplatform.ErgoScriptPredef.{boxCreationHeight, expectedMinerOutScriptBytesVal} import org.ergoplatform.{Height, MinerPubkey, Outputs, Self} import org.ergoplatform.settings.MonetarySettings import sigmastate.{AND, EQ, GE, GT, LE, Minus, OR, SBox, SCollection, STuple} import sigmastate.Values.{ByteArrayConstant, ErgoTree, IntConstant, LongConstant, SigmaPropValue, Value} import sigmastate.utxo.{ByIndex, ExtractAmount, ExtractRegisterAs, ExtractScriptBytes, OptionGet, SelectField, SizeOf} import org.ergoplatform.mining.emission.EmissionRules.CoinsInOneErgo /** * Container for re-emission related contracts. Contains re-emission contract and pay-to-reemission contract. */ trait ReemissionContracts { /** * How much miner can take per block from re-emission contract */ val reemissionRewardPerBlock: Long = 3 * CoinsInOneErgo // 3 ERG /** * @return - ID of NFT token associated with re-emission contract */ def reemissionNftIdBytes: Array[Byte] /** * @return - height when reemission starts */ def reemissionStartHeight: Int /** Helper method to extract tokens from a box. */ private def extractTokens(box: Value[SBox.type]): OptionGet[SCollection[STuple]] = { val rOutTokens = OptionGet(ExtractRegisterAs(box, R2)(STokensRegType)) rOutTokens } /** Helper method to produce v1 tree from a SigmaPropValue instance (i.e. root node of AST).*/ private def v1Tree(prop: SigmaPropValue): ErgoTree = { val version: Byte = 1 val headerFlags = ErgoTree.headerWithVersion(version) ErgoTree.fromProposition(headerFlags, prop) } /** * Contract for boxes miners paying to remission contract according to EIP-27. * Anyone can merge multiple boxes locked by this contract with reemission box */ lazy val payToReemission: ErgoTree = v1Tree({ // output of the reemission contract val reemissionOut = ByIndex(Outputs, IntConstant(0)) val rOutTokens = extractTokens(reemissionOut) val firstTokenId = SelectField(ByIndex(rOutTokens, IntConstant(0)), 1.toByte) EQ(firstTokenId, ByteArrayConstant(reemissionNftIdBytes)) }) /** * Re-emission contract */ def reemissionBoxProp(ms: MonetarySettings): ErgoTree = v1Tree({ // output of the reemission contract val reemissionOut = ByIndex(Outputs, IntConstant(0)) val secondOut = ByIndex(Outputs, IntConstant(1)) // output to pay miner val minerOut = secondOut // check that first (re-emission) output contains re-emission NFT (in the first position) val rOutTokens = extractTokens(reemissionOut) val firstTokenId = SelectField(ByIndex(rOutTokens, IntConstant(0)), 1.toByte) val correctNftId = EQ(firstTokenId, ByteArrayConstant(reemissionNftIdBytes)) // miner's output must have script which is time-locking reward for miner's pubkey // box height must be the same as block height val correctMinerOutput = AND( EQ(ExtractScriptBytes(minerOut), expectedMinerOutScriptBytesVal(ms.minerRewardDelay, MinerPubkey)), EQ(Height, boxCreationHeight(minerOut)) ) // reemission output's height must be the same as block height val heightCorrect = EQ(boxCreationHeight(reemissionOut), Height) // reemission output's height is greater than reemission input val heightIncreased = GT(Height, boxCreationHeight(Self)) // check that height is greater than end of emission (>= 2,080,800 for the mainnet) val afterEmission = GE(Height, IntConstant(reemissionStartHeight)) // reemission contract must be preserved val sameScriptRule = EQ(ExtractScriptBytes(Self), ExtractScriptBytes(reemissionOut)) // miner's reward condition val correctCoinsIssued = EQ(reemissionRewardPerBlock, Minus(ExtractAmount(Self), ExtractAmount(reemissionOut))) // when reemission contract box got merged with other boxes val merging = { val feeOut = secondOut AND( GT(ExtractAmount(reemissionOut), ExtractAmount(Self)), LE(ExtractAmount(feeOut), LongConstant(CoinsInOneErgo / 100)), // 0.01 ERG EQ(SizeOf(Outputs), 2) ) } AND( correctNftId, sameScriptRule, OR( merging, AND( heightCorrect, correctMinerOutput, afterEmission, heightIncreased, correctCoinsIssued ) ) ) }.toSigmaProp) }
ccellado/ergo
src/test/scala/org/ergoplatform/nodeView/state/wrapped/WrappedDigestState.scala
package org.ergoplatform.nodeView.state.wrapped import org.ergoplatform.ErgoLikeContext.Height import org.ergoplatform.modifiers.ErgoPersistentModifier import org.ergoplatform.nodeView.ErgoNodeViewHolder.ReceivableMessages.LocallyGeneratedModifier import org.ergoplatform.nodeView.state.DigestState import org.ergoplatform.settings.ErgoSettings import scorex.core.VersionTag import scala.util.Try class WrappedDigestState(val digestState: DigestState, val wrappedUtxoState: WrappedUtxoState, val settings: ErgoSettings) extends DigestState(digestState.version, digestState.rootHash, digestState.store, settings) { override def applyModifier(mod: ErgoPersistentModifier, estimatedTip: Option[Height]) (generate: LocallyGeneratedModifier => Unit): Try[WrappedDigestState] = { wrapped(super.applyModifier(mod, estimatedTip)(_ => ()), wrappedUtxoState.applyModifier(mod, estimatedTip)(_ => ())) } override def rollbackTo(version: VersionTag): Try[WrappedDigestState] = { wrapped(super.rollbackTo(version), wrappedUtxoState.rollbackTo(version)) } private def wrapped(digestT: Try[DigestState], utxoT: Try[WrappedUtxoState]): Try[WrappedDigestState] = digestT.flatMap(digest => utxoT.map(utxo => new WrappedDigestState(digest, utxo, settings))) }
ccellado/ergo
src/main/scala/scorex/core/network/DeliveryTracker.scala
package scorex.core.network import akka.actor.Cancellable import io.circe.{Encoder, Json} import org.ergoplatform.modifiers.history.header.Header import org.ergoplatform.network.ErgoNodeViewSynchronizer.ReceivableMessages.CheckDelivery import org.ergoplatform.nodeView.mempool.ExpiringApproximateCache import org.ergoplatform.settings.{ErgoSettings, NetworkCacheSettings} import scorex.core.ModifierTypeId import scorex.core.consensus.ContainsModifiers import scorex.core.network.DeliveryTracker._ import scorex.core.network.ModifiersStatus._ import scorex.core.utils._ import scorex.util.{ModifierId, ScorexLogging} import scala.collection.mutable import scala.util.{Failure, Try} /** * This class tracks modifier statuses. * Modifier can be in one of the following states: Unknown, Requested, Received, Held, Invalid. * See ModifiersStatus for states description. * Modifiers in `Requested` state are kept in `requested` map containing info about peer and number of retries. * Modifiers in `Received` state are kept in `received` set. * Modifiers in `Invalid` state are kept in `invalid` set to prevent this modifier download and processing. * Modifiers in `Held` state are not kept in this class - we can get this status from object, that contains * these modifiers (History for PersistentNodeViewModifier, Mempool for EphemerealNodeViewModifier). * If we can't identify modifiers status based on the rules above, it's status is Unknown. * * In success path modifier changes his statuses `Unknown`->`Requested`->`Received`->`Held`. * If something went wrong (e.g. modifier was not delivered) it goes back to `Unknown` state * (if we are going to receive it in future) or to `Invalid` state (if we are not going to receive * this modifier anymore) * Locally generated modifiers may go to `Held` or `Invalid` states at any time. * These rules are also described in `isCorrectTransition` function. * * This class is not thread-save so it should be used only as a local field of an actor * and its methods should not be called from lambdas, Future, Future.map, etc. * @param maxDeliveryChecks how many times to check whether modifier was delivered in given timeout * @param cacheSettings network cache settings * @param desiredSizeOfExpectingModifierQueue Approximate number of modifiers to be downloaded simultaneously, * headers are much faster to process */ class DeliveryTracker(maxDeliveryChecks: Int, cacheSettings: NetworkCacheSettings, desiredSizeOfExpectingModifierQueue: Int) extends ScorexLogging with ScorexEncoding { // when a remote peer is asked for a modifier we add the requested data to `requested` protected val requested: mutable.Map[ModifierTypeId, Map[ModifierId, RequestedInfo]] = mutable.Map() // when our node received a modifier we put it to `received` protected val received: mutable.Map[ModifierTypeId, Map[ModifierId, ConnectedPeer]] = mutable.Map() private val desiredSizeOfExpectingHeaderQueue: Int = desiredSizeOfExpectingModifierQueue * 5 /** Bloom Filter based cache with invalid modifier ids */ private var invalidModifierCache = emptyExpiringApproximateCache private def emptyExpiringApproximateCache = { val bloomFilterCapacity = cacheSettings.invalidModifiersBloomFilterCapacity val bloomFilterExpirationRate = cacheSettings.invalidModifiersBloomFilterExpirationRate val frontCacheSize = cacheSettings.invalidModifiersCacheSize val frontCacheExpiration = cacheSettings.invalidModifiersCacheExpiration ExpiringApproximateCache.empty(bloomFilterCapacity, bloomFilterExpirationRate, frontCacheSize, frontCacheExpiration) } def fullInfo: FullInfo = DeliveryTracker.FullInfo(invalidModifierCache.approximateElementCount, requested.toSeq, received.toSeq) def reset(): Unit = { log.info(s"Resetting state of DeliveryTracker...") requested.clear() received.clear() invalidModifierCache = emptyExpiringApproximateCache } /** * @return how many header modifiers to download */ def headersToDownload: Int = Math.max(0, desiredSizeOfExpectingHeaderQueue - requested.get(Header.modifierTypeId).fold(0)(_.size)) /** * @return how many modifiers to download */ def modifiersToDownload: Int = { val nonHeaderModifiersCount = requested.foldLeft(0) { case (sum, (modTypeId, _)) if modTypeId == Header.modifierTypeId => sum case (sum, (_, mid)) => sum + mid.size } Math.max(0, desiredSizeOfExpectingModifierQueue - nonHeaderModifiersCount) } /** * @return status of modifier `id`. * Since this class do not keep statuses for modifiers that are already in NodeViewHolder, * `modifierKeepers` are required here to check that modifier is in `Held` status */ def status(modifierId: ModifierId, modifierTypeId: ModifierTypeId, modifierKeepers: Seq[ContainsModifiers[_]]): ModifiersStatus = if (received.get(modifierTypeId).exists(_.contains(modifierId))) Received else if (requested.get(modifierTypeId).exists(_.contains(modifierId))) Requested else if (invalidModifierCache.mightContain(modifierId)) Invalid else if (modifierKeepers.exists(_.contains(modifierId))) Held else Unknown def requireStatus(oldStatus: ModifiersStatus, expectedStatues: ModifiersStatus): Unit = { require(isCorrectTransition(oldStatus, expectedStatues), s"Illegal status transition: $oldStatus -> $expectedStatues") } /** * Our node have requested a modifier, but did not received it yet. * Stops processing and if the number of checks did not exceed the maximum continue to waiting. * @param schedule that schedules a delivery check message * @return `true` if number of checks was not exceed, `false` otherwise */ def onStillWaiting(cp: ConnectedPeer, modifierTypeId: ModifierTypeId, modifierId: ModifierId) (schedule: CheckDelivery => Cancellable): Try[Unit] = tryWithLogging { val checks = requested(modifierTypeId)(modifierId).checks + 1 setUnknown(modifierId, modifierTypeId) if (checks < maxDeliveryChecks) setRequested(modifierId, modifierTypeId, Some(cp), checks)(schedule) else throw new StopExpectingError(modifierId, modifierTypeId, checks) } /** * Set status of modifier with id `id` to `Requested` */ private def setRequested(id: ModifierId, typeId: ModifierTypeId, supplierOpt: Option[ConnectedPeer], checksDone: Int = 0) (schedule: CheckDelivery => Cancellable): Unit = tryWithLogging { requireStatus(status(id, typeId, Seq.empty), Requested) val cancellable = schedule(CheckDelivery(supplierOpt, typeId, id)) val requestedInfo = RequestedInfo(supplierOpt, cancellable, checksDone) requested.adjust(typeId)(_.fold(Map(id -> requestedInfo))(_.updated(id, requestedInfo))) } /** * Set status of multiple modifiers to `Requested` * @param schedule function that schedules a delivery check message */ def setRequested(ids: Seq[ModifierId], typeId: ModifierTypeId, cp: Option[ConnectedPeer]) (schedule: CheckDelivery => Cancellable): Unit = ids.foreach(setRequested(_, typeId, cp)(schedule)) /** Get peer we're communicating with in regards with modifier `id` **/ def getSource(id: ModifierId, modifierTypeId: ModifierTypeId): Option[ConnectedPeer] = { status(id, modifierTypeId, Seq.empty) match { case Requested => requested.get(modifierTypeId).flatMap(_.get(id)).flatMap(_.peer) case Received => received.get(modifierTypeId).flatMap(_.get(id)) case _ => None } } /** * Modified with id `id` is permanently invalid - set its status to `Invalid` * and return [[ConnectedPeer]] which sent bad modifier. */ def setInvalid(id: ModifierId, modifierTypeId: ModifierTypeId): Option[ConnectedPeer] = { val oldStatus: ModifiersStatus = status(id, modifierTypeId, Seq.empty) val transitionCheck = tryWithLogging { requireStatus(oldStatus, Invalid) } transitionCheck .toOption .flatMap { _ => val senderOpt = oldStatus match { case Requested => requested.get(modifierTypeId).flatMap { infoById => infoById.get(id) match { case None => log.warn(s"Requested modifier $id of type $modifierTypeId not found while invalidating it") None case Some(info) => info.cancellable.cancel() requested.flatAdjust(modifierTypeId)(_.map(_ - id)) info.peer } } case Received => received.get(modifierTypeId).flatMap { peerById => peerById.get(id) match { case None => log.warn(s"Received modifier $id of type $modifierTypeId not found while invalidating it") None case Some(sender) => received.flatAdjust(modifierTypeId)(_.map(_ - id)) Option(sender) } } case _ => None } invalidModifierCache = invalidModifierCache.put(id) senderOpt } } /** * Modifier with id `id` was successfully applied to history - set its status to `Held`. */ def setHeld(id: ModifierId, modifierTypeId: ModifierTypeId): Unit = tryWithLogging { val oldStatus = status(id, modifierTypeId, Seq.empty) requireStatus(oldStatus, Held) clearStatusForModifier(id, modifierTypeId, oldStatus) // clear old status } /** * Set status of modifier with id `id` to `Unknown`. * * We're not trying to process modifier anymore in this case. * This may happen when received modifier bytes does not correspond to declared modifier id, * this modifier was removed from cache because cache is overfull or * we stop trying to download this modifiers due to exceeded number of retries */ def setUnknown(id: ModifierId, modifierTypeId: ModifierTypeId): Unit = tryWithLogging { val oldStatus = status(id, modifierTypeId, Seq.empty) requireStatus(oldStatus, Unknown) clearStatusForModifier(id, modifierTypeId, oldStatus) // clear old status } /** * Modifier with id `id` was received from remote peer - set its status to `Received`. */ def setReceived(id: ModifierId, modifierTypeId: ModifierTypeId, sender: ConnectedPeer): Unit = tryWithLogging { val oldStatus = status(id, modifierTypeId, Seq.empty) requireStatus(oldStatus, Received) if (oldStatus != Received) { requested.flatAdjust(modifierTypeId)(_.map { infoById => infoById.get(id) match { case None => log.warn(s"Requested modifier $id of type $modifierTypeId not found while receiving it") infoById case Some(info) => info.cancellable.cancel() infoById - id } }) received.adjust(modifierTypeId)(_.fold(Map(id -> sender))(_.updated(id, sender))) } } /** * Self-check that transition between states is correct. * * Modifier may stay in current state, * go to Requested state form Unknown * go to Received state from Requested * go to Invalid state from any state (this may happen on invalid locally generated modifier) * go to Unknown state from Requested and Received states */ private def isCorrectTransition(oldStatus: ModifiersStatus, newStatus: ModifiersStatus): Boolean = oldStatus match { case old if old == newStatus => true case _ if newStatus == Invalid || newStatus == Held => true case Unknown => newStatus == Requested case Requested => newStatus == Unknown || newStatus == Received case Received => newStatus == Unknown case _ => false } def clearStatusForModifier(id: ModifierId, modifierTypeId: ModifierTypeId, oldStatus: ModifiersStatus): Unit = oldStatus match { case Requested => requested.flatAdjust(modifierTypeId)(_.map { infoById => infoById.get(id) match { case None => log.warn(s"Requested modifier $id of type $modifierTypeId not found while clearing status") infoById case Some(info) => info.cancellable.cancel() infoById - id } }) case Received => received.flatAdjust(modifierTypeId)(_.map { peerById => peerById.get(id) match { case None => log.warn(s"Received modifier $id of type $modifierTypeId not found while clearing status") peerById case Some(_) => peerById - id } }) case _ => () } class StopExpectingError(mid: ModifierId, mType: ModifierTypeId, checks: Int) extends Error(s"Stop expecting ${encoder.encodeId(mid)} of type $mType due to exceeded number of retries $checks") private def tryWithLogging[T](fn: => T): Try[T] = Try(fn).recoverWith { case e: StopExpectingError => log.warn(e.getMessage) Failure(e) case e => log.warn("Unexpected error", e) Failure(e) } override def toString: String = { val invalidModCount = s"invalid modifiers count : ${invalidModifierCache.approximateElementCount}" val requestedStr = requested.map { case (mType, infoByMid) => val peersCheckTimes = infoByMid.toSeq.sortBy(_._2.checks).reverse.map { case (_, info) => s"${info.peer.map(_.connectionId.remoteAddress)} checked ${info.checks} times" }.mkString(", ") s"$mType : $peersCheckTimes" }.mkString("\n") val receivedStr = received.map { case (mType, peerByMid) => val listOfPeers = peerByMid.values.toSet.mkString(", ") s"$mType : $listOfPeers" }.mkString("\n") s"$invalidModCount\nrequested modifiers:\n$requestedStr\nreceived modifiers:\n$receivedStr" } } object DeliveryTracker { case class RequestedInfo(peer: Option[ConnectedPeer], cancellable: Cancellable, checks: Int) object RequestedInfo { import io.circe.syntax._ implicit val jsonEncoder: Encoder[RequestedInfo] = { info: RequestedInfo => val checksField = "checks" -> info.checks.asJson val optionalFields = List( info.peer.map(_.connectionId.remoteAddress.toString).map("address" -> _.asJson), info.peer.flatMap(_.peerInfo.map(_.peerSpec.protocolVersion.toString)).map("version" -> _.asJson) ).flatten val fields = checksField :: optionalFields Json.obj(fields:_*) } } case class FullInfo( invalidModifierApproxSize: Long, requested: Seq[(ModifierTypeId, Map[ModifierId, RequestedInfo])], received: Seq[(ModifierTypeId, Map[ModifierId, ConnectedPeer])] ) object FullInfo { import io.circe.syntax._ implicit val encodeState: Encoder[FullInfo] = new Encoder[FullInfo] { def nestedMapAsJson[T : Encoder](requested: Seq[(ModifierTypeId, Map[ModifierId, T])]): Json = Json.obj( requested.map { case (k, v) => k.toString -> Json.obj(v.mapValues(_.asJson).toSeq:_*) }:_* ) final def apply(state: FullInfo): Json = Json.obj( ("invalidModifierApproxSize", state.invalidModifierApproxSize.asJson), ("requested", nestedMapAsJson(state.requested)), ("received", nestedMapAsJson(state.received)) ) } } def empty(settings: ErgoSettings): DeliveryTracker = { new DeliveryTracker( settings.scorexSettings.network.maxDeliveryChecks, settings.cacheSettings.network, settings.scorexSettings.network.desiredInvObjects ) } }
ccellado/ergo
src/test/scala/org/ergoplatform/utils/MempoolTestHelpers.scala
package org.ergoplatform.utils import org.ergoplatform.ErgoBox.BoxId import org.ergoplatform.modifiers.mempool.ErgoTransaction import org.ergoplatform.nodeView.mempool.{ErgoMemPoolReader, OrderedTxPool} import scorex.util.ModifierId trait MempoolTestHelpers { // mempool reader stub specifically for this test only take is defined as only this method is used in rebroadcasting class FakeMempool(txs: Seq[ErgoTransaction]) extends ErgoMemPoolReader { override def modifierById(modifierId: ModifierId): Option[ErgoTransaction] = ??? override def getAll(ids: Seq[ModifierId]): Seq[ErgoTransaction] = ??? override def size: Int = ??? override def weightedTransactionIds(limit: Int): Seq[OrderedTxPool.WeightedTxId] = ??? override def getAll: Seq[ErgoTransaction] = ??? override def getAllPrioritized: Seq[ErgoTransaction] = txs override def take(limit: Int): Iterable[ErgoTransaction] = txs.take(limit) override def random(limit: Int): Iterable[ErgoTransaction] = take(limit) override def spentInputs: Iterator[BoxId] = txs.flatMap(_.inputs).map(_.boxId).toIterator override def getRecommendedFee(expectedWaitTimeMinutes: Int, txSize: Int) : Long = 0 override def getExpectedWaitTime(txFee: Long, txSize: Int): Long = 0 } }
ccellado/ergo
avldb/src/test/scala/scorex/crypto/authds/avltree/batch/helpers/TestHelper.scala
<filename>avldb/src/test/scala/scorex/crypto/authds/avltree/batch/helpers/TestHelper.scala package scorex.crypto.authds.avltree.batch.helpers import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{ADDigest, SerializedAdProof} import scorex.util.encode.Base58 import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.db.LDBVersionedStore trait TestHelper extends FileHelper { type HF = Blake2b256.type type D = Digest32 type AD = ADDigest type P = SerializedAdProof type PROVER = BatchAVLProver[D, HF] type VERIFIER = BatchAVLVerifier[D, HF] type PERSISTENT_PROVER = PersistentBatchAVLProver[D, HF] type STORAGE = VersionedLDBAVLStorage[D] protected val KL: Int protected val VL: Int protected val LL: Int implicit val hf: HF = Blake2b256 def createVersionedStore(initialKeepVersions: Int = 10): LDBVersionedStore = { val dir = getRandomTempDir new LDBVersionedStore(dir, initialKeepVersions = initialKeepVersions) } def createVersionedStorage(store: LDBVersionedStore): STORAGE = new VersionedLDBAVLStorage(store, NodeParameters(KL, Some(VL), LL)) def createPersistentProver(storage: STORAGE): PERSISTENT_PROVER = { val prover = new BatchAVLProver[D, HF](KL, Some(VL)) createPersistentProver(storage, prover) } def createPersistentProver(storage: STORAGE, prover: PROVER): PERSISTENT_PROVER = PersistentBatchAVLProver.create[D, HF](prover, storage, paranoidChecks = true).get def createPersistentProver(keepVersions: Int = 10): PERSISTENT_PROVER = { val store = createVersionedStore(keepVersions) val storage = createVersionedStorage(store) createPersistentProver(storage) } def createVerifier(digest: AD, proof: P): VERIFIER = new BatchAVLVerifier[D, HF](digest, proof, KL, Some(VL)) implicit class DigestToBase58String(d: ADDigest) { def toBase58: String = Base58.encode(d) } }
ccellado/ergo
avldb/src/main/scala/scorex/db/LDBVersionedStore.scala
<reponame>ccellado/ergo<filename>avldb/src/main/scala/scorex/db/LDBVersionedStore.scala package scorex.db import java.io.File import scorex.db.LDBFactory.factory import org.iq80.leveldb._ import java.nio.ByteBuffer import scala.collection.mutable.ArrayBuffer import java.util.concurrent.locks.ReentrantReadWriteLock import scorex.crypto.hash.Blake2b256 import scala.util.Try /** * Implementation of versioned storage on top of LevelDB. * * LevelDB implementation of versioned store is based on maintaining "compensating transaction" list, * list of reverse operations needed to undo changes of applied transactions. * This list is stored in separate LevelDB database (undo) and size of list is limited by the keepVersions parameter. * If keepVersions == 0, then undo list is not maintained and rollback of the committed transactions is not possible. * * @param dir - folder to store data * @param initialKeepVersions - number of versions to keep when the store is created. Can be changed after. * */ class LDBVersionedStore(protected val dir: File, val initialKeepVersions: Int) extends KVStoreReader { type VersionID = Array[Byte] type LSN = Long // logical serial number: type used to provide order of records in undo list private val last_version_key = Blake2b256("last_version") private var keepVersions: Int = initialKeepVersions override val db: DB = createDB(dir, "ldb_main") // storage for main data override val lock = new ReentrantReadWriteLock() private val undo: DB = createDB(dir, "ldb_undo") // storage for undo data private var lsn: LSN = getLastLSN // last assigned logical serial number private var versionLsn = ArrayBuffer.empty[LSN] // LSNs of versions (var because we need to invert this array) // mutable array of all the kept versions private val versions: ArrayBuffer[VersionID] = getAllVersions private var lastVersion: Option[VersionID] = versions.lastOption //default write options, no sync! private val writeOptions = new WriteOptions() private def createDB(dir: File, storeName: String): DB = { val op = new Options() op.createIfMissing(true) op.paranoidChecks(true) factory.open(new File(dir, storeName), op) } /** Set new keep versions threshold, remove not needed versions and return old value of keep versions */ def setKeepVersions(newKeepVersions: Int): Int = { lock.writeLock().lock() val oldKeepVersions = keepVersions try { if (newKeepVersions < oldKeepVersions) { cleanStart(newKeepVersions) } keepVersions = newKeepVersions } finally { lock.writeLock().unlock() } oldKeepVersions } def getKeepVersions: Int = keepVersions /** returns value associated with the key or throws `NoSuchElementException` */ def apply(key: K): V = getOrElse(key, { throw new NoSuchElementException() }) /** * Batch get with callback for result value. * * Finds all keys from given iterable. * Results are passed to callable consumer. * * It uses latest (most recent) version available in store * * @param keys keys to lookup * @param consumer callback method to consume results */ def get(keys: Iterable[K], consumer: (K, Option[V]) => Unit): Unit = { for (key <- keys) { val value = get(key) consumer(key, value) } } def processAll(consumer: (K, V) => Unit): Unit = { lock.readLock().lock() val iterator = db.iterator() try { iterator.seekToFirst() while (iterator.hasNext) { val n = iterator.next() consumer(n.getKey, n.getValue) } } finally { iterator.close() lock.readLock().unlock() } } private def newLSN(): Array[Byte] = { lsn += 1 encodeLSN(lsn) } /** * Invert word to provide descending key order. * Java implementation of LevelDB org.iq80.leveldb doesn't support iteration in backward direction. */ private def decodeLSN(lsn: Array[Byte]): LSN = { ~ByteBuffer.wrap(lsn).getLong } private def encodeLSN(lsn: LSN): Array[Byte] = { val buf = ByteBuffer.allocate(8) buf.putLong(~lsn) buf.array() } private def getLastLSN: LSN = { val iterator = undo.iterator try { iterator.seekToFirst() if (iterator.hasNext) { decodeLSN(iterator.peekNext().getKey) } else { 0 } } finally { iterator.close() } } def lastVersionID: Option[VersionID] = { lastVersion } def versionIdExists(versionID: VersionID): Boolean = { lock.readLock().lock() try { versions.exists(_.sameElements(versionID)) } finally { lock.readLock().unlock() } } private def getAllVersions: ArrayBuffer[VersionID] = { val versions = ArrayBuffer.empty[VersionID] var lastVersion: Option[VersionID] = None var lastLsn: LSN = 0 // We iterate in LSN descending order val iterator = undo.iterator() iterator.seekToFirst() while (iterator.hasNext) { val entry = iterator.next val currVersion = deserializeUndo(entry.getValue).versionID lastLsn = decodeLSN(entry.getKey) if (!lastVersion.exists(_.sameElements(currVersion))) { versionLsn += lastLsn + 1 // this is first LSN of successor version versions += currVersion lastVersion = Some(currVersion) } } iterator.close() // As far as org.iq80.leveldb doesn't support iteration in reverse order, we have to iterate in the order // of decreasing LSNs and then revert version list. For each version we store first (smallest) LSN. versionLsn += lastLsn // first LSN of oldest version versionLsn = versionLsn.reverse // LSNs should be in ascending order versionLsn.remove(versionLsn.size - 1) // remove last element which corresponds to next assigned LSN if (versions.nonEmpty) { versions.reverse } else { val dbVersion = db.get(last_version_key) if (dbVersion != null) { versions += dbVersion versionLsn += lastLsn } versions } } /** * Undo action. To implement recovery to the specified version, we store in the separate undo database * sequence of undo operations corresponding to the updates done by the committed transactions. */ case class Undo(versionID: VersionID, key: Array[Byte], value: Array[Byte]) private def serializeUndo(versionID: VersionID, key: Array[Byte], value: Array[Byte]): Array[Byte] = { val valueSize = if (value != null) value.length else 0 val versionSize = versionID.length val keySize = key.length val packed = new Array[Byte](2 + versionSize + keySize + valueSize) require(keySize <= 0xFF) packed(0) = versionSize.asInstanceOf[Byte] packed(1) = keySize.asInstanceOf[Byte] Array.copy(versionID, 0, packed, 2, versionSize) Array.copy(key, 0, packed, 2 + versionSize, keySize) if (value != null) { Array.copy(value, 0, packed, 2 + versionSize + keySize, valueSize) } packed } private def deserializeUndo(undo: Array[Byte]): Undo = { val versionSize = undo(0) & 0xFF val keySize = undo(1) & 0xFF val valueSize = undo.length - versionSize - keySize - 2 val versionID = undo.slice(2, 2 + versionSize) val key = undo.slice(2 + versionSize, 2 + versionSize + keySize) val value = if (valueSize == 0){ null } else{ undo.slice(2 + versionSize + keySize, undo.length) } Undo(versionID, key, value) } def update(versionID: VersionID, toRemove: Iterable[Array[Byte]], toUpdate: Iterable[(Array[Byte], Array[Byte])]): Try[Unit] = Try { lock.writeLock().lock() val lastLsn = lsn // remember current LSN value val batch = db.createWriteBatch() val undoBatch = undo.createWriteBatch() try { toRemove.foreach(key => { batch.delete(key) if (keepVersions > 0) { val value = db.get(key) if (value != null) { // attempt to delete not existed key undoBatch.put(newLSN(), serializeUndo(versionID, key, value)) } } }) for ((key, v) <- toUpdate) { require(key.length != 0) // empty keys are not allowed if (keepVersions > 0) { val old = db.get(key) undoBatch.put(newLSN(), serializeUndo(versionID, key, old)) } batch.put(key, v) } if (keepVersions > 0) { if (lsn == lastLsn) { // no records were written for this version: generate dummy record undoBatch.put(newLSN(), serializeUndo(versionID, new Array[Byte](0), null)) } undo.write(undoBatch, writeOptions) if (lastVersion.isEmpty || !versionID.sameElements(lastVersion.get)) { versions += versionID versionLsn += lastLsn + 1 // first LSN for this version cleanStart(keepVersions) } } else { //keepVersions = 0 if (lastVersion.isEmpty || !versionID.sameElements(lastVersion.get)) { batch.put(last_version_key, versionID) versions.clear() versions += versionID if (versionLsn.isEmpty) { versionLsn += lastLsn } } } db.write(batch, writeOptions) lastVersion = Some(versionID) } finally { // Make sure you close the batch to avoid resource leaks. batch.close() undoBatch.close() lock.writeLock().unlock() } } def insert(versionID: VersionID, toInsert: Seq[(K, V)]): Try[Unit] = update(versionID, Seq.empty, toInsert) def remove(versionID: VersionID, toRemove: Seq[K]): Try[Unit] = update(versionID, toRemove, Seq.empty) // Keep last "count"+1 versions and remove undo information for older versions private def cleanStart(count: Int): Unit = { val deteriorated = versions.size - count - 1 if (deteriorated >= 0) { val fromLsn = versionLsn(0) val tillLsn = if (deteriorated+1 < versions.size) versionLsn(deteriorated+1) else lsn+1 val batch = undo.createWriteBatch() try { for (lsn <- fromLsn until tillLsn) { batch.delete(encodeLSN(lsn)) } undo.write(batch, writeOptions) } finally { batch.close() } versions.remove(0, deteriorated) versionLsn.remove(0, deteriorated) if (count == 0) { db.put(last_version_key, versions(0)) } } } def clean(count: Int): Unit = { lock.writeLock().lock() try { cleanStart(count) } finally { lock.writeLock().unlock() } undo.resumeCompactions() db.resumeCompactions() } def cleanStop(): Unit = { undo.suspendCompactions() db.suspendCompactions() } override def close(): Unit = { lock.writeLock().lock() try { undo.close() db.close() } finally { lock.writeLock().unlock() } } // Rollback to the specified version: undo all changes done after specified version def rollbackTo(versionID: VersionID): Try[Unit] = Try { lock.writeLock().lock() try { val versionIndex = versions.indexWhere(_.sameElements(versionID)) if (versionIndex >= 0) { if (versionIndex != versions.size-1) { val batch = db.createWriteBatch() val undoBatch = undo.createWriteBatch() var nUndoRecords: Long = 0 val iterator = undo.iterator() var lastLsn: LSN = 0 try { var undoing = true iterator.seekToFirst() while (undoing && iterator.hasNext) { val entry = iterator.next() val undo = deserializeUndo(entry.getValue) if (undo.versionID.sameElements(versionID)) { undoing = false lastLsn = decodeLSN(entry.getKey) } else { undoBatch.delete(entry.getKey) nUndoRecords += 1 if (undo.value == null) { if (undo.key.length != 0) { // dummy record batch.delete(undo.key) } } else { batch.put(undo.key, undo.value) } } } db.write(batch, writeOptions) undo.write(undoBatch, writeOptions) } finally { // Make sure you close the batch to avoid resource leaks. iterator.close() batch.close() undoBatch.close() } val nVersions = versions.size require((versionIndex + 1 == nVersions && nUndoRecords == 0) || (versionIndex + 1 < nVersions && lsn - versionLsn(versionIndex + 1) + 1 == nUndoRecords)) versions.remove(versionIndex + 1, nVersions - versionIndex - 1) versionLsn.remove(versionIndex + 1, nVersions - versionIndex - 1) lsn -= nUndoRecords // reuse deleted LSN to avoid holes in LSNs require(lastLsn == 0 || lsn == lastLsn) require(versions.last.sameElements(versionID)) lastVersion = Some(versionID) } else { require(lastVersion.get.sameElements(versionID)) } } else { throw new NoSuchElementException("versionID not found, can not rollback") } } finally { lock.writeLock().unlock() } } def rollbackVersions(): Iterable[VersionID] = { versions.reverse } }
ccellado/ergo
ergo-wallet/src/main/scala/org/ergoplatform/wallet/boxes/ReemissionData.scala
package org.ergoplatform.wallet.boxes import scorex.util.ModifierId /** * Re-emission settings which are needed in order to construct transactions * (any of them, except ones using re-emission contract (as this class does not have all the needed data to * obtain re-emission contract. However, it is possible to use re-emission contracts in apps using Ergo Wallet API * by providing re-emission contract from outside). */ case class ReemissionData(reemissionNftId: ModifierId, reemissionTokenId: ModifierId)
ccellado/ergo
src/test/scala/org/ergoplatform/http/routes/NipopowApiRoutesSpec.scala
<reponame>ccellado/ergo package org.ergoplatform.http.routes import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.{Route, ValidationRejection} import akka.http.scaladsl.testkit.ScalatestRouteTest import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport import io.circe.Json import org.ergoplatform.http.api.NipopowApiRoute import org.ergoplatform.utils.Stubs import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class NipopowApiRoutesSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with FailFastCirceSupport with Stubs { private val route: Route = NipopowApiRoute(nodeViewRef, utxoReadersRef, settings).route it should "return proof for min superchain & suffix length" in { Get("/nipopow/proof/1/1") ~> route ~> check { status shouldBe StatusCodes.OK val json = responseAs[Json] log.info(s"Received nipopow proof response : $json") val c = json.hcursor c.downField("prefix").as[List[Json]].right.get shouldNot be(empty) } } it should "proof request with invalid minimum and suffix length" in { Get("/nipopow/proof/12/24") ~> route ~> check { status shouldBe StatusCodes.BadRequest } } it should "proof request with missing headerId" in { Get("/nipopow/proof/1/1/05bf63aa1ecfc9f4e3fadc993f87b33edb4d58e151c1891816d734dd5a0e2e09") ~> route ~> check { status shouldBe StatusCodes.BadRequest } } it should "proof request with invalid headerId" in { Get("/nipopow/proof/1/1/x") ~> route ~> check { rejection shouldEqual ValidationRejection("Wrong modifierId format", None) } } it should "return proof for min superchain & suffix length & header id" in { val existingHeaderId = history.bestHeaderOpt.get.id Get(s"/nipopow/proof/1/1/$existingHeaderId") ~> route ~> check { status shouldBe StatusCodes.OK val json = responseAs[Json] log.info(s"Received nipopow proof response : $json") val c = json.hcursor c.downField("prefix").as[List[Json]].right.get shouldNot be(empty) } } it should "get popow header by id" in { val existingHeaderId = history.bestHeaderOpt.get.id Get(s"/nipopow/popowHeaderById/$existingHeaderId") ~> route ~> check { status shouldBe StatusCodes.OK val json = responseAs[Json] log.info(s"Received popow header response : $json") val c = json.hcursor c.downField("interlinks").as[List[Json]].right.get shouldNot be(empty) } } it should "get popow header by height" in { Get(s"/nipopow/popowHeaderByHeight/2") ~> route ~> check { status shouldBe StatusCodes.OK val json = responseAs[Json] log.info(s"Received popow header response : $json") val c = json.hcursor c.downField("interlinks").as[List[Json]].right.get shouldNot be(empty) } } }
ccellado/ergo
src/test/scala/scorex/testkit/properties/state/StateApplicationTest.scala
package scorex.testkit.properties.state import org.ergoplatform.modifiers.ErgoPersistentModifier import org.ergoplatform.nodeView.state.{DigestState, ErgoState} import org.scalacheck.Gen import scala.collection.mutable.ListBuffer trait StateApplicationTest[ST <: ErgoState[ST]] extends StateTests[ST] { lazy val stateGenWithValidModifier: Gen[(ST, ErgoPersistentModifier)] = { stateGen.map { s => (s, semanticallyValidModifier(s)) } } lazy val stateGenWithInvalidModifier: Gen[(ST, ErgoPersistentModifier)] = { stateGen.map { s => (s, semanticallyInvalidModifier(s))} } private def propertyNameGenerator(propName: String): String = s"StateTests: $propName" property(propertyNameGenerator("apply modifier")) { forAll(stateGenWithValidModifier) { case (s, m) => val ver = s.version val sTry = s.applyModifier(m, None)(_ => ()) sTry.isSuccess shouldBe true sTry.get.version == ver shouldBe false } } property(propertyNameGenerator("do not apply same valid modifier twice")) { forAll(stateGenWithValidModifier) { case (s, m) => val ver = s.version val sTry = s.applyModifier(m, None)(_ => ()) sTry.isSuccess shouldBe true val s2 = sTry.get s2.version == ver shouldBe false s2.applyModifier(m, None)(_ => ()).isSuccess shouldBe false } } property(propertyNameGenerator("do not apply invalid modifier")) { forAll(stateGenWithInvalidModifier) { case (s, m) => val sTry = s.applyModifier(m, None)(_ => ()) sTry.isSuccess shouldBe false } } property(propertyNameGenerator("apply valid modifier after rollback")) { forAll(stateGenWithValidModifier) { case (s, m) => val ver = s.version s.store.setKeepVersions(10) val sTry = s.applyModifier(m, Some(0))(_ => ()) sTry.isSuccess shouldBe true val s2 = sTry.get s2.version == ver shouldBe false val ver2 = s2.version val s3 = s2.rollbackTo(ver).get s3.version == ver shouldBe true val sTry2 = s3.applyModifier(m, None)(_ => ()) sTry2.isSuccess shouldBe true val s4 = sTry2.get s4.version == ver shouldBe false s4.version == ver2 shouldBe true } } property(propertyNameGenerator("application after rollback is possible")) { forAll(stateGen) { s => s.store.setKeepVersions(10) val maxRollbackDepth = s match { case ds: DigestState => ds.store.rollbackVersions().size case _ => 10 } @SuppressWarnings(Array("org.wartremover.warts.OptionPartial")) val rollbackDepth = Gen.chooseNum(1, maxRollbackDepth).sample.get val buf = new ListBuffer[ErgoPersistentModifier]() val ver = s.version val s2 = (0 until rollbackDepth).foldLeft(s) { case (state, _) => val modifier = semanticallyValidModifier(state) buf += modifier val sTry = state.applyModifier(modifier, Some(rollbackDepth))(_ => ()) sTry shouldBe 'success sTry.get } val lastVersion = s2.version val rollbackTry = s2.rollbackTo(ver) rollbackTry.toOption shouldBe defined val s3 = rollbackTry.get s3.version == ver shouldBe true val s4 = buf.foldLeft(s3) { case (state, m) => val sTry = state.applyModifier(m, Some(0))(_ => ()) sTry shouldBe 'success sTry.get } s4.version == lastVersion shouldBe true } } }
ccellado/ergo
src/main/scala/org/ergoplatform/nodeView/wallet/scanning/ScanningPredicate.scala
<reponame>ccellado/ergo package org.ergoplatform.nodeView.wallet.scanning import org.ergoplatform.ErgoBox import scorex.util.encode.Base16 import sigmastate.Values.EvaluatedValue import sigmastate.{SType, Values} /** * Basic interface for box scanning predicate functionality * * See EIP-0001 for details (https://github.com/ergoplatform/eips/blob/master/eip-0001.md) */ sealed trait ScanningPredicate { def filter(box: ErgoBox): Boolean } /** * Scanning predicate to track boxes which contain a register which, in turn, contains certain value * (wildcard matching, so register contains e.g. value bytes) * * @param regId - register identifier * @param value - sigma-value used in track */ case class ContainsScanningPredicate(regId: ErgoBox.RegisterId, value: EvaluatedValue[SType]) extends ScanningPredicate { override def filter(box: ErgoBox): Boolean = { value match { case Values.ByteArrayConstant(bytes) => box.get(regId).exists { _ match { case Values.ByteArrayConstant(arr) => arr.toArray.containsSlice(bytes.toArray) case _ => false } } case _ => false } } override def equals(obj: Any): Boolean = obj match { case other: ContainsScanningPredicate => other.regId == regId && other.value == value case _ => false } override def toString: String = s"ContainsScanningPredicate($regId, $value)" override def hashCode(): Int = regId.hashCode() * 31 + value.hashCode() } /** * Scanning predicate to track boxes which contain a register which, in turn, contains certain bytes * (exact matching, so register contains exactly bytes) * * @param regId - register identifier * @param value - bytes to track */ case class EqualsScanningPredicate(regId: ErgoBox.RegisterId, value: EvaluatedValue[SType]) extends ScanningPredicate { //todo: try to remove boilerplate below override def filter(box: ErgoBox): Boolean = { value match { case Values.ByteArrayConstant(bytes) => if(box.get(regId).isDefined && box.get(regId).get.tpe.equals(value.tpe)) { box.get(regId).exists { _ match { case Values.ByteArrayConstant(arr) => arr.toArray.sameElements(bytes.toArray) case _ => false } } } else { false } case Values.GroupElementConstant(groupElement) => box.get(regId).exists { _ match { case Values.GroupElementConstant(ge) => groupElement == ge case _ => false } } case Values.BooleanConstant(bool) => box.get(regId).exists { _ match { case Values.BooleanConstant(b) => bool == b case _ => false } } case Values.IntConstant(int) => box.get(regId).exists { _ match { case Values.IntConstant(i) => int == i case _ => false } } case Values.LongConstant(long) => box.get(regId).exists { _ match { case Values.IntConstant(l) => long == l case _ => false } } case _ => false } } override def equals(obj: Any): Boolean = obj match { case other: EqualsScanningPredicate => other.regId == regId && other.value == value case _ => false } override def hashCode(): Int = regId.hashCode() * 31 + value.hashCode() override def toString: String = s"EqualsScanningPredicate($regId, $value)" } /** * Scanning predicate to track boxes which certain asset. * * @param assetId - bytes to track */ case class ContainsAssetPredicate(assetId: ErgoBox.TokenId) extends ScanningPredicate { override def filter(box: ErgoBox): Boolean = { box.additionalTokens.exists(_._1.sameElements(assetId)) } override def equals(obj: Any): Boolean = obj match { case other: ContainsAssetPredicate => other.assetId.sameElements(assetId) case _ => false } override def hashCode(): Int = assetId.toSeq.hashCode() override def toString: String = s"ContainsAssetPredicate(${Base16.encode(assetId)})" } /** * Scanning predicate to track boxes which satisfy all the sub-predicates at the same time. * * @param subPredicates - arbitrary number of sub-predicates */ case class AndScanningPredicate(subPredicates: ScanningPredicate*) extends ScanningPredicate { override def filter(box: ErgoBox): Boolean = subPredicates.forall(p => p.filter(box)) } /** * Scanning predicate to track boxes which satisfy any of the sub-predicates. * * @param subPredicates - arbitrary number of sub-predicates */ case class OrScanningPredicate(subPredicates: ScanningPredicate*) extends ScanningPredicate { override def filter(box: ErgoBox): Boolean = subPredicates.exists(p => p.filter(box)) }
ccellado/ergo
src/main/scala/org/ergoplatform/nodeView/wallet/ErgoWalletReader.scala
package org.ergoplatform.nodeView.wallet import java.util.concurrent.TimeUnit import akka.actor.ActorRef import akka.pattern.ask import akka.util.Timeout import org.ergoplatform.ErgoBox.BoxId import org.ergoplatform.{ErgoBox, P2PKAddress} import org.ergoplatform.modifiers.mempool.{ErgoTransaction, UnsignedErgoTransaction} import org.ergoplatform.nodeView.wallet.ErgoWalletActor._ import org.ergoplatform.nodeView.wallet.ErgoWalletService.DeriveNextKeyResult import org.ergoplatform.nodeView.wallet.persistence.WalletDigest import org.ergoplatform.nodeView.wallet.scanning.ScanRequest import org.ergoplatform.nodeView.wallet.requests.{BoxesRequest, ExternalSecret, TransactionGenerationRequest} import org.ergoplatform.wallet.interface4j.SecretString import org.ergoplatform.wallet.boxes.ChainStatus import org.ergoplatform.wallet.boxes.ChainStatus.{OffChain, OnChain} import org.ergoplatform.wallet.Constants.ScanId import org.ergoplatform.wallet.interpreter.TransactionHintsBag import scorex.core.transaction.wallet.VaultReader import scorex.util.ModifierId import sigmastate.Values.SigmaBoolean import scala.concurrent.Future import scala.util.Try trait ErgoWalletReader extends VaultReader { val walletActor: ActorRef private implicit val timeout: Timeout = Timeout(60, TimeUnit.SECONDS) /** Returns the Future generated mnemonic phrase. * @param pass storage encription password * @param mnemonicPassOpt mnemonic encription password * @return menmonic phrase for the new wallet */ def initWallet(pass: SecretString, mnemonicPassOpt: Option[SecretString]): Future[Try[SecretString]] = (walletActor ? InitWallet(pass, mnemonicPassOpt)).mapTo[Try[SecretString]] def restoreWallet(encryptionPass: SecretString, mnemonic: SecretString, mnemonicPassOpt: Option[SecretString] = None): Future[Try[Unit]] = (walletActor ? RestoreWallet(mnemonic, mnemonicPassOpt, encryptionPass)).mapTo[Try[Unit]] def unlockWallet(pass: SecretString): Future[Try[Unit]] = (walletActor ? UnlockWallet(pass)).mapTo[Try[Unit]] def lockWallet(): Unit = walletActor ! LockWallet def rescanWallet(fromHeight: Int): Future[Try[Unit]] = (walletActor ? RescanWallet(fromHeight)).mapTo[Try[Unit]] def getWalletStatus: Future[WalletStatus] = (walletActor ? GetWalletStatus).mapTo[WalletStatus] def checkSeed(mnemonic: SecretString, mnemonicPassOpt: Option[SecretString] = None): Future[Boolean] = { (walletActor ? CheckSeed(mnemonic, mnemonicPassOpt)).mapTo[Boolean] } def deriveKey(path: String): Future[Try[P2PKAddress]] = (walletActor ? DeriveKey(path)).mapTo[Try[P2PKAddress]] def deriveNextKey: Future[DeriveNextKeyResult] = (walletActor ? DeriveNextKey).mapTo[DeriveNextKeyResult] def balances(chainStatus: ChainStatus): Future[WalletDigest] = (walletActor ? ReadBalances(chainStatus)).mapTo[WalletDigest] def confirmedBalances: Future[WalletDigest] = balances(OnChain) def balancesWithUnconfirmed: Future[WalletDigest] = balances(OffChain) def publicKeys(from: Int, to: Int): Future[Seq[P2PKAddress]] = (walletActor ? ReadPublicKeys(from, to)).mapTo[Seq[P2PKAddress]] def walletBoxes(unspentOnly: Boolean, considerUnconfirmed: Boolean): Future[Seq[WalletBox]] = (walletActor ? GetWalletBoxes(unspentOnly, considerUnconfirmed)).mapTo[Seq[WalletBox]] def scanUnspentBoxes(scanId: ScanId, considerUnconfirmed: Boolean = false): Future[Seq[WalletBox]] = (walletActor ? GetScanUnspentBoxes(scanId, considerUnconfirmed)).mapTo[Seq[WalletBox]] def scanSpentBoxes(scanId: ScanId): Future[Seq[WalletBox]] = (walletActor ? GetScanSpentBoxes(scanId)).mapTo[Seq[WalletBox]] def updateChangeAddress(address: P2PKAddress): Future[Unit] = walletActor.askWithStatus(UpdateChangeAddress(address)).mapTo[Unit] def transactions: Future[Seq[AugWalletTransaction]] = (walletActor ? GetTransactions).mapTo[Seq[AugWalletTransaction]] def transactionById(id: ModifierId): Future[Option[AugWalletTransaction]] = (walletActor ? GetTransaction(id)).mapTo[Option[AugWalletTransaction]] def generateTransaction(requests: Seq[TransactionGenerationRequest], inputsRaw: Seq[String] = Seq.empty, dataInputsRaw: Seq[String] = Seq.empty): Future[Try[ErgoTransaction]] = (walletActor ? GenerateTransaction(requests, inputsRaw, dataInputsRaw, sign = true)).mapTo[Try[ErgoTransaction]] def generateCommitmentsFor(unsignedErgoTransaction: UnsignedErgoTransaction, externalSecretsOpt: Option[Seq[ExternalSecret]], boxesToSpend: Option[Seq[ErgoBox]], dataBoxes: Option[Seq[ErgoBox]]): Future[GenerateCommitmentsResponse] = (walletActor ? GenerateCommitmentsFor(unsignedErgoTransaction, externalSecretsOpt, boxesToSpend, dataBoxes)) .mapTo[GenerateCommitmentsResponse] def generateUnsignedTransaction(requests: Seq[TransactionGenerationRequest], inputsRaw: Seq[String] = Seq.empty, dataInputsRaw: Seq[String] = Seq.empty): Future[Try[UnsignedErgoTransaction]] = (walletActor ? GenerateTransaction(requests, inputsRaw, dataInputsRaw, sign = false)).mapTo[Try[UnsignedErgoTransaction]] def signTransaction(tx: UnsignedErgoTransaction, secrets: Seq[ExternalSecret], hints: TransactionHintsBag, boxesToSpend: Option[Seq[ErgoBox]], dataBoxes: Option[Seq[ErgoBox]]): Future[Try[ErgoTransaction]] = (walletActor ? SignTransaction(tx, secrets, hints, boxesToSpend, dataBoxes)).mapTo[Try[ErgoTransaction]] def extractHints(tx: ErgoTransaction, real: Seq[SigmaBoolean], simulated: Seq[SigmaBoolean], boxesToSpend: Option[Seq[ErgoBox]], dataBoxes: Option[Seq[ErgoBox]]): Future[ExtractHintsResult] = (walletActor ? ExtractHints(tx, real, simulated, boxesToSpend, dataBoxes)).mapTo[ExtractHintsResult] def addScan(appRequest: ScanRequest): Future[AddScanResponse] = (walletActor ? AddScan(appRequest)).mapTo[AddScanResponse] def removeScan(scanId: ScanId): Future[RemoveScanResponse] = (walletActor ? RemoveScan(scanId)).mapTo[RemoveScanResponse] def readScans(): Future[ReadScansResponse] = (walletActor ? ReadScans).mapTo[ReadScansResponse] def stopTracking(scanId: ScanId, boxId: BoxId): Future[StopTrackingResponse] = (walletActor ? StopTracking(scanId, boxId)).mapTo[StopTrackingResponse] def addBox(box: ErgoBox, scanIds: Set[ScanId]): Future[AddBoxResponse] = (walletActor ? AddBox(box, scanIds)).mapTo[AddBoxResponse] def collectBoxes(request: BoxesRequest): Future[ReqBoxesResponse] = (walletActor ? CollectWalletBoxes(request.targetBalance, request.targetAssets)).mapTo[ReqBoxesResponse] def transactionsByScanId(scanId: ScanId, includeUnconfirmed: Boolean): Future[ScanRelatedTxsResponse] = (walletActor ? GetScanTransactions(scanId, includeUnconfirmed)).mapTo[ScanRelatedTxsResponse] /** * Get filtered scan-related txs * @param scanIds - scan identifiers * @param minHeight - minimal tx inclusion height * @param maxHeight - maximal tx inclusion height * @param minConfNum - minimal confirmations number * @param maxConfNum - maximal confirmations number * @param includeUnconfirmed - whether to include transactions from mempool that match given scanId */ def filteredScanTransactions(scanIds: List[ScanId], minHeight: Int, maxHeight: Int, minConfNum: Int, maxConfNum: Int, includeUnconfirmed: Boolean): Future[Seq[AugWalletTransaction]] = (walletActor ? GetFilteredScanTxs(scanIds, minHeight, maxHeight, minConfNum, maxConfNum, includeUnconfirmed)).mapTo[Seq[AugWalletTransaction]] }
ccellado/ergo
ergo-wallet/src/main/scala/org/ergoplatform/wallet/boxes/BoxSelector.scala
package org.ergoplatform.wallet.boxes import org.ergoplatform.ErgoBoxAssets import org.ergoplatform.SigmaConstants.MaxBoxSize import org.ergoplatform.wallet.TokensMap import org.ergoplatform.wallet.boxes.BoxSelector.{BoxSelectionError, BoxSelectionResult} import scorex.util.ScorexLogging /** * An interface which is exposing a method to select unspent boxes according to target amounts in Ergo tokens and * assets and possible user-defined filter. The interface could have many instantiations implementing * different strategies. */ trait BoxSelector extends ScorexLogging { /** * Re-emission settings, if provided. Used to consider re-emission tokens * stored in boxes being spent. */ def reemissionDataOpt: Option[ReemissionData] /** * A method which is selecting boxes to spend in order to collect needed amounts of ergo tokens and assets. * * @param inputBoxes - unspent boxes to choose from. * @param filterFn - user-provided filter function for boxes. From inputBoxes, only ones to be chosen for which * filterFn(box) returns true * @param targetBalance - ergo balance to be met * @param targetAssets - assets balances to be met * @return Left(error) if select() is failing to pick appropriate boxes, otherwise Right(res), where res contains boxes * to spend as well as monetary values and assets for boxes containing change * (wrapped in a special BoxSelectionResult class). */ def select[T <: ErgoBoxAssets](inputBoxes: Iterator[T], filterFn: T => Boolean, targetBalance: Long, targetAssets: TokensMap): Either[BoxSelectionError, BoxSelectionResult[T]] def select[T <: ErgoBoxAssets](inputBoxes: Iterator[T], targetBalance: Long, targetAssets: TokensMap ): Either[BoxSelectionError, BoxSelectionResult[T]] = select(inputBoxes, _ => true, targetBalance, targetAssets) /** * Helper method to get total amount of re-emission tokens stored in input `boxes`. */ def reemissionAmount[T <: ErgoBoxAssets](boxes: Seq[T]): Long = { reemissionDataOpt.map { reemissionData => boxes .flatMap(_.tokens.get(reemissionData.reemissionTokenId)) .sum }.getOrElse(0L) } } object BoxSelector { // from https://github.com/ergoplatform/ergo/blob/2ce78a0380977b8ca354518edca93a5269ac9f53/src/main/scala/org/ergoplatform/settings/Parameters.scala#L258-L258 private val MinValuePerByteDefault = 30 * 12 val MinBoxValue: Long = (MaxBoxSize.value / 2L) * MinValuePerByteDefault /** * Factor which is showing how many inputs selector is going through to optimize inputs. * Bigger factor is slowing down inputs selection but minimizing chance of transaction failure. */ val ScanDepthFactor = 300 final case class BoxSelectionResult[T <: ErgoBoxAssets](boxes: Seq[T], changeBoxes: Seq[ErgoBoxAssets]) /** * Returns how much ERG can be taken from a box when it is spent. * * @param box - box which may be spent * @param reemissionDataOpt - re-emission data, if box selector is checking re-emission rules * @return if no re-emission tokens are there, returns ERG value of the box, otherwise, * subtract amount of re-emission tokens in the box from its ERG value. */ def valueOf[T <: ErgoBoxAssets](box: T, reemissionDataOpt: Option[ReemissionData]): Long = { reemissionDataOpt match { case Some(reemissionData) => box.value - box.tokens.getOrElse(reemissionData.reemissionTokenId, 0L) case None => box.value } } trait BoxSelectionError { def message: String } }
ccellado/ergo
src/main/scala/org/ergoplatform/settings/WalletSettings.scala
package org.ergoplatform.settings import org.ergoplatform.wallet.settings.SecretStorageSettings case class WalletSettings(secretStorage: SecretStorageSettings, seedStrengthBits: Int, mnemonicPhraseLanguage: String, usePreEip3Derivation: Boolean = false, keepSpentBoxes: Boolean = false, defaultTransactionFee: Long = 1000000L, dustLimit: Option[Long] = None, maxInputs: Int = 100, optimalInputs: Int = 3, testMnemonic: Option[String] = None, testKeysQty: Option[Int] = None, // Some(Seq(x)) burns all except x, Some(Seq.empty) burns all, None ignores that feature tokensWhitelist: Option[Seq[String]] = None, checkEIP27: Boolean = false)
ccellado/ergo
src/test/scala/org/ergoplatform/local/MempoolAuditorSpec.scala
package org.ergoplatform.local import akka.actor.{ActorRef, ActorSystem} import akka.testkit.{TestActorRef, TestProbe} import org.ergoplatform.{ErgoAddressEncoder, ErgoScriptPredef} import org.ergoplatform.nodeView.state.ErgoState import org.ergoplatform.nodeView.state.wrapped.WrappedUtxoState import org.ergoplatform.settings.{Algos, Constants, ErgoSettings} import org.ergoplatform.utils.fixtures.NodeViewFixture import org.ergoplatform.utils.{ErgoTestHelpers, MempoolTestHelpers, NodeViewTestOps, RandomWrapper} import org.scalatest.flatspec.AnyFlatSpec import org.ergoplatform.nodeView.ErgoNodeViewHolder.ReceivableMessages.LocallyGeneratedTransaction import scorex.core.network.NetworkController.ReceivableMessages.SendToNetwork import org.ergoplatform.network.ErgoNodeViewSynchronizer.ReceivableMessages.{ChangedMempool, ChangedState, FailedTransaction, SuccessfulTransaction} import sigmastate.Values.ErgoTree import sigmastate.eval.{IRContext, RuntimeIRContext} import sigmastate.interpreter.Interpreter.emptyEnv import scala.concurrent.duration._ import scala.util.Random import sigmastate.lang.Terms.ValueOps import sigmastate.serialization.ErgoTreeSerializer class MempoolAuditorSpec extends AnyFlatSpec with NodeViewTestOps with ErgoTestHelpers with MempoolTestHelpers { implicit lazy val context: IRContext = new RuntimeIRContext val cleanupDuration: FiniteDuration = 3.seconds val settingsToTest: ErgoSettings = settings.copy( nodeSettings = settings.nodeSettings.copy( mempoolCleanupDuration = cleanupDuration, rebroadcastCount = 1 )) val fixture = new NodeViewFixture(settingsToTest, parameters) val newTx: Class[SuccessfulTransaction] = classOf[SuccessfulTransaction] it should "remove transactions which become invalid" in { import fixture._ val testProbe = new TestProbe(actorSystem) actorSystem.eventStream.subscribe(testProbe.ref, newTx) val (us, bh) = createUtxoState(parameters) val genesis = validFullBlock(parentOpt = None, us, bh) val wusAfterGenesis = WrappedUtxoState(us, bh, stateConstants, parameters).applyModifier(genesis) { mod => nodeViewHolderRef ! mod } .get applyBlock(genesis) shouldBe 'success getRootHash shouldBe Algos.encode(wusAfterGenesis.rootHash) val boxes = ErgoState.newBoxes(genesis.transactions).find(_.ergoTree == Constants.TrueLeaf) boxes.nonEmpty shouldBe true val script = s"{sigmaProp(HEIGHT == ${genesis.height})}" val prop = ErgoScriptPredef.compileWithCosting(emptyEnv, script, ErgoAddressEncoder.MainnetNetworkPrefix) val tree = ErgoTree.fromProposition(prop.asSigmaProp) val bs = ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(tree) ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bs) shouldBe tree val validTx = validTransactionFromBoxes(boxes.toIndexedSeq, outputsProposition = tree) val temporarilyValidTx = validTransactionFromBoxes(validTx.outputs, outputsProposition = proveDlogGen.sample.get) subscribeEvents(classOf[FailedTransaction]) nodeViewHolderRef ! LocallyGeneratedTransaction(validTx) testProbe.expectMsgClass(cleanupDuration, newTx) nodeViewHolderRef ! LocallyGeneratedTransaction(temporarilyValidTx) testProbe.expectMsgClass(cleanupDuration, newTx) getPoolSize shouldBe 2 val _: ActorRef = MempoolAuditorRef(nodeViewHolderRef, nodeViewHolderRef, settingsToTest) // include first transaction in the block val block = validFullBlock(Some(genesis), wusAfterGenesis, Seq(validTx)) applyBlock(block) shouldBe 'success getPoolSize shouldBe 1 // first tx removed from pool during node view update scorex.core.utils.untilTimeout(cleanupDuration * 4, 100.millis) { getPoolSize shouldBe 0 // another tx invalidated by `MempoolAuditor` } } it should "rebroadcast transactions correctly" in { val (us0, bh0) = createUtxoState(parameters) val (txs0, bh1) = validTransactionsFromBoxHolder(bh0) val b1 = validFullBlock(None, us0, txs0) val us = us0.applyModifier(b1, None)(_ => ()).get val bxs = bh1.boxes.values.toList.filter(_.proposition != genesisEmissionBox.proposition) val txs = validTransactionsFromBoxes(200000, bxs, new RandomWrapper)._1 implicit val system = ActorSystem() val probe = TestProbe() val auditor: ActorRef = TestActorRef(new MempoolAuditor(probe.ref, probe.ref, settingsToTest)) val coin = Random.nextBoolean() def sendState(): Unit = auditor ! ChangedState(us) def sendPool(): Unit = auditor ! ChangedMempool(new FakeMempool(txs)) if (coin) { sendPool() sendState() } else { sendState() sendPool() } probe.expectMsgType[SendToNetwork] } }
ccellado/ergo
src/main/scala/org/ergoplatform/settings/ErgoSettings.scala
<gh_stars>0 package org.ergoplatform.settings import java.io.{File, FileOutputStream} import java.nio.channels.Channels import com.typesafe.config.{Config, ConfigFactory, ConfigValueFactory} import net.ceedubs.ficus.Ficus._ import net.ceedubs.ficus.readers.ArbitraryTypeReader._ import org.ergoplatform.mining.groupElemFromBytes import org.ergoplatform.nodeView.state.StateType.Digest import org.ergoplatform.{ErgoAddressEncoder, ErgoApp, P2PKAddress} import scorex.core.settings.{ScorexSettings, SettingsReaders} import scorex.util.ScorexLogging import scorex.util.encode.Base16 import sigmastate.basics.DLogProtocol.ProveDlog import scala.util.Try case class ErgoSettings(directory: String, networkType: NetworkType, chainSettings: ChainSettings, nodeSettings: NodeConfigurationSettings, scorexSettings: ScorexSettings, walletSettings: WalletSettings, cacheSettings: CacheSettings, votingTargets: VotingTargets = VotingTargets.empty) { val addressEncoder = ErgoAddressEncoder(chainSettings.addressPrefix) val miningRewardDelay: Int = chainSettings.monetary.minerRewardDelay val miningPubKey: Option[ProveDlog] = nodeSettings.miningPubKeyHex .flatMap { str => val keyBytes = Base16.decode(str) .getOrElse(throw new Error(s"Failed to parse `miningPubKeyHex = ${nodeSettings.miningPubKeyHex}`")) Try(ProveDlog(groupElemFromBytes(keyBytes))) .orElse(addressEncoder.fromString(str).collect { case p2pk: P2PKAddress => p2pk.pubkey }) .toOption } } object ErgoSettings extends ScorexLogging with PowSchemeReaders with NodeConfigurationReaders with SettingsReaders { val configPath: String = "ergo" val scorexConfigPath: String = "scorex" def read(args: Args = Args.empty): ErgoSettings = { fromConfig(readConfig(args), args.networkTypeOpt) } def fromConfig(config: Config, desiredNetworkTypeOpt: Option[NetworkType] = None): ErgoSettings = { val directory = config.as[String](s"$configPath.directory") val networkTypeName = config.as[String](s"$configPath.networkType") val networkType = NetworkType.fromString(networkTypeName) .getOrElse(throw new Error(s"Unknown `networkType = $networkTypeName`")) val nodeSettings = config.as[NodeConfigurationSettings](s"$configPath.node") val chainSettings = config.as[ChainSettings](s"$configPath.chain") val walletSettings = config.as[WalletSettings](s"$configPath.wallet") val cacheSettings = config.as[CacheSettings](s"$configPath.cache") val scorexSettings = config.as[ScorexSettings](scorexConfigPath) val votingTargets = VotingTargets.fromConfig(config) if (nodeSettings.stateType == Digest && nodeSettings.mining) { log.error("Malformed configuration file was provided! Mining is not possible with digest state. Aborting!") ErgoApp.forceStopApplication() } consistentSettings( ErgoSettings( directory, networkType, chainSettings, nodeSettings, scorexSettings, walletSettings, cacheSettings, votingTargets ), desiredNetworkTypeOpt ) } // Helper method to read user-provided `configFile` with network-specific `fallbackConfig` // to be used for default fallback values before reference.conf (which is the last resort) private def configWithOverrides(configFile: File, fallbackConfig: Option[File]) = { val firstFallBack = fallbackConfig.map(ConfigFactory.parseFile).getOrElse(ConfigFactory.empty()) val cfg = ConfigFactory.parseFile(configFile) val keystorePath = "ergo.wallet.secretStorage.secretDir" // Check that user-provided Ergo directory exists and has write access (if provided at all) val userDirOpt = Try(cfg.getString("ergo.directory")).toOption userDirOpt.foreach { ergoDirName => require(new File(s"$ergoDirName").canWrite, s"Folder $ergoDirName does not exist or not writable") } // Check that user-provided wallet secret directory exists and has read access (if provided at all) val walletKeystoreDirOpt = Try(cfg.getString(keystorePath)).toOption walletKeystoreDirOpt.foreach { secretDirName => require(new File(s"$secretDirName").canRead, s"Folder $secretDirName does not exist or not readable") } val fullConfig = ConfigFactory .defaultOverrides() .withFallback(cfg) .withFallback(firstFallBack) .withFallback(ConfigFactory.defaultApplication()) .withFallback(ConfigFactory.defaultReference()) .resolve() // If user provided only ergo.directory but not ergo.wallet.secretStorage.secretDir in his config, // set ergo.wallet.secretStorage.secretDir like in reference.conf (so ergo.directory + "/wallet/keystore") // Otherwise, a user may have an issue, especially with Powershell it seems from reports. userDirOpt.map { userDir => if(walletKeystoreDirOpt.isEmpty) { fullConfig.withValue(keystorePath, ConfigValueFactory.fromAnyRef(userDir + "/wallet/keystore")) } else { fullConfig } }.getOrElse(fullConfig) } private def readConfig(args: Args): Config = { val networkConfigFileOpt = args.networkTypeOpt .flatMap { networkType => val confName = s"${networkType.verboseName}.conf" val classLoader = ClassLoader.getSystemClassLoader val destDir = System.getProperty("java.io.tmpdir") + "/" Option(classLoader.getResourceAsStream(confName)) .map { stream => val source = Channels.newChannel(stream) val fileOut = new File(destDir, confName) val dest = new FileOutputStream(fileOut) dest.getChannel.transferFrom(source, 0, Long.MaxValue) source.close() dest.close() sys.addShutdownHook { new File(destDir, confName).delete } fileOut } } val userConfigFileOpt = for { filePathOpt <- args.userConfigPathOpt file = new File(filePathOpt) if file.exists } yield file networkConfigFileOpt.flatMap(_ => args.networkTypeOpt).fold(log.warn("Running without network config"))( x => log.info(s"Running in ${x.verboseName} network mode")) (networkConfigFileOpt, userConfigFileOpt) match { // if no user config is supplied, the library will handle overrides/application/reference automatically case (Some(networkConfigFile), None) => log.warn("NO CONFIGURATION FILE WAS PROVIDED. STARTING WITH DEFAULT SETTINGS!") ConfigFactory .defaultOverrides() .withFallback(ConfigFactory.parseFile(networkConfigFile)) .withFallback(ConfigFactory.defaultReference()) .resolve() // application config needs to be resolved wrt both system properties *and* user-supplied config. case (Some(networkConfigFile), Some(file)) => configWithOverrides(file, Some(networkConfigFile)) case (None, Some(file)) => configWithOverrides(file, None) case (None, None) => ConfigFactory.load() } } private def consistentSettings(settings: ErgoSettings, desiredNetworkTypeOpt: Option[NetworkType]): ErgoSettings = { if (settings.nodeSettings.keepVersions < 0) { failWithError("nodeSettings.keepVersions should not be negative") } else if (!settings.nodeSettings.verifyTransactions && !settings.nodeSettings.stateType.requireProofs) { failWithError("Can not use UTXO state when nodeSettings.verifyTransactions is false") } else if (desiredNetworkTypeOpt.exists(_ != settings.networkType)) { failWithError(s"Malformed network config. Desired networkType is `${desiredNetworkTypeOpt.get}`, " + s"but one declared in config is `${settings.networkType}`") } else if(settings.networkType.isMainNet && settings.nodeSettings.mining && !settings.chainSettings.reemission.checkReemissionRules) { failWithError(s"Mining is enabled, but chain.reemission.checkReemissionRules = false , set it to true") } else { settings } } private def failWithError(msg: String): Nothing = { log.error(s"Stop application due to malformed configuration file: $msg") ErgoApp.forceStopApplication() } }
ccellado/ergo
src/test/scala/org/ergoplatform/reemission/ReemissionRulesSpec.scala
<filename>src/test/scala/org/ergoplatform/reemission/ReemissionRulesSpec.scala<gh_stars>0 package org.ergoplatform.reemission import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoLikeTransaction, ErgoScriptPredef, Input} import org.ergoplatform.settings.{MonetarySettings, ReemissionSettings} import org.ergoplatform.utils.{ErgoPropertyTest, ErgoTestConstants} import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.ModifierId import sigmastate.AvlTreeData import sigmastate.TrivialProp.TrueProp import sigmastate.eval.{Colls, Digest32RType, IRContext, RuntimeCosting} import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers.testBox import sigmastate.interpreter.Interpreter.emptyEnv import scala.util.{Failure, Success, Try} // done similarly to ErgoScriptPredefSpec in sigma repo class ReemissionRulesSpec extends ErgoPropertyTest with ErgoTestConstants { private val ms = MonetarySettings() private val checkReemissionRules: Boolean = true private val emissionNftId: ModifierId = ModifierId @@ "06f29034fb69b23d519f84c4811a19694b8cdc2ce076147aaa050276f0b840f4" private val reemissionTokenId: ModifierId = ModifierId @@ "01345f0ed87b74008d1c46aefd3e7ad6ee5909a2324f2899031cdfee3cc1e022" private val reemissionNftId: ModifierId = ModifierId @@ "06f2c3adfe52304543f7b623cc3fccddc0174a7db52452fef8e589adacdfdfee" private val activationHeight: Int = 0 private val reemissionStartHeight: Int = 100 private val injectionBoxBytesEncoded: ModifierId = ModifierId @@ "a0f9e1b5fb011003040005808098f4e9b5ca6a0402d1ed91c1b2a4730000730193c5a7c5b2a4730200f6ac0b0201345f0ed87b74008d1c46aefd3e7ad6ee5909a2324f2899031cdfee3cc1e02280808cfaf49aa53506f29034fb69b23d519f84c4811a19694b8cdc2ce076147aaa050276f0b840f40100325c3679e7e0e2f683e4a382aa74c2c1cb989bb6ad6a1d4b1c5a021d7b410d0f00" private val rs = ReemissionSettings(checkReemissionRules, emissionNftId, reemissionTokenId, reemissionNftId, activationHeight, reemissionStartHeight, injectionBoxBytesEncoded) private val rr = new ReemissionRules(rs) private val reemissionBoxAssets = Colls.fromMap[Digest32, Long]( Map((Digest32 @@ rs.reemissionNftIdBytes) -> 1L) ) private val fakeMessage = Blake2b256("Hello World") private def prover = new ContextEnrichingTestProvingInterpreter private def verifier = new ErgoLikeTestInterpreter private val prop = rr.reemissionBoxProp(ms) def checkRewardsTx(nextHeight: Int, pkBytes: Array[Byte], inputBoxes: IndexedSeq[ErgoBox], spendingTransaction: ErgoLikeTransaction, expectedValidity: Boolean) = { val ctx = ErgoLikeContextTesting( currentHeight = nextHeight, lastBlockUtxoRoot = AvlTreeData.dummy, minerPubkey = pkBytes, boxesToSpend = inputBoxes, spendingTransaction, self = inputBoxes.head, 1: Byte) //activated script version Try(prover.prove(emptyEnv, prop, ctx, fakeMessage).get) match { case Success(pr) => verifier.verify(emptyEnv, prop, ctx, pr, fakeMessage).get._1 shouldBe expectedValidity case Failure(e) if expectedValidity => throw new Exception("Unexpected exception thrown: ", e) case _ => } } class TestingIRContext extends IRContext with RuntimeCosting private implicit lazy val IR: TestingIRContext = new TestingIRContext { override val okPrintEvaluatedEntries: Boolean = false } ignore("reemission rules test vectors") { } property("reemissionBoxProp - spending path") { val minerPk = prover.dlogSecrets.head.publicImage val pkBytes = minerPk.pkBytes val minerProp = ErgoScriptPredef.rewardOutputScript(ms.minerRewardDelay, minerPk) val currentHeight = rs.reemissionStartHeight val nextHeight = currentHeight + 1 val initialErgValue = 1000000000000L val reemissionBox = testBox(initialErgValue, prop, currentHeight, reemissionBoxAssets.toArray, Map()) val reemissionReward = rr.reemissionRewardPerBlock val inputBoxes = IndexedSeq(reemissionBox) val inputs = inputBoxes.map(b => Input(b.id, emptyProverResult)) val newReemissionBox = new ErgoBoxCandidate(reemissionBox.value - reemissionReward, prop, nextHeight, reemissionBoxAssets) val minerBox = new ErgoBoxCandidate(reemissionReward, minerProp, nextHeight) val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox, minerBox)) // normal execution checkRewardsTx(nextHeight, pkBytes, inputBoxes, spendingTransaction, true) // miner tries to take too much from reemission contract val newReemissionBox2 = new ErgoBoxCandidate(reemissionBox.value - reemissionReward - 1, prop, nextHeight, reemissionBoxAssets) val minerBox2 = new ErgoBoxCandidate(reemissionReward + 1, minerProp, nextHeight) val spendingTransaction2 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox2, minerBox2)) checkRewardsTx(nextHeight, pkBytes, inputBoxes, spendingTransaction2, false) //... and it is not okay to take less even val newReemissionBox3 = new ErgoBoxCandidate(reemissionBox.value - reemissionReward + 1, prop, nextHeight, reemissionBoxAssets) val minerBox3 = new ErgoBoxCandidate(reemissionReward - 1, minerProp, nextHeight) val spendingTransaction3 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox3, minerBox3)) checkRewardsTx(nextHeight, pkBytes, inputBoxes, spendingTransaction3, false) // re-emission NFT must be preserved val newReemissionBox4 = new ErgoBoxCandidate(reemissionBox.value - reemissionReward, prop, nextHeight, Colls.emptyColl) val spendingTransaction4 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox4, minerBox)) checkRewardsTx(nextHeight, pkBytes, inputBoxes, spendingTransaction4, false) // not possible to charge before re-emission start val nextHeight5 = currentHeight - 10 val emissionBox5 = testBox(initialErgValue, prop, nextHeight5 - 1, reemissionBoxAssets.toArray, Map()) val inputBoxes5 = IndexedSeq(emissionBox5) val inputs5 = inputBoxes5.map(b => Input(b.id, emptyProverResult)) val newReemissionBox5 = new ErgoBoxCandidate(emissionBox5.value - reemissionReward, prop, nextHeight5, reemissionBoxAssets) val minerBox5 = new ErgoBoxCandidate(reemissionReward, minerProp, nextHeight5) val spendingTransaction5 = ErgoLikeTransaction(inputs5, IndexedSeq(newReemissionBox5, minerBox5)) checkRewardsTx(nextHeight5, pkBytes, inputBoxes5, spendingTransaction5, false) // can be spent to miner pubkey only val prover6 = new ContextEnrichingTestProvingInterpreter val minerPk6 = prover6.dlogSecrets.head.publicImage val pkBytes6 = minerPk6.pkBytes checkRewardsTx(nextHeight, pkBytes6, inputBoxes, spendingTransaction, false) // we modify reward delay here, not PK val minerProp7 = ErgoScriptPredef.rewardOutputScript(ms.minerRewardDelay - 1, minerPk) val minerBox7 = new ErgoBoxCandidate(reemissionReward, minerProp7, nextHeight) val spendingTransaction7 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox, minerBox7)) checkRewardsTx(nextHeight, pkBytes, inputBoxes, spendingTransaction7, false) } // also testing payToReemission contract property("reemissionBoxProp - merging path") { val minerPk = prover.dlogSecrets.head.publicImage val pkBytes = minerPk.pkBytes val rewardsProp = prop val pay2RewardsProp = rr.payToReemission val mergedValue = 100000000L val currentHeight = rs.reemissionStartHeight - 1 val pay2RBox = testBox(mergedValue, pay2RewardsProp, currentHeight, reemissionBoxAssets.toArray, Map()) val reemissionBox = testBox(mergedValue * 100, rewardsProp, currentHeight, reemissionBoxAssets.toArray, Map()) val inputBoxes = IndexedSeq(reemissionBox, pay2RBox) val inputs = inputBoxes.map(b => Input(b.id, emptyProverResult)) val feeValue = 10000000L // merging with 1 box - successful case val newReemissionBox = new ErgoBoxCandidate(reemissionBox.value + mergedValue - feeValue, prop, currentHeight, reemissionBoxAssets) val feeBox = new ErgoBoxCandidate(feeValue, TrueProp, currentHeight) val spendingTransaction = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox, feeBox)) checkRewardsTx(currentHeight, pkBytes, inputBoxes, spendingTransaction, true) // merging with 2 boxex - successful case val inputBoxes2 = IndexedSeq(reemissionBox, pay2RBox, pay2RBox) val inputs2 = inputBoxes2.map(b => Input(b.id, emptyProverResult)) val newReemissionBox2 = new ErgoBoxCandidate(reemissionBox.value + 2 * mergedValue - feeValue, prop, currentHeight, reemissionBoxAssets) val spendingTransaction2 = ErgoLikeTransaction(inputs2, IndexedSeq(newReemissionBox2, feeBox)) checkRewardsTx(currentHeight, pkBytes, inputBoxes, spendingTransaction2, true) // paying too high fee val newReemissionBox3 = new ErgoBoxCandidate(reemissionBox.value + mergedValue - feeValue - 1, prop, currentHeight, reemissionBoxAssets) val feeBox3 = new ErgoBoxCandidate(feeValue + 1, TrueProp, currentHeight) val spendingTransaction3 = ErgoLikeTransaction(inputs2, IndexedSeq(newReemissionBox3, feeBox3)) checkRewardsTx(currentHeight, pkBytes, inputBoxes, spendingTransaction3, false) // reemission NFT must be preserved val newReemissionBox4 = new ErgoBoxCandidate(reemissionBox.value + mergedValue - feeValue, prop, currentHeight) val spendingTransaction4 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox4, feeBox)) checkRewardsTx(currentHeight, pkBytes, inputBoxes, spendingTransaction4, false) // reemission box value must be increased val feeValue5 = mergedValue val newReemissionBox5 = new ErgoBoxCandidate(reemissionBox.value + mergedValue - feeValue5, prop, currentHeight, reemissionBoxAssets) val feeBox5 = new ErgoBoxCandidate(feeValue5, TrueProp, currentHeight) val spendingTransaction5 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox5, feeBox5)) checkRewardsTx(currentHeight, pkBytes, inputBoxes, spendingTransaction5, false) // pay-2-reemission box can be spent only with a box with reemission NFT as input #0 val reemissionBoxAssets6 = Colls.fromMap[Digest32, Long]( Map((Digest32 @@ rs.reemissionNftIdBytes.reverse) -> 1L) ) val newReemissionBox6 = new ErgoBoxCandidate(reemissionBox.value + mergedValue - feeValue, prop, currentHeight, reemissionBoxAssets6) val spendingTransaction6 = ErgoLikeTransaction(inputs, IndexedSeq(newReemissionBox6, feeBox)) val ctx = ErgoLikeContextTesting( currentHeight = currentHeight, lastBlockUtxoRoot = AvlTreeData.dummy, minerPubkey = pkBytes, boxesToSpend = inputBoxes, spendingTransaction6, self = inputBoxes(1), 0) prover.prove(emptyEnv, pay2RewardsProp, ctx, fakeMessage).isFailure shouldBe true } }
ccellado/ergo
src/main/scala/org/ergoplatform/settings/LaunchParameters.scala
package org.ergoplatform.settings /** * Parameters corresponding to initial moment of time in the mainnet and the testnet */ object LaunchParameters extends Parameters(height = 0, parametersTable = Parameters.DefaultParameters, proposedUpdate = ErgoValidationSettingsUpdate.empty)
ccellado/ergo
ergo-wallet/src/main/scala/org/ergoplatform/wallet/boxes/DefaultBoxSelector.scala
<gh_stars>0 package org.ergoplatform.wallet.boxes import org.ergoplatform.contracts.ReemissionContracts import scorex.util.ModifierId import org.ergoplatform.{ErgoBoxAssets, ErgoBoxAssetsHolder, ErgoBoxCandidate} import org.ergoplatform.wallet.Constants.MaxAssetsPerBox import org.ergoplatform.wallet.{AssetUtils, TokensMap} import scala.annotation.tailrec import scala.collection.mutable import org.ergoplatform.wallet.Utils._ import org.ergoplatform.wallet.boxes.BoxSelector.BoxSelectionError /** * Default implementation of the box selector. It simply picks boxes till sum of their monetary values * meets target Ergo balance, then it checks which assets are not fulfilled and adds boxes till target * asset values are met. * * @param reemissionDataOpt - reemission parameters, if wallet is checking re-emission rules */ class DefaultBoxSelector(override val reemissionDataOpt: Option[ReemissionData]) extends BoxSelector { import DefaultBoxSelector._ import BoxSelector._ import scorex.util.idToBytes // helper function which returns count of assets in `initialMap` not fully spent in `subtractor` private def diffCount(initialMap: mutable.Map[ModifierId, Long], subtractor: TokensMap): Int = { initialMap.foldLeft(0){case (cnt, (tokenId, tokenAmt)) => if (tokenAmt - subtractor.getOrElse(tokenId, 0L) > 0) { cnt + 1 } else { cnt } } } override def select[T <: ErgoBoxAssets](inputBoxes: Iterator[T], externalFilter: T => Boolean, targetBalance: Long, targetAssets: TokensMap): Either[BoxSelectionError, BoxSelectionResult[T]] = { //mutable structures to collect results val res = mutable.Buffer[T]() var currentBalance = 0L val currentAssets = mutable.Map[ModifierId, Long]() def pickUp(unspentBox: T) = { currentBalance = currentBalance + valueOf(unspentBox, reemissionDataOpt) AssetUtils.mergeAssetsMut(currentAssets, unspentBox.tokens) res += unspentBox } /** * Helper functions which checks whether enough ERGs collected */ def balanceMet: Boolean = { val diff = currentBalance - targetBalance // We estimate how many ERG needed for assets in change boxes val assetsDiff = diffCount(currentAssets, targetAssets) val diffThreshold = if (assetsDiff <= 0) { 0 } else { MinBoxValue * (assetsDiff / MaxAssetsPerBox + 1) } diff >= diffThreshold } /** * Helper functions which checks whether enough assets collected */ def assetsMet: Boolean = { targetAssets.forall { case (id, targetAmt) => currentAssets.getOrElse(id, 0L) >= targetAmt } } @tailrec def pickBoxes(boxesIterator: Iterator[T], filterFn: T => Boolean, successFn: => Boolean): Boolean = if (successFn) { true } else if (!boxesIterator.hasNext) { false } else { val box = boxesIterator.next() if (filterFn(box)) pickUp(box) pickBoxes(boxesIterator, filterFn, successFn) } //first, we pick all the boxes until ergo target balance is met if (pickBoxes(inputBoxes, externalFilter, balanceMet)) { //then we pick boxes until all the target asset amounts are met (we pick only boxes containing needed assets). //If this condition is satisfied on the previous step, we will do one extra call to pickBoxes //with no touching the iterator (which is not that much). if (pickBoxes( inputBoxes, bc => externalFilter(bc) && bc.tokens.exists { case (id, _) => val targetAmt = targetAssets.getOrElse(id, 0L) lazy val currentAmt = currentAssets.getOrElse(id, 0L) targetAmt > 0 && targetAmt > currentAmt }, assetsMet )) { val ra = reemissionAmount(res) formChangeBoxes(currentBalance, targetBalance, currentAssets, targetAssets, ra).mapRight { changeBoxes => BoxSelectionResult(res, changeBoxes) } } else { Left(NotEnoughTokensError( s"not enough boxes to meet token needs $targetAssets (found only $currentAssets)", currentAssets.toMap) ) } } else { Left(NotEnoughErgsError( s"not enough boxes to meet ERG needs $targetBalance (found only $currentBalance)", currentBalance) ) } } /** * Helper method to construct change outputs * * @param foundBalance - ERG balance of boxes collected * (spendable only, so after possibly deducting re-emission tokens) * @param targetBalance - ERG amount to be transferred to recipients * @param foundBoxAssets - assets balances of boxes * @param targetBoxAssets - assets amounts to be transferred to recipients * @param reemissionAmt - amount of re-emission tokens in collected boxes * @return */ def formChangeBoxes(foundBalance: Long, targetBalance: Long, foundBoxAssets: mutable.Map[ModifierId, Long], targetBoxAssets: TokensMap, reemissionAmt: Long): Either[BoxSelectionError, Seq[ErgoBoxAssets]] = { AssetUtils.subtractAssetsMut(foundBoxAssets, targetBoxAssets) val changeBoxesAssets: Seq[mutable.Map[ModifierId, Long]] = foundBoxAssets.grouped(MaxAssetsPerBox).toSeq val changeBalance = foundBalance - targetBalance //at least a minimum amount of ERG should be assigned per a created box if (changeBoxesAssets.size * MinBoxValue > changeBalance) { Left(NotEnoughCoinsForChangeBoxesError( s"Not enough nanoERGs ($changeBalance nanoERG) to create ${changeBoxesAssets.size} change boxes, \nfor $changeBoxesAssets" )) } else { val changeBoxes = if (changeBoxesAssets.nonEmpty) { val baseChangeBalance = changeBalance / changeBoxesAssets.size val changeBoxesNoBalanceAdjusted = changeBoxesAssets.map { a => ErgoBoxAssetsHolder(baseChangeBalance, a.toMap) } val modifiedBoxOpt = changeBoxesNoBalanceAdjusted.headOption.map { firstBox => ErgoBoxAssetsHolder( changeBalance - baseChangeBalance * (changeBoxesAssets.size - 1), firstBox.tokens ) } modifiedBoxOpt.toSeq ++ changeBoxesNoBalanceAdjusted.tail } else if (changeBalance > 0) { Seq(ErgoBoxAssetsHolder(changeBalance)) } else { Seq.empty } if (reemissionAmt > 0) { reemissionDataOpt match { case Some(reemissionData) => // we construct this instance to get pay-to-reemission contract from it // we set re-emission contract NFT id, re-emission start height is not used so we set it to 0 val rc: ReemissionContracts = new ReemissionContracts { override val reemissionNftIdBytes: Array[Byte] = idToBytes(reemissionData.reemissionNftId) override val reemissionStartHeight: Int = 0 } val p2r = rc.payToReemission val payToReemissionBox = new ErgoBoxCandidate(reemissionAmt, p2r, creationHeight = 0) Right(payToReemissionBox +: changeBoxes) case None => log.error("reemissionData when reemissionAmt > 0, should not happen at all") Right(changeBoxes) } } else { Right(changeBoxes) } } } } object DefaultBoxSelector { final case class NotEnoughErgsError(message: String, balanceFound: Long) extends BoxSelectionError final case class NotEnoughTokensError(message: String, tokensFound: Map[ModifierId, Long]) extends BoxSelectionError final case class NotEnoughCoinsForChangeBoxesError(message: String) extends BoxSelectionError }
ccellado/ergo
src/test/scala/org/ergoplatform/utils/fixtures/NodeViewFixture.scala
package org.ergoplatform.utils.fixtures import akka.actor.{ActorRef, ActorSystem} import akka.testkit.TestProbe import org.ergoplatform.mining.emission.EmissionRules import org.ergoplatform.nodeView.ErgoNodeViewRef import org.ergoplatform.settings.{ErgoSettings, Parameters} import org.ergoplatform.utils.{ErgoTestHelpers, NodeViewTestContext} import org.ergoplatform.wallet.utils.TestFileUtils import scorex.core.utils.NetworkTimeProvider import scala.concurrent.ExecutionContext /** This uses TestProbe to receive messages from actor. * To make TestProbe work `defaultSender` implicit should be imported */ class NodeViewFixture(protoSettings: ErgoSettings, parameters: Parameters) extends NodeViewTestContext with TestFileUtils { self => implicit val actorSystem: ActorSystem = ActorSystem() implicit val executionContext: ExecutionContext = actorSystem.dispatchers.lookup("scorex.executionContext") implicit def ctx: NodeViewTestContext = this val nodeViewDir: java.io.File = createTempDir @volatile var settings: ErgoSettings = protoSettings.copy(directory = nodeViewDir.getAbsolutePath) val timeProvider: NetworkTimeProvider = ErgoTestHelpers.defaultTimeProvider val emission: EmissionRules = new EmissionRules(settings.chainSettings.monetary) @volatile var nodeViewHolderRef: ActorRef = ErgoNodeViewRef(settings, timeProvider) val testProbe = new TestProbe(actorSystem) /** This sender should be imported to make TestProbe work! */ implicit val defaultSender: ActorRef = testProbe.testActor def apply[T](test: self.type => T): T = try test(self) finally stop() def startNodeViewHolder(): Unit = { nodeViewHolderRef = ErgoNodeViewRef(settings, timeProvider) } def stopNodeViewHolder(): Unit = { actorSystem.stop(nodeViewHolderRef) Thread.sleep(2000) } /** Restarts nodeViewHolder and applies config override */ def updateConfig(settingsOverride: ErgoSettings => ErgoSettings): Unit = { stopNodeViewHolder() settings = settingsOverride(settings) startNodeViewHolder() } def stop(): Unit = { stopNodeViewHolder() actorSystem.stop(testProbe.testActor) actorSystem.terminate() } } object NodeViewFixture { def apply(protoSettings: ErgoSettings, parameters: Parameters): NodeViewFixture = new NodeViewFixture(protoSettings, parameters) }
ccellado/ergo
src/main/scala/org/ergoplatform/mining/CandidateGenerator.scala
<reponame>ccellado/ergo package org.ergoplatform.mining import akka.actor.{Actor, ActorRef, ActorRefFactory, Props} import akka.pattern.StatusReply import com.google.common.primitives.Longs import org.ergoplatform.ErgoBox.TokenId import org.ergoplatform.mining.AutolykosPowScheme.derivedHeaderFields import org.ergoplatform.mining.difficulty.RequiredDifficulty import org.ergoplatform.modifiers.ErgoFullBlock import org.ergoplatform.modifiers.history._ import org.ergoplatform.modifiers.history.extension.Extension import org.ergoplatform.modifiers.history.header.{Header, HeaderWithoutPow} import org.ergoplatform.modifiers.history.popow.NipopowAlgos import org.ergoplatform.modifiers.mempool.ErgoTransaction import org.ergoplatform.network.ErgoNodeViewSynchronizer.ReceivableMessages import ReceivableMessages.{ChangedHistory, ChangedMempool, ChangedState, NodeViewChange, SemanticallySuccessfulModifier} import org.ergoplatform.nodeView.ErgoReadersHolder.{GetReaders, Readers} import org.ergoplatform.nodeView.history.ErgoHistory.Height import org.ergoplatform.nodeView.history.{ErgoHistory, ErgoHistoryReader} import org.ergoplatform.nodeView.mempool.ErgoMemPoolReader import org.ergoplatform.nodeView.state.{ErgoState, ErgoStateContext, StateType, UtxoStateReader} import org.ergoplatform.settings.{ErgoSettings, ErgoValidationSettingsUpdate} import org.ergoplatform.wallet.Constants.MaxAssetsPerBox import org.ergoplatform.wallet.interpreter.ErgoInterpreter import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoScriptPredef, Input} import org.ergoplatform.nodeView.ErgoNodeViewHolder.ReceivableMessages.{EliminateTransactions, LocallyGeneratedModifier} import scorex.core.utils.NetworkTimeProvider import scorex.crypto.hash.Digest32 import scorex.util.encode.Base16 import scorex.util.{ModifierId, ScorexLogging} import sigmastate.SType.ErgoBoxRType import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.eval.Extensions._ import sigmastate.eval._ import sigmastate.interpreter.ProverResult import special.collection.Coll import scala.annotation.tailrec import scala.concurrent.duration._ import scala.util.{Failure, Random, Success, Try} /** Responsible for generating block candidates and validating solutions. * It is observing changes of history, utxo state, mempool and newly applied blocks * to generate valid block candidates when it is needed. */ class CandidateGenerator( minerPk: ProveDlog, readersHolderRef: ActorRef, viewHolderRef: ActorRef, timeProvider: NetworkTimeProvider, ergoSettings: ErgoSettings ) extends Actor with ScorexLogging { import org.ergoplatform.mining.CandidateGenerator._ /** retrieve Readers once on start and then get updated by events */ override def preStart(): Unit = { log.info("CandidateGenerator is starting") readersHolderRef ! GetReaders } /** Send solved block to local blockchain controller */ private def sendToNodeView(newBlock: ErgoFullBlock): Unit = { log.info( s"New block ${newBlock.id} w. nonce ${Longs.fromByteArray(newBlock.header.powSolution.n)}" ) viewHolderRef ! LocallyGeneratedModifier(newBlock.header) val sectionsToApply = if (ergoSettings.nodeSettings.stateType == StateType.Digest) { newBlock.blockSections } else { newBlock.mandatoryBlockSections } sectionsToApply.foreach(viewHolderRef ! LocallyGeneratedModifier(_)) } override def receive: Receive = { /** first we need to get Readers to have some initial state to work with */ case Readers(h, s: UtxoStateReader, m, _) => val lastHeaders = h.lastHeaders(500).headers val avgMiningTime = getBlockMiningTimeAvg(lastHeaders.map(_.timestamp)) val avgTxsCount = getTxsPerBlockCountAvg( lastHeaders.flatMap(h.getFullBlock).map(_.transactions.size) ) log.info( s"CandidateGenerator initialized, avgMiningTime: ${avgMiningTime.toSeconds}s, avgTxsCount: $avgTxsCount" ) context.become( initialized( CandidateGeneratorState( cache = None, solvedBlock = None, h, s, m, avgGenTime = 1000.millis ) ) ) self ! GenerateCandidate(txsToInclude = Seq.empty, reply = false) context.system.eventStream .subscribe(self, classOf[SemanticallySuccessfulModifier]) context.system.eventStream.subscribe(self, classOf[NodeViewChange]) case Readers(_, _, _, _) => log.error("Invalid readers state, mining is possible in UTXO mode only") case m => // retry until initialized context.system.scheduler .scheduleOnce(100.millis, self, m)(context.dispatcher, sender()) } private def initialized(state: CandidateGeneratorState): Receive = { case ChangedHistory(h: ErgoHistoryReader) => context.become(initialized(state.copy(hr = h))) case ChangedState(s: UtxoStateReader) => context.become(initialized(state.copy(sr = s))) case ChangedMempool(mp: ErgoMemPoolReader) => context.become(initialized(state.copy(mpr = mp))) case _: NodeViewChange => // Just ignore all other NodeView Changes /** * When new block is applied, either one mined by us or received from peers isn't equal to our candidate's parent, * we need to generate new candidate and possibly also discard existing solution if it is also behind */ case SemanticallySuccessfulModifier(mod: ErgoFullBlock) => log.info( s"Preparing new candidate on getting new block at ${mod.height}" ) if (needNewCandidate(state.cache, mod)) { if (needNewSolution(state.solvedBlock, mod)) context.become(initialized(state.copy(cache = None, solvedBlock = None))) else context.become(initialized(state.copy(cache = None))) self ! GenerateCandidate(txsToInclude = Seq.empty, reply = false) } else { context.become(initialized(state)) } case SemanticallySuccessfulModifier(_) => // Just ignore all other modifiers. case gen @ GenerateCandidate(txsToInclude, reply) => val senderOpt = if (reply) Some(sender()) else None if (cachedFor(state.cache, txsToInclude)) { senderOpt.foreach(_ ! StatusReply.success(state.cache.get)) } else { val start = System.currentTimeMillis() CandidateGenerator.generateCandidate( state.hr, state.sr, state.mpr, timeProvider, minerPk, txsToInclude, ergoSettings ) match { case Some(Failure(ex)) => log.error(s"Candidate generation failed", ex) senderOpt.foreach( _ ! StatusReply.error(s"Candidate generation failed : ${ex.getMessage}") ) case Some(Success((candidate, eliminatedTxs))) => if (eliminatedTxs.ids.nonEmpty) viewHolderRef ! eliminatedTxs val generationTook = System.currentTimeMillis() - start log.info(s"Generated new candidate in $generationTook ms") context.become( initialized( state.copy(cache = Some(candidate), avgGenTime = generationTook.millis) ) ) senderOpt.foreach(_ ! StatusReply.success(candidate)) case None => log.warn( "Can not generate block candidate: either mempool is empty or chain is not synced (maybe last block not fully applied yet" ) senderOpt.foreach { s => context.system.scheduler.scheduleOnce(state.avgGenTime, self, gen)( context.system.dispatcher, s ) } } } case preSolution: AutolykosSolution if state.solvedBlock.isEmpty && state.cache.nonEmpty => // Inject node pk if it is not externally set (in Autolykos 2) val solution = if (preSolution.pk.isInfinity) { AutolykosSolution(minerPk.value, preSolution.w, preSolution.n, preSolution.d) } else { preSolution } val result: StatusReply[Unit] = { val newBlock = completeBlock(state.cache.get.candidateBlock, solution) log.info(s"New block mined, header: ${newBlock.header}") ergoSettings.chainSettings.powScheme .validate(newBlock.header) .map(_ => newBlock) match { case Success(newBlock) => sendToNodeView(newBlock) context.become(initialized(state.copy(solvedBlock = Some(newBlock)))) StatusReply.success(()) case Failure(exception) => log.warn(s"Removing candidate due to invalid block", exception) context.become(initialized(state.copy(cache = None))) StatusReply.error( new Exception(s"Invalid block mined: ${exception.getMessage}", exception) ) } } log.info(s"Processed solution $solution with the result $result") sender() ! result case _: AutolykosSolution => sender() ! StatusReply.error( s"Block already solved : ${state.solvedBlock.map(_.id)}" ) } } object CandidateGenerator extends ScorexLogging { /** * Holder for both candidate block and data for external miners derived from it * (to avoid possibly costly recalculation) * * @param candidateBlock - block candidate * @param externalVersion - message for external miner * @param txsToInclude - transactions which were prioritized for inclusion in the block candidate */ case class Candidate( candidateBlock: CandidateBlock, externalVersion: WorkMessage, txsToInclude: Seq[ErgoTransaction] ) case class GenerateCandidate( txsToInclude: Seq[ErgoTransaction], reply: Boolean ) /** Local state of candidate generator to avoid mutable vars */ case class CandidateGeneratorState( cache: Option[Candidate], solvedBlock: Option[ErgoFullBlock], hr: ErgoHistoryReader, sr: UtxoStateReader, mpr: ErgoMemPoolReader, avgGenTime: FiniteDuration // approximation of average block generation time for more efficient retries ) def apply( minerPk: ProveDlog, readersHolderRef: ActorRef, viewHolderRef: ActorRef, timeProvider: NetworkTimeProvider, ergoSettings: ErgoSettings )(implicit context: ActorRefFactory): ActorRef = context.actorOf( Props( new CandidateGenerator( minerPk, readersHolderRef, viewHolderRef, timeProvider, ergoSettings ) ), s"CandidateGenerator-${Random.alphanumeric.take(5).mkString}" ) /** checks that current candidate block is cached with given `txs` */ def cachedFor( candidateOpt: Option[Candidate], txs: Seq[ErgoTransaction] ): Boolean = { candidateOpt.isDefined && candidateOpt.exists { c => txs.isEmpty || (txs.size == c.txsToInclude.size && txs.forall( c.txsToInclude.contains )) } } /** we need new candidate if given block is not parent of our cached block */ def needNewCandidate( cache: Option[Candidate], bestFullBlock: ErgoFullBlock ): Boolean = { val parentHeaderIdOpt = cache.map(_.candidateBlock).flatMap(_.parentOpt).map(_.id) !parentHeaderIdOpt.contains(bestFullBlock.header.id) } /** Solution is valid only if bestFullBlock on the chain is its parent */ def needNewSolution( solvedBlock: Option[ErgoFullBlock], bestFullBlock: ErgoFullBlock ): Boolean = solvedBlock.nonEmpty && !solvedBlock.map(_.parentId).contains(bestFullBlock.id) /** Calculate average mining time from latest block header timestamps */ def getBlockMiningTimeAvg( timestamps: IndexedSeq[Header.Timestamp] ): FiniteDuration = { val miningTimes = timestamps.sorted .sliding(2, 1) .map { case IndexedSeq(prev, next) => next - prev } .toVector Math.round(miningTimes.sum / miningTimes.length.toDouble).millis } /** Get average count of transactions per block */ def getTxsPerBlockCountAvg(txsPerBlock: IndexedSeq[Int]): Long = Math.round(txsPerBlock.sum / txsPerBlock.length.toDouble) /** Helper which is checking that inputs of the transaction are not spent */ private def inputsNotSpent(tx: ErgoTransaction, s: UtxoStateReader): Boolean = tx.inputs.forall(inp => s.boxById(inp.boxId).isDefined) /** * @return None if chain is not synced or Some of attempt to create candidate */ def generateCandidate( h: ErgoHistoryReader, s: UtxoStateReader, m: ErgoMemPoolReader, timeProvider: NetworkTimeProvider, pk: ProveDlog, txsToInclude: Seq[ErgoTransaction], ergoSettings: ErgoSettings ): Option[Try[(Candidate, EliminateTransactions)]] = { //mandatory transactions to include into next block taken from the previous candidate lazy val unspentTxsToInclude = txsToInclude.filter { tx => inputsNotSpent(tx, s) } val stateContext = s.stateContext //only transactions valid from against the current utxo state we take from the mem pool lazy val poolTransactions = m.getAllPrioritized lazy val emissionTxOpt = CandidateGenerator.collectEmission(s, pk, stateContext) def chainSynced = h.bestFullBlockOpt.map(_.id) == stateContext.lastHeaderOpt.map(_.id) def hasAnyMemPoolOrMinerTx = poolTransactions.nonEmpty || unspentTxsToInclude.nonEmpty || emissionTxOpt.nonEmpty if (!hasAnyMemPoolOrMinerTx) { log.info(s"Avoiding generation of a block without any transactions") None } else if (!chainSynced) { log.info( "Chain not synced probably due to racing condition when last block is not fully applied yet" ) None } else { val desiredUpdate = ergoSettings.votingTargets.desiredUpdate Some( createCandidate( pk, h, desiredUpdate, s, timeProvider, poolTransactions, emissionTxOpt, unspentTxsToInclude, ergoSettings ) ) } } /** * Assemble correct block candidate based on * * @param minerPk - public key of the miner * @param history - blockchain reader (to extract parent) * @param proposedUpdate - votes for parameters update or/and soft-fork * @param state - UTXO set reader * @param timeProvider - network time provider * @param poolTxs - memory pool transactions * @param emissionTxOpt - optional emission transaction * @param prioritizedTransactions - transactions which are going into the block in the first place * (before transactions from the pool). No guarantee of inclusion in general case. * @return - candidate or an error */ def createCandidate( minerPk: ProveDlog, history: ErgoHistoryReader, proposedUpdate: ErgoValidationSettingsUpdate, state: UtxoStateReader, timeProvider: NetworkTimeProvider, poolTxs: Seq[ErgoTransaction], emissionTxOpt: Option[ErgoTransaction], prioritizedTransactions: Seq[ErgoTransaction], ergoSettings: ErgoSettings ): Try[(Candidate, EliminateTransactions)] = Try { val popowAlgos = new NipopowAlgos(ergoSettings.chainSettings.powScheme) // Extract best header and extension of a best block user their data for assembling a new block val bestHeaderOpt: Option[Header] = history.bestFullBlockOpt.map(_.header) val bestExtensionOpt: Option[Extension] = bestHeaderOpt .flatMap(h => history.typedModifierById[Extension](h.extensionId)) // Make progress in time since last block. // If no progress is made, then, by consensus rules, the block will be rejected. val timestamp = Math.max(timeProvider.time(), bestHeaderOpt.map(_.timestamp + 1).getOrElse(0L)) val stateContext = state.stateContext // Calculate required difficulty for the new block val nBits: Long = bestHeaderOpt .map(parent => history.requiredDifficultyAfter(parent)) .map(d => RequiredDifficulty.encodeCompactBits(d)) .getOrElse(ergoSettings.chainSettings.initialNBits) // Obtain NiPoPoW interlinks vector to pack it into the extension section val updInterlinks = popowAlgos.updateInterlinks(bestHeaderOpt, bestExtensionOpt) val interlinksExtension = popowAlgos.interlinksToExtension(updInterlinks) val votingSettings = ergoSettings.chainSettings.voting val (extensionCandidate, votes: Array[Byte], version: Byte) = bestHeaderOpt .map { header => val newHeight = header.height + 1 val currentParams = stateContext.currentParameters val betterVersion = ergoSettings.chainSettings.protocolVersion > header.version val votingFinishHeight: Option[Height] = currentParams.softForkStartingHeight .map(_ + votingSettings.votingLength * votingSettings.softForkEpochs) val forkVotingAllowed = votingFinishHeight.forall(fh => newHeight < fh) val forkOrdered = ergoSettings.votingTargets.softFork != 0 val voteForFork = betterVersion && forkOrdered && forkVotingAllowed if (newHeight % votingSettings.votingLength == 0 && newHeight > 0) { val (newParams, activatedUpdate) = currentParams.update( newHeight, voteForFork, stateContext.votingData.epochVotes, proposedUpdate, votingSettings ) val newValidationSettings = stateContext.validationSettings.updated(activatedUpdate) ( newParams.toExtensionCandidate ++ interlinksExtension ++ newValidationSettings.toExtensionCandidate, newParams.suggestVotes(ergoSettings.votingTargets.targets, voteForFork), newParams.blockVersion ) } else { ( interlinksExtension, currentParams.vote( ergoSettings.votingTargets.targets, stateContext.votingData.epochVotes, voteForFork ), currentParams.blockVersion ) } } .getOrElse( (interlinksExtension, Array(0: Byte, 0: Byte, 0: Byte), Header.InitialVersion) ) val upcomingContext = state.stateContext.upcoming( minerPk.h, timestamp, nBits, votes, proposedUpdate, version ) val emissionTxs = emissionTxOpt.toSeq // todo: remove in 5.0 // we allow for some gap, to avoid possible problems when different interpreter version can estimate cost // differently due to bugs in AOT costing val safeGap = if(state.stateContext.currentParameters.maxBlockCost < 1000000) { 0 } else if(state.stateContext.currentParameters.maxBlockCost < 5000000) { 150000 } else { 1000000 } val (txs, toEliminate) = collectTxs( minerPk, state.stateContext.currentParameters.maxBlockCost - safeGap, state.stateContext.currentParameters.maxBlockSize, state, upcomingContext, emissionTxs ++ prioritizedTransactions ++ poolTxs ) val eliminateTransactions = EliminateTransactions(toEliminate) if (txs.isEmpty) { throw new IllegalArgumentException( s"Proofs for 0 txs cannot be generated : emissionTxs: ${emissionTxs.size}, priorityTxs: ${prioritizedTransactions.size}, poolTxs: ${poolTxs.size}" ) } def deriveWorkMessage(block: CandidateBlock) = { ergoSettings.chainSettings.powScheme.deriveExternalCandidate( block, minerPk, prioritizedTransactions.map(_.id) ) } state.proofsForTransactions(txs) match { case Success((adProof, adDigest)) => val candidate = CandidateBlock( bestHeaderOpt, version, nBits, adDigest, adProof, txs, timestamp, extensionCandidate, votes ) val ext = deriveWorkMessage(candidate) log.info( s"Got candidate block at height ${ErgoHistory.heightOf(candidate.parentOpt) + 1}" + s" with ${candidate.transactions.size} transactions, msg ${Base16.encode(ext.msg)}" ) Success( Candidate(candidate, ext, prioritizedTransactions) -> eliminateTransactions ) case Failure(t: Throwable) => // We can not produce a block for some reason, so print out an error // and collect only emission transaction if it exists. // We consider that emission transaction is always valid. emissionTxOpt match { case Some(emissionTx) => log.error( "Failed to produce proofs for transactions, but emission box is found: ", t ) val fallbackTxs = Seq(emissionTx) state.proofsForTransactions(fallbackTxs).map { case (adProof, adDigest) => val candidate = CandidateBlock( bestHeaderOpt, version, nBits, adDigest, adProof, fallbackTxs, timestamp, extensionCandidate, votes ) Candidate( candidate, deriveWorkMessage(candidate), prioritizedTransactions ) -> eliminateTransactions } case None => log.error( "Failed to produce proofs for transactions and no emission box available: ", t ) Failure(t) } } }.flatten /** * Transaction and its cost. */ type CostedTransaction = (ErgoTransaction, Int) //TODO move ErgoMiner to mining package and make `collectTxs` and `fixTxsConflicts` private[mining] def collectEmission( state: UtxoStateReader, minerPk: ProveDlog, stateContext: ErgoStateContext ): Option[ErgoTransaction] = { collectRewards( state.emissionBoxOpt, state.stateContext.currentHeight, Seq.empty, minerPk, stateContext, Colls.emptyColl ).headOption } def collectFees( currentHeight: Int, txs: Seq[ErgoTransaction], minerPk: ProveDlog, stateContext: ErgoStateContext ): Option[ErgoTransaction] = { collectRewards(None, currentHeight, txs, minerPk, stateContext, Colls.emptyColl).headOption } /** * Generate from 0 to 2 transaction that collecting rewards from fee boxes in block transactions `txs` and * emission box `emissionBoxOpt` */ def collectRewards( emissionBoxOpt: Option[ErgoBox], currentHeight: Int, txs: Seq[ErgoTransaction], minerPk: ProveDlog, stateContext: ErgoStateContext, assets: Coll[(TokenId, Long)] = Colls.emptyColl ): Seq[ErgoTransaction] = { val chainSettings = stateContext.ergoSettings.chainSettings val propositionBytes = chainSettings.monetary.feePropositionBytes val emission = chainSettings.emissionRules // forming transaction collecting emission val reemissionSettings = chainSettings.reemission val reemissionRules = reemissionSettings.reemissionRules val eip27ActivationHeight = reemissionSettings.activationHeight val reemissionTokenId = Digest32 @@ reemissionSettings.reemissionTokenIdBytes val nextHeight = currentHeight + 1 val minerProp = ErgoScriptPredef.rewardOutputScript(emission.settings.minerRewardDelay, minerPk) val emissionTxOpt: Option[ErgoTransaction] = emissionBoxOpt.map { emissionBox => val prop = emissionBox.ergoTree val emissionAmount = emission.minersRewardAtHeight(nextHeight) // how many nanoERG should be re-emitted lazy val reemissionAmount = reemissionRules.reemissionForHeight(nextHeight, emission) val emissionBoxAssets: Coll[(TokenId, Long)] = if (nextHeight == eip27ActivationHeight) { // we inject emission box NFT and reemission tokens on activation height // see "Activation Details" section of EIP-27 val injTokens = reemissionSettings.injectionBox.additionalTokens //swap tokens if emission NFT is going after reemission if (injTokens.apply(1)._2 == 1) { Colls.fromItems(injTokens.apply(1), injTokens.apply(0)) } else { injTokens } } else { emissionBox.additionalTokens } val updEmissionAssets = if (nextHeight >= eip27ActivationHeight) { // deduct reemission from emission box val reemissionTokens = emissionBoxAssets.apply(1)._2 val updAmount = reemissionTokens - reemissionAmount emissionBoxAssets.updated(1, reemissionTokenId -> updAmount) } else { emissionBoxAssets } val newEmissionBox: ErgoBoxCandidate = new ErgoBoxCandidate(emissionBox.value - emissionAmount, prop, nextHeight, updEmissionAssets) val inputs = if (nextHeight == eip27ActivationHeight) { // injection - second input is injection box IndexedSeq( new Input(emissionBox.id, ProverResult.empty), new Input(reemissionSettings.injectionBox.id, ProverResult.empty) ) } else { IndexedSeq(new Input(emissionBox.id, ProverResult.empty)) } val minerAmt = if (nextHeight == eip27ActivationHeight) { // injection - injection box value going to miner emissionAmount + reemissionSettings.injectionBox.value } else { emissionAmount } val minersAssets = if (nextHeight >= eip27ActivationHeight) { // miner is getting reemission tokens assets.append(Colls.fromItems(reemissionTokenId -> reemissionAmount)) } else { assets } val minerBox = new ErgoBoxCandidate(minerAmt, minerProp, nextHeight, minersAssets) val emissionTx = ErgoTransaction( inputs, dataInputs = IndexedSeq.empty, IndexedSeq(newEmissionBox, minerBox) ) log.info(s"Emission tx for nextHeight = $nextHeight: $emissionTx") emissionTx } // forming transaction collecting tx fees val inputs = txs.flatMap(_.inputs) val feeBoxes: Seq[ErgoBox] = ErgoState .newBoxes(txs) .filter(b => java.util.Arrays.equals(b.propositionBytes, propositionBytes) && !inputs.exists(i => java.util.Arrays.equals(i.boxId, b.id))) val feeTxOpt: Option[ErgoTransaction] = if (feeBoxes.nonEmpty) { val feeAmount = feeBoxes.map(_.value).sum val feeAssets = feeBoxes.toColl.flatMap(_.additionalTokens).take(MaxAssetsPerBox) val inputs = feeBoxes.map(b => new Input(b.id, ProverResult.empty)) val minerBox = new ErgoBoxCandidate(feeAmount, minerProp, nextHeight, feeAssets, Map()) Some(ErgoTransaction(inputs.toIndexedSeq, IndexedSeq(), IndexedSeq(minerBox))) } else { None } Seq(emissionTxOpt, feeTxOpt).flatten } /** * Helper function which decides whether transactions can fit into a block with given cost and size limits */ def correctLimits( blockTxs: Seq[CostedTransaction], maxBlockCost: Long, maxBlockSize: Long ): Boolean = { blockTxs.map(_._2).sum < maxBlockCost && blockTxs.map(_._1.size).sum < maxBlockSize } /** * Collects valid non-conflicting transactions from `mandatoryTxs` and then `mempoolTxsIn` and adds a transaction * collecting fees from them to `minerPk`. * * Resulting transactions total cost does not exceed `maxBlockCost`, total size does not exceed `maxBlockSize`, * and the miner's transaction is correct. * * @return - transactions to include into the block, transaction ids turned out to be invalid. */ def collectTxs( minerPk: ProveDlog, maxBlockCost: Int, maxBlockSize: Int, us: UtxoStateReader, upcomingContext: ErgoStateContext, transactions: Seq[ErgoTransaction] ): (Seq[ErgoTransaction], Seq[ModifierId]) = { val currentHeight = us.stateContext.currentHeight val nextHeight = upcomingContext.currentHeight log.info( s"Assembling a block candidate for block #$nextHeight from ${transactions.length} transactions available" ) val verifier: ErgoInterpreter = ErgoInterpreter(upcomingContext.currentParameters) @tailrec def loop( mempoolTxs: Iterable[ErgoTransaction], acc: Seq[CostedTransaction], lastFeeTx: Option[CostedTransaction], invalidTxs: Seq[ModifierId] ): (Seq[ErgoTransaction], Seq[ModifierId]) = { // transactions from mempool and fee txs from the previous step def current: Seq[ErgoTransaction] = (acc ++ lastFeeTx).map(_._1) val stateWithTxs = us.withTransactions(current) mempoolTxs.headOption match { case Some(tx) => if (!inputsNotSpent(tx, stateWithTxs) || doublespend(current, tx)) { //mark transaction as invalid if it tries to do double-spending or trying to spend outputs not present //do these checks before validating the scripts to save time log.debug(s"Transaction ${tx.id} double-spending or spending non-existing inputs") loop(mempoolTxs.tail, acc, lastFeeTx, invalidTxs :+ tx.id) } else { // check validity and calculate transaction cost stateWithTxs.validateWithCost( tx, Some(upcomingContext), maxBlockCost, Some(verifier) ) match { case Success(costConsumed) => val newTxs = acc :+ (tx -> costConsumed) val newBoxes = newTxs.flatMap(_._1.outputs) collectFees(currentHeight, newTxs.map(_._1), minerPk, upcomingContext) match { case Some(feeTx) => val boxesToSpend = feeTx.inputs.flatMap(i => newBoxes.find(b => java.util.Arrays.equals(b.id, i.boxId)) ) feeTx.statefulValidity(boxesToSpend, IndexedSeq(), upcomingContext)(verifier) match { case Success(cost) => val blockTxs: Seq[CostedTransaction] = (feeTx -> cost) +: newTxs if (correctLimits(blockTxs, maxBlockCost, maxBlockSize)) { loop(mempoolTxs.tail, newTxs, Some(feeTx -> cost), invalidTxs) } else { current -> invalidTxs } case Failure(e) => log.warn( s"Fee collecting tx is invalid, not including it, " + s"details: ${e.getMessage} from ${stateWithTxs.stateContext}" ) current -> invalidTxs } case None => log.info(s"No fee proposition found in txs ${newTxs.map(_._1.id)} ") val blockTxs: Seq[CostedTransaction] = newTxs ++ lastFeeTx.toSeq if (correctLimits(blockTxs, maxBlockCost, maxBlockSize)) { loop(mempoolTxs.tail, blockTxs, lastFeeTx, invalidTxs) } else { current -> invalidTxs } } case Failure(e) => log.info(s"Not included transaction ${tx.id} due to ${e.getMessage}: ", e) loop(mempoolTxs.tail, acc, lastFeeTx, invalidTxs :+ tx.id) } } case _ => // mempool is empty current -> invalidTxs } } val res = loop(transactions, Seq.empty, None, Seq.empty) log.debug( s"Collected ${res._1.length} transactions for block #$currentHeight, " + s"${res._2.length} transactions turned out to be invalid" ) log.whenDebugEnabled { log.debug(s"Invalid trandaction ids for block #$currentHeight : ${res._2}") } res } /** Checks that transaction "tx" is not spending outputs spent already by transactions "txs" */ def doublespend(txs: Seq[ErgoTransaction], tx: ErgoTransaction): Boolean = { val txsInputs = txs.flatMap(_.inputs.map(_.boxId)) tx.inputs.exists(i => txsInputs.exists(_.sameElements(i.boxId))) } /** * Derives header without pow from [[CandidateBlock]]. */ def deriveUnprovenHeader(candidate: CandidateBlock): HeaderWithoutPow = { val (parentId, height) = derivedHeaderFields(candidate.parentOpt) val transactionsRoot = BlockTransactions.transactionsRoot(candidate.transactions, candidate.version) val adProofsRoot = ADProofs.proofDigest(candidate.adProofBytes) val extensionRoot: Digest32 = candidate.extension.digest HeaderWithoutPow( candidate.version, parentId, adProofsRoot, candidate.stateRoot, transactionsRoot, candidate.timestamp, candidate.nBits, height, extensionRoot, candidate.votes ) } /** * Assemble `ErgoFullBlock` using candidate block and provided pow solution. */ def completeBlock( candidate: CandidateBlock, solution: AutolykosSolution ): ErgoFullBlock = { val header = deriveUnprovenHeader(candidate).toHeader(solution, None) val adProofs = ADProofs(header.id, candidate.adProofBytes) val blockTransactions = BlockTransactions(header.id, candidate.version, candidate.transactions) val extension = Extension(header.id, candidate.extension.fields) new ErgoFullBlock(header, blockTransactions, extension, Some(adProofs)) } }
ccellado/ergo
src/test/scala/org/ergoplatform/http/routes/EmissionApiRouteSpec.scala
package org.ergoplatform.http.routes import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Route import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest} import akka.testkit.TestDuration import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport import io.circe.Json import io.circe.syntax._ import org.ergoplatform.http.api.EmissionApiRoute import org.ergoplatform.mining.emission.EmissionRules import org.ergoplatform.settings.{ErgoSettings, ReemissionSettings} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.duration._ class EmissionApiRouteSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest with FailFastCirceSupport { val prefix = "/emission/at" implicit val timeout: RouteTestTimeout = RouteTestTimeout(15.seconds.dilated) val ergoSettings: ErgoSettings = ErgoSettings.read() val coinEmission: EmissionRules = ergoSettings.chainSettings.emissionRules val reemissionSettings: ReemissionSettings = ergoSettings.chainSettings.reemission val route: Route = EmissionApiRoute(ergoSettings).route it should "get correct emission values" in { Get(prefix + "/1") ~> route ~> check { status shouldBe StatusCodes.OK EmissionApiRoute.emissionInfoAtHeight(1, coinEmission, reemissionSettings).asJson shouldEqual responseAs[Json] } Get(prefix + "/10000") ~> route ~> check { status shouldBe StatusCodes.OK EmissionApiRoute.emissionInfoAtHeight(10000, coinEmission, reemissionSettings).asJson shouldEqual responseAs[Json] } Get(prefix + "/1000000") ~> route ~> check { status shouldBe StatusCodes.OK EmissionApiRoute.emissionInfoAtHeight(1000000, coinEmission, reemissionSettings).asJson shouldEqual responseAs[Json] } } }
ccellado/ergo
src/test/scala/org/ergoplatform/network/ErgoSyncTrackerSpecification.scala
package org.ergoplatform.network import akka.actor.ActorSystem import org.ergoplatform.utils.ErgoPropertyTest import scorex.core.consensus.History.{Older, Younger} import scorex.core.network.{ConnectedPeer, ConnectionId, Incoming} import scorex.core.network.peer.PeerInfo class ErgoSyncTrackerSpecification extends ErgoPropertyTest { property("getters test") { val time = 10L val peerInfo = PeerInfo(defaultPeerSpec, time, Some(Incoming)) val cid = ConnectionId(inetAddr1, inetAddr2, Incoming) val connectedPeer = ConnectedPeer(cid, handlerRef = null, lastMessage = 5L, Some(peerInfo)) val syncTracker = ErgoSyncTracker(ActorSystem(), settings.scorexSettings.network, timeProvider) val height = 1000 // add peer to sync syncTracker.updateStatus(connectedPeer, Younger, Some(height)) syncTracker.statuses(connectedPeer) shouldBe ErgoPeerStatus(connectedPeer, Younger, height, None, None) // updating status should change status and height of existing peer syncTracker.updateStatus(connectedPeer, Older, Some(height+1)) syncTracker.getStatus(connectedPeer) shouldBe Some(Older) syncTracker.fullInfo().head.height shouldBe height+1 syncTracker.peersByStatus.apply(Older).head shouldBe connectedPeer // peer should not be synced yet syncTracker.notSyncedOrOutdated(connectedPeer) shouldBe true syncTracker.outdatedPeers shouldBe Vector.empty // peer should be ready for sync syncTracker.peersToSyncWith().head shouldBe connectedPeer syncTracker.updateLastSyncSentTime(connectedPeer) // peer should be synced now syncTracker.notSyncedOrOutdated(connectedPeer) shouldBe false syncTracker.clearStatus(connectedPeer.connectionId.remoteAddress) // peer should not be tracked anymore syncTracker.getStatus(connectedPeer) shouldBe None syncTracker.peersByStatus.isEmpty shouldBe true syncTracker.statuses.get(connectedPeer) shouldBe None syncTracker.peersToSyncWith().length shouldBe 0 } }
ccellado/ergo
src/main/scala/org/ergoplatform/nodeView/wallet/ErgoWalletState.scala
package org.ergoplatform.nodeView.wallet import com.google.common.hash.BloomFilter import org.ergoplatform.ErgoBox.BoxId import org.ergoplatform._ import org.ergoplatform.nodeView.history.ErgoHistory.Height import org.ergoplatform.nodeView.mempool.ErgoMemPoolReader import org.ergoplatform.nodeView.state.{ErgoStateContext, ErgoStateReader, UtxoStateReader} import org.ergoplatform.nodeView.wallet.ErgoWalletState.FilterFn import org.ergoplatform.nodeView.wallet.persistence.{OffChainRegistry, WalletRegistry, WalletStorage} import org.ergoplatform.settings.{ErgoSettings, Parameters} import org.ergoplatform.wallet.boxes.{BoxSelector, TrackedBox} import org.ergoplatform.wallet.secrets.JsonSecretStorage import scorex.util.ScorexLogging import scala.util.Try case class ErgoWalletState( storage: WalletStorage, secretStorageOpt: Option[JsonSecretStorage], registry: WalletRegistry, offChainRegistry: OffChainRegistry, outputsFilter: Option[BloomFilter[Array[Byte]]], // Bloom filter for boxes not being spent to the moment walletVars: WalletVars, stateReaderOpt: Option[ErgoStateReader], mempoolReaderOpt: Option[ErgoMemPoolReader], utxoStateReaderOpt: Option[UtxoStateReader], parameters: Parameters, maxInputsToUse: Int, error: Option[String] = None, rescanInProgress: Boolean ) extends ScorexLogging { /** * This filter is selecting boxes which are onchain and not spent offchain yet or created offchain * (and not spent offchain, but that is ensured by offChainRegistry). * This filter is used when the wallet is going through its boxes to assemble a transaction. */ val walletFilter: FilterFn = (trackedBox: TrackedBox) => { val preStatus = if (trackedBox.chainStatus.onChain) { offChainRegistry.onChainBalances.exists(_.id == trackedBox.boxId) } else { true } val bid = trackedBox.box.id // double-check that box is not spent yet by inputs of mempool transactions def notInInputs: Boolean = { mempoolReaderOpt match { case Some(mr) => !mr.spentInputs.exists(_.sameElements(bid)) case None => true } } // double-check that box is exists in UTXO set or outputs of offchain transaction def inOutputs: Boolean = { utxoStateReaderOpt.forall { utxo => utxo.boxById(bid).isDefined } } preStatus && notInInputs && inOutputs } // Secret is set in form of keystore file of testMnemonic in the config def secretIsSet(testMnemonic: Option[String]): Boolean = secretStorageOpt.nonEmpty || testMnemonic.nonEmpty // State context used to sign transactions and check that coins found in the blockchain are indeed belonging // to the wallet (by executing testing transactions against them). // The state context is being updated by listening to state updates. def stateContext: ErgoStateContext = storage.readStateContext(parameters) /** * @return height of the last block scanned by the wallet */ def getWalletHeight: Int = registry.fetchDigest().height /** * @return Height of the chain as reported by the state (i.e. height of a last block applied to the state, not the wallet). Wallet's height may be behind it. */ def fullHeight: Int = stateContext.currentHeight def getChangeAddress(addrEncoder: ErgoAddressEncoder): Option[P2PKAddress] = { walletVars.proverOpt.map { prover => storage.readChangeAddress.getOrElse { log.debug("Change address not specified. Using root address from wallet.") P2PKAddress(prover.hdPubKeys.head.key)(addrEncoder) } } } // Read a box from UTXO set if the node has it, otherwise, from the wallet def readBoxFromUtxoWithWalletFallback(boxId: BoxId): Option[ErgoBox] = { utxoStateReaderOpt match { case Some(utxoReader) => utxoReader.boxById(boxId) case None => registry.getBox(boxId).map(_.box) } } // expected height of a next block when the wallet is receiving a new block with the height blockHeight def expectedNextBlockHeight(blockHeight: Height, isFullBlocksPruned: Boolean): Height = { val walletHeight = getWalletHeight if (!isFullBlocksPruned) { // Node has all the full blocks and applies them sequentially walletHeight + 1 } else { // Node has pruned blockchain if (walletHeight == 0) { blockHeight // todo: should be height of first non-pruned block } else { walletHeight + 1 } } } /** * A helper method that returns unspent boxes */ def getBoxesToSpend: Seq[TrackedBox] = { require(walletVars.publicKeyAddresses.nonEmpty, "No public keys in the prover to extract change address from") (registry.walletUnspentBoxes(maxInputsToUse * BoxSelector.ScanDepthFactor) ++ offChainRegistry.offChainBoxes).distinct } } object ErgoWalletState { private type FilterFn = TrackedBox => Boolean /** * This filter is not filtering out anything, used when the wallet works with externally provided boxes. */ val noWalletFilter: FilterFn = (_: TrackedBox) => true def initial(ergoSettings: ErgoSettings, parameters: Parameters): Try[ErgoWalletState] = { WalletRegistry.apply(ergoSettings).map { registry => val ergoStorage: WalletStorage = WalletStorage.readOrCreate(ergoSettings) val offChainRegistry = OffChainRegistry.init(registry) val walletVars = WalletVars.apply(ergoStorage, ergoSettings) val maxInputsToUse = ergoSettings.walletSettings.maxInputs ErgoWalletState( ergoStorage, secretStorageOpt = None, registry, offChainRegistry, outputsFilter = None, walletVars, stateReaderOpt = None, mempoolReaderOpt = None, utxoStateReaderOpt = None, parameters, maxInputsToUse, rescanInProgress = false ) } } }
ybasket/scaffeine
project/plugins.sbt
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.8.2") addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.7") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2") addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.5.3") addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.9.2") addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.7") addSbtPlugin("com.thoughtworks.sbt-api-mappings" % "sbt-api-mappings" % "3.0.0")
ybasket/scaffeine
src/main/scala/com/github/blemale/scaffeine/AsyncCache.scala
package com.github.blemale.scaffeine import java.util.concurrent.Executor import com.github.benmanes.caffeine.cache.{AsyncCache => CaffeineAsyncCache} import scala.collection.JavaConverters._ import scala.compat.java8.FunctionConverters._ import scala.compat.java8.FutureConverters._ import scala.concurrent.{ExecutionContext, Future} object AsyncCache { def apply[K, V](asyncCache: CaffeineAsyncCache[K, V]): AsyncCache[K, V] = new AsyncCache(asyncCache) } class AsyncCache[K, V](val underlying: CaffeineAsyncCache[K, V]) { implicit private[this] val ec: ExecutionContext = DirectExecutionContext /** Returns the future associated with `key` in this cache, or `None` if there is no * cached future for `key`. * * @param key key whose associated value is to be returned * @return an option containing the current (existing or computed) future value to which the * specified key is mapped, or `None` if this map contains no mapping for the key */ def getIfPresent(key: K): Option[Future[V]] = Option(underlying.getIfPresent(key)).map(_.toScala) /** Returns the future associated with `key` in this cache, obtaining that value from * `mappingFunction` if necessary. This method provides a simple substitute for the * conventional "if cached, return; otherwise create, cache and return" pattern. * * @param key key with which the specified value is to be associated * @param mappingFunction the function to asynchronously compute a value * @return the current (existing or computed) future value associated with the specified key */ def get(key: K, mappingFunction: K => V): Future[V] = underlying.get(key, asJavaFunction(mappingFunction)).toScala /** Returns the future associated with `key` in this cache, obtaining that value from * `mappingFunction` if necessary. This method provides a simple substitute for the * conventional "if cached, return; otherwise create, cache and return" pattern. * * @param key key with which the specified value is to be associated * @param mappingFunction the function to asynchronously compute a value * @return the current (existing or computed) future value associated with the specified key * @throws java.lang.RuntimeException or Error if the mappingFunction does when constructing the future, * in which case the mapping is left unestablished */ def getFuture(key: K, mappingFunction: K => Future[V]): Future[V] = underlying .get( key, asJavaBiFunction((k: K, _: Executor) => mappingFunction(k).toJava.toCompletableFuture ) ) .toScala /** Returns the future of a map of the values associated with `keys`, creating or retrieving * those values if necessary. The returned map contains entries that were already cached, combined * with newly loaded entries. If the any of the asynchronous computations fail, those entries will * be automatically removed from this cache. * * A single request to the `mappingFunction` is performed for all keys which are not already * present in the cache. * * @param keys the keys whose associated values are to be returned * @param mappingFunction the function to asynchronously compute the values * @return the future containing an unmodifiable mapping of keys to values for the specified keys * in this cache * @throws java.lang.RuntimeException or Error if the mappingFunction does when constructing the future, * in which case the mapping is left unestablished */ def getAll( keys: Iterable[K], mappingFunction: Iterable[K] => Map[K, V] ): Future[Map[K, V]] = underlying .getAll( keys.asJava, asJavaFunction((ks: java.lang.Iterable[_ <: K]) => mappingFunction(ks.asScala).asJava ) ) .toScala .map(_.asScala.toMap) /** Returns the future of a map of the values associated with `keys`, creating or retrieving * those values if necessary. The returned map contains entries that were already cached, combined * with newly loaded entries. If the any of the asynchronous computations fail, those entries will * be automatically removed from this cache. * * A single request to the `mappingFunction` is performed for all keys which are not already * present in the cache. * * @param keys the keys whose associated values are to be returned * @param mappingFunction the function to asynchronously compute the values * @return the future containing an unmodifiable mapping of keys to values for the specified keys * in this cache * @throws java.lang.RuntimeException or Error if the mappingFunction does when constructing the future, * in which case the mapping is left unestablished */ def getAllFuture( keys: Iterable[K], mappingFunction: Iterable[K] => Future[Map[K, V]] ): Future[Map[K, V]] = underlying .getAll( keys.asJava, asJavaBiFunction((ks: java.lang.Iterable[_ <: K], _: Executor) => mappingFunction(ks.asScala).map(_.asJava).toJava.toCompletableFuture ) ) .toScala .map(_.asScala.toMap) /** Associates `value` with `key` in this cache. If the cache previously contained a * value associated with `key`, the old value is replaced by `value`. If the * asynchronous computation fails, the entry will be automatically removed. * * @param key key with which the specified value is to be associated * @param valueFuture value to be associated with the specified key */ def put(key: K, valueFuture: Future[V]): Unit = underlying.put(key, valueFuture.toJava.toCompletableFuture) /** Returns a view of the entries stored in this cache as a synchronous [[Cache]]. A * mapping is not present if the value is currently being loaded. Modifications made to the * synchronous cache directly affect the asynchronous cache. If a modification is made to a * mapping that is currently loading, the operation blocks until the computation completes. * * @return a thread-safe synchronous view of this cache */ def synchronous(): Cache[K, V] = Cache(underlying.synchronous()) }
ybasket/scaffeine
project/CaffeineVersion.scala
object CaffeineVersion { val value: String = "3.0.2" }
ybasket/scaffeine
src/main/scala/com/github/blemale/scaffeine/DirectExecutionContext.scala
package com.github.blemale.scaffeine import scala.concurrent.ExecutionContext private[scaffeine] object DirectExecutionContext extends ExecutionContext { override def execute(command: Runnable): Unit = command.run() override def reportFailure(cause: Throwable): Unit = throw new IllegalStateException( "problem in scaffeine internal callback", cause ) }
ybasket/scaffeine
src/test/scala/com/github/blemale/scaffeine/DirectExecutor.scala
package com.github.blemale.scaffeine import java.util.concurrent.Executor object DirectExecutor extends Executor { override def execute(command: Runnable): Unit = command.run() }
cquiroz/scalatest
examples/src/main/scala/org/scalatest/examples/fixture/wordspec/sharing/ExampleSpec.scala
/* * 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.examples.fixture.wordspec.sharing import java.util.concurrent.ConcurrentHashMap import org.scalatest._ import DbServer._ import java.util.UUID.randomUUID object DbServer { // Simulating a database server type Db = StringBuffer private val databases = new ConcurrentHashMap[String, Db] def createDb(name: String): Db = { val db = new StringBuffer databases.put(name, db) db } def removeDb(name: String) { databases.remove(name) } } trait DbFixture { this: fixture.Suite => type FixtureParam = Db // Allow clients to populate the database after // it is created def populateDb(db: Db) {} def withFixture(test: OneArgTest): Outcome = { val dbName = randomUUID.toString val db = createDb(dbName) // create the fixture try { populateDb(db) // setup the fixture withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test } finally removeDb(dbName) // clean up the fixture } } class ExampleSpec extends fixture.WordSpec with DbFixture { override def populateDb(db: Db) { // setup the fixture db.append("ScalaTest is ") } "Testing" should { "should be easy" in { db => db.append("easy!") assert(db.toString === "ScalaTest is easy!") } "should be fun" in { db => db.append("fun!") assert(db.toString === "ScalaTest is fun!") } } // This test doesn't need a Db "Test code" should { "should be clear" in { () => val buf = new StringBuffer buf.append("ScalaTest code is ") buf.append("clear!") assert(buf.toString === "ScalaTest code is clear!") } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/concurrent/TimeoutsSpec.scala
/* * 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.concurrent import org.scalatest.OptionValues._ import Timeouts._ import org.scalatest.SharedHelpers.thisLineNumber import java.io.ByteArrayInputStream import java.net.SocketException import java.net.ServerSocket import java.net.Socket import java.nio.channels.SelectionKey import java.nio.channels.Selector import java.nio.channels.ServerSocketChannel import java.net.InetSocketAddress import java.nio.channels.SocketChannel import org.scalatest.time._ import org.scalatest.{SeveredStackTraces, FunSpec, Resources} import org.scalatest.exceptions.TestFailedException import org.scalatest.exceptions.TestCanceledException import org.scalatest.Retries._ import org.scalatest.tagobjects.Retryable import org.scalatest.Matchers class TimeoutsSpec extends FunSpec with Matchers with SeveredStackTraces { override def withFixture(test: NoArgTest) = { if (isRetryable(test)) withRetry { super.withFixture(test) } else super.withFixture(test) } describe("The failAfter construct") { it("should blow up with TestFailedException when it times out", Retryable) { val caught = the [TestFailedException] thrownBy { failAfter(Span(100, Millis)) { Thread.sleep(200) } } caught.message.value should be (Resources.timeoutFailedAfter("100 milliseconds")) caught.failedCodeLineNumber.value should equal (thisLineNumber - 5) caught.failedCodeFileName.value should be ("TimeoutsSpec.scala") } it("should pass normally when the timeout is not reached") { failAfter(Span(200, Millis)) { Thread.sleep(100) } } it("should blow up with TestFailedException when the task does not response interrupt request and pass after the timeout") { val caught = the [TestFailedException] thrownBy { failAfter(timeout = Span(100, Millis)) { for (i <- 1 to 10) { try { Thread.sleep(50) } catch { case _: InterruptedException => Thread.interrupted() // Swallow the interrupt } } } } } it("should not catch exception thrown from the test") { val caught = the [InterruptedException] thrownBy { failAfter(Span(100, Millis)) { throw new InterruptedException } } } it("should set the exception thrown from the test after timeout as cause of TestFailedException") { val caught = the [TestFailedException] thrownBy { failAfter(Span(100, Millis)) { for (i <- 1 to 10) { try { Thread.sleep(50) } catch { case _: InterruptedException => Thread.interrupted() // Swallow the interrupt } } throw new IllegalArgumentException("Something went wrong!") } } caught.getCause().getClass === classOf[IllegalArgumentException] } it("should close a Socket connection via SocketInterruptor when the timeout is reached") { val serverSocket = new ServerSocket(0) @volatile var drag = true val serverThread = new Thread() { override def run() { val clientSocket = serverSocket.accept() while(drag) { try { Thread.sleep(100) } catch { case _: InterruptedException => Thread.interrupted() } } serverSocket.close() } } serverThread.start() val clientSocket = new Socket("localhost", serverSocket.getLocalPort()) val inputStream = clientSocket.getInputStream() val caught = the [TestFailedException] thrownBy { failAfter(Span(100, Millis)) { inputStream.read() } (SocketInterruptor(clientSocket)) } clientSocket.close() drag = false } it("should close a Socket connection via FunInterruptor when the timeout is reached") { val serverSocket = new ServerSocket(0) @volatile var drag = true val serverThread = new Thread() { override def run() { val clientSocket = serverSocket.accept() while(drag) { try { Thread.sleep(100) } catch { case _: InterruptedException => Thread.interrupted() } } serverSocket.close() } } serverThread.start() val clientSocket = new Socket("localhost", serverSocket.getLocalPort()) val inputStream = clientSocket.getInputStream() val caught = the [TestFailedException] thrownBy { failAfter(Span(100, Millis)) { inputStream.read() } (Interruptor { t => clientSocket.close() }) } clientSocket.close() drag = false } it("should wait for the test to finish when DoNotInterrupt is used.") { var x = 0 val caught = the [TestFailedException] thrownBy { failAfter(Span(100, Millis)) { Thread.sleep(200) x = 1 } (DoNotInterrupt) } x should be (1) } it("should close a Selector connection via SelectorInterruptor when the timeout is reached") { val selector = Selector.open() val ssChannel = ServerSocketChannel.open() ssChannel.configureBlocking(false) ssChannel.socket().bind(new InetSocketAddress(0)) ssChannel.register(selector, SelectionKey.OP_ACCEPT) @volatile var drag = true val serverThread = new Thread() { override def run() { selector.select() val it = selector.selectedKeys.iterator while (it.hasNext) { val selKey = it.next().asInstanceOf[SelectionKey] it.remove() if (selKey.isAcceptable()) { val ssChannel = selKey.channel().asInstanceOf[ServerSocketChannel] while(drag) { try { Thread.sleep(100) } catch { case _: InterruptedException => Thread.interrupted() } } } } ssChannel.close() } } val clientSelector = Selector.open(); val sChannel = SocketChannel.open() sChannel.configureBlocking(false); sChannel.connect(new InetSocketAddress("localhost", ssChannel.socket().getLocalPort())); sChannel.register(selector, sChannel.validOps()); val caught = the [TestFailedException] thrownBy { failAfter(Span(100, Millis)) { clientSelector.select() } (SelectorInterruptor(clientSelector)) } clientSelector.close() drag = false } } describe("The cancelAfter construct") { it("should blow up with TestCanceledException when it times out") { val caught = the [TestCanceledException] thrownBy { cancelAfter(Span(1000, Millis)) { Thread.sleep(2000) } } caught.message.value should be (Resources.timeoutCanceledAfter("1000 milliseconds")) caught.failedCodeLineNumber.value should equal (thisLineNumber - 5) caught.failedCodeFileName.value should be ("TimeoutsSpec.scala") } it("should pass normally when timeout is not reached") { cancelAfter(Span(2000, Millis)) { Thread.sleep(1000) } } it("should blow up with TestCanceledException when the task does not response interrupt request and pass after the timeout") { val caught = the [TestCanceledException] thrownBy { cancelAfter(timeout = Span(1000, Millis)) { for (i <- 1 to 10) { try { Thread.sleep(500) } catch { case _: InterruptedException => Thread.interrupted() // Swallow the interrupt } } } } } it("should not catch exception thrown from the test") { val caught = the [InterruptedException] thrownBy { cancelAfter(Span(1000, Millis)) { throw new InterruptedException } } } it("should set exception thrown from the test after timeout as cause of TestCanceledException") { val caught = the [TestCanceledException] thrownBy { cancelAfter(Span(1000, Millis)) { for (i <- 1 to 10) { try { Thread.sleep(500) } catch { case _: InterruptedException => Thread.interrupted() // Swallow the interrupt } } throw new IllegalArgumentException("Something goes wrong!") } } caught.getCause().getClass === classOf[IllegalArgumentException] } it("should close Socket connection via SocketInterruptor when timeout reached") { val serverSocket = new ServerSocket(0) @volatile var drag = true val serverThread = new Thread() { override def run() { val clientSocket = serverSocket.accept() while(drag) { try { Thread.sleep(1000) } catch { case _: InterruptedException => Thread.interrupted() } } serverSocket.close() } } serverThread.start() val clientSocket = new Socket("localhost", serverSocket.getLocalPort()) val inputStream = clientSocket.getInputStream() val caught = the [TestCanceledException] thrownBy { cancelAfter(Span(1000, Millis)) { inputStream.read() } (SocketInterruptor(clientSocket)) } clientSocket.close() drag = false } it("should close Socket connection via FunInterruptor when timeout reached") { val serverSocket = new ServerSocket(0) @volatile var drag = true val serverThread = new Thread() { override def run() { val clientSocket = serverSocket.accept() while(drag) { try { Thread.sleep(1000) } catch { case _: InterruptedException => Thread.interrupted() } } serverSocket.close() } } serverThread.start() val clientSocket = new Socket("localhost", serverSocket.getLocalPort()) val inputStream = clientSocket.getInputStream() val caught = the [TestCanceledException] thrownBy { cancelAfter(Span(1000, Millis)) { inputStream.read() } ( Interruptor { t => clientSocket.close() } ) } clientSocket.close() drag = false } it("should wait for the test to finish when DoNotInterrupt is used.") { var x = 0 val caught = the [TestCanceledException] thrownBy { cancelAfter(Span(1000, Millis)) { Thread.sleep(2000) x = 1 } (DoNotInterrupt) } x should be (1) } it("should close Selector connection via SelectorInterruptor when timeout reached") { val selector = Selector.open() val ssChannel = ServerSocketChannel.open() ssChannel.configureBlocking(false) ssChannel.socket().bind(new InetSocketAddress(0)) ssChannel.register(selector, SelectionKey.OP_ACCEPT) @volatile var drag = true val serverThread = new Thread() { override def run() { selector.select() val it = selector.selectedKeys.iterator while (it.hasNext) { val selKey = it.next().asInstanceOf[SelectionKey] it.remove() if (selKey.isAcceptable()) { val ssChannel = selKey.channel().asInstanceOf[ServerSocketChannel] while(drag) { try { Thread.sleep(1000) } catch { case _: InterruptedException => Thread.interrupted() } } } } ssChannel.close() } } val clientSelector = Selector.open(); val sChannel = SocketChannel.open() sChannel.configureBlocking(false); sChannel.connect(new InetSocketAddress("localhost", ssChannel.socket().getLocalPort())); sChannel.register(selector, sChannel.validOps()); val caught = the [TestCanceledException] thrownBy { cancelAfter(Span(1000, Millis)) { clientSelector.select() } (SelectorInterruptor(clientSelector)) } clientSelector.close() drag = false } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/tools/SuiteDiscoveryHelperSuite.scala
/* * 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.tools import org.scalatest._ import scala.collection.mutable import java.io.File import java.util.regex.Pattern import SuiteDiscoveryHelper.discoverTests class SuiteDiscoveryHelperFriend(sdt: SuiteDiscoveryHelper.type) { def transformToClassName(fileName: String, fileSeparator: Char): Option[String] = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("org$scalatest$tools$SuiteDiscoveryHelper$$transformToClassName", Array(classOf[String], classOf[Char]): _*) m.setAccessible(true) m.invoke(sdt, Array[Object](fileName, new java.lang.Character(fileSeparator)): _*).asInstanceOf[Option[String]] } def extractClassNames(fileNames: Iterator[String], fileSeparator: Char): Iterator[String] = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("extractClassNames", Array(classOf[Iterator[String]], classOf[Char]): _*) m.setAccessible(true) m.invoke(sdt, Array[Object](fileNames, new java.lang.Character(fileSeparator)): _*).asInstanceOf[Iterator[String]] } def isAccessibleSuite(clazz: java.lang.Class[_]): Boolean = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("isAccessibleSuite", Array(classOf[Class[_]]): _*) // This one works in 2.7 // Array(classOf[Class])) // This one works in 2.6 m.setAccessible(true) m.invoke(sdt, Array[Object](clazz): _*).asInstanceOf[Boolean] } def isRunnable(clazz: java.lang.Class[_]): Boolean = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("isRunnable", Array(classOf[Class[_]]): _*) // This one works in 2.7 m.setAccessible(true) m.invoke(sdt, Array[Object](clazz): _*).asInstanceOf[Boolean] } def processFileNames(fileNames: Iterator[String], fileSeparator: Char, loader: ClassLoader, suffixes: Option[Pattern]): Set[String] = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("org$scalatest$tools$SuiteDiscoveryHelper$$processFileNames", Array(classOf[Iterator[String]], classOf[Char], classOf[ClassLoader], classOf[Option[Pattern]]): _*) m.setAccessible(true) m.invoke(sdt, Array[Object](fileNames, new java.lang.Character(fileSeparator), loader, suffixes): _*).asInstanceOf[Set[String]] } def getFileNamesSetFromFile(file: File, fileSeparator: Char): Set[String] = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("org$scalatest$tools$SuiteDiscoveryHelper$$getFileNamesSetFromFile", Array(classOf[File], classOf[Char]): _*) m.setAccessible(true) m.invoke(sdt, Array[Object](file, new java.lang.Character(fileSeparator)): _*).asInstanceOf[Set[String]] } def isDiscoverableSuite(clazz: java.lang.Class[_]): Boolean = { val m = Class.forName("org.scalatest.tools.SuiteDiscoveryHelper$").getDeclaredMethod("isDiscoverableSuite", Array(classOf[Class[_]]): _*) m.setAccessible(true) m.invoke(sdt, Array[Object](clazz): _*).asInstanceOf[Boolean] } } class SuiteDiscoveryHelperSpec extends Spec { val sdtf = new SuiteDiscoveryHelperFriend(SuiteDiscoveryHelper) val loader = getClass.getClassLoader val accessibleSuites = Set( "org.scalatest.tools.RunnerSpec", "org.scalatest.tools.SuiteDiscoveryHelperSpec", "org.scalatest.tools.SuiteDiscoveryHelperSpec2") // // Given this Suite's name and one of its test names, // discoverTests should return a SuiteParam object for this // Suite and the specified test. // def `test discover tests 1` = { val testSpecs = List(TestSpec("test discover tests 1", false)) val suiteParams = discoverTests(testSpecs, accessibleSuites, loader) assert(suiteParams.length === 1) val suiteParam = suiteParams(0) assert(suiteParam.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec") assert(suiteParam.testNames.length === 1) assert(suiteParam.testNames(0) === "test discover tests 1") assert(suiteParam.wildcardTestNames.length === 0) assert(suiteParam.nestedSuites.length === 0) } // // Given two test names, where only one is found, discoverTests should // return a SuiteParam with just the one test name. // def `test discover tests 2` = { val testSpecs = List( TestSpec("test discover tests 2", false), TestSpec("test discover tests X", false) ) val suiteParams = discoverTests(testSpecs, accessibleSuites, loader) assert(suiteParams.length === 1) val suiteParam = suiteParams(0) assert(suiteParam.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec") assert(suiteParam.testNames.length === 1) assert(suiteParam.testNames(0) === "test discover tests 2") assert(suiteParam.wildcardTestNames.length === 0) assert(suiteParam.nestedSuites.length === 0) } // // Given two test names, where both are found, discoverTests should // return a SuiteParam with both test names. // def `test discover tests 3` = { val testSpecs = List( TestSpec("test discover tests 2", false), TestSpec("test discover tests 1", false) ) val suiteParams = discoverTests(testSpecs, accessibleSuites, loader) assert(suiteParams.length === 1) val suiteParam = suiteParams(0) assert(suiteParam.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec") assert(suiteParam.testNames.length === 2) assert(suiteParam.testNames(0) === "test discover tests 1") assert(suiteParam.testNames(1) === "test discover tests 2") assert(suiteParam.wildcardTestNames.length === 0) assert(suiteParam.nestedSuites.length === 0) } // // Two test names, where both are in one Suite and one is in // two Suites. // def `test discover tests 4` = { val testSpecs = List( TestSpec("test discover tests 4", false), TestSpec("test discover tests 1", false) ) val suiteParams = discoverTests(testSpecs, accessibleSuites, loader) assert(suiteParams.length === 2) val suiteParam0 = suiteParams(0) assert(suiteParam0.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec") assert(suiteParam0.testNames.length === 2) assert(suiteParam0.testNames(0) === "test discover tests 1") assert(suiteParam0.testNames(1) === "test discover tests 4") assert(suiteParam0.wildcardTestNames.length === 0) assert(suiteParam0.nestedSuites.length === 0) val suiteParam1 = suiteParams(1) assert(suiteParam1.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec2") assert(suiteParam1.testNames.length === 1) assert(suiteParam1.testNames(0) === "test discover tests 4") assert(suiteParam1.wildcardTestNames.length === 0) assert(suiteParam1.nestedSuites.length === 0) } // // Discover tests using a substring. This should discover tests in // two Suites. // def `test discover tests A1` = { val testSpecs = List( TestSpec("test discover tests A", true) ) val suiteParams = discoverTests(testSpecs, accessibleSuites, loader) assert(suiteParams.length === 2) val suiteParam0 = suiteParams(0) assert(suiteParam0.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec") assert(suiteParam0.testNames.length === 0) assert(suiteParam0.wildcardTestNames.length === 1) assert(suiteParam0.wildcardTestNames(0) === "test discover tests A") assert(suiteParam0.nestedSuites.length === 0) val suiteParam1 = suiteParams(1) assert(suiteParam1.className === "org.scalatest.tools.SuiteDiscoveryHelperSpec2") assert(suiteParam1.testNames.length === 0) assert(suiteParam1.wildcardTestNames.length === 1) assert(suiteParam1.wildcardTestNames(0) === "test discover tests A") assert(suiteParam1.nestedSuites.length === 0) } def `test transform to class name` = { assert(sdtf.transformToClassName("bob.class", '/') === Some("bob")) assert(sdtf.transformToClassName("a.b.c.bob.class", '/') === Some("a.b.c.bob")) assert(sdtf.transformToClassName("a.b.c.bob", '/') === None) assert(sdtf.transformToClassName("", '/') === None) assert(sdtf.transformToClassName("notdotclass", '/') === None) assert(sdtf.transformToClassName(".class", '/') === None) assert(sdtf.transformToClassName("a/b/c/bob.class", '/') === Some("a.b.c.bob")) assert(sdtf.transformToClassName("a/b/c/bob", '/') === None) assert(sdtf.transformToClassName("/.class", '/') === None) assert(sdtf.transformToClassName("..class", '/') === Some(".")) assert(sdtf.transformToClassName("a\\b\\c\\bob.class", '\\') === Some("a.b.c.bob")) assert(sdtf.transformToClassName("a\\b\\c\\bob", '\\') === None) assert(sdtf.transformToClassName("\\.class", '\\') === None) } def `test is accessible suite` = { assert(sdtf.isAccessibleSuite(classOf[SuiteDiscoveryHelperSpec])) assert(!sdtf.isAccessibleSuite(classOf[PackageAccessSuite])) assert(!sdtf.isAccessibleSuite(classOf[PackageAccessConstructorSuite])) assert(!sdtf.isAccessibleSuite(classOf[Suite])) assert(!sdtf.isAccessibleSuite(classOf[Object])) } def `test extract class names` = { assert(sdtf.extractClassNames(List("bob.class").iterator, '/').toList === List("bob")) assert(sdtf.extractClassNames(List("bob.class", "manifest.txt", "a/b/c/bob.class").iterator, '/').toList === List("bob", "a.b.c.bob")) assert(sdtf.extractClassNames(List("bob.class", "manifest.txt", "a\\b\\c\\bob.class").iterator, '\\').toList === List("bob", "a.b.c.bob")) assert(sdtf.extractClassNames(List("bob.class", "manifest.txt", "/a/b/c/bob.class").iterator, '/').toList === List("bob", "a.b.c.bob")) } def `test process file names` = { val loader = getClass.getClassLoader val discoveredSet1 = sdtf.processFileNames(List("doesNotExist.txt", "noSuchfile.class").iterator, '/', loader, None) assert(discoveredSet1.isEmpty) val discoveredSet2 = sdtf.processFileNames(List("org/scalatest/EasySuite.class", "noSuchfile.class", "org/scalatest/FastAsLight.class").iterator, '/', loader, None) assert(discoveredSet2 === Set("org.scalatest.EasySuite")) val fileNames3 = List( "org/scalatest/EasySuite.class", "org/scalatest/RunnerSuite.class", "org/scalatest/SlowAsMolasses.class", "org/scalatest/SuiteSuite.class", "noSuchfile.class", "org/scalatest/FastAsLight.class" ) val classNames3 = Set( "org.scalatest.EasySuite", // "org.scalatest.RunnerSuite", dropped this when moved RunnerSuite to tools "org.scalatest.SuiteSuite" ) val discoveredSet3 = sdtf.processFileNames(fileNames3.iterator, '/', loader, None) assert(discoveredSet3 === classNames3) // Test with backslashes val fileNames4 = List( "org\\scalatest\\EasySuite.class", "org\\scalatest\\RunnerSuite.class", "org\\scalatest\\SlowAsMolasses.class", "org\\scalatest\\SuiteSuite.class", "noSuchfile.class", "org\\scalatest\\FastAsLight.class" ) val discoveredSet4 = sdtf.processFileNames(fileNames4.iterator, '\\', loader, None) assert(discoveredSet4 === classNames3) // Test with leading slashes val fileNames5 = List( "/org/scalatest/EasySuite.class", "/org/scalatest/RunnerSuite.class", "/org/scalatest/SlowAsMolasses.class", "/org/scalatest/SuiteSuite.class", "/noSuchfile.class", "/org/scalatest/FastAsLight.class" ) val discoveredSet5 = sdtf.processFileNames(fileNames5.iterator, '/', loader, None) assert(discoveredSet5 === classNames3) // Test for specified suffixes only val fileNames6 = List( "/org/scalatest/EasySuite.class", "/org/scalatest/RunnerSuite.class", "/org/scalatest/SlowAsMolasses.class", "/org/scalatest/SuiteSuite.class", "/org/scalatest/FilterSpec.class", "/noSuchfile.class", "/org/scalatest/FastAsLight.class" ) val classNames4 = Set( "org.scalatest.EasySuite", "org.scalatest.SuiteSuite", "org.scalatest.FilterSpec" ) val discoveredSet6 = sdtf.processFileNames(fileNames6.iterator, '/', loader, Some(Pattern.compile(".*(Suite)$"))) assert(discoveredSet6 === classNames3) val discoveredSet7 = sdtf.processFileNames(fileNames6.iterator, '/', loader, Some(Pattern.compile(".*(Spec|Suite)$"))) assert(discoveredSet7 === classNames4) } def `test get file names set from file` = { assert(sdtf.getFileNamesSetFromFile(new File("harness/fnIteratorTest/empty.txt"), '/') === Set("empty.txt")) /* This one doesn't work now that I've checked the harness into subversion, because it finds the svn files. So I need to first copy just the files I want somewhere, then run this. assert(sdtf.getFileNamesSetFromFile(new File("harness/fnIteratorTest"), '/') === Set("subDir2/inSubDir2.class", "subDir2/subSubDir/inSubSubDir.class", "empty.txt", "empty.class", "subDir1/inSubDir1.class")) */ } def `test is discoverable suite` = { assert(sdtf.isDiscoverableSuite(classOf[SuiteDiscoveryHelperSpec])) @DoNotDiscover class NotDiscoverable {} assert(!sdtf.isDiscoverableSuite(classOf[NotDiscoverable])) } def `test is runnable` = { class NormalClass {} class SuiteClass extends Suite @WrapWith(classOf[SuiteClass]) class AnnotateDefaultConstructor class WrongSuiteClass(testValue: String) extends Suite @WrapWith(classOf[WrongSuiteClass]) class AnnotateWrongConstructor assert(!sdtf.isRunnable(classOf[NormalClass])) assert(!sdtf.isRunnable(classOf[SuiteClass])) assert(!sdtf.isRunnable(classOf[AnnotateDefaultConstructor])) assert(!sdtf.isRunnable(classOf[AnnotateWrongConstructor])) assert(sdtf.isRunnable(classOf[SomeApiClass])) assert(sdtf.isRunnable(classOf[SomeApiSubClass])) } } // // This class is just used by tests in SuiteDiscoveryHelperSpec // for testing Suite discovery by test name. // class SuiteDiscoveryHelperSpec2 extends Spec { def `test discover tests 4` = { } def `test discover tests A2` = { } def `test discover tests A3` = { } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldBeEqualitySpec.scala
<reponame>cquiroz/scalatest /* * 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 import scala.collection.GenSeq import scala.collection.GenMap import scala.collection.GenSet import scala.collection.GenIterable import scala.collection.GenTraversable import scala.collection.GenTraversableOnce import scala.collection.mutable import scala.collection.mutable.ListBuffer import org.scalactic.Equality import org.scalactic.TripleEquals import Matchers._ class ShouldBeEqualitySpec extends Spec { object `the should be syntax should use the appropriate Equality type class` { def `for Any` { () should be (()) () shouldBe () () should not be (7) implicit val e = new Equality[Unit] { def areEqual(a: Unit, b: Any): Boolean = a != b } () should not be (()) () should be (7) () shouldBe 7 } def `for String` { "hi" should be ("hi") "hi" shouldBe "hi" "hi" should not be ("ho") implicit val e = new Equality[String] { def areEqual(a: String, b: Any): Boolean = a != b } "hi" should not be ("hi") "hi" should be ("ho") "hi" shouldBe "ho" } def `for Numeric` { 3 should be (3) 3 shouldBe 3 3 should not be (4) implicit val e = new Equality[Int] { def areEqual(a: Int, b: Any): Boolean = a != b } 3 should not be (3) 3 should be (4) 3 shouldBe 4 } object `for Map` { def `with default beity` { Map("I" -> 1, "II" -> 2) should be (Map("I" -> 1, "II" -> 2)) Map("I" -> 1, "II" -> 2) shouldBe Map("I" -> 1, "II" -> 2) Map("I" -> 1, "II" -> 2) should not be (Map("one" -> 1, "two" -> 2)) implicit val e = new Equality[GenMap[String, Int]] { def areEqual(a: GenMap[String, Int], b: Any): Boolean = a != b } Map("I" -> 1, "II" -> 2) should be (Map("I" -> 1, "II" -> 2)) Map("I" -> 1, "II" -> 2) shouldBe Map("I" -> 1, "II" -> 2) Map("I" -> 1, "II" -> 2) should not be (Map("one" -> 1, "two" -> 2)) } def `with inferred GenMap beity` { implicit def travEq[T <: GenMap[String, Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } Map("I" -> 1, "II" -> 2) should not be (Map("I" -> 1, "II" -> 2)) Map("I" -> 1, "II" -> 2) should be (Map("one" -> 1, "two" -> 2)) Map("I" -> 1, "II" -> 2) shouldBe Map("one" -> 1, "two" -> 2) } def `with specific Map beity` { implicit val e = new Equality[Map[String, Int]] { def areEqual(a: Map[String, Int], b: Any): Boolean = a != b } Map("I" -> 1, "II" -> 2) should not be (Map("I" -> 1, "II" -> 2)) Map("I" -> 1, "II" -> 2) should be (Map("one" -> 1, "two" -> 2)) Map("I" -> 1, "II" -> 2) shouldBe Map("one" -> 1, "two" -> 2) } def `with both GenMap and specific Map beity, though I don't know why this compiles` { implicit val e = new Equality[GenMap[String, Int]] { def areEqual(a: GenMap[String, Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[Map[String, Int]] { // Should pick the most specific one def areEqual(a: Map[String, Int], b: Any): Boolean = a != b } Map("I" -> 1, "II" -> 2) should not be (Map("I" -> 1, "II" -> 2)) Map("I" -> 1, "II" -> 2) should be (Map("one" -> 1, "two" -> 2)) Map("I" -> 1, "II" -> 2) shouldBe Map("one" -> 1, "two" -> 2) } def `with both inferred GenMap and specific Map beity` { implicit def travEq[T <: GenMap[String, Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } implicit val e2 = new Equality[Map[String, Int]] { // Should pick the most specific one def areEqual(a: Map[String, Int], b: Any): Boolean = a != b } Map("I" -> 1, "II" -> 2) should not be (Map("I" -> 1, "II" -> 2)) Map("I" -> 1, "II" -> 2) should be (Map("one" -> 1, "two" -> 2)) Map("I" -> 1, "II" -> 2) shouldBe Map("one" -> 1, "two" -> 2) } } object `for mutable.Map` { def `with default beity` { mutable.Map("I" -> 1, "II" -> 2) should be (mutable.Map("I" -> 1, "II" -> 2)) mutable.Map("I" -> 1, "II" -> 2) shouldBe mutable.Map("I" -> 1, "II" -> 2) mutable.Map("I" -> 1, "II" -> 2) should not be (mutable.Map("one" -> 1, "two" -> 2)) implicit val e = new Equality[GenMap[String, Int]] { def areEqual(a: GenMap[String, Int], b: Any): Boolean = a != b } mutable.Map("I" -> 1, "II" -> 2) should be (mutable.Map("I" -> 1, "II" -> 2)) mutable.Map("I" -> 1, "II" -> 2) shouldBe mutable.Map("I" -> 1, "II" -> 2) mutable.Map("I" -> 1, "II" -> 2) should not be (mutable.Map("one" -> 1, "two" -> 2)) } def `with inferred GenMap beity` { implicit def travEq[T <: GenMap[String, Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } mutable.Map("I" -> 1, "II" -> 2) should not be (mutable.Map("I" -> 1, "II" -> 2)) mutable.Map("I" -> 1, "II" -> 2) should be (mutable.Map("one" -> 1, "two" -> 2)) mutable.Map("I" -> 1, "II" -> 2) shouldBe mutable.Map("one" -> 1, "two" -> 2) } def `with specific mutable.Map beity` { implicit val e = new Equality[mutable.Map[String, Int]] { def areEqual(a: mutable.Map[String, Int], b: Any): Boolean = a != b } mutable.Map("I" -> 1, "II" -> 2) should not be (mutable.Map("I" -> 1, "II" -> 2)) mutable.Map("I" -> 1, "II" -> 2) should be (mutable.Map("one" -> 1, "two" -> 2)) mutable.Map("I" -> 1, "II" -> 2) shouldBe mutable.Map("one" -> 1, "two" -> 2) } def `with both GenMap and specific mutable.Map beity, though I don't know why this compiles` { implicit val e = new Equality[GenMap[String, Int]] { def areEqual(a: GenMap[String, Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[mutable.Map[String, Int]] { // Should pick the most specific one def areEqual(a: mutable.Map[String, Int], b: Any): Boolean = a != b } mutable.Map("I" -> 1, "II" -> 2) should not be (mutable.Map("I" -> 1, "II" -> 2)) mutable.Map("I" -> 1, "II" -> 2) should be (mutable.Map("one" -> 1, "two" -> 2)) mutable.Map("I" -> 1, "II" -> 2) shouldBe mutable.Map("one" -> 1, "two" -> 2) } def `with both inferred GenMap and specific mutable.Map beity` { implicit def travEq[T <: GenMap[String, Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } implicit val e2 = new Equality[mutable.Map[String, Int]] { // Should pick the most specific one def areEqual(a: mutable.Map[String, Int], b: Any): Boolean = a != b } mutable.Map("I" -> 1, "II" -> 2) should not be (mutable.Map("I" -> 1, "II" -> 2)) mutable.Map("I" -> 1, "II" -> 2) should be (mutable.Map("one" -> 1, "two" -> 2)) mutable.Map("I" -> 1, "II" -> 2) shouldBe mutable.Map("one" -> 1, "two" -> 2) } } def `for AnyRef` { case class Person(name: String) Person("Joe") should be (Person("Joe")) Person("Joe") shouldBe Person("Joe") Person("Joe") should not be (Person("Sally")) implicit val e = new Equality[Person] { def areEqual(a: Person, b: Any): Boolean = a != b } Person("Joe") should not be (Person("Joe")) Person("Joe") should be (Person("Sally")) Person("Joe") shouldBe Person("Sally") } object `for Traversable` { def `with default beity` { Set(1, 2, 3) should be (Set(1, 2, 3)) Set(1, 2, 3) shouldBe Set(1, 2, 3) Set(1, 2, 3) should not be (Set(1, 2, 4)) implicit val e = new Equality[GenTraversable[Int]] { def areEqual(a: GenTraversable[Int], b: Any): Boolean = a != b } Set(1, 2, 3) should be (Set(1, 2, 3)) Set(1, 2, 3) shouldBe Set(1, 2, 3) Set(1, 2, 3) should not be (Set(1, 2, 4)) } def `with inferred GenTraversable beity` { implicit def travEq[T <: GenTraversable[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } Set(1, 2, 3) should not be (Set(1, 2, 3)) Set(1, 2, 3) should be (Set(1, 2, 4)) Set(1, 2, 3) shouldBe Set(1, 2, 4) } def `with specific Traversable beity` { implicit val e = new Equality[Set[Int]] { def areEqual(a: Set[Int], b: Any): Boolean = a != b } Set(1, 2, 3) should not be (Set(1, 2, 3)) Set(1, 2, 3) should be (Set(1, 2, 4)) Set(1, 2, 3) shouldBe Set(1, 2, 4) } def `with both GenTraversable and specific Traversable beity` { implicit val e = new Equality[GenTraversable[Int]] { def areEqual(a: GenTraversable[Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[Set[Int]] { // Should pick the most specific one def areEqual(a: Set[Int], b: Any): Boolean = a != b } Set(1, 2, 3) should not be (Set(1, 2, 3)) Set(1, 2, 3) should be (Set(1, 2, 4)) Set(1, 2, 3) shouldBe Set(1, 2, 4) } def `with both inferred GenTraversable and specific Traversable beity` { implicit def travEq[T <: GenTraversable[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } implicit val e2 = new Equality[Set[Int]] { // Should pick the most specific one def areEqual(a: Set[Int], b: Any): Boolean = a != b } Set(1, 2, 3) should not be (Set(1, 2, 3)) Set(1, 2, 3) shouldBe Set(1, 2, 4) } } object `for mutable.Traversable` { def `with default beity` { mutable.Set(1, 2, 3) should be (mutable.Set(1, 2, 3)) mutable.Set(1, 2, 3) shouldBe mutable.Set(1, 2, 3) mutable.Set(1, 2, 3) should not be (mutable.Set(1, 2, 4)) implicit val e = new Equality[GenTraversable[Int]] { def areEqual(a: GenTraversable[Int], b: Any): Boolean = a != b } mutable.Set(1, 2, 3) should be (mutable.Set(1, 2, 3)) mutable.Set(1, 2, 3) shouldBe mutable.Set(1, 2, 3) mutable.Set(1, 2, 3) should not be (mutable.Set(1, 2, 4)) } def `with inferred GenTraversable beity` { implicit def travEq[T <: GenTraversable[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } mutable.Set(1, 2, 3) should not be (mutable.Set(1, 2, 3)) mutable.Set(1, 2, 3) should be (mutable.Set(1, 2, 4)) mutable.Set(1, 2, 3) shouldBe mutable.Set(1, 2, 4) } def `with specific mutable.Traversable beity` { implicit val e = new Equality[mutable.Set[Int]] { def areEqual(a: mutable.Set[Int], b: Any): Boolean = a != b } mutable.Set(1, 2, 3) should not be (mutable.Set(1, 2, 3)) mutable.Set(1, 2, 3) should be (mutable.Set(1, 2, 4)) mutable.Set(1, 2, 3) shouldBe mutable.Set(1, 2, 4) } def `with both GenTraversable and specific Traversable beity` { implicit val e = new Equality[GenTraversable[Int]] { def areEqual(a: GenTraversable[Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[mutable.Set[Int]] { // Should pick the most specific one def areEqual(a: mutable.Set[Int], b: Any): Boolean = a != b } mutable.Set(1, 2, 3) should not be (mutable.Set(1, 2, 3)) mutable.Set(1, 2, 3) should be (mutable.Set(1, 2, 4)) mutable.Set(1, 2, 3) shouldBe mutable.Set(1, 2, 4) } def `with both inferred GenTraversable and specific Traversable beity` { implicit def travEq[T <: GenTraversable[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } implicit val e2 = new Equality[mutable.Set[Int]] { // Should pick the most specific one def areEqual(a: mutable.Set[Int], b: Any): Boolean = a != b } mutable.Set(1, 2, 3) should not be (mutable.Set(1, 2, 3)) mutable.Set(1, 2, 3) should be (mutable.Set(1, 2, 4)) mutable.Set(1, 2, 3) shouldBe mutable.Set(1, 2, 4) } } object `for Java Collection` { val javaSet123: java.util.Set[Int] = new java.util.HashSet javaSet123.add(1) javaSet123.add(2) javaSet123.add(3) val javaSet124: java.util.Set[Int] = new java.util.HashSet javaSet124.add(1) javaSet124.add(2) javaSet124.add(4) def `with default beity` { javaSet123 should be (javaSet123) javaSet123 shouldBe javaSet123 javaSet123 should not be (javaSet124) implicit val e = new Equality[java.util.Collection[Int]] { def areEqual(a: java.util.Collection[Int], b: Any): Boolean = a != b } javaSet123 should be (javaSet123) javaSet123 shouldBe javaSet123 javaSet123 should not be (javaSet124) } def `with inferred Collection beity` { implicit def travEq[T <: java.util.Collection[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } javaSet123 should not be (javaSet123) javaSet123 should be (javaSet124) javaSet123 shouldBe javaSet124 } def `with specific Collection beity` { implicit val e = new Equality[java.util.Set[Int]] { def areEqual(a: java.util.Set[Int], b: Any): Boolean = a != b } javaSet123 should not be (javaSet123) javaSet123 should be (javaSet124) javaSet123 shouldBe javaSet124 } def `with both Collection and specific Collection beity` { implicit val e = new Equality[java.util.Collection[Int]] { def areEqual(a: java.util.Collection[Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[java.util.Set[Int]] { // Should pick the most specific one def areEqual(a: java.util.Set[Int], b: Any): Boolean = a != b } javaSet123 should not be (javaSet123) javaSet123 should be (javaSet124) javaSet123 shouldBe javaSet124 } def `with both inferred Collection and specific Collection beity` { implicit def travEq[T <: java.util.Collection[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } implicit val e2 = new Equality[java.util.Set[Int]] { // Should pick the most specific one def areEqual(a: java.util.Set[Int], b: Any): Boolean = a != b } javaSet123 should not be (javaSet123) javaSet123 should be (javaSet124) javaSet123 shouldBe javaSet124 } } object `for Java Map` { val javaMap123: java.util.HashMap[String, Int] = new java.util.HashMap javaMap123.put("one",1) javaMap123.put("two", 2) javaMap123.put("three", 3) val javaMap124: java.util.HashMap[String, Int] = new java.util.HashMap javaMap124.put("one",1) javaMap124.put("two", 2) javaMap124.put("four", 4) def `with default beity` { javaMap123 should be (javaMap123) javaMap123 shouldBe javaMap123 javaMap123 should not be (javaMap124) implicit val e = new Equality[java.util.Map[String, Int]] { def areEqual(a: java.util.Map[String, Int], b: Any): Boolean = a != b } javaMap123 should be (javaMap123) javaMap123 shouldBe javaMap123 javaMap123 should not be (javaMap124) } def `with inferred Map beity` { implicit def travEq[T <: java.util.Map[String, Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } javaMap123 should not be (javaMap123) javaMap123 should be (javaMap124) javaMap123 shouldBe javaMap124 } def `with specific HashMap beity` { implicit val e = new Equality[java.util.HashMap[String, Int]] { def areEqual(a: java.util.HashMap[String, Int], b: Any): Boolean = a != b } javaMap123 should not be (javaMap123) javaMap123 should be (javaMap124) javaMap123 shouldBe javaMap124 } def `with both Map and specific HashMap beity` { implicit val e = new Equality[java.util.Map[String, Int]] { def areEqual(a: java.util.Map[String, Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[java.util.HashMap[String, Int]] { // Should pick this because it is an exact match def areEqual(a: java.util.HashMap[String, Int], b: Any): Boolean = a != b } javaMap123 should not be (javaMap123) javaMap123 should be (javaMap124) javaMap123 shouldBe javaMap124 } def `with both inferred Map and specific HashMap beity` { implicit def travEq[T <: java.util.Map[String, Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } implicit val e2 = new Equality[java.util.HashMap[String, Int]] { // Should pick the most specific one def areEqual(a: java.util.HashMap[String, Int], b: Any): Boolean = a != b } javaMap123 should not be (javaMap123) javaMap123 should be (javaMap124) javaMap123 shouldBe javaMap124 } } object `for Seq` { def `with default beity` { Vector(1, 2, 3) should be (Vector(1, 2, 3)) Vector(1, 2, 3) shouldBe Vector(1, 2, 3) Vector(1, 2, 3) should not be (Vector(1, 2, 4)) } def `with inferred GenSeq beity` { implicit def travEq[T <: GenSeq[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } Vector(1, 2, 3) should not be (Vector(1, 2, 3)) Vector(1, 2, 3) should be (Vector(1, 2, 4)) Vector(1, 2, 3) shouldBe Vector(1, 2, 4) } def `with specific Seq beity` { implicit val e = new Equality[Vector[Int]] { def areEqual(a: Vector[Int], b: Any): Boolean = a != b } Vector(1, 2, 3) should not be (Vector(1, 2, 3)) Vector(1, 2, 3) should be (Vector(1, 2, 4)) Vector(1, 2, 3) shouldBe Vector(1, 2, 4) } def `with both GenSeq and specific Seq beity` { implicit val e = new Equality[GenSeq[Int]] { def areEqual(a: GenSeq[Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[Vector[Int]] { // Should pick the exact one def areEqual(a: Vector[Int], b: Any): Boolean = a != b } Vector(1, 2, 3) should not be (Vector(1, 2, 3)) Vector(1, 2, 3) should be (Vector(1, 2, 4)) Vector(1, 2, 3) shouldBe Vector(1, 2, 4) } def `with both inferred GenSeq and specific Seq beity` { implicit def travEq[T <: GenSeq[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a == b } implicit val e2 = new Equality[Vector[Int]] { // Should pick the exact one def areEqual(a: Vector[Int], b: Any): Boolean = a != b } Vector(1, 2, 3) should not be (Vector(1, 2, 3)) Vector(1, 2, 3) should be (Vector(1, 2, 4)) Vector(1, 2, 3) shouldBe Vector(1, 2, 4) } } object `for mutable.Seq` { def `with default beity` { ListBuffer(1, 2, 3) should be (ListBuffer(1, 2, 3)) ListBuffer(1, 2, 3) shouldBe ListBuffer(1, 2, 3) ListBuffer(1, 2, 3) should not be (ListBuffer(1, 2, 4)) } def `with inferred GenSeq beity` { implicit def travEq[T <: GenSeq[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } ListBuffer(1, 2, 3) should not be (ListBuffer(1, 2, 3)) ListBuffer(1, 2, 3) should be (ListBuffer(1, 2, 4)) ListBuffer(1, 2, 3) shouldBe ListBuffer(1, 2, 4) } def `with specific Seq beity` { implicit val e = new Equality[ListBuffer[Int]] { def areEqual(a: ListBuffer[Int], b: Any): Boolean = a != b } ListBuffer(1, 2, 3) should not be (ListBuffer(1, 2, 3)) ListBuffer(1, 2, 3) should be (ListBuffer(1, 2, 4)) ListBuffer(1, 2, 3) shouldBe ListBuffer(1, 2, 4) } def `with both GenSeq and specific Seq beity` { implicit val e = new Equality[GenSeq[Int]] { def areEqual(a: GenSeq[Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[ListBuffer[Int]] { // Should pick the exact one def areEqual(a: ListBuffer[Int], b: Any): Boolean = a != b } ListBuffer(1, 2, 3) should not be (ListBuffer(1, 2, 3)) ListBuffer(1, 2, 3) should be (ListBuffer(1, 2, 4)) ListBuffer(1, 2, 3) shouldBe ListBuffer(1, 2, 4) } def `with both inferred GenSeq and specific Seq beity` { implicit def travEq[T <: GenSeq[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a == b } implicit val e2 = new Equality[ListBuffer[Int]] { // Should pick the exact one def areEqual(a: ListBuffer[Int], b: Any): Boolean = a != b } ListBuffer(1, 2, 3) should not be (ListBuffer(1, 2, 3)) ListBuffer(1, 2, 3) shouldBe ListBuffer(1, 2, 4) } } def `for Array` { Array(1, 2, 3) should be (Array(1, 2, 3)) Array(1, 2, 3) shouldBe Array(1, 2, 3) Array(1, 2, 3) should not be (Array(1, 2, 4)) implicit val e = new Equality[Array[Int]] { def areEqual(a: Array[Int], b: Any): Boolean = a.deep != b.asInstanceOf[Array[Int]].deep } Array(1, 2, 3) should not be (Array(1, 2, 3)) Array(1, 2, 3) should be (Array(1, 2, 4)) Array(1, 2, 3) shouldBe Array(1, 2, 4) } object `for Java List` { val javaList123: java.util.List[Int] = new java.util.ArrayList javaList123.add(1) javaList123.add(2) javaList123.add(3) val javaList124: java.util.List[Int] = new java.util.ArrayList javaList124.add(1) javaList124.add(2) javaList124.add(4) def `with default beity` { javaList123 should be (javaList123) javaList123 shouldBe javaList123 javaList123 should not be (javaList124) implicit val e = new Equality[java.util.Collection[Int]] { def areEqual(a: java.util.Collection[Int], b: Any): Boolean = a != b } javaList123 should be (javaList123) javaList123 shouldBe javaList123 javaList123 should not be (javaList124) } def `with inferred java.util.Collection beity` { implicit def travEq[T <: java.util.Collection[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a != b } javaList123 should not be (javaList123) javaList123 should be (javaList124) javaList123 shouldBe javaList124 } def `with specific java.util.List beity` { implicit val e = new Equality[java.util.List[Int]] { def areEqual(a: java.util.List[Int], b: Any): Boolean = a != b } javaList123 should not be (javaList123) javaList123 should be (javaList124) javaList123 shouldBe javaList124 } def `with both java.util.Collection and java.util.List beity` { implicit val e = new Equality[java.util.Collection[Int]] { def areEqual(a: java.util.Collection[Int], b: Any): Boolean = a == b } implicit val e2 = new Equality[java.util.List[Int]] { // Should pick the exact one def areEqual(a: java.util.List[Int], b: Any): Boolean = a != b } javaList123 should not be (javaList123) javaList123 should be (javaList124) javaList123 shouldBe javaList124 } def `with both inferred java.util.List and specific java.util.List beity` { implicit def travEq[T <: java.util.List[Int]] = new Equality[T] { def areEqual(a: T, b: Any): Boolean = a == b } implicit val e2 = new Equality[java.util.List[Int]] { // Should pick the exact one def areEqual(a: java.util.List[Int], b: Any): Boolean = a != b } javaList123 should not be (javaList123) javaList123 should be (javaList124) javaList123 shouldBe javaList124 } } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldExistSpec.scala
<reponame>cquiroz/scalatest /* * 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 import java.io.File import SharedHelpers.{createTempDirectory, thisLineNumber} import Matchers._ class ShouldExistSpec extends Spec { val tempDir = createTempDirectory() val existFile = File.createTempFile("delete", "me", tempDir) val imaginaryFile = new File(tempDir, "imaginary") val fileName = "ShouldExistSpec.scala" def doesNotExist(left: Any): String = FailureMessages.doesNotExist(left) def exists(left: Any): String = FailureMessages.exists(left) def allError(left: Any, message: String, lineNumber: Int): String = { val messageWithIndex = UnquotedString(" " + FailureMessages.forAssertionsGenTraversableMessageWithStackDepth(0, UnquotedString(message), UnquotedString(fileName + ":" + lineNumber))) FailureMessages.allShorthandFailed(messageWithIndex, left) } object `The exist syntax when used with File` { def `should do nothing when the file exists` { existFile should exist } def `should throw TFE with correct stack depth and message when the file does not exist` { val e = intercept[exceptions.TestFailedException] { imaginaryFile should exist } assert(e.message === Some(doesNotExist(imaginaryFile))) assert(e.failedCodeFileName === Some(fileName)) assert(e.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should do nothing when it is used with not and the file does not exists` { imaginaryFile should not (exist) } def `should throw TFE with correct stack depth and message when it is used with not and the file exists` { val e = intercept[exceptions.TestFailedException] { existFile should not (exist) } assert(e.message === Some(exists(existFile))) assert(e.failedCodeFileName === Some(fileName)) assert(e.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should do nothing when it is used with shouldNot and the file does not exists` { imaginaryFile shouldNot exist } def `should throw TFE with correct stack depth and message when it is used with shouldNot and the file exists` { val e = intercept[exceptions.TestFailedException] { existFile shouldNot exist } assert(e.message === Some(exists(existFile))) assert(e.failedCodeFileName === Some(fileName)) assert(e.failedCodeLineNumber === Some(thisLineNumber - 4)) } } object `The exist syntax when used with all(xs)` { def `should do nothing when the file exists` { all(List(existFile)) should exist } def `should throw TFE with correct stack depth and message when the file does not exist` { val left = List(imaginaryFile) val e = intercept[exceptions.TestFailedException] { all(left) should exist } assert(e.message === Some(allError(left, doesNotExist(imaginaryFile), thisLineNumber - 2))) assert(e.failedCodeFileName === Some(fileName)) assert(e.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should do nothing when it is used with not and the file does not exists` { all(List(imaginaryFile)) should not (exist) } def `should throw TFE with correct stack depth and message when it is used with not and the file exists` { val left = List(existFile) val e = intercept[exceptions.TestFailedException] { all(left) should not (exist) } assert(e.message === Some(allError(left, exists(existFile), thisLineNumber - 2))) assert(e.failedCodeFileName === Some(fileName)) assert(e.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should do nothing when it is used with shouldNot and the file does not exists` { all(List(imaginaryFile)) shouldNot exist } def `should throw TFE with correct stack depth and message when it is used with shouldNot and the file exists` { val left = List(existFile) val e = intercept[exceptions.TestFailedException] { all(left) shouldNot exist } assert(e.message === Some(allError(left, exists(existFile), thisLineNumber - 2))) assert(e.failedCodeFileName === Some(fileName)) assert(e.failedCodeLineNumber === Some(thisLineNumber - 4)) } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/matchers/Matcher.scala
/* * 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.matchers import org.scalatest.enablers._ import org.scalatest.MatchersHelper.orMatchersAndApply import org.scalatest.MatchersHelper.andMatchersAndApply import org.scalatest.words._ import scala.collection.GenTraversable import scala.reflect.ClassTag import scala.util.matching.Regex import org.scalactic.Equality import org.scalactic.EqualityPolicy.Spread import org.scalactic.EqualityPolicy.TripleEqualsInvocation import org.scalactic.Prettifier import org.scalatest.FailureMessages import org.scalatest.Resources /** * Trait extended by objects that can match a value of the specified type. The value to match is * passed to the matcher's <code>apply</code> method. The result is a <code>MatchResult</code>. * A matcher is, therefore, a function from the specified type, <code>T</code>, to a <code>MatchResult</code>. * <p></p> <!-- needed otherwise the heading below shows up in the wrong place. dumb scaladoc algo --> * * <h2>Creating custom matchers</h2> * * <p> * If none of the built-in matcher syntax satisfies 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, although you can ensure that a <code>java.io.File</code> has a name * that ends with a particular extension like this: * </p> * * <pre class="stHighlight"> * file.getName should endWith (".txt") * </pre> * * <p> * You might prefer * to create a custom <code>Matcher[java.io.File]</code> * named <code>endWithExtension</code>, so you could write expressions like: * </p> * * <pre class="stHighlight"> * file should endWithExtension ("txt") * file should not endWithExtension "txt" * file should (exist and endWithExtension ("txt")) * </pre> * * <p> * One good way to organize custom matchers is to place them inside one or more * traits that you can then mix into the suites that need them. Here's an example: * </p> * * <pre class="stHighlight"> * import org.scalatest._ * import matchers._ * * trait CustomMatchers { * * class FileEndsWithExtensionMatcher(expectedExtension: String) extends Matcher[java.io.File] { * * def apply(left: java.io.File) = { * val name = left.getName * MatchResult( * name.endsWith(expectedExtension), * s"""File $name did not end with extension "$expectedExtension"""", * s"""File $name ended with extension "$expectedExtension"""" * ) * } * } * * def endWithExtension(expectedExtension: String) = new FileEndsWithExtensionMatcher(expectedExtension) * } * * // Make them easy to import with: * // import CustomMatchers._ * object CustomMatchers extends CustomMatchers * </pre> * * <p> * Note: the <code>CustomMatchers</code> companion object exists to make it easy to bring the * matchers defined in this trait into scope via importing, instead of mixing in the trait. The ability * to import them is useful, for example, when you want to use the matchers defined in a trait in the Scala interpreter console. * </p> * * <p> * This trait contains one matcher class, <code>FileEndsWithExtensionMatcher</code>, and a <code>def</code> named <code>endWithExtension</code> that returns a new * instance of <code>FileEndsWithExtensionMatcher</code>. Because the class extends <code>Matcher[java.io.File]</code>, * the compiler will only allow it be used to match against instances of <code>java.io.File</code>. A matcher must declare an * <code>apply</code> method that takes the type decared in <code>Matcher</code>'s type parameter, in this case <code>java.io.File</code>. * The apply method will return a <code>MatchResult</code> whose <code>matches</code> field will indicate whether the match succeeded. * The <code>failureMessage</code> field will provide a programmer-friendly error message indicating, in the event of a match failure, what caused * the match to fail. * </p> * * <p> * The <code>FileEndsWithExtensionMatcher</code> matcher in this example determines success by determining if the passed <code>java.io.File</code> ends with * the desired extension. It does this in the first argument passed to the <code>MatchResult</code> factory method: * </p> * * <pre class="stHighlight"> * name.endsWith(expectedExtension) * </pre> * * <p> * In other words, if the file name has the expected extension, this matcher matches. * The next argument to <code>MatchResult</code>'s factory method produces the failure message string: * </p> * * <pre class="stHighlight"> * s"""File $name did not end with extension "$expectedExtension"""", * </pre> * * <p> * For example, consider this matcher expression: * </p> * * <pre class="stHighlight"> * import org.scalatest._ * import Matchers._ * import java.io.File * import CustomMatchers._ * * new File("essay.text") should endWithExtension ("txt") * </pre> * * <p> * Because the passed <code>java.io.File</code> has the name <code>essay.text</code>, but the expected extension is <code>"txt"</code>, the failure * message would be: * </p> * * <pre> * File essay.text did not have extension "txt" * </pre> * * <p> * For more information on the fields in a <code>MatchResult</code>, including the subsequent field (or fields) that follow the failure message, * please see the documentation for <a href="MatchResult.html"><code>MatchResult</code></a>. * </p> * * <a name="otherways"></a> * <h2>Creating dynamic matchers</h2> * * <p> * There are other ways to create new matchers besides defining one as shown above. For example, you might check that a file is hidden like this: * </p> * * <pre class="stHighlight"> * new File("secret.txt") should be ('hidden) * </pre> * * <p> * If you wanted to get rid of the tick mark, you could simply define <code>hidden</code> like this: * </p> * * <pre class="stHighlight"> * val hidden = 'hidden * </pre> * * <p> * Now you can check that an file is hidden without the tick mark: * </p> * * <pre class="stHighlight"> * new File("secret.txt") should be (hidden) * </pre> * * <p> * You could get rid of the parens with by using <code>shouldBe</code>: * </p> * * <pre class="stHighlight"> * new File("secret.txt") shouldBe hidden * </pre> * * <h2>Creating matchers using logical operators</h2> * * <p> * You can also use ScalaTest matchers' logical operators to combine existing matchers into new ones, like this: * </p> * * <pre class="stHighlight"> * val beWithinTolerance = be &gt;= 0 and be &lt;= 10 * </pre> * * <p> * Now you could check that a number is within the tolerance (in this case, between 0 and 10, inclusive), like this: * </p> * * <pre class="stHighlight"> * num should beWithinTolerance * </pre> * * <p> * When defining a full blown matcher, one shorthand is to use one of the factory methods in <code>Matcher</code>'s companion * object. For example, instead of writing this: * </p> * * <pre class="stHighlight"> * val beOdd = * new Matcher[Int] { * def apply(left: Int) = * MatchResult( * left % 2 == 1, * left + " was not odd", * left + " was odd" * ) * } * </pre> * * <p> * You could alternately write this: * </p> * * <pre class="stHighlight"> * val beOdd = * Matcher { (left: Int) =&gt; * MatchResult( * left % 2 == 1, * left + " was not odd", * left + " was odd" * ) * } * </pre> * * <p> * Either way you define the <code>beOdd</code> matcher, you could use it like this: * </p> * * <pre class="stHighlight"> * 3 should beOdd * 4 should not (beOdd) * </pre> * * <a name="composingMatchers"></a> * <h2>Composing matchers</h2> * * <p> * You can also compose matchers. For example, the <code>endWithExtension</code> matcher from the example above * can be more easily created by composing a function with the existing <code>endWith</code> matcher: * </p> * * <pre class="stREPL"> * scala&gt; import org.scalatest._ * import org.scalatest._ * * scala&gt; import Matchers._ * import Matchers._ * * scala&gt; import java.io.File * import java.io.File * * scala&gt; def endWithExtension(ext: String) = endWith(ext) compose { (f: File) =&gt; f.getPath } * endWithExtension: (ext: String)org.scalatest.matchers.Matcher[java.io.File] * </pre> * * <p> * Now you have a <code>Matcher[File]</code> whose <code>apply</code> method first * invokes the converter function to convert the passed <code>File</code> to a <code>String</code>, * then passes the resulting <code>String</code> to <code>endWith</code>. Thus, you could use this version * <code>endWithExtension</code> like the previous one: * </p> * * <pre class="stREPL"> * scala&gt; new File("output.txt") should endWithExtension("txt") * </pre> * * <p> * In addition, by composing twice, you can modify the type of both sides of a match statement * with the same function, like this: * </p> * * <pre class="stREPL"> * scala&gt; val f = be &gt; (_: Int) * f: Int =&gt; org.scalatest.matchers.Matcher[Int] = &lt;function1&gt; * * scala&gt; val g = (_: String).toInt * g: String =&gt; Int = &lt;function1&gt; * * scala&gt; val beAsIntsGreaterThan = (f compose g) andThen (_ compose g) * beAsIntsGreaterThan: String =&gt; org.scalatest.matchers.Matcher[String] = &lt;function1&gt; * * scala&gt; "8" should beAsIntsGreaterThan ("7") * </pre> * * <p> * At thsi point, however, the error message for the <code>beAsIntsGreaterThan</code> * gives no hint that the <code>Int</code>s being compared were parsed from <code>String</code>s: * </p> * * <pre class="stREPL"> * scala&gt; "7" should beAsIntsGreaterThan ("8") * org.scalatest.exceptions.TestFailedException: 7 was not greater than 8 * </pre> * * <p> * To modify error message, you can use trait <a href="MatcherProducers.html"><code>MatcherProducers</code></a>, which * also provides a <code>composeTwice</code> method that performs the <code>compose</code> ... * <code>andThen</code> ... <code>compose</code> operation: * </p> * * <pre class="stREPL"> * scala&gt; import matchers._ * import matchers._ * * scala&gt; import MatcherProducers._ * import MatcherProducers._ * * scala&gt; val beAsIntsGreaterThan = f composeTwice g // means: (f compose g) andThen (_ compose g) * beAsIntsGreaterThan: String =&gt; org.scalatest.matchers.Matcher[String] = &lt;function1&gt; * * scala&gt; "8" should beAsIntsGreaterThan ("7") * </pre> * * <p> * Of course, the error messages is still the same: * </p> * * <pre class="stREPL"> * scala&gt; "7" should beAsIntsGreaterThan ("8") * org.scalatest.exceptions.TestFailedException: 7 was not greater than 8 * </pre> * * <p> * To modify the error messages, you can use <code>mapResult</code> from <code>MatcherProducers</code>. Here's an example: * </p> * * <pre class="stREPL"> * scala&gt; val beAsIntsGreaterThan = * f composeTwice g mapResult { mr =&gt; * mr.copy( * failureMessageArgs = * mr.failureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})), * negatedFailureMessageArgs = * mr.negatedFailureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})), * midSentenceFailureMessageArgs = * mr.midSentenceFailureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})), * midSentenceNegatedFailureMessageArgs = * mr.midSentenceNegatedFailureMessageArgs.map((LazyArg(_) { "\"" + _.toString + "\".toInt"})) * ) * } * beAsIntsGreaterThan: String =&gt; org.scalatest.matchers.Matcher[String] = &lt;function1&gt; * </pre> * * <p> * The <code>mapResult</code> method takes a function that accepts a <code>MatchResult</code> and produces a new * <code>MatchResult</code>, which can contain modified arguments and modified error messages. In this example, * the error messages are being modified by wrapping the old arguments in <a href="LazyArg.html"><code>LazyArg</code></a> * instances that lazily apply the given prettification functions to the <code>toString</code> result of the old args. * Now the error message is clearer: * </p> * * <pre class="stREPL"> * scala&gt; "7" should beAsIntsGreaterThan ("8") * org.scalatest.exceptions.TestFailedException: "7".toInt was not greater than "8".toInt * </pre> * * <h2>Matcher's variance</h2> * * <p> * <code>Matcher</code> is contravariant in its type parameter, <code>T</code>, to make its use more flexible. * As an example, consider the hierarchy: * </p> * * <pre class="stHighlight"> * class Fruit * class Orange extends Fruit * class ValenciaOrange extends Orange * </pre> * * <p> * Given an orange: * </p> * * <pre class="stHighlight"> * val orange = Orange * </pre> * * <p> * The expression "<code>orange should</code>" will, via an implicit conversion in <code>Matchers</code>, * result in an object that has a <code>should</code> * method that takes a <code>Matcher[Orange]</code>. If the static type of the matcher being passed to <code>should</code> is * <code>Matcher[Valencia]</code> it shouldn't (and won't) compile. The reason it shouldn't compile is that * the left value is an <code>Orange</code>, but not necessarily a <code>Valencia</code>, and a * <code>Matcher[Valencia]</code> only knows how to match against a <code>Valencia</code>. The reason * it won't compile is given that <code>Matcher</code> is contravariant in its type parameter, <code>T</code>, a * <code>Matcher[Valencia]</code> is <em>not</em> a subtype of <code>Matcher[Orange]</code>. * </p> * * <p> * By contrast, if the static type of the matcher being passed to <code>should</code> is <code>Matcher[Fruit]</code>, * it should (and will) compile. The reason it <em>should</em> compile is that given the left value is an <code>Orange</code>, * it is also a <code>Fruit</code>, and a <code>Matcher[Fruit]</code> knows how to match against <code>Fruit</code>s. * The reason it <em>will</em> compile is that given that <code>Matcher</code> is contravariant in its type parameter, <code>T</code>, a * <code>Matcher[Fruit]</code> is indeed a subtype of <code>Matcher[Orange]</code>. * </p> * * @author <NAME> */ trait Matcher[-T] extends Function1[T, MatchResult] { outerInstance => /** * Check to see if the specified object, <code>left</code>, matches, and report the result in * the returned <code>MatchResult</code>. The parameter is named <code>left</code>, because it is * usually the value to the left of a <code>should</code> or <code>must</code> invocation. For example, * in: * * <pre class="stHighlight"> * list should equal (List(1, 2, 3)) * </pre> * * The <code>equal (List(1, 2, 3))</code> expression results in a matcher that holds a reference to the * right value, <code>List(1, 2, 3)</code>. The <code>should</code> method invokes <code>apply</code> * on this matcher, passing in <code>list</code>, which is therefore the "<code>left</code>" value. The * matcher will compare the <code>list</code> (the <code>left</code> value) with <code>List(1, 2, 3)</code> (the right * value), and report the result in the returned <code>MatchResult</code>. * * @param left the value against which to match * @return the <code>MatchResult</code> that represents the result of the match */ def apply(left: T): MatchResult /** * Compose this matcher with the passed function, returning a new matcher. * * <p> * This method overrides <code>compose</code> on <code>Function1</code> to * return a more specific function type of <code>Matcher</code>. For example, given * a <code>beOdd</code> matcher defined like this: * </p> * * <pre class="stHighlight"> * val beOdd = * new Matcher[Int] { * def apply(left: Int) = * MatchResult( * left % 2 == 1, * left + " was not odd", * left + " was odd" * ) * } * </pre> * * <p> * You could use <code>beOdd</code> like this: * </p> * * <pre class="stHighlight"> * 3 should beOdd * 4 should not (beOdd) * </pre> * * <p> * If for some odd reason, you wanted a <code>Matcher[String]</code> that * checked whether a string, when converted to an <code>Int</code>, * was odd, you could make one by composing <code>beOdd</code> with * a function that converts a string to an <code>Int</code>, like this: * </p> * * <pre class="stHighlight"> * val beOddAsInt = beOdd compose { (s: String) => s.toInt } * </pre> * * <p> * Now you have a <code>Matcher[String]</code> whose <code>apply</code> method first * invokes the converter function to convert the passed string to an <code>Int</code>, * then passes the resulting <code>Int</code> to <code>beOdd</code>. Thus, you could use * <code>beOddAsInt</code> like this: * </p> * * <pre class="stHighlight"> * "3" should beOddAsInt * "4" should not (beOddAsInt) * </pre> */ override def compose[U](g: U => T): Matcher[U] = new Matcher[U] { def apply(u: U) = outerInstance.apply(g(u)) } // TODO: mention not short circuited, and the precendence is even between and and or /** * Returns a matcher whose <code>apply</code> method returns a <code>MatchResult</code> * that represents the logical-and of the results of the wrapped and the passed matcher applied to * the same value. * * <p> * The reason <code>and</code> has an upper bound on its type parameter is so that the <code>Matcher</code> * resulting from an invocation of <code>and</code> will have the correct type parameter. If you call * <code>and</code> on a <code>Matcher[Orange]</code>, passing in a <code>Matcher[Valencia]</code>, * the result will have type <code>Matcher[Valencia]</code>. This is correct because both a * <code>Matcher[Orange]</code> and a <code>Matcher[Valencia]</code> know how to match a * <code>Valencia</code> (but a <code>Matcher[Valencia]</code> doesn't know how to * match any old <code>Orange</code>). If you call * <code>and</code> on a <code>Matcher[Orange]</code>, passing in a <code>Matcher[Fruit]</code>, * the result will have type <code>Matcher[Orange]</code>. This is also correct because both a * <code>Matcher[Orange]</code> and a <code>Matcher[Fruit]</code> know how to match an * <code>Orange</code> (but a <code>Matcher[Orange]</code> doesn't know how to * match any old <code>Fruit</code>). * </p> * * @param the matcher to logical-and with this matcher * @return a matcher that performs the logical-and of this and the passed matcher */ def and[U <: T](rightMatcher: Matcher[U]): Matcher[U] = new Matcher[U] { def apply(left: U): MatchResult = { andMatchersAndApply(left, outerInstance, rightMatcher) } override def toString: String = "(" + Prettifier.default(outerInstance) + ") and (" + Prettifier.default(rightMatcher) + ")" } import scala.language.higherKinds /** * Returns a <code>MatcherFactory</code> whose <code>matcher</code> method returns a <code>Matcher</code>, * which has <code>apply</code> method that returns a <code>MatchResult</code> that represents the logical-and * of the results of the wrapped and the passed <code>MatcherFactory</code> applied to the same value. * * @param rightMatcherFactory1 the <code>MatcherFactory</code> to logical-and with this <code>MatcherFactory</code> * @return a <code>MatcherFactory</code> that performs the logical-and of this and the passed <code>MatcherFactory</code> */ def and[U, TC1[_]](rightMatcherFactory1: MatcherFactory1[U, TC1]): MatcherFactory1[T with U, TC1] = new MatcherFactory1[T with U, TC1] { def matcher[V <: T with U : TC1]: Matcher[V] = { new Matcher[V] { def apply(left: V): MatchResult = { val rightMatcher = rightMatcherFactory1.matcher andMatchersAndApply(left, outerInstance, rightMatcher) } } } override def toString: String = "(" + Prettifier.default(outerInstance) + ") and (" + Prettifier.default(rightMatcherFactory1) + ")" } /** * Returns a matcher whose <code>apply</code> method returns a <code>MatchResult</code> * that represents the logical-or of the results of this and the passed matcher applied to * the same value. * * <p> * The reason <code>or</code> has an upper bound on its type parameter is so that the <code>Matcher</code> * resulting from an invocation of <code>or</code> will have the correct type parameter. If you call * <code>or</code> on a <code>Matcher[Orange]</code>, passing in a <code>Matcher[Valencia]</code>, * the result will have type <code>Matcher[Valencia]</code>. This is correct because both a * <code>Matcher[Orange]</code> and a <code>Matcher[Valencia]</code> know how to match a * <code>Valencia</code> (but a <code>Matcher[Valencia]</code> doesn't know how to * match any old <code>Orange</code>). If you call * <code>or</code> on a <code>Matcher[Orange]</code>, passing in a <code>Matcher[Fruit]</code>, * the result will have type <code>Matcher[Orange]</code>. This is also correct because both a * <code>Matcher[Orange]</code> and a <code>Matcher[Fruit]</code> know how to match an * <code>Orange</code> (but a <code>Matcher[Orange]</code> doesn't know how to * match any old <code>Fruit</code>). * </p> * * @param rightMatcher the matcher to logical-or with this matcher * @return a matcher that performs the logical-or of this and the passed matcher */ def or[U <: T](rightMatcher: Matcher[U]): Matcher[U] = new Matcher[U] { def apply(left: U): MatchResult = { orMatchersAndApply(left, outerInstance, rightMatcher) } override def toString: String = "(" + Prettifier.default(outerInstance) + ") or (" + Prettifier.default(rightMatcher) + ")" } /** * Returns a <code>MatcherFactory</code> whose <code>matcher</code> method returns a <code>Matcher</code>, * which has <code>apply</code> method that returns a <code>MatchResult</code> that represents the logical-or * of the results of the wrapped and the passed <code>MatcherFactory</code> applied to the same value. * * @param rightMatcherFactory1 the <code>MatcherFactory</code> to logical-or with this <code>MatcherFactory</code> * @return a <code>MatcherFactory</code> that performs the logical-or of this and the passed <code>MatcherFactory</code> */ def or[U, TC1[_]](rightMatcherFactory1: MatcherFactory1[U, TC1]): MatcherFactory1[T with U, TC1] = new MatcherFactory1[T with U, TC1] { def matcher[V <: T with U : TC1]: Matcher[V] = { new Matcher[V] { def apply(left: V): MatchResult = { val rightMatcher = rightMatcherFactory1.matcher orMatchersAndApply(left, outerInstance, rightMatcher) } override def toString: String = "(" + Prettifier.default(outerInstance) + ") or (" + Prettifier.default(rightMatcherFactory1) + ")" } } override def toString: String = "(" + Prettifier.default(outerInstance) + ") or (" + Prettifier.default(rightMatcherFactory1) + ")" } /** * 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 <NAME> */ final class AndHaveWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and have length (3 - 1) * ^ * </pre> */ def length(expectedLength: Long): MatcherFactory1[T, Length] = and(MatcherWords.have.length(expectedLength)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and have size (3 - 1) * ^ * </pre> */ def size(expectedSize: Long): MatcherFactory1[T, Size] = and(MatcherWords.have.size(expectedSize)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and have message ("A message from Mars") * ^ * </pre> */ def message(expectedMessage: String): MatcherFactory1[T, Messaging] = and(MatcherWords.have.message(expectedMessage)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and have size (3 - 1) * ^ * </pre> */ def and(haveWord: HaveWord): AndHaveWord = new AndHaveWord /** * 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 <NAME> */ final class AndContainWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain (3 - 1) * ^ * </pre> */ def apply[R](expectedElement: R): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.contain(expectedElement)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain key ("one") * ^ * </pre> */ def key(expectedKey: Any): MatcherFactory1[T, KeyMapping] = outerInstance.and(MatcherWords.contain.key(expectedKey)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain value (1) * ^ * </pre> */ def value(expectedValue: Any): MatcherFactory1[T, ValueMapping] = outerInstance.and(MatcherWords.contain.value(expectedValue)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain theSameElementsAs List(1, 2, 3) * ^ * </pre> */ def theSameElementsAs[R](right: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.theSameElementsAs(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain theSameElementsInOrderAs List(1, 2, 3) * ^ * </pre> */ def theSameElementsInOrderAs[R](right: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.contain.theSameElementsInOrderAs(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain inOrderOnly (1, 2, 3) * ^ * </pre> */ def inOrderOnly[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.contain.inOrderOnly(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain allOf (1, 2, 3) * ^ * </pre> */ def allOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.allOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain allElementsOf List(1, 2, 3) * ^ * </pre> */ def allElementsOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.allElementsOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain inOrder (1, 2, 3) * ^ * </pre> */ def inOrder[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.contain.inOrder(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain inOrderElementsOf List(1, 2, 3) * ^ * </pre> */ def inOrderElementsOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.contain.inOrderElementsOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain oneOf (1, 2, 3) * ^ * </pre> */ def oneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.contain.oneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain oneElementOf List(1, 2, 3) * ^ * </pre> */ def oneElementOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.contain.oneElementOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain atLeastOneOf (1, 2, 3) * ^ * </pre> */ def atLeastOneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.atLeastOneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain atLeastOneElementOf (1, 2, 3) * ^ * </pre> */ def atLeastOneElementOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.atLeastOneElementOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain only (1, 2, 3) * ^ * </pre> */ def only[R](right: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.only(right.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain noneOf (1, 2, 3) * ^ * </pre> */ def noneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.contain.noneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain noElementsOf (1, 2, 3) * ^ * </pre> */ def noElementsOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.contain.noElementsOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain atMostOneOf (1, 2, 3) * ^ * </pre> */ def atMostOneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.atMostOneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain atMostOneElementOf List(1, 2, 3) * ^ * </pre> */ def atMostOneElementOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.contain.atMostOneElementOf(elements)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and contain key ("one") * ^ * </pre> */ def and(containWord: ContainWord): AndContainWord = new AndContainWord /** * 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 <NAME> */ final class AndBeWord { // SKIP-SCALATESTJS-START /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and be a ('file) * ^ * </pre> */ def a(symbol: Symbol): Matcher[T with AnyRef] = and(MatcherWords.be.a(symbol)) // SKIP-SCALATESTJS-END /** * This method enables the following syntax, where <code>file</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and be a (file) * ^ * </pre> */ def a[U](bePropertyMatcher: BePropertyMatcher[U]): Matcher[T with AnyRef with U] = and(MatcherWords.be.a(bePropertyMatcher)) /** * This method enables the following syntax, where <code>positiveNumber</code> and <code>validNumber</code> are <a href="AMatcher.html"><code>AMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and be a (validNumber) * ^ * </pre> */ def a[U](aMatcher: AMatcher[U]): Matcher[T with U] = and(MatcherWords.be.a(aMatcher)) // SKIP-SCALATESTJS-START /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and be an ('apple) * ^ * </pre> */ def an(symbol: Symbol): Matcher[T with AnyRef] = and(MatcherWords.be.an(symbol)) // SKIP-SCALATESTJS-END /** * This method enables the following syntax, where <code>apple</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and be an (apple) * ^ * </pre> */ def an[U](bePropertyMatcher: BePropertyMatcher[U]): Matcher[T with AnyRef with U] = and(MatcherWords.be.an(bePropertyMatcher)) /** * This method enables the following syntax, where <code>integerNumber</code> is an <a href="AnMatcher.html"><code>AnMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and be an (integerNumber) * ^ * </pre> */ def an[U](anMatcher: AnMatcher[U]): Matcher[T with U] = and(MatcherWords.be.an(anMatcher)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and be theSameInstanceAs (string) * ^ * </pre> */ def theSameInstanceAs(anyRef: AnyRef): Matcher[T with AnyRef] = and(MatcherWords.be.theSameInstanceAs(anyRef)) /** * This method enables the following syntax, where <code>fraction</code> refers to a <code>PartialFunction</code>: * * <pre class="stHighlight"> * aMatcher and be definedAt (8) * ^ * </pre> */ def definedAt[A, U <: PartialFunction[A, _]](right: A): Matcher[T with U] = and(MatcherWords.be.definedAt(right)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and be a ('file) * ^ * </pre> */ def and(beWord: BeWord): AndBeWord = new AndBeWord /** * 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 <NAME> */ final class AndFullyMatchWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and fullyMatch regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = and(MatcherWords.fullyMatch.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and fullyMatch regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = and(MatcherWords.fullyMatch.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and fullyMatch regex (decimalRegex) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = and(MatcherWords.fullyMatch.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and fullyMatch regex (decimalRegex) * ^ * </pre> */ def and(fullyMatchWord: FullyMatchWord): AndFullyMatchWord = new AndFullyMatchWord /** * 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 <NAME> */ final class AndIncludeWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and include regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = and(MatcherWords.include.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and include regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = and(MatcherWords.include.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and include regex (decimalRegex) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = and(MatcherWords.include.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and include regex ("wor.d") * ^ * </pre> */ def and(includeWord: IncludeWord): AndIncludeWord = new AndIncludeWord /** * 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 <NAME> */ final class AndStartWithWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and startWith regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = and(MatcherWords.startWith.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and startWith regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = and(MatcherWords.startWith.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and startWith regex (decimalRegex) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = and(MatcherWords.startWith.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and startWith regex ("1.7") * ^ * </pre> */ def and(startWithWord: StartWithWord): AndStartWithWord = new AndStartWithWord /** * 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 <NAME> */ final class AndEndWithWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and endWith regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = and(MatcherWords.endWith.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and endWith regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = and(MatcherWords.endWith.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and endWith regex (decimalRegex) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = and(MatcherWords.endWith.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and endWith regex (decimalRegex) * ^ * </pre> */ def and(endWithWord: EndWithWord): AndEndWithWord = new AndEndWithWord /** * 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 <NAME> */ final class AndNotWord { /** * Get the <code>Matcher</code> instance, currently used by macro only. */ val owner = outerInstance /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not equal (3 - 1) * ^ * </pre> */ def equal[R](any: R): MatcherFactory1[T, EvidenceThat[R]#CanEqual] = outerInstance.and(MatcherWords.not.apply(MatcherWords.equal(any))) /** * This method enables the following syntax, for the "primitive" numeric types: * * <pre class="stHighlight"> * aMatcher and not equal (17.0 +- 0.2) * ^ * </pre> */ def equal[U](spread: Spread[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.equal(spread)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not equal (null) * ^ * </pre> */ def equal(o: Null): Matcher[T] = { outerInstance and { new Matcher[T] { def apply(left: T): MatchResult = { MatchResult( left != null, Resources.rawEqualedNull, Resources.rawDidNotEqualNull, Resources.rawMidSentenceEqualedNull, Resources.rawDidNotEqualNull, Vector.empty, Vector(left) ) } override def toString: String = "not equal null" } } } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be_== (3 - 1) * ^ * </pre> */ def be_==(any: Any): Matcher[T] = outerInstance.and(MatcherWords.not.apply(MatcherWords.be_==(any))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be_== (null) * ^ * </pre> */ def be_==(o: Null): Matcher[T with AnyRef] = outerInstance.and(MatcherWords.not.be_==(o)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be (3 - 1) * ^ * </pre> */ def be[R](any: R): MatcherFactory1[T, EvidenceThat[R]#CanEqual] = outerInstance.and(MatcherWords.not.apply(MatcherWords.be(any))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not have length (3) * ^ * </pre> */ def have(resultOfLengthWordApplication: ResultOfLengthWordApplication): MatcherFactory1[T, Length] = outerInstance.and(MatcherWords.not.apply(MatcherWords.have.length(resultOfLengthWordApplication.expectedLength))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not have size (3) * ^ * </pre> */ def have(resultOfSizeWordApplication: ResultOfSizeWordApplication): MatcherFactory1[T, Size] = outerInstance.and(MatcherWords.not.apply(MatcherWords.have.size(resultOfSizeWordApplication.expectedSize))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not have message ("Message from Mars!") * ^ * </pre> */ def have(resultOfMessageWordApplication: ResultOfMessageWordApplication): MatcherFactory1[T, Messaging] = outerInstance.and(MatcherWords.not.apply(MatcherWords.have.message(resultOfMessageWordApplication.expectedMessage))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not have (author ("Melville")) * ^ * </pre> */ def have[U](firstPropertyMatcher: HavePropertyMatcher[U, _], propertyMatchers: HavePropertyMatcher[U, _]*): Matcher[T with U] = outerInstance.and(MatcherWords.not.apply(MatcherWords.have(firstPropertyMatcher, propertyMatchers: _*))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be &lt; (6) * ^ * </pre> */ def be[U](resultOfLessThanComparison: ResultOfLessThanComparison[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfLessThanComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be (null) * ^ * </pre> */ def be(o: Null): Matcher[T with AnyRef] = outerInstance.and(MatcherWords.not.be(o)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be &gt; (6) * ^ * </pre> */ def be[U](resultOfGreaterThanComparison: ResultOfGreaterThanComparison[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfGreaterThanComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be &lt;= (2) * ^ * </pre> */ def be[U](resultOfLessThanOrEqualToComparison: ResultOfLessThanOrEqualToComparison[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfLessThanOrEqualToComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be &gt;= (6) * ^ * </pre> */ def be[U](resultOfGreaterThanOrEqualToComparison: ResultOfGreaterThanOrEqualToComparison[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfGreaterThanOrEqualToComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be === (6) * ^ * </pre> */ def be(tripleEqualsInvocation: TripleEqualsInvocation[_]): Matcher[T] = outerInstance.and(MatcherWords.not.be(tripleEqualsInvocation)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be ('empty) * ^ * </pre> */ def be(symbol: Symbol): Matcher[T with AnyRef] = outerInstance.and(MatcherWords.not.be(symbol)) /** * This method enables the following syntax, where <code>odd</code> is a <a href="BeMatcher.html"><code>BeMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be (odd) * ^ * </pre> */ def be[U](beMatcher: BeMatcher[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(beMatcher)) /** * This method enables the following syntax, where <code>directory</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be (directory) * ^ * </pre> */ def be[U](bePropertyMatcher: BePropertyMatcher[U]): Matcher[T with AnyRef with U] = outerInstance.and(MatcherWords.not.be(bePropertyMatcher)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be a ('file) * ^ * </pre> */ def be(resultOfAWordApplication: ResultOfAWordToSymbolApplication): Matcher[T with AnyRef] = outerInstance.and(MatcherWords.not.be(resultOfAWordApplication)) /** * This method enables the following syntax, where <code>validMarks</code> is an <a href="AMatcher.html"><code>AMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be a (validMarks) * ^ * </pre> */ def be[U](resultOfAWordApplication: ResultOfAWordToAMatcherApplication[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfAWordApplication)) /** * This method enables the following syntax, where <code>directory</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be a (directory) * ^ * </pre> */ def be[U <: AnyRef](resultOfAWordApplication: ResultOfAWordToBePropertyMatcherApplication[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfAWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be an ('apple) * ^ * </pre> */ def be(resultOfAnWordApplication: ResultOfAnWordToSymbolApplication): Matcher[T with AnyRef] = outerInstance.and(MatcherWords.not.be(resultOfAnWordApplication)) /** * This method enables the following syntax, where <code>directory</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be an (directory) * ^ * </pre> */ def be[T <: AnyRef](resultOfAnWordApplication: ResultOfAnWordToBePropertyMatcherApplication[T]) = outerInstance.and(MatcherWords.not.be(resultOfAnWordApplication)) /** * This method enables the following syntax, where <code>invalidMarks</code> is an <a href="AnMatcher.html"><code>AnMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be an (invalidMarks) * ^ * </pre> */ def be[U](resultOfAnWordApplication: ResultOfAnWordToAnMatcherApplication[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfAnWordApplication)) import language.experimental.macros /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be a [Book] * ^ * </pre> */ def be(aType: ResultOfATypeInvocation[_]): Matcher[T] = macro TypeMatcherMacro.andNotATypeMatcher /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be an [Apple] * ^ * </pre> */ def be(anType: ResultOfAnTypeInvocation[_]): Matcher[T] = macro TypeMatcherMacro.andNotAnTypeMatcher /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be theSameInstanceAs (otherString) * ^ * </pre> */ def be(resultOfTheSameInstanceAsApplication: ResultOfTheSameInstanceAsApplication): Matcher[T with AnyRef] = outerInstance.and(MatcherWords.not.be(resultOfTheSameInstanceAsApplication)) /** * This method enables the following syntax, for the "primitive" numeric types: * * <pre class="stHighlight"> * aMatcher and not be (17.0 +- 0.2) * ^ * </pre> */ def be[U](spread: Spread[U]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(spread)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be definedAt (8) * ^ * </pre> */ def be[A, U <: PartialFunction[A, _]](resultOfDefinedAt: ResultOfDefinedAt[A]): Matcher[T with U] = outerInstance.and(MatcherWords.not.be(resultOfDefinedAt)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be sorted * ^ * </pre> */ def be(sortedWord: SortedWord) = outerInstance.and(MatcherWords.not.be(sortedWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be readable * ^ * </pre> */ def be(readableWord: ReadableWord) = outerInstance.and(MatcherWords.not.be(readableWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be writable * ^ * </pre> */ def be(writableWord: WritableWord) = outerInstance.and(MatcherWords.not.be(writableWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be empty * ^ * </pre> */ def be(emptyWord: EmptyWord) = outerInstance.and(MatcherWords.not.be(emptyWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not be defined * ^ * </pre> */ def be(definedWord: DefinedWord) = outerInstance.and(MatcherWords.not.be(definedWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not fullyMatch regex (decimal) * ^ * </pre> */ def fullyMatch(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.and(MatcherWords.not.fullyMatch(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not include regex (decimal) * ^ * </pre> */ def include(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.and(MatcherWords.not.include(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not include ("1.7") * ^ * </pre> */ def include(expectedSubstring: String): Matcher[T with String] = outerInstance.and(MatcherWords.not.include(expectedSubstring)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not startWith regex (decimal) * ^ * </pre> */ def startWith(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.and(MatcherWords.not.startWith(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not startWith ("1.7") * ^ * </pre> */ def startWith(expectedSubstring: String): Matcher[T with String] = outerInstance.and(MatcherWords.not.startWith(expectedSubstring)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not endWith regex (decimal) * ^ * </pre> */ def endWith(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.and(MatcherWords.not.endWith(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not endWith ("1.7") * ^ * </pre> */ def endWith(expectedSubstring: String): Matcher[T with String] = outerInstance.and(MatcherWords.not.endWith(expectedSubstring)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain (3) * ^ * </pre> */ def contain[R](expectedElement: R): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.not.contain(expectedElement)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain oneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfOneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain oneElementOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfOneElementOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain atLeastOneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAtLeastOneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain atLeastOneElementOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfAtLeastOneElementOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain noneOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfNoneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain noElementsOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfNoElementsOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain theSameElementsAs (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfTheSameElementsAsApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain theSameElementsInOrderAs (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfTheSameElementsInOrderAsApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain only (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfOnlyApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain inOrderOnly (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfInOrderOnlyApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain allOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAllOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain allElementsOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAllElementsOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain inOrder (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfInOrderApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain inOrderElementsOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfInOrderElementsOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain atMostOneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAtMostOneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain atMostOneOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfAtMostOneElementOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.and(MatcherWords.not.contain(right)) // TODO: Write tests and impl for contain ResultOfKey/ValueWordApplication /** * This method enables the following syntax given a <code>Matcher</code>: * * <pre class="stHighlight"> * aMatcher and not contain key ("three") * ^ * </pre> */ def contain(resultOfKeyWordApplication: ResultOfKeyWordApplication): MatcherFactory1[T, KeyMapping] = outerInstance.and(MatcherWords.not.contain(resultOfKeyWordApplication)) /** * This method enables the following syntax given a <code>Matcher</code>: * * <pre class="stHighlight"> * aMatcher and not contain value (3) * ^ * </pre> */ def contain(resultOfValueWordApplication: ResultOfValueWordApplication): MatcherFactory1[T, ValueMapping] = outerInstance.and(MatcherWords.not.contain(resultOfValueWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not matchPattern { case Person("Bob", _) =>} * ^ * </pre> */ def matchPattern(right: PartialFunction[Any, _]) = macro MatchPatternMacro.andNotMatchPatternMatcher } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not contain value (3) * ^ * </pre> */ def and(notWord: NotWord): AndNotWord = new AndNotWord /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and exist * ^ * </pre> */ def and(existWord: ExistWord): MatcherFactory1[T, Existence] = outerInstance.and(MatcherWords.exist.matcherFactory) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher and not (exist) * ^ * </pre> */ def and(notExist: ResultOfNotExist): MatcherFactory1[T, Existence] = outerInstance.and(MatcherWords.not.exist) /** * 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 <NAME> */ final class OrHaveWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or have length (3 - 1) * ^ * </pre> */ def length(expectedLength: Long): MatcherFactory1[T, Length] = or(MatcherWords.have.length(expectedLength)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or have size (3 - 1) * ^ * </pre> */ def size(expectedSize: Long): MatcherFactory1[T, Size] = or(MatcherWords.have.size(expectedSize)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or have message ("Message from Mars!") * ^ * </pre> */ def message(expectedMessage: String): MatcherFactory1[T, Messaging] = or(MatcherWords.have.message(expectedMessage)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or have size (3 - 1) * ^ * </pre> */ def or(haveWord: HaveWord): OrHaveWord = new OrHaveWord /** * 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 <NAME> */ final class OrContainWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain (3 - 1) * ^ * </pre> */ def apply[R](expectedElement: R): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.contain(expectedElement)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain key ("one") * ^ * </pre> */ def key(expectedKey: Any): MatcherFactory1[T, KeyMapping] = outerInstance.or(MatcherWords.contain.key(expectedKey)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain value (1) * ^ * </pre> */ def value(expectedValue: Any): MatcherFactory1[T, ValueMapping] = outerInstance.or(MatcherWords.contain.value(expectedValue)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain theSameElementsAs List(1, 2, 3) * ^ * </pre> */ def theSameElementsAs[R](right: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.theSameElementsAs(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain theSameElementsInOrderAs List(1, 2, 3) * ^ * </pre> */ def theSameElementsInOrderAs[R](right: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.contain.theSameElementsInOrderAs(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain allOf (1, 2, 3) * ^ * </pre> */ def allOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.allOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain allElementsOf List(1, 2, 3) * ^ * </pre> */ def allElementsOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.allElementsOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain inOrder (1, 2, 3) * ^ * </pre> */ def inOrder[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.contain.inOrder(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain inOrderElementsOf List(1, 2, 3) * ^ * </pre> */ def inOrderElementsOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.contain.inOrderElementsOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain oneOf (1, 2, 3) * ^ * </pre> */ def oneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.contain.oneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain oneElementOf (1, 2, 3) * ^ * </pre> */ def oneElementOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.contain.oneElementOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain atLeastOneOf (1, 2, 3) * ^ * </pre> */ def atLeastOneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.atLeastOneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain atLeastOneElementOf (1, 2, 3) * ^ * </pre> */ def atLeastOneElementOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.atLeastOneElementOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain only (1, 2, 3) * ^ * </pre> */ def only[R](right: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.only(right.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain inOrderOnly (1, 2, 3) * ^ * </pre> */ def inOrderOnly[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.contain.inOrderOnly(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain noneOf (1, 2, 3) * ^ * </pre> */ def noneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.contain.noneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain noElementsOf (1, 2, 3) * ^ * </pre> */ def noElementsOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.contain.noElementsOf(elements)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain atMostOneOf (1, 2, 3) * ^ * </pre> */ def atMostOneOf[R](firstEle: R, secondEle: R, remainingEles: R*): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.atMostOneOf(firstEle, secondEle, remainingEles.toList: _*)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain atMostOneOf List(1, 2, 3) * ^ * </pre> */ def atMostOneElementOf[R](elements: GenTraversable[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.contain.atMostOneElementOf(elements)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or contain value (1) * ^ * </pre> */ def or(containWord: ContainWord): OrContainWord = new OrContainWord /** * 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 <NAME> */ final class OrBeWord { // SKIP-SCALATESTJS-START /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or be a ('directory) * ^ * </pre> */ def a(symbol: Symbol): Matcher[T with AnyRef] = or(MatcherWords.be.a(symbol)) // SKIP-SCALATESTJS-END /** * This method enables the following syntax, where <code>directory</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or be a (directory) * ^ * </pre> */ def a[U](bePropertyMatcher: BePropertyMatcher[U]): Matcher[T with AnyRef with U] = or(MatcherWords.be.a(bePropertyMatcher)) /** * This method enables the following syntax, where <code>positiveNumber</code> and <code>validNumber</code> are <a href="AMatcher.html"><code>AMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or be a (validNumber) * ^ * </pre> */ def a[U](aMatcher: AMatcher[U]): Matcher[T with U] = or(MatcherWords.be.a(aMatcher)) // SKIP-SCALATESTJS-START /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or be an ('apple) * ^ * </pre> */ def an(symbol: Symbol): Matcher[T with AnyRef] = or(MatcherWords.be.an(symbol)) // SKIP-SCALATESTJS-END /** * This method enables the following syntax, where <code>orange</code> and <code>apple</code> are <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or be an (apple) * ^ * </pre> */ def an[U](bePropertyMatcher: BePropertyMatcher[U]): Matcher[T with AnyRef with U] = or(MatcherWords.be.an(bePropertyMatcher)) /** * This method enables the following syntax, where <code>oddNumber</code> and <code>integerNumber</code> are <a href="AnMatcher.html"><code>AnMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or be an (integerNumber) * ^ * </pre> */ def an[U](anMatcher: AnMatcher[U]): Matcher[T with U] = or(MatcherWords.be.an(anMatcher)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or be theSameInstanceAs (otherString) * ^ * </pre> */ def theSameInstanceAs(anyRef: AnyRef): Matcher[T with AnyRef] = or(MatcherWords.be.theSameInstanceAs(anyRef)) /** * This method enables the following syntax, where <code>fraction</code> refers to a <code>PartialFunction</code>: * * <pre class="stHighlight"> * aMatcher or be definedAt (8) * ^ * </pre> */ def definedAt[A, U <: PartialFunction[A, _]](right: A): Matcher[T with U] = or(MatcherWords.be.definedAt(right)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or be a ('directory) * ^ * </pre> */ def or(beWord: BeWord): OrBeWord = new OrBeWord /** * 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 <NAME> */ final class OrFullyMatchWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or fullyMatch regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = or(MatcherWords.fullyMatch.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or fullyMatch regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = or(MatcherWords.fullyMatch.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or fullyMatch regex (decimal) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = or(MatcherWords.fullyMatch.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or fullyMatch regex (decimal) * ^ * </pre> */ def or(fullyMatchWord: FullyMatchWord): OrFullyMatchWord = new OrFullyMatchWord /** * 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 <NAME> */ final class OrIncludeWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or include regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = or(MatcherWords.include.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or include regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = or(MatcherWords.include.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or include regex (decimal) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = or(MatcherWords.include.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or include regex ("1.7") * ^ * </pre> */ def or(includeWord: IncludeWord): OrIncludeWord = new OrIncludeWord /** * 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 <NAME> */ final class OrStartWithWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or startWith regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = or(MatcherWords.startWith.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or startWith regex ("a(b*)c" withGroup "bb") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = or(MatcherWords.startWith.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or startWith regex (decimal) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = or(MatcherWords.startWith.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or startWith regex ("1.7") * ^ * </pre> */ def or(startWithWord: StartWithWord): OrStartWithWord = new OrStartWithWord /** * 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 <NAME> */ final class OrEndWithWord { /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or endWith regex (decimal) * ^ * </pre> */ def regex(regexString: String): Matcher[T with String] = or(MatcherWords.endWith.regex(regexString)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or endWith regex ("d(e*)f" withGroup "ee") * ^ * </pre> */ def regex(regexWithGroups: RegexWithGroups): Matcher[T with String] = or(MatcherWords.endWith.regex(regexWithGroups)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or endWith regex (decimal) * ^ * </pre> */ def regex(regex: Regex): Matcher[T with String] = or(MatcherWords.endWith.regex(regex)) } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or endWith regex ("7b") * ^ * </pre> */ def or(endWithWord: EndWithWord): OrEndWithWord = new OrEndWithWord /** * 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 <NAME> */ final class OrNotWord { /** * Get the <code>Matcher</code> instance, currently used by macro only. */ val owner = outerInstance /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not equal (2) * ^ * </pre> */ def equal[R](any: R): MatcherFactory1[T, EvidenceThat[R]#CanEqual] = outerInstance.or(MatcherWords.not.apply(MatcherWords.equal(any))) /** * This method enables the following syntax for the "primitive" numeric types: * * <pre class="stHighlight"> * aMatcher or not equal (17.0 +- 0.2) * ^ * </pre> */ def equal[U](spread: Spread[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.equal(spread)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not equal (null) * ^ * </pre> */ def equal(o: Null): Matcher[T] = { outerInstance or { new Matcher[T] { def apply(left: T): MatchResult = { MatchResult( left != null, Resources.rawEqualedNull, Resources.rawDidNotEqualNull, Resources.rawMidSentenceEqualedNull, Resources.rawDidNotEqualNull, Vector.empty, Vector(left) ) } override def toString: String = "not equal null" } } } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be_== (2) * ^ * </pre> */ def be_==(any: Any): Matcher[T] = outerInstance.or(MatcherWords.not.apply(MatcherWords.be_==(any))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be_== (null) * ^ * </pre> */ def be_==(o: Null): Matcher[T with AnyRef] = outerInstance.or(MatcherWords.not.be_==(o)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be (2) * ^ * </pre> */ def be[R](any: R): MatcherFactory1[T, EvidenceThat[R]#CanEqual] = outerInstance.or(MatcherWords.not.apply(MatcherWords.be(any))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not have length (3) * ^ * </pre> */ def have(resultOfLengthWordApplication: ResultOfLengthWordApplication): MatcherFactory1[T, Length] = outerInstance.or(MatcherWords.not.apply(MatcherWords.have.length(resultOfLengthWordApplication.expectedLength))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not have size (3) * ^ * </pre> */ def have(resultOfSizeWordApplication: ResultOfSizeWordApplication): MatcherFactory1[T, Size] = outerInstance.or(MatcherWords.not.apply(MatcherWords.have.size(resultOfSizeWordApplication.expectedSize))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not have message ("Message from Mars!") * ^ * </pre> */ def have(resultOfMessageWordApplication: ResultOfMessageWordApplication): MatcherFactory1[T, Messaging] = outerInstance.or(MatcherWords.not.apply(MatcherWords.have.message(resultOfMessageWordApplication.expectedMessage))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not have (author ("Melville")) * ^ * </pre> */ def have[U](firstPropertyMatcher: HavePropertyMatcher[U, _], propertyMatchers: HavePropertyMatcher[U, _]*): Matcher[T with U] = outerInstance.or(MatcherWords.not.apply(MatcherWords.have(firstPropertyMatcher, propertyMatchers: _*))) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be (null) * ^ * </pre> */ def be(o: Null): Matcher[T with AnyRef] = outerInstance.or(MatcherWords.not.be(o)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be &lt; (8) * ^ * </pre> */ def be[U](resultOfLessThanComparison: ResultOfLessThanComparison[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfLessThanComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be &gt; (6) * ^ * </pre> */ def be[U](resultOfGreaterThanComparison: ResultOfGreaterThanComparison[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfGreaterThanComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be &lt;= (2) * ^ * </pre> */ def be[U](resultOfLessThanOrEqualToComparison: ResultOfLessThanOrEqualToComparison[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfLessThanOrEqualToComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be &gt;= (6) * ^ * </pre> */ def be[U](resultOfGreaterThanOrEqualToComparison: ResultOfGreaterThanOrEqualToComparison[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfGreaterThanOrEqualToComparison)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be === (8) * ^ * </pre> */ def be(tripleEqualsInvocation: TripleEqualsInvocation[_]): Matcher[T] = outerInstance.or(MatcherWords.not.be(tripleEqualsInvocation)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be ('empty) * ^ * </pre> */ def be(symbol: Symbol): Matcher[T with AnyRef] = outerInstance.or(MatcherWords.not.be(symbol)) /** * This method enables the following syntax, where <code>odd</code> is a <a href="BeMatcher.html"><code>BeMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or not be (odd) * ^ * </pre> */ def be[U](beMatcher: BeMatcher[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(beMatcher)) /** * This method enables the following syntax, where <code>file</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or not be (file) * ^ * </pre> */ def be[U](bePropertyMatcher: BePropertyMatcher[U]): Matcher[T with AnyRef with U] = outerInstance.or(MatcherWords.not.be(bePropertyMatcher)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be a ('file) * ^ * </pre> */ def be(resultOfAWordApplication: ResultOfAWordToSymbolApplication): Matcher[T with AnyRef] = outerInstance.or(MatcherWords.not.be(resultOfAWordApplication)) /** * This method enables the following syntax, where <code>validMarks</code> is an <a href="AMatcher.html"><code>AMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or not be a (validMarks) * ^ * </pre> */ def be[U](resultOfAWordApplication: ResultOfAWordToAMatcherApplication[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfAWordApplication)) /** * This method enables the following syntax, where <code>file</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or not be a (file) * ^ * </pre> */ def be[U <: AnyRef](resultOfAWordApplication: ResultOfAWordToBePropertyMatcherApplication[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfAWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be an ('apple) * ^ * </pre> */ def be(resultOfAnWordApplication: ResultOfAnWordToSymbolApplication): Matcher[T with AnyRef] = outerInstance.or(MatcherWords.not.be(resultOfAnWordApplication)) /** * This method enables the following syntax, where <code>apple</code> is a <a href="BePropertyMatcher.html"><code>BePropertyMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher or not be an (apple) * ^ * </pre> */ def be[U <: AnyRef](resultOfAnWordApplication: ResultOfAnWordToBePropertyMatcherApplication[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfAnWordApplication)) /** * This method enables the following syntax, where <code>invalidMarks</code> is an <a href="AnMatcher.html"><code>AnMatcher</code></a>: * * <pre class="stHighlight"> * aMatcher and not be an (invalidMarks) * ^ * </pre> */ def be[U](resultOfAnWordApplication: ResultOfAnWordToAnMatcherApplication[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfAnWordApplication)) import language.experimental.macros /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be a [Book] * ^ * </pre> */ def be(aType: ResultOfATypeInvocation[_]): Matcher[T] = macro TypeMatcherMacro.orNotATypeMatcher /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be an [Book] * ^ * </pre> */ def be(anType: ResultOfAnTypeInvocation[_]): Matcher[T] = macro TypeMatcherMacro.orNotAnTypeMatcher /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be theSameInstanceAs (string) * ^ * </pre> */ def be(resultOfTheSameInstanceAsApplication: ResultOfTheSameInstanceAsApplication): Matcher[T with AnyRef] = outerInstance.or(MatcherWords.not.be(resultOfTheSameInstanceAsApplication)) /** * This method enables the following syntax for the "primitive" numeric types: * * <pre class="stHighlight"> * aMatcher or not be (17.0 +- 0.2) * ^ * </pre> */ def be[U](spread: Spread[U]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(spread)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be definedAt (8) * ^ * </pre> */ def be[A, U <: PartialFunction[A, _]](resultOfDefinedAt: ResultOfDefinedAt[A]): Matcher[T with U] = outerInstance.or(MatcherWords.not.be(resultOfDefinedAt)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be sorted * ^ * </pre> */ def be(sortedWord: SortedWord) = outerInstance.or(MatcherWords.not.be(sortedWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be readable * ^ * </pre> */ def be(readableWord: ReadableWord) = outerInstance.or(MatcherWords.not.be(readableWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be empty * ^ * </pre> */ def be(emptyWord: EmptyWord) = outerInstance.or(MatcherWords.not.be(emptyWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be writable * ^ * </pre> */ def be(writableWord: WritableWord) = outerInstance.or(MatcherWords.not.be(writableWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not be defined * ^ * </pre> */ def be(definedWord: DefinedWord) = outerInstance.or(MatcherWords.not.be(definedWord)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not fullyMatch regex (decimal) * ^ * </pre> */ def fullyMatch(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.or(MatcherWords.not.fullyMatch(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not include regex (decimal) * ^ * </pre> */ def include(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.or(MatcherWords.not.include(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not include ("1.7") * ^ * </pre> */ def include(expectedSubstring: String): Matcher[T with String] = outerInstance.or(MatcherWords.not.include(expectedSubstring)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not startWith regex (decimal) * ^ * </pre> */ def startWith(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.or(MatcherWords.not.startWith(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not startWith ("1.7") * ^ * </pre> */ def startWith(expectedSubstring: String): Matcher[T with String] = outerInstance.or(MatcherWords.not.startWith(expectedSubstring)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not endWith regex (decimal) * ^ * </pre> */ def endWith(resultOfRegexWordApplication: ResultOfRegexWordApplication): Matcher[T with String] = outerInstance.or(MatcherWords.not.endWith(resultOfRegexWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not endWith ("1.7") * ^ * </pre> */ def endWith(expectedSubstring: String): Matcher[T with String] = outerInstance.or(MatcherWords.not.endWith(expectedSubstring)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain (3) * ^ * </pre> */ def contain[R](expectedElement: R): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.not.contain(expectedElement)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain oneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfOneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain oneElementOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfOneElementOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain atLeastOneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAtLeastOneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain atLeastOneElementOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAtLeastOneElementOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain noneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfNoneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain noElementsOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfNoElementsOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedIn] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain theSameElementsAs (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfTheSameElementsAsApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain theSameElementsInOrderAs (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfTheSameElementsInOrderAsApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain inOrderOnly (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfInOrderOnlyApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain only (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfOnlyApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain allOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAllOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain allElementsOf List(8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAllElementsOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain inOrder (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfInOrderApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain inOrderElementsOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfInOrderElementsOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInSequence] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher not contain atMostOneOf (8, 1, 2) * ^ * </pre> */ def contain[R](right: ResultOfAtMostOneOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher not contain atMostOneElementOf (List(8, 1, 2)) * ^ * </pre> */ def contain[R](right: ResultOfAtMostOneElementOfApplication[R]): MatcherFactory1[T, EvidenceThat[R]#CanBeContainedInAggregation] = outerInstance.or(MatcherWords.not.contain(right)) /** * This method enables the following syntax given a <code>Matcher</code>: * * <pre class="stHighlight"> * aMatcher or not contain key ("three") * ^ * </pre> */ def contain(resultOfKeyWordApplication: ResultOfKeyWordApplication): MatcherFactory1[T, KeyMapping] = outerInstance.or(MatcherWords.not.contain(resultOfKeyWordApplication)) /** * This method enables the following syntax given a <code>Matcher</code>: * * <pre class="stHighlight"> * aMatcher or not contain value (3) * ^ * </pre> */ def contain(resultOfValueWordApplication: ResultOfValueWordApplication): MatcherFactory1[T, ValueMapping] = outerInstance.or(MatcherWords.not.contain(resultOfValueWordApplication)) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not matchPattern { case Person("Bob", _) =>} * ^ * </pre> */ def matchPattern(right: PartialFunction[Any, _]) = macro MatchPatternMacro.orNotMatchPatternMatcher } /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not contain value (3) * ^ * </pre> */ def or(notWord: NotWord): OrNotWord = new OrNotWord /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or exist * ^ * </pre> */ def or(existWord: ExistWord): MatcherFactory1[T, Existence] = outerInstance.or(MatcherWords.exist.matcherFactory) /** * This method enables the following syntax: * * <pre class="stHighlight"> * aMatcher or not (exist) * ^ * </pre> */ def or(notExist: ResultOfNotExist): MatcherFactory1[T, Existence] = outerInstance.or(MatcherWords.not.exist) /** * Creates a new <code>Matcher</code> that will produce <code>MatchResult</code>s by applying the original <code>MatchResult</code> * produced by this <code>Matcher</code> to the passed <code>prettify</code> function. In other words, the <code>MatchResult</code> * produced by this <code>Matcher</code> will be passed to <code>prettify</code> to produce the final <code>MatchResult</code> * * @param prettify a function to apply to the original <code>MatchResult</code> produced by this <code>Matcher</code> * @return a new <code>Matcher</code> that will produce <code>MatchResult</code>s by applying the original <code>MatchResult</code> * produced by this <code>Matcher</code> to the passed <code>prettify</code> function */ def mapResult(prettify: MatchResult => MatchResult): Matcher[T] = new Matcher[T] { def apply(o: T): MatchResult = prettify(outerInstance(o)) } /** * Creates a new <code>Matcher</code> that will produce <code>MatchResult</code>s that contain error messages constructed * using arguments that are transformed by the passed <code>prettify</code> function. In other words, the <code>MatchResult</code> * produced by this <code>Matcher</code> will use arguments transformed by <code>prettify</code> function to construct the final * error messages. * * @param prettify a function with which to transform the arguments of error messages. * @return a new <code>Matcher</code> that will produce <code>MatchResult</code>s that contain error messages constructed * using arguments transformed by the passed <code>prettify</code> function. */ def mapArgs(prettify: Any => String): Matcher[T] = new Matcher[T] { def apply(o: T): MatchResult = { val mr = outerInstance(o) mr.copy( failureMessageArgs = mr.failureMessageArgs.map((LazyArg(_) { prettify })), negatedFailureMessageArgs = mr.negatedFailureMessageArgs.map((LazyArg(_) { prettify })), midSentenceFailureMessageArgs = mr.midSentenceFailureMessageArgs.map((LazyArg(_) { prettify })), midSentenceNegatedFailureMessageArgs = mr.midSentenceNegatedFailureMessageArgs.map((LazyArg(_) { prettify })) ) } } } /** * Companion object for trait <code>Matcher</code> that provides a * factory method that creates a <code>Matcher[T]</code> from a * passed function of type <code>(T =&gt; MatchResult)</code>. * * @author <NAME> */ object Matcher { /** * Factory method that creates a <code>Matcher[T]</code> from a * passed function of type <code>(T =&gt; MatchResult)</code>. * * @author <NAME> */ def apply[T](fun: T => MatchResult)(implicit ev: ClassTag[T]): Matcher[T] = new Matcher[T] { def apply(left: T) = fun(left) override def toString: String = "Matcher[" + ev.runtimeClass.getName + "](" + ev.runtimeClass.getName + " => MatchResult)" } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/TestNameProp.scala
<reponame>cquiroz/scalatest<gh_stars>1-10 /* * 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 import org.scalatest.junit.JUnit3Suite import org.scalatest.junit.JUnitSuite import org.junit.Test import org.testng.annotations.{Test => TestNG } import org.scalatest.testng.TestNGSuite class TestNameProp extends AllSuiteProp { type FixtureServices = TestNameFixtureServices def spec = new ExampleTestNameSpec def fixtureSpec = new ExampleTestNameFixtureSpec def junit3Suite = new ExampleTestNameJUnit3Suite def junitSuite = new ExampleTestNameJUnitSuite def testngSuite = new ExampleTestNameTestNGSuite def funSuite = new ExampleTestNameFunSuite def fixtureFunSuite = new ExampleTestNameFixtureFunSuite def funSpec = new ExampleTestNameFunSpec def fixtureFunSpec = new ExampleTestNameFixtureFunSpec def featureSpec = new ExampleTestNameFeatureSpec def fixtureFeatureSpec = new ExampleTestNameFixtureFeatureSpec def flatSpec = new ExampleTestNameFlatSpec def fixtureFlatSpec = new ExampleTestNameFixtureFlatSpec def freeSpec = new ExampleTestNameFreeSpec def fixtureFreeSpec = new ExampleTestNameFixtureFreeSpec def propSpec = new ExampleTestNamePropSpec def fixturePropSpec = new ExampleTestNameFixturePropSpec def wordSpec = new ExampleTestNameWordSpec def fixtureWordSpec = new ExampleTestNameFixtureWordSpec def pathFreeSpec = new ExampleTestNamePathFreeSpec def pathFunSpec = new ExampleTestNamePathFunSpec test("test name will be constructed by concatennating scopes, outer to inner, followed by the test text, separated by a space after each component is trimmed.") { forAll(examples) { s => s.assertTestNames() } } } trait TestNameFixtureServices { suite: Suite => val expectedTestNames: Set[String] def assertTestNames() { val expectedSet = expectedTestNames val testNameSet = testNames assert(expectedSet.size === testNameSet.size) expectedSet.foreach { tn => assert(testNameSet contains tn, "Unable to find test name: '" + tn + "', testNames is: \n" + testNameSet.map("'" + _ + "'").mkString("\n")) } } } @DoNotDiscover class ExampleTestNameSpec extends Spec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) object `Testing 1` { object `Scala code` { def `should be fun` {} } } object `Testing 2 ` { object `Scala code` { def `should be fun` {} } } object `Testing 3` { object ` Scala code` { def `should be fun` {} } } object `Testing 4` { object `Scala code ` { def `should be fun` {} } } object `Testing 5` { object `Scala code` { def ` should be fun` {} } } object ` Testing 6` { object `Scala code` { def `should be fun` {} } } object `Testing 7` { object `Scala code` { def `should be fun ` {} } } object `Testing 8 ` { object ` Scala code` { def `should be fun` {} } } object `Testing 9 ` { object `Scala code` { def `should be fun` {} } } } @DoNotDiscover class ExampleTestNameFixtureSpec extends fixture.Spec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) object `Testing 1` { object `Scala code` { def `should be fun`(fixture: String) {} } } object `Testing 2 ` { object `Scala code` { def `should be fun`(fixture: String) {} } } object `Testing 3` { object ` Scala code` { def `should be fun`(fixture: String) {} } } object `Testing 4` { object `Scala code ` { def `should be fun`(fixture: String) {} } } object `Testing 5` { object `Scala code` { def ` should be fun`(fixture: String) {} } } object ` Testing 6` { object `Scala code` { def `should be fun`(fixture: String) {} } } object `Testing 7` { object `Scala code` { def `should be fun `(fixture: String) {} } } object `Testing 8 ` { object ` Scala code` { def `should be fun`(fixture: String) {} } } object `Testing 9 ` { object `Scala code` { def `should be fun`(fixture: String) {} } } } @DoNotDiscover class ExampleTestNameJUnit3Suite extends JUnit3Suite with TestNameFixtureServices { val expectedTestNames = Set( "testingShouldBeFun" ) def testingShouldBeFun() { } } @DoNotDiscover class ExampleTestNameJUnitSuite extends JUnitSuite with TestNameFixtureServices { val expectedTestNames = Set( "testingShouldBeFun" ) @Test def testingShouldBeFun() {} } @DoNotDiscover class ExampleTestNameTestNGSuite extends TestNGSuite with TestNameFixtureServices { val expectedTestNames = Set( "testingShouldBeFun" ) @TestNG def testingShouldBeFun() {} } @DoNotDiscover class ExampleTestNameFunSuite extends FunSuite with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 should be fun", "Testing 2 should be fun", "Testing 3 should be fun", "Testing 4 should be fun", "Testing 5 should be fun" ) test("Testing 1 should be fun") {} test(" Testing 2 should be fun") {} test("Testing 3 should be fun ") {} test(" Testing 4 should be fun") {} test("Testing 5 should be fun ") {} } @DoNotDiscover class ExampleTestNameFixtureFunSuite extends fixture.FunSuite with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 should be fun", "Testing 2 should be fun", "Testing 3 should be fun", "Testing 4 should be fun", "Testing 5 should be fun" ) test("Testing 1 should be fun") { s => } test(" Testing 2 should be fun") { s => } test("Testing 3 should be fun ") { s => } test(" Testing 4 should be fun") { s => } test("Testing 5 should be fun ") { s => } } @DoNotDiscover class ExampleTestNameFunSpec extends FunSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) describe("Testing 1") { describe("Scala code") { it("should be fun") {} } } describe("Testing 2 ") { describe("Scala code") { it("should be fun") {} } } describe("Testing 3") { describe(" Scala code") { it("should be fun") {} } } describe("Testing 4") { describe("Scala code ") { it("should be fun") {} } } describe("Testing 5") { describe("Scala code") { it(" should be fun") {} } } describe(" Testing 6") { describe("Scala code") { it("should be fun") {} } } describe("Testing 7") { describe("Scala code") { it("should be fun ") {} } } describe("Testing 8 ") { describe(" Scala code") { it("should be fun") {} } } describe("Testing 9 ") { describe("Scala code") { it("should be fun") {} } } } @DoNotDiscover class ExampleTestNameFixtureFunSpec extends fixture.FunSpec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) describe("Testing 1") { describe("Scala code") { it("should be fun") { s => } } } describe("Testing 2 ") { describe("Scala code") { it("should be fun") { s => } } } describe("Testing 3") { describe(" Scala code") { it("should be fun") { s => } } } describe("Testing 4") { describe("Scala code ") { it("should be fun") { s => } } } describe("Testing 5") { describe("Scala code") { it(" should be fun") { s => } } } describe(" Testing 6") { describe("Scala code") { it("should be fun") { s => } } } describe("Testing 7") { describe("Scala code") { it("should be fun ") { s => } } } describe("Testing 8 ") { describe(" Scala code") { it("should be fun") { s => } } } describe("Testing 9 ") { describe("Scala code") { it("should be fun") { s => } } } } @DoNotDiscover class ExampleTestNameFeatureSpec extends FeatureSpec with TestNameFixtureServices { val expectedTestNames = Set( "Feature: Testing 1 Scenario: Scala code should be fun", "Feature: Testing 2 Scenario: Scala code should be fun", "Feature: Testing 3 Scenario: Scala code should be fun", "Feature: Testing 4 Scenario: Scala code should be fun", "Feature: Testing 5 Scenario: Scala code should be fun", "Feature: Testing 6 Scenario: Scala code should be fun", "Feature: Testing 7 Scenario: Scala code should be fun" ) feature("Testing 1") { scenario("Scala code should be fun") {} } feature("Testing 2 ") { scenario("Scala code should be fun") {} } feature("Testing 3") { scenario(" Scala code should be fun") {} } feature("Testing 4") { scenario("Scala code should be fun ") {} } feature(" Testing 5") { scenario("Scala code should be fun") {} } feature("Testing 6 ") { scenario(" Scala code should be fun") {} } feature("Testing 7 ") { scenario("Scala code should be fun") {} } } @DoNotDiscover class ExampleTestNameFixtureFeatureSpec extends fixture.FeatureSpec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Feature: Testing 1 Scenario: Scala code should be fun", "Feature: Testing 2 Scenario: Scala code should be fun", "Feature: Testing 3 Scenario: Scala code should be fun", "Feature: Testing 4 Scenario: Scala code should be fun", "Feature: Testing 5 Scenario: Scala code should be fun", "Feature: Testing 6 Scenario: Scala code should be fun", "Feature: Testing 7 Scenario: Scala code should be fun" ) feature("Testing 1") { scenario("Scala code should be fun") { s => } } feature("Testing 2 ") { scenario("Scala code should be fun") { s => } } feature("Testing 3") { scenario(" Scala code should be fun") { s => } } feature("Testing 4") { scenario("Scala code should be fun ") { s => } } feature(" Testing 5") { scenario("Scala code should be fun") { s => } } feature("Testing 6 ") { scenario(" Scala code should be fun") { s => } } feature("Testing 7 ") { scenario("Scala code should be fun") { s => } } } @DoNotDiscover class ExampleTestNameFlatSpec extends FlatSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 should be fun to code in Scala", "Testing 2 should be fun to code in Scala", "Testing 3 should be fun to code in Scala", "Testing 4 should be fun to code in Scala", "Testing 5 should be fun to code in Scala", "Testing 6 should be fun to code in Scala", "Testing 7 should be fun to code in Scala" ) "Testing 1" should "be fun to code in Scala" in { } "Testing 2 " should "be fun to code in Scala" in { } "Testing 3" should " be fun to code in Scala" in { } "Testing 4" should "be fun to code in Scala " in { } " Testing 5" should "be fun to code in Scala" in { } "Testing 6 " should " be fun to code in Scala" in { } "Testing 7 " should "be fun to code in Scala" in { } } @DoNotDiscover class ExampleTestNameFixtureFlatSpec extends fixture.FlatSpec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 should be fun to code in Scala", "Testing 2 should be fun to code in Scala", "Testing 3 should be fun to code in Scala", "Testing 4 should be fun to code in Scala", "Testing 5 should be fun to code in Scala", "Testing 6 should be fun to code in Scala", "Testing 7 should be fun to code in Scala" ) "Testing 1" should "be fun to code in Scala" in { s => } "Testing 2 " should "be fun to code in Scala" in { s => } "Testing 3" should " be fun to code in Scala" in { s => } "Testing 4" should "be fun to code in Scala " in { s => } " Testing 5" should "be fun to code in Scala" in { s => } "Testing 6 " should " be fun to code in Scala" in { s => } "Testing 7 " should "be fun to code in Scala" in { s => } } @DoNotDiscover class ExampleTestNameFreeSpec extends FreeSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) "Testing 1" - { "Scala code" - { "should be fun" in {} } } "Testing 2 " - { "Scala code" - { "should be fun" in {} } } "Testing 3" - { " Scala code" - { "should be fun" in {} } } "Testing 4" - { "Scala code " - { "should be fun" in {} } } "Testing 5" - { "Scala code" - { " should be fun" in {} } } " Testing 6" - { "Scala code" - { "should be fun" in {} } } "Testing 7" - { "Scala code" - { "should be fun " in {} } } "Testing 8 " - { " Scala code" - { "should be fun" in {} } } "Testing 9 " - { "Scala code" - { "should be fun" in {} } } } @DoNotDiscover class ExampleTestNameFixtureFreeSpec extends fixture.FreeSpec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) "Testing 1" - { "Scala code" - { "should be fun" in { s => } } } "Testing 2 " - { "Scala code" - { "should be fun" in { s => } } } "Testing 3" - { " Scala code" - { "should be fun" in { s => } } } "Testing 4" - { "Scala code " - { "should be fun" in { s => } } } "Testing 5" - { "Scala code" - { " should be fun" in { s => } } } " Testing 6" - { "Scala code" - { "should be fun" in { s => } } } "Testing 7" - { "Scala code" - { "should be fun " in { s => } } } "Testing 8 " - { " Scala code" - { "should be fun" in { s => } } } "Testing 9 " - { "Scala code" - { "should be fun" in { s => } } } } @DoNotDiscover class ExampleTestNamePropSpec extends PropSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun" ) property("Testing 1 Scala code should be fun") {} property(" Testing 2 Scala code should be fun") {} property("Testing 3 Scala code should be fun ") {} property(" Testing 4 Scala code should be fun") {} property("Testing 5 Scala code should be fun ") {} property(" Testing 6 Scala code should be fun ") {} } @DoNotDiscover class ExampleTestNameFixturePropSpec extends fixture.PropSpec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun" ) property("Testing 1 Scala code should be fun") { s => } property(" Testing 2 Scala code should be fun") { s => } property("Testing 3 Scala code should be fun ") { s => } property(" Testing 4 Scala code should be fun") { s => } property("Testing 5 Scala code should be fun ") { s => } property(" Testing 6 Scala code should be fun ") { s => } } @DoNotDiscover class ExampleTestNameWordSpec extends WordSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 should test Scala code should be fun", "Testing 2 should test Scala code should be fun", "Testing 3 should test Scala code should be fun", "Testing 4 should test Scala code should be fun", "Testing 5 should test Scala code should be fun", "Testing 6 should test Scala code should be fun", "Testing 7 should test Scala code should be fun", "Testing 8 should test Scala code should be fun", "Testing 9 should test Scala code should be fun" ) "Testing 1" should { "test Scala code" should { "be fun" in {} } } "Testing 2 " should { "test Scala code" should { "be fun" in {} } } "Testing 3" should { " test Scala code" should { "be fun" in {} } } "Testing 4" should { "test Scala code " should { "be fun" in {} } } "Testing 5" should { "test Scala code" should { " be fun" in {} } } " Testing 6" should { "test Scala code" should { "be fun" in {} } } "Testing 7" should { "test Scala code" should { "be fun " in {} } } "Testing 8 " should { " test Scala code" should { "be fun" in {} } } "Testing 9 " should { "test Scala code" should { "be fun" in {} } } } @DoNotDiscover class ExampleTestNameFixtureWordSpec extends fixture.WordSpec with TestNameFixtureServices with StringFixture { val expectedTestNames = Set( "Testing 1 should test Scala code should be fun", "Testing 2 should test Scala code should be fun", "Testing 3 should test Scala code should be fun", "Testing 4 should test Scala code should be fun", "Testing 5 should test Scala code should be fun", "Testing 6 should test Scala code should be fun", "Testing 7 should test Scala code should be fun", "Testing 8 should test Scala code should be fun", "Testing 9 should test Scala code should be fun" ) "Testing 1" should { "test Scala code" should { "be fun" in { s => } } } "Testing 2 " should { "test Scala code" should { "be fun" in { s => } } } "Testing 3" should { " test Scala code" should { "be fun" in { s => } } } "Testing 4" should { "test Scala code " should { "be fun" in { s => } } } "Testing 5" should { "test Scala code" should { " be fun" in { s => } } } " Testing 6" should { "test Scala code" should { "be fun" in { s => } } } "Testing 7" should { "test Scala code" should { "be fun " in { s => } } } "Testing 8 " should { " test Scala code" should { "be fun" in { s => } } } "Testing 9 " should { "test Scala code" should { "be fun" in { s => } } } } @DoNotDiscover class ExampleTestNamePathFreeSpec extends path.FreeSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) "Testing 1" - { "Scala code" - { "should be fun" in {} } } "Testing 2 " - { "Scala code" - { "should be fun" in {} } } "Testing 3" - { " Scala code" - { "should be fun" in {} } } "Testing 4" - { "Scala code " - { "should be fun" in {} } } "Testing 5" - { "Scala code" - { " should be fun" in {} } } " Testing 6" - { "Scala code" - { "should be fun" in {} } } "Testing 7" - { "Scala code" - { "should be fun " in {} } } "Testing 8 " - { " Scala code" - { "should be fun" in {} } } "Testing 9 " - { "Scala code" - { "should be fun" in {} } } } @DoNotDiscover class ExampleTestNamePathFunSpec extends path.FunSpec with TestNameFixtureServices { val expectedTestNames = Set( "Testing 1 Scala code should be fun", "Testing 2 Scala code should be fun", "Testing 3 Scala code should be fun", "Testing 4 Scala code should be fun", "Testing 5 Scala code should be fun", "Testing 6 Scala code should be fun", "Testing 7 Scala code should be fun", "Testing 8 Scala code should be fun", "Testing 9 Scala code should be fun" ) describe("Testing 1") { describe("Scala code") { it("should be fun") {} } } describe("Testing 2 ") { describe("Scala code") { it("should be fun") {} } } describe("Testing 3") { describe(" Scala code") { it("should be fun") {} } } describe("Testing 4") { describe("Scala code ") { it("should be fun") {} } } describe("Testing 5") { describe("Scala code") { it(" should be fun") {} } } describe(" Testing 6") { describe("Scala code") { it("should be fun") {} } } describe("Testing 7") { describe("Scala code") { it("should be fun ") {} } } describe("Testing 8 ") { describe(" Scala code") { it("should be fun") {} } } describe("Testing 9 ") { describe("Scala code") { it("should be fun") {} } } }
cquiroz/scalatest
scalatest.js/src/main/scala/org/scalatest/tools/SlaveRunner.scala
package org.scalatest.tools import org.scalatest.Tracker import org.scalatest.events.Summary import sbt.testing.{Framework => BaseFramework, Event => SbtEvent, Status => SbtStatus, _} import scala.compat.Platform class SlaveRunner(theArgs: Array[String], theRemoteArgs: Array[String], testClassLoader: ClassLoader, notifyServer: String => Unit) extends Runner { // TODO: To take these from test arguments val presentAllDurations: Boolean = true val presentInColor: Boolean = true val presentShortStackTraces: Boolean = true val presentFullStackTraces: Boolean = true val presentUnformatted: Boolean = false val presentReminder: Boolean = false val presentReminderWithShortStackTraces: Boolean = false val presentReminderWithFullStackTraces: Boolean = false val presentReminderWithoutCanceledTests: Boolean = false val tracker = new Tracker def done(): String = "" def remoteArgs(): Array[String] = { theRemoteArgs } def args: Array[String] = { theArgs } def tasks(list: Array[TaskDef]): Array[Task] = { list.map(t => new TaskRunner(t, testClassLoader, tracker, presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests, Some(notifyServer))) } def receiveMessage(msg: String): Option[String] = None def serializeTask(task: Task, serializer: (TaskDef) => String): String = serializer(task.taskDef()) def deserializeTask(task: String, deserializer: (String) => TaskDef): Task = new TaskRunner(deserializer(task), testClassLoader, tracker, presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests, Some(notifyServer)) }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/Informer.scala
<reponame>cquiroz/scalatest /* * 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 /** * Trait to which custom information about a running suite of tests can be reported. * * <p> * An <code>Informer</code> is essentially * used to wrap a <code>Reporter</code> and provide easy ways to send custom information * to that <code>Reporter</code> via an <code>InfoProvided</code> event. * <code>Informer</code> contains an <code>apply</code> method that takes a string and * an optional payload object of type <code>Any</code>. * The <code>Informer</code> will forward the passed <code>message</code> string to the * <a href="Reporter.html"><code>Reporter</code></a> as the <code>message</code> parameter, and the optional * payload object as the <code>payload</code> parameter, of an <a href="InfoProvided.html"><code>InfoProvided</code></a> event. * </p> * * <p> * Here's an example in which the <code>Informer</code> is used both directly via <code>info</code> * method of trait <a href="FlatSpec.html"><code>FlatSpec</code></a> and indirectly via the methods of * trait <a href="GivenWhenThen.html"><code>GivenWhenThen</code></a>: * </p> * * <pre class="stHighlight"> * package org.scalatest.examples.flatspec.info * * import collection.mutable * import org.scalatest._ * * class SetSpec extends FlatSpec with GivenWhenThen { * * "A mutable Set" should "allow an element to be added" in { * given("an empty mutable Set") * val set = mutable.Set.empty[String] * * when("an element is added") * set += "clarity" * * then("the Set should have size 1") * assert(set.size === 1) * * and("the Set should contain the added element") * assert(set.contains("clarity")) * * info("That's all folks!") * } * } * </pre> * * <p> * If you run this <code>SetSpec</code> from the interpreter, you will see the following output: * </p> * * <pre class="stREPL"> * scala&gt; new SetSpec execute * <span class="stGreen">A mutable Set * - should allow an element to be added * + Given an empty mutable Set * + When an element is added * + Then the Set should have size 1 * + And the Set should contain the added element * + That's all folks! </span> * </pre> * * @author <NAME> */ trait Informer { // TODO: Make sure all the informer implementations check for null /** * Provide information and optionally, a payload, to the <code>Reporter</code> via an * <code>InfoProvided</code> event. * * @param message a string that will be forwarded to the wrapped <code>Reporter</code> * via an <code>InfoProvided</code> event. * @param payload an optional object which will be forwarded to the wrapped <code>Reporter</code> * as a payload via an <code>InfoProvided</code> event. * * @throws NullPointerException if <code>message</code> or <code>payload</code> reference is <code>null</code> */ def apply(message: String, payload: Option[Any] = None): Unit /** * Provide information and additional payload to the <code>Reporter</code> as the . * * @param message an object whose <code>toString</code> result will be forwarded to the wrapped <code>Reporter</code> * via an <code>InfoProvided</code> event. * @param payload an object which will be forwarded to the wrapped <code>Reporter</code> * via an <code>InfoProvided</code> event. * * @throws NullPointerException if <code>message</code> reference is <code>null</code> */ //def apply(message: String, payload: Any): Unit }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ParallelTestExecutionParallelSuiteExamples.scala
/* * 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 import org.scalatest.prop.Tables import org.scalatest.events.Event trait ParallelSuites extends EventHelpers { def suite1: Suite def suite2: Suite def assertParallelSuites(events: List[Event]) } object ParallelTestExecutionParallelSuiteExamples extends Tables { def parallelExamples = Table( "pair", new ExampleParallelTestExecutionParallelSpecPair, new ExampleParallelTestExecutionParallelFunSuitePair, new ExampleParallelTestExecutionParallelFunSpecPair, new ExampleParallelTestExecutionParallelFeatureSpecPair, new ExampleParallelTestExecutionParallelFlatSpecPair, new ExampleParallelTestExecutionParallelFreeSpecPair, new ExampleParallelTestExecutionParallelPropSpecPair, new ExampleParallelTestExecutionParallelWordSpecPair ) } class ExampleParallelTestExecutionParallelSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderSpec def suite2 = new ExampleParallelTestExecutionOrderFixtureSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 16) checkSuiteStarting(events(0), suite1.suiteId) checkTestStarting(events(1), "test 1") checkTestSucceeded(events(2), "test 1") checkTestStarting(events(3), "test 2") checkTestSucceeded(events(4), "test 2") checkTestStarting(events(5), "test 3") checkTestSucceeded(events(6), "test 3") checkSuiteCompleted(events(7), suite1.suiteId) checkSuiteStarting(events(8), suite2.suiteId) checkTestStarting(events(9), "test 1") checkTestSucceeded(events(10), "test 1") checkTestStarting(events(11), "test 2") checkTestSucceeded(events(12), "test 2") checkTestStarting(events(13), "test 3") checkTestSucceeded(events(14), "test 3") checkSuiteCompleted(events(15), suite2.suiteId) } } class ExampleParallelTestExecutionParallelFunSuitePair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderFunSuite def suite2 = new ExampleParallelTestExecutionOrderFixtureFunSuite def assertParallelSuites(events: List[Event]) { assert(events.size === 16) checkSuiteStarting(events(0), suite1.suiteId) checkTestStarting(events(1), "Test 1") checkTestSucceeded(events(2), "Test 1") checkTestStarting(events(3), "Test 2") checkTestSucceeded(events(4), "Test 2") checkTestStarting(events(5), "Test 3") checkTestSucceeded(events(6), "Test 3") checkSuiteCompleted(events(7), suite1.suiteId) checkSuiteStarting(events(8), suite2.suiteId) checkTestStarting(events(9), "Fixture Test 1") checkTestSucceeded(events(10), "Fixture Test 1") checkTestStarting(events(11), "Fixture Test 2") checkTestSucceeded(events(12), "Fixture Test 2") checkTestStarting(events(13), "Fixture Test 3") checkTestSucceeded(events(14), "Fixture Test 3") checkSuiteCompleted(events(15), suite2.suiteId) } } class ExampleParallelTestExecutionParallelFunSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderFunSpec def suite2 = new ExampleParallelTestExecutionOrderFixtureFunSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 28) checkSuiteStarting(events(0), suite1.suiteId) checkScopeOpened(events(1), "Scope 1") checkTestStarting(events(2), "Scope 1 Test 1") checkTestSucceeded(events(3), "Scope 1 Test 1") checkTestStarting(events(4), "Scope 1 Test 2") checkTestSucceeded(events(5), "Scope 1 Test 2") checkScopeClosed(events(6), "Scope 1") checkScopeOpened(events(7), "Scope 2") checkTestStarting(events(8), "Scope 2 Test 3") checkTestSucceeded(events(9), "Scope 2 Test 3") checkTestStarting(events(10), "Scope 2 Test 4") checkTestSucceeded(events(11), "Scope 2 Test 4") checkScopeClosed(events(12), "Scope 2") checkSuiteCompleted(events(13), suite1.suiteId) checkSuiteStarting(events(14), suite2.suiteId) checkScopeOpened(events(15), "Fixture Scope 1") checkTestStarting(events(16), "Fixture Scope 1 Fixture Test 1") checkTestSucceeded(events(17), "Fixture Scope 1 Fixture Test 1") checkTestStarting(events(18), "Fixture Scope 1 Fixture Test 2") checkTestSucceeded(events(19), "Fixture Scope 1 Fixture Test 2") checkScopeClosed(events(20), "Fixture Scope 1") checkScopeOpened(events(21), "Fixture Scope 2") checkTestStarting(events(22), "Fixture Scope 2 Fixture Test 3") checkTestSucceeded(events(23), "Fixture Scope 2 Fixture Test 3") checkTestStarting(events(24), "Fixture Scope 2 Fixture Test 4") checkTestSucceeded(events(25), "Fixture Scope 2 Fixture Test 4") checkScopeClosed(events(26), "Fixture Scope 2") checkSuiteCompleted(events(27), suite2.suiteId) } } class ExampleParallelTestExecutionParallelFeatureSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderFeatureSpec def suite2 = new ExampleParallelTestExecutionOrderFixtureFeatureSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 28) checkSuiteStarting(events(0), suite1.suiteId) checkScopeOpened(events(1), "Feature: Scope 1") checkTestStarting(events(2), "Feature: Scope 1 Scenario: Test 1") checkTestSucceeded(events(3), "Feature: Scope 1 Scenario: Test 1") checkTestStarting(events(4), "Feature: Scope 1 Scenario: Test 2") checkTestSucceeded(events(5), "Feature: Scope 1 Scenario: Test 2") checkScopeClosed(events(6), "Feature: Scope 1") checkScopeOpened(events(7), "Feature: Scope 2") checkTestStarting(events(8), "Feature: Scope 2 Scenario: Test 3") checkTestSucceeded(events(9), "Feature: Scope 2 Scenario: Test 3") checkTestStarting(events(10), "Feature: Scope 2 Scenario: Test 4") checkTestSucceeded(events(11), "Feature: Scope 2 Scenario: Test 4") checkScopeClosed(events(12), "Feature: Scope 2") checkSuiteCompleted(events(13), suite1.suiteId) checkSuiteStarting(events(14), suite2.suiteId) checkScopeOpened(events(15), "Feature: Fixture Scope 1") checkTestStarting(events(16), "Feature: Fixture Scope 1 Scenario: Fixture Test 1") checkTestSucceeded(events(17), "Feature: Fixture Scope 1 Scenario: Fixture Test 1") checkTestStarting(events(18), "Feature: Fixture Scope 1 Scenario: Fixture Test 2") checkTestSucceeded(events(19), "Feature: Fixture Scope 1 Scenario: Fixture Test 2") checkScopeClosed(events(20), "Feature: Fixture Scope 1") checkScopeOpened(events(21), "Feature: Fixture Scope 2") checkTestStarting(events(22), "Feature: Fixture Scope 2 Scenario: Fixture Test 3") checkTestSucceeded(events(23), "Feature: Fixture Scope 2 Scenario: Fixture Test 3") checkTestStarting(events(24), "Feature: Fixture Scope 2 Scenario: Fixture Test 4") checkTestSucceeded(events(25), "Feature: Fixture Scope 2 Scenario: Fixture Test 4") checkScopeClosed(events(26), "Feature: Fixture Scope 2") checkSuiteCompleted(events(27), suite2.suiteId) } } class ExampleParallelTestExecutionParallelFlatSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderFlatSpec def suite2 = new ExampleParallelTestExecutionOrderFixtureFlatSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 28) checkSuiteStarting(events(0), suite1.suiteId) checkScopeOpened(events(1), "Scope 1") checkTestStarting(events(2), "Scope 1 should Test 1") checkTestSucceeded(events(3), "Scope 1 should Test 1") checkTestStarting(events(4), "Scope 1 should Test 2") checkTestSucceeded(events(5), "Scope 1 should Test 2") checkScopeClosed(events(6), "Scope 1") checkScopeOpened(events(7), "Scope 2") checkTestStarting(events(8), "Scope 2 should Test 3") checkTestSucceeded(events(9), "Scope 2 should Test 3") checkTestStarting(events(10), "Scope 2 should Test 4") checkTestSucceeded(events(11), "Scope 2 should Test 4") checkScopeClosed(events(12), "Scope 2") checkSuiteCompleted(events(13), suite1.suiteId) checkSuiteStarting(events(14), suite2.suiteId) checkScopeOpened(events(15), "Fixture Scope 1") checkTestStarting(events(16), "Fixture Scope 1 should Fixture Test 1") checkTestSucceeded(events(17), "Fixture Scope 1 should Fixture Test 1") checkTestStarting(events(18), "Fixture Scope 1 should Fixture Test 2") checkTestSucceeded(events(19), "Fixture Scope 1 should Fixture Test 2") checkScopeClosed(events(20), "Fixture Scope 1") checkScopeOpened(events(21), "Fixture Scope 2") checkTestStarting(events(22), "Fixture Scope 2 should Fixture Test 3") checkTestSucceeded(events(23), "Fixture Scope 2 should Fixture Test 3") checkTestStarting(events(24), "Fixture Scope 2 should Fixture Test 4") checkTestSucceeded(events(25), "Fixture Scope 2 should Fixture Test 4") checkScopeClosed(events(26), "Fixture Scope 2") checkSuiteCompleted(events(27), suite2.suiteId) } } class ExampleParallelTestExecutionParallelFreeSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderFreeSpec def suite2 = new ExampleParallelTestExecutionOrderFixtureFreeSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 28) checkSuiteStarting(events(0), suite1.suiteId) checkScopeOpened(events(1), "Scope 1") checkTestStarting(events(2), "Scope 1 Test 1") checkTestSucceeded(events(3), "Scope 1 Test 1") checkTestStarting(events(4), "Scope 1 Test 2") checkTestSucceeded(events(5), "Scope 1 Test 2") checkScopeClosed(events(6), "Scope 1") checkScopeOpened(events(7), "Scope 2") checkTestStarting(events(8), "Scope 2 Test 3") checkTestSucceeded(events(9), "Scope 2 Test 3") checkTestStarting(events(10), "Scope 2 Test 4") checkTestSucceeded(events(11), "Scope 2 Test 4") checkScopeClosed(events(12), "Scope 2") checkSuiteCompleted(events(13), suite1.suiteId) checkSuiteStarting(events(14), suite2.suiteId) checkScopeOpened(events(15), "Fixture Scope 1") checkTestStarting(events(16), "Fixture Scope 1 Fixture Test 1") checkTestSucceeded(events(17), "Fixture Scope 1 Fixture Test 1") checkTestStarting(events(18), "Fixture Scope 1 Fixture Test 2") checkTestSucceeded(events(19), "Fixture Scope 1 Fixture Test 2") checkScopeClosed(events(20), "Fixture Scope 1") checkScopeOpened(events(21), "Fixture Scope 2") checkTestStarting(events(22), "Fixture Scope 2 Fixture Test 3") checkTestSucceeded(events(23), "Fixture Scope 2 Fixture Test 3") checkTestStarting(events(24), "Fixture Scope 2 Fixture Test 4") checkTestSucceeded(events(25), "Fixture Scope 2 Fixture Test 4") checkScopeClosed(events(26), "Fixture Scope 2") checkSuiteCompleted(events(27), suite2.suiteId) } } class ExampleParallelTestExecutionParallelPropSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderPropSpec def suite2 = new ExampleParallelTestExecutionOrderFixturePropSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 16) checkSuiteStarting(events(0), suite1.suiteId) checkTestStarting(events(1), "Test 1") checkTestSucceeded(events(2), "Test 1") checkTestStarting(events(3), "Test 2") checkTestSucceeded(events(4), "Test 2") checkTestStarting(events(5), "Test 3") checkTestSucceeded(events(6), "Test 3") checkSuiteCompleted(events(7), suite1.suiteId) checkSuiteStarting(events(8), suite2.suiteId) checkTestStarting(events(9), "Fixture Test 1") checkTestSucceeded(events(10), "Fixture Test 1") checkTestStarting(events(11), "Fixture Test 2") checkTestSucceeded(events(12), "Fixture Test 2") checkTestStarting(events(13), "Fixture Test 3") checkTestSucceeded(events(14), "Fixture Test 3") checkSuiteCompleted(events(15), suite2.suiteId) } } class ExampleParallelTestExecutionParallelWordSpecPair extends ParallelSuites { def suite1 = new ExampleParallelTestExecutionOrderWordSpec def suite2 = new ExampleParallelTestExecutionOrderFixtureWordSpec def assertParallelSuites(events: List[Event]) { assert(events.size === 28) checkSuiteStarting(events(0), suite1.suiteId) checkScopeOpened(events(1), "Scope 1") checkTestStarting(events(2), "Scope 1 should Test 1") checkTestSucceeded(events(3), "Scope 1 should Test 1") checkTestStarting(events(4), "Scope 1 should Test 2") checkTestSucceeded(events(5), "Scope 1 should Test 2") checkScopeClosed(events(6), "Scope 1") checkScopeOpened(events(7), "Scope 2") checkTestStarting(events(8), "Scope 2 should Test 3") checkTestSucceeded(events(9), "Scope 2 should Test 3") checkTestStarting(events(10), "Scope 2 should Test 4") checkTestSucceeded(events(11), "Scope 2 should Test 4") checkScopeClosed(events(12), "Scope 2") checkSuiteCompleted(events(13), suite1.suiteId) checkSuiteStarting(events(14), suite2.suiteId) checkScopeOpened(events(15), "Fixture Scope 1") checkTestStarting(events(16), "Fixture Scope 1 should Fixture Test 1") checkTestSucceeded(events(17), "Fixture Scope 1 should Fixture Test 1") checkTestStarting(events(18), "Fixture Scope 1 should Fixture Test 2") checkTestSucceeded(events(19), "Fixture Scope 1 should Fixture Test 2") checkScopeClosed(events(20), "Fixture Scope 1") checkScopeOpened(events(21), "Fixture Scope 2") checkTestStarting(events(22), "Fixture Scope 2 should Fixture Test 3") checkTestSucceeded(events(23), "Fixture Scope 2 should Fixture Test 3") checkTestStarting(events(24), "Fixture Scope 2 should Fixture Test 4") checkTestSucceeded(events(25), "Fixture Scope 2 should Fixture Test 4") checkScopeClosed(events(26), "Fixture Scope 2") checkSuiteCompleted(events(27), suite2.suiteId) } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/Requirements.scala
/* * Copyright 2001-2012 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.scalactic import reflect.macros.Context /** * Trait that contains <code>require</code>, and <code>requireState</code>, and <code>requireNonNull</code> methods for checking pre-conditions * that give descriptive error messages extracted via a macro. * * <p>These methods of trait <code>Requirements</code> aim to improve error messages provided when a pre-condition check fails at runtime in * production code. Although it is recommended practice to supply helpful error messages when doing pre-condition checks, often people * don't. Instead of this: * * <pre class="stREPL"> * scala&gt; val length = 5 * length: Int = 5 * * scala&gt; val idx = 6 * idx: Int = 6 * * scala&gt; require(idx &gt;= 0 &amp;&amp; idx &lt;= length, "index, " + idx + ", was less than zero or greater than or equal to length, " + length) * java.lang.IllegalArgumentException: <strong>requirement failed: index, 6, was less than zero or greater than or equal to length, 5</strong> * at scala.Predef$.require(Predef.scala:233) * ... * </pre> * * <p> * People write simply: * </p> * * <pre class="stREPL"> * scala&gt; require(idx &gt;= 0 &amp;&amp; idx &lt;= length) * java.lang.IllegalArgumentException: <strong>requirement failed</strong> * at scala.Predef$.require(Predef.scala:221) * ... * </pre> * * <p> * Note that the detail message of the <code>IllegalArgumentException</code> thrown by the previous line of code is simply, <code>"requirement failed"</code>. * Such messages often end up in a log file or bug report, where a better error message can save time in debugging the problem. * By importing the members of <code>Requirements</code> (or mixing in its companion trait), you'll get a more helpful error message * extracted by a macro, whether or not a clue message is provided: * </p> * * <pre class="stREPL"> * scala&gt; import org.scalactic._ * import org.scalactic._ * * scala&gt; import Requirements._ * import Requirements._ * * scala&gt; require(idx &gt;= 0 &amp;&amp; idx &lt;= length) * java.lang.IllegalArgumentException: <strong>6 was greater than or equal to 0, but 6 was not less than or equal to 5</strong> * at org.scalactic.Requirements$RequirementsHelper.macroRequire(Requirements.scala:56) * ... * * scala&gt; require(idx &gt;= 0 &amp;&amp; idx &lt;= length, "(hopefully that helps)") * java.lang.IllegalArgumentException: <strong>6 was greater than or equal to 0, but 6 was not less than or equal to 5 (hopefully that helps)</strong> * at org.scalactic.Requirements$RequirementsHelper.macroRequire(Requirements.scala:56) * ... * </pre> * * <p> * The <code>requireState</code> method provides identical error messages to <code>require</code>, but throws * <code>IllegalStateException</code> instead of <code>IllegalArgumentException</code>: * </p> * * <pre class="stREPL"> * scala&gt; val connectionOpen = false * connectionOpen: Boolean = false * * scala&gt; requireState(connectionOpen) * java.lang.IllegalStateException: <strong>connectionOpen was false</strong> * at org.scalactic.Requirements$RequirementsHelper.macroRequireState(Requirements.scala:71) * ... * </pre> * * <p> * Thus, whereas the <code>require</code> methods throw the Java platform's standard exception indicating a passed argument * violated a precondition, <code>IllegalArgumentException</code>, the <code>requireState</code> methods throw the standard * exception indicating an object's method was invoked when the object was in an inappropriate state for that method, * <code>IllegalStateException</code>. * </p> * * <p> * The <code>requireNonNull</code> method takes one or more variables as arguments and throws <code>NullPointerException</code> * with an error messages that includes the variable names if any are <code>null</code>. Here's an example: * </p> * * <pre class="stREPL"> * scala&gt; val e: String = null * e: String = null * * scala&gt; val f: java.util.Date = null * f: java.util.Date = null * * scala&gt; requireNonNull(a, b, c, d, e, f) * java.lang.NullPointerException: <strong>e and f were null</strong> * at org.scalactic.Requirements$RequirementsHelper.macroRequireNonNull(Requirements.scala:101) * ... * </pre> * * <p> * Although trait <code>Requirements</code> can help you debug problems that occur in production, bear in mind that a much * better alternative is to make it impossible for such events to occur at all. Use the type system to ensure that all * pre-conditions are met so that the compiler can find broken pre-conditions and point them out with compiler error messages. * When this is not possible or practical, however, trait <code>Requirements</code> is helpful. * </p> */ trait Requirements { import language.experimental.macros /** * Helper class used by code generated by the <code>require</code> macro. */ class RequirementsHelper { private def append(currentMessage: String, clue: Any): String = { val clueStr = clue.toString if (clueStr.isEmpty) currentMessage else { val firstChar = clueStr.head if (firstChar.isWhitespace || firstChar == '.' || firstChar == ',' || firstChar == ';' || currentMessage.isEmpty) currentMessage + clueStr else currentMessage + " " + clueStr } } /** * Require that the passed in <code>Bool</code> is <code>true</code>, else fail with <code>IllegalArgumentException</code>. * * @param bool the <code>Bool</code> to check as requirement * @param clue optional clue to be included in <code>IllegalArgumentException</code>'s error message when the requirement failed */ def macroRequire(bool: Bool, clue: Any) { if (clue == null) throw new NullPointerException("clue was null") if (!bool.value) { val failureMessage = if (Bool.isSimpleWithoutExpressionText(bool)) append("", clue) else append(bool.failureMessage, clue) throw new IllegalArgumentException(if (failureMessage.isEmpty) FailureMessages.expressionWasFalse else failureMessage) } } /** * Require that the passed in <code>Bool</code> is <code>true</code>, else fail with <code>IllegalStateException</code>. * * @param bool the <code>Bool</code> to check as requirement * @param clue optional clue to be included in <code>IllegalStateException</code>'s error message when the requirement failed */ def macroRequireState(bool: Bool, clue: Any) { if (clue == null) throw new NullPointerException("clue was null") if (!bool.value) { val failureMessage = if (Bool.isSimpleWithoutExpressionText(bool)) append("", clue) else append(bool.failureMessage, clue) throw new IllegalStateException(if (failureMessage.isEmpty) FailureMessages.expressionWasFalse else failureMessage) } } /** * Require that all of the passed in arguments are not <code>null</code>, else fail with <code>NullPointerException</code>. * * @param variableNames names of variable passed as appear in source * @param arguments arguments to check for <code>null</code> value */ def macroRequireNonNull(variableNames: Array[String], arguments: Array[Any]) { val nullList: Array[(Any, Int)] = arguments.zipWithIndex.filter { case (e, idx) => e == null } val nullCount = nullList.size if (nullCount > 0) { val nullVariableNames = nullList.map { case (e, idx) => variableNames(idx) } val errorMessage = if (nullCount == 1) FailureMessages.wasNull(UnquotedString(nullVariableNames(0))) else if (nullCount == 2) { val combinedVariableNames = Resources.and(nullVariableNames.head, nullVariableNames.last) FailureMessages.wereNull(UnquotedString(combinedVariableNames)) } else { val combinedVariableNames = Resources.commaAnd(nullVariableNames.dropRight(1).mkString(Resources.comma), nullVariableNames.last) FailureMessages.wereNull(UnquotedString(combinedVariableNames)) } throw new NullPointerException(errorMessage) } } } /** * Helper instance used by code generated by macro assertion. */ val requirementsHelper = new RequirementsHelper /** * Require that a boolean condition is true about an argument passed to a method, function, or constructor. * * <p> * If the condition is <code>true</code>, this method returns normally. * Else, it throws <code>IllegalArgumentException</code>. * </p> * * <p> * This method is implemented in terms of a Scala macro that will generate an error message. * See the main documentation for this trait for examples. * </p> * * @param condition the boolean condition to check as requirement * @throws IllegalArgumentException if the condition is <code>false</code>. */ def require(condition: Boolean): Unit = macro RequirementsMacro.require /** * Require that a boolean condition about an argument passed to a method, function, or constructor, * and described in the given <code>clue</code>, is true. * * If the condition is <code>true</code>, this method returns normally. * Else, it throws <code>IllegalArgumentException</code> with the * <code>String</code> obtained by invoking <code>toString</code> on the * specified <code>clue</code> and appending that to the macro-generated * error message as the exception's detail message. * * @param condition the boolean condition to check as requirement * @param clue an objects whose <code>toString</code> method returns a message to include in a failure report. * @throws IllegalArgumentException if the condition is <code>false</code>. * @throws NullPointerException if <code>message</code> is <code>null</code>. */ def require(condition: Boolean, clue: Any): Unit = macro RequirementsMacro.requireWithClue /** * Require that a boolean condition is true about the state of an object on which a method has been invoked. * * <p> * If the condition is <code>true</code>, this method returns normally. * Else, it throws <code>IllegalStateException</code>. * </p> * * <p> * This method is implemented in terms of a Scala macro that will generate an error message. * </p> * * @param condition the boolean condition to check as requirement * @throws IllegalStateException if the condition is <code>false</code>. */ def requireState(condition: Boolean): Unit = macro RequirementsMacro.requireState /** * Require that a boolean condition about the state of an object on which a method has been * invoked, and described in the given <code>clue</code>, is true. * * <p> * If the condition is <code>true</code>, this method returns normally. * Else, it throws <code>IllegalStateException</code> with the * <code>String</code> obtained by invoking <code>toString</code> on the * specified <code>clue</code> appended to the macro-generated error message * as the exception's detail message. * </p> * * @param condition the boolean condition to check as a requirement * @param clue an object whose <code>toString</code> method returns a message to include in a failure report. * @throws IllegalStateException if the condition is <code>false</code>. * @throws NullPointerException if <code>message</code> is <code>null</code>. */ def requireState(condition: Boolean, clue: Any): Unit = macro RequirementsMacro.requireStateWithClue /** * Require that all passed arguments are non-null. * * <p> * If none of the passed arguments are <code>null</code>, this method returns normally. * Else, it throws <code>NullPointerException</code> with an error message that includes the name * (as it appeared in the source) of each argument that was <code>null</code>. * </p> * * @param arguments arguments to check for <code>null</code> value * @throws NullPointerException if any of the arguments are <code>null</code>. */ def requireNonNull(arguments: Any*): Unit = macro RequirementsMacro.requireNonNull } /** * Macro implementation that provides rich error message for boolean expression requirements. */ private[scalactic] object RequirementsMacro { /** * Provides requirement implementation for <code>Requirements.require(booleanExpr: Boolean)</code>, with rich error message. * * @param context macro context * @param condition original condition expression * @return transformed expression that performs the requirement check and throw <code>IllegalArgumentException</code> with rich error message if requirement failed */ def require(context: Context)(condition: context.Expr[Boolean]): context.Expr[Unit] = new BooleanMacro[context.type](context, "requirementsHelper").genMacro(condition, "macroRequire", context.literal("")) /** * Provides requirement implementation for <code>Requirements.require(booleanExpr: Boolean, clue: Any)</code>, with rich error message. * * @param context macro context * @param condition original condition expression * @param clue original clue expression * @return transformed expression that performs the requirement check and throw <code>IllegalArgumentException</code> with rich error message (clue included) if requirement failed */ def requireWithClue(context: Context)(condition: context.Expr[Boolean], clue: context.Expr[Any]): context.Expr[Unit] = new BooleanMacro[context.type](context, "requirementsHelper").genMacro(condition, "macroRequire", clue) /** * Provides requirement implementation for <code>Requirements.requireState(booleanExpr: Boolean)</code>, with rich error message. * * @param context macro context * @param condition original condition expression * @return transformed expression that performs the requirement check and throw <code>IllegalStateException</code> with rich error message if requirement failed */ def requireState(context: Context)(condition: context.Expr[Boolean]): context.Expr[Unit] = new BooleanMacro[context.type](context, "requirementsHelper").genMacro(condition, "macroRequireState", context.literal("")) /** * Provides requirement implementation for <code>Requirements.requireState(booleanExpr: Boolean, clue: Any)</code>, with rich error message. * * @param context macro context * @param condition original condition expression * @param clue original clue expression * @return transformed expression that performs the requirement check and throw <code>IllegalStateException</code> with rich error message (clue included) if requirement failed */ def requireStateWithClue(context: Context)(condition: context.Expr[Boolean], clue: context.Expr[Any]): context.Expr[Unit] = new BooleanMacro[context.type](context, "requirementsHelper").genMacro(condition, "macroRequireState", clue) /** * Provides requirement implementation for <code>Requirements.requireNonNull(arguments: Any*)</code>, with rich error message. * * @param context macro context * @param arguments original arguments expression(s) * @return transformed expression that performs the requirement check and throw <code>NullPointerException</code> with rich error message if requirement failed */ def requireNonNull(context: Context)(arguments: context.Expr[Any]*): context.Expr[Unit] = { import context.universe._ // generate AST that create array containing the argument name in source (get from calling 'show') // for example, if you have: // val a = "1" // val b = null // val c = "3" // requireNonNull(a, b, c) // it will generate the following code: // // Array("a", "b", "c") val variablesNamesArray = Apply( Select( Ident("Array"), newTermName("apply") ), List(arguments.map(e => context.literal(show(e.tree)).tree): _*) ) // generate AST that create array containing the argument values // for example, if you have: // val a = "1" // val b = null // val c = "3" // requireNonNull(a, b, c) // it will generate the following code: // // Array(a, b, c) val argumentsArray = Apply( Select( Ident("Array"), newTermName("apply") ), List(arguments.map(e => e.tree): _*) ) // Generate AST to call requirementsHelper.macroRequireNonNull and pass in both variable names and values array: // // requirementsHelper.macroRequireNonNull(variableNamesArray, valuesArray) context.Expr( Apply( Select( Ident("requirementsHelper"), newTermName("macroRequireNonNull") ), List(variablesNamesArray, argumentsArray) ) ) } } /** * Companion object that facilitates the importing of <code>Requirements</code> members as * an alternative to mixing it in. One use case is to import <code>Requirements</code> members so you can use * them in the Scala interpreter: * * <pre class="stREPL"> * $scala -classpath scalatest.jar * Welcome to Scala version 2.10.3.final (Java HotSpot(TM) Client VM, Java xxxxxx). * Type in expressions to have them evaluated. * Type :help for more information. * &nbsp; * scala&gt; import org.scalactic.Requirements._ * import org.scalactic.Requirements._ * &nbsp; * scala&gt; val a = 1 * a: Int = 1 * &nbsp; * scala&gt; require(a == 2) * java.lang.IllegalArgumentException: 1 did not equal 2 * at org.scalactic.Requirements$RequirementsHelper.macroRequire(Requirements.scala:56) * at .&lt;init&gt;(&lt;console&gt;:20) * at .&lt;clinit&gt;(&lt;console&gt;) * at .&lt;init&gt;(&lt;console&gt;:7) * at .&lt;clinit&gt;(&lt;console&gt;) * at $print(&lt;console&gt;) * at sun.reflect.NativeMethodAccessorImpl.invoke... */ object Requirements extends Requirements
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldBeEmptyStructuralSpec.scala
<reponame>cquiroz/scalatest /* * 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 import SharedHelpers.thisLineNumber import Matchers._ import exceptions.TestFailedException class ShouldBeEmptyStructuralSpec extends FunSpec { val fileName: String = "ShouldBeEmptyStructuralSpec.scala" def wasNotEmpty(left: Any): String = FailureMessages.wasNotEmpty(left) def wasEmpty(left: Any): String = FailureMessages.wasEmpty(left) describe("empty matcher") { describe("when work with arbitrary object with isEmpty() method") { class MyEmptiness(value: Boolean) { def isEmpty(): Boolean = value override def toString = "emptiness" } val objTrue = new MyEmptiness(true) val objFalse = new MyEmptiness(false) it("should do nothing for 'objTrue should be (empty)'") { objTrue should be (empty) } it("should throw TFE with correct stack depth for 'objFalse should be (empty)'") { val caught1 = intercept[TestFailedException] { objFalse should be (empty) } assert(caught1.message === Some(wasNotEmpty(objFalse))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } it("should do nothing if for 'objFalse should not be empty'") { objFalse should not be empty } it("should throw TFE with correct stack depth for 'objTrue should not be empty'") { val caught1 = intercept[TestFailedException] { objTrue should not be empty } assert(caught1.message === Some(wasEmpty(objTrue))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } } describe("when work with arbitrary object with isEmpty method") { class MyEmptiness(value: Boolean) { def isEmpty: Boolean = value override def toString = "emptiness" } val objTrue = new MyEmptiness(true) val objFalse = new MyEmptiness(false) it("should do nothing for 'objTrue should be (empty)'") { objTrue should be (empty) } it("should throw TFE with correct stack depth for 'objFalse should be (empty)'") { val caught1 = intercept[TestFailedException] { objFalse should be (empty) } assert(caught1.message === Some(wasNotEmpty(objFalse))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } it("should do nothing if for 'objFalse should not be empty'") { objFalse should not be empty } it("should throw TFE with correct stack depth for 'objTrue should not be empty'") { val caught1 = intercept[TestFailedException] { objTrue should not be empty } assert(caught1.message === Some(wasEmpty(objTrue))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } } describe("when work with arbitrary object with isEmpty val") { class MyEmptiness(value: Boolean) { val isEmpty: Boolean = value override def toString = "emptiness" } val objTrue = new MyEmptiness(true) val objFalse = new MyEmptiness(false) it("should do nothing for 'objTrue should be (empty)'") { objTrue should be (empty) } it("should throw TFE with correct stack depth for 'objFalse should be (empty)'") { val caught1 = intercept[TestFailedException] { objFalse should be (empty) } assert(caught1.message === Some(wasNotEmpty(objFalse))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } it("should do nothing if for 'objFalse should not be empty'") { objFalse should not be empty } it("should throw TFE with correct stack depth for 'objTrue should not be empty'") { val caught1 = intercept[TestFailedException] { objTrue should not be empty } assert(caught1.message === Some(wasEmpty(objTrue))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } } } }
cquiroz/scalatest
scalactic-macro/src/main/scala/org/scalactic/anyvals/GuessANumber.scala
<gh_stars>1-10 /* * Copyright 2001-2014 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.scalactic.anyvals private[scalactic] final class GuessANumber private (val value: Int) extends AnyVal { override def toString: String = s"GuessANumber($value)" } private[scalactic] object GuessANumber { def from(value: Int): Option[GuessANumber] = if (value >= 1 && value <= 10) Some(new GuessANumber(value)) else None import scala.language.experimental.macros def apply(value: Int): GuessANumber = macro GuessANumberMacro.apply } private[scalactic] final class LGuessANumber private (val value: Long) extends AnyVal { override def toString: String = s"LGuessANumber($value)" } private[scalactic] object LGuessANumber { def from(value: Long): Option[LGuessANumber] = if (value >= 1L && value <= 10L) Some(new LGuessANumber(value)) else None } private[scalactic] final class FGuessANumber private (val value: Float) extends AnyVal { override def toString: String = s"FGuessANumber($value)" } private[scalactic] object FGuessANumber { def from(value: Float): Option[FGuessANumber] = if (value >= 1.0F && value <= 10.0F) Some(new FGuessANumber(value)) else None } private[scalactic] final class DGuessANumber private (val value: Double) extends AnyVal { override def toString: String = s"DGuessANumber($value)" } private[scalactic] object DGuessANumber { def from(value: Double): Option[DGuessANumber] = if (value >= 1.0 && value <= 10.0) Some(new DGuessANumber(value)) else None }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/tools/PrintReporter.scala
/* * 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.tools import org.scalatest._ // SKIP-SCALATESTJS-START import java.io.BufferedOutputStream import java.io.File import java.io.FileOutputStream // SKIP-SCALATESTJS-END import java.io.OutputStreamWriter import java.io.OutputStream import java.io.PrintWriter import org.scalatest.events._ import PrintReporter._ /** * A <code>Reporter</code> that prints test status information to * a <code>Writer</code>, <code>OutputStream</code>, or file. * * @author <NAME> */ private[scalatest] abstract class PrintReporter( pw: PrintWriter, presentAllDurations: Boolean, presentInColor: Boolean, presentShortStackTraces: Boolean, presentFullStackTraces: Boolean, presentUnformatted: Boolean, presentReminder: Boolean, presentReminderWithShortStackTraces: Boolean, presentReminderWithFullStackTraces: Boolean, presentReminderWithoutCanceledTests: Boolean ) extends StringReporter( presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests ) { /** * Construct a <code>PrintReporter</code> with passed * <code>OutputStream</code>. Information about events reported to instances of this * class will be written to the <code>OutputStream</code> using the * default character encoding. * * @param os the <code>OutputStream</code> to which to print reported info * @throws NullPointerException if passed <code>os</code> reference is <code>null</code> */ def this( // Used by subclasses StandardOutReporter and StandardErrReporter os: OutputStream, presentAllDurations: Boolean, presentInColor: Boolean, presentShortStackTraces: Boolean, presentFullStackTraces: Boolean, presentUnformatted: Boolean, presentReminder: Boolean, presentReminderWithShortStackTraces: Boolean, presentReminderWithFullStackTraces: Boolean, presentReminderWithoutCanceledTests: Boolean ) = this( new PrintWriter( new OutputStreamWriter( new BufferedOutputStream(os, BufferSize) ) ), presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests ) // SKIP-SCALATESTJS-START /** * Construct a <code>PrintReporter</code> with passed * <code>String</code> file name. Information about events reported to instances of this * class will be written to the specified file using the * default character encoding. * * @param filename the <code>String</code> name of the file to which to print reported info * @throws NullPointerException if passed <code>filename</code> reference is <code>null</code> * @throws IOException if unable to open the specified file for writing */ def this( // Used by subclass FileReporter filename: String, presentAllDurations: Boolean, presentInColor: Boolean, presentShortStackTraces: Boolean, presentFullStackTraces: Boolean, presentUnformatted: Boolean, presentReminder: Boolean, presentReminderWithShortStackTraces: Boolean, presentReminderWithFullStackTraces: Boolean, presentReminderWithoutCanceledTests: Boolean ) = this( new PrintWriter(new BufferedOutputStream(new FileOutputStream(new File(filename)), BufferSize)), presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests ) // SKIP-SCALATESTJS-END protected def printPossiblyInColor(fragment: Fragment) { pw.println(fragment.toPossiblyColoredText(presentInColor)) } override def apply(event: Event) { super.apply(event) pw.flush() } // Closes the print writer. Subclasses StandardOutReporter and StandardErrReporter override dispose to do nothing // so that those aren't closed. override def dispose() { pw.close() } // We subtract one from test reports because we add "- " in front, so if one is actually zero, it will come here as -1 // private def indent(s: String, times: Int) = if (times <= 0) s else (" " * times) + s // Stupid properties file won't let me put spaces at the beginning of a property // " {0}" comes out as "{0}", so I can't do indenting in a localizable way. For now // just indent two space to the left. // if (times <= 0) s // else Resources.indentOnce(indent(s, times - 1)) } private[scalatest] object PrintReporter { final val BufferSize = 4096 }
cquiroz/scalatest
scalatest.js/src/main/scala/org/scalatest/tools/MasterRunner.scala
package org.scalatest.tools import org.scalatest.Tracker import org.scalatest.events.Summary import sbt.testing.{Framework => BaseFramework, Event => SbtEvent, Status => SbtStatus, _} import scala.compat.Platform class MasterRunner(theArgs: Array[String], theRemoteArgs: Array[String], testClassLoader: ClassLoader) extends Runner { // TODO: To take these from test arguments val presentAllDurations: Boolean = true val presentInColor: Boolean = true val presentShortStackTraces: Boolean = true val presentFullStackTraces: Boolean = true val presentUnformatted: Boolean = false val presentReminder: Boolean = false val presentReminderWithShortStackTraces: Boolean = false val presentReminderWithFullStackTraces: Boolean = false val presentReminderWithoutCanceledTests: Boolean = false val runStartTime = Platform.currentTime val tracker = new Tracker val summaryCounter = new SummaryCounter def done(): String = { val duration = Platform.currentTime - runStartTime val summary = new Summary(summaryCounter.testsSucceededCount, summaryCounter.testsFailedCount, summaryCounter.testsIgnoredCount, summaryCounter.testsPendingCount, summaryCounter.testsCanceledCount, summaryCounter.suitesCompletedCount, summaryCounter.suitesAbortedCount, summaryCounter.scopesPendingCount) val fragments: Vector[Fragment] = StringReporter.summaryFragments( true, Some(duration), Some(summary), Vector.empty ++ summaryCounter.reminderEventsQueue, presentAllDurations, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests ) fragments.map(_.toPossiblyColoredText(presentInColor)).mkString("\n") } def remoteArgs(): Array[String] = { theRemoteArgs } def args: Array[String] = { theArgs } def tasks(list: Array[TaskDef]): Array[Task] = { list.map(t => new TaskRunner(t, testClassLoader, tracker, presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests, None)) } def receiveMessage(msg: String): Option[String] = { msg match { case "org.scalatest.events.TestPending" => summaryCounter.incrementTestsPendingCount() case "org.scalatest.events.TestFailed" => summaryCounter.incrementTestsFailedCount() case "org.scalatest.events.TestSucceeded" => summaryCounter.incrementTestsSucceededCount() case "org.scalatest.events.TestIgnored" => summaryCounter.incrementTestsIgnoredCount() case "org.scalatest.events.TestCanceled" => summaryCounter.incrementTestsCanceledCount() case "org.scalatest.events.SuiteCompleted" => summaryCounter.incrementSuitesCompletedCount() case "org.scalatest.events.SuiteAborted" => summaryCounter.incrementSuitesAbortedCount() case "org.scalatest.events.ScopePending" => summaryCounter.incrementScopesPendingCount() case _ => } None } def serializeTask(task: Task, serializer: (TaskDef) => String): String = serializer(task.taskDef()) def deserializeTask(task: String, deserializer: (String) => TaskDef): Task = new TaskRunner(deserializer(task), testClassLoader, tracker, presentAllDurations, presentInColor, presentShortStackTraces, presentFullStackTraces, presentUnformatted, presentReminder, presentReminderWithShortStackTraces, presentReminderWithFullStackTraces, presentReminderWithoutCanceledTests, None) }
cquiroz/scalatest
scalatest.js/src/main/scala/org/scalatest/exceptions/StackDepthExceptionHelper.scala
package org.scalatest.exceptions private[scalatest] object StackDepthExceptionHelper { def getStackDepth(stackTraces: Array[StackTraceElement], fileName: String, methodName: String, adjustment: Int = 0): Int = { stackTraces.takeWhile(_.getFileName.startsWith("https://")).length } def getStackDepthFun(fileName: String, methodName: String, adjustment: Int = 0): (StackDepthException => Int) = { sde => getStackDepth(sde.getStackTrace, fileName, methodName, adjustment) } def getFailedCodeFileName(stackTraceElement: StackTraceElement): Option[String] = { val fileName = stackTraceElement.getFileName if (fileName != null) { val lastPathSeparatorIdx = fileName.lastIndexOf("/") if (lastPathSeparatorIdx >= 0) Some(fileName.substring(lastPathSeparatorIdx + 1)) else Some(fileName) } else None } val macroCodeStackDepth: Int = 9 }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/package.scala
/* * 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 import scala.util.control.NonFatal package object scalactic { /** * Type alias for <code>String</code>. */ type ErrorMessage = String /** * Returns the result of evaluating the given block <code>f</code>, wrapped in a <code>Good</code>, or * if an exception is thrown, the <code>Throwable</code>, wrapped in a <code>Bad</code>. * * <p> * Here are some examples: * </p> * * <pre class="stREPL"> * scala&gt; import org.scalactic._ * import org.scalactic._ * * scala&gt; attempt { 2 / 1 } * res0: org.scalactic.Or[Int,Throwable] = Good(2) * * scala&gt; attempt { 2 / 0 } * res1: org.scalactic.Or[Int,Throwable] = Bad(java.lang.ArithmeticException: / by zero) * </pre> * * @param f the block to attempt to evaluate * @return the result of evaluating the block, wrapped in a <code>Good</code>, or the * thrown exception, wrapped in a <code>Bad</code> */ def attempt[R](f: => R): R Or Throwable = try Good(f) catch { case e: Throwable if NonFatal(e) => Bad(e) } /** * The version number of Scalactic. * * @return the Scalactic version number. */ val ScalacticVersion: String = ScalacticVersions.ScalacticVersion @deprecated("Please use org.scalactic.EqualityPolicy instead.") type TripleEqualsSupport = org.scalactic.EqualityPolicy @deprecated("Please use org.scalactic.EqualityPolicy instead.") val TripleEqualsSupport = org.scalactic.EqualityPolicy }
cquiroz/scalatest
scalactic-macro/src/main/scala/org/scalactic/anyvals/PosZLong.scala
<reponame>cquiroz/scalatest<filename>scalactic-macro/src/main/scala/org/scalactic/anyvals/PosZLong.scala /* * Copyright 2001-2014 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.scalactic.anyvals import scala.collection.immutable.NumericRange // // Numbers greater than or equal to zero. // // (Pronounced like "posey".) // /** * TODO * * @param value The <code>Long</code> value underlying this <code>PosZLong</code>. */ final class PosZLong private (val value: Long) extends AnyVal { /** * A string representation of this <code>PosZLong</code>. */ override def toString: String = s"PosZLong($value)" /** * Converts this <code>PosZLong</code> to a <code>Byte</code>. */ def toByte: Byte = value.toByte /** * Converts this <code>PosZLong</code> to a <code>Short</code>. */ def toShort: Short = value.toShort /** * Converts this <code>PosZLong</code> to a <code>Char</code>. */ def toChar: Char = value.toChar /** * Converts this <code>PosZLong</code> to an <code>Int</code>. */ def toInt: Int = value.toInt /** * Converts this <code>PosZLong</code> to a <code>Long</code>. */ def toLong: Long = value.toLong /** * Converts this <code>PosZLong</code> to a <code>Float</code>. */ def toFloat: Float = value.toFloat /** * Converts this <code>PosZLong</code> to a <code>Double</code>. */ def toDouble: Double = value.toDouble /** * Returns the bitwise negation of this value. * @example {{{ * ~5 == -6 * // in binary: ~00000101 == * // 11111010 * }}} */ def unary_~ : Long = ~value /** Returns this value, unmodified. */ def unary_+ : PosZLong = this /** Returns the negation of this value. */ def unary_- : Long = -value /** * Converts this <code>PosZLong</code>'s value to a string then concatenates the given string. */ def +(x: String): String = value + x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the new right bits with zeroes. * @example {{{ 6 << 3 == 48 // in binary: 0110 << 3 == 0110000 }}} */ def <<(x: Int): Long = value << x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the new right bits with zeroes. * @example {{{ 6 << 3 == 48 // in binary: 0110 << 3 == 0110000 }}} */ def <<(x: Long): Long = value << x /** * Returns this value bit-shifted right by the specified number of bits, * filling the new left bits with zeroes. * @example {{{ 21 >>> 3 == 2 // in binary: 010101 >>> 3 == 010 }}} * @example {{{ * -21 >>> 3 == 536870909 * // in binary: 11111111 11111111 11111111 11101011 >>> 3 == * // 00011111 11111111 11111111 11111101 * }}} */ def >>>(x: Int): Long = value >>> x /** * Returns this value bit-shifted right by the specified number of bits, * filling the new left bits with zeroes. * @example {{{ 21 >>> 3 == 2 // in binary: 010101 >>> 3 == 010 }}} * @example {{{ * -21 >>> 3 == 536870909 * // in binary: 11111111 11111111 11111111 11101011 >>> 3 == * // 00011111 11111111 11111111 11111101 * }}} */ def >>>(x: Long): Long = value >>> x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the right bits with the same value as the left-most bit of this. * The effect of this is to retain the sign of the value. * @example {{{ * -21 >> 3 == -3 * // in binary: 11111111 11111111 11111111 11101011 >> 3 == * // 11111111 11111111 11111111 11111101 * }}} */ def >>(x: Int): Long = value >> x /** * Returns this value bit-shifted left by the specified number of bits, * filling in the right bits with the same value as the left-most bit of this. * The effect of this is to retain the sign of the value. * @example {{{ * -21 >> 3 == -3 * // in binary: 11111111 11111111 11111111 11101011 >> 3 == * // 11111111 11111111 11111111 11111101 * }}} */ def >>(x: Long): Long = value >> x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Byte): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Short): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Char): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Int): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Long): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Float): Boolean = value < x /** Returns `true` if this value is less than x, `false` otherwise. */ def <(x: Double): Boolean = value < x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Byte): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Short): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Char): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Int): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Long): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Float): Boolean = value <= x /** Returns `true` if this value is less than or equal to x, `false` otherwise. */ def <=(x: Double): Boolean = value <= x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Byte): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Short): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Char): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Int): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Long): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Float): Boolean = value > x /** Returns `true` if this value is greater than x, `false` otherwise. */ def >(x: Double): Boolean = value > x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Byte): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Short): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Char): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Int): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Long): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Float): Boolean = value >= x /** Returns `true` if this value is greater than or equal to x, `false` otherwise. */ def >=(x: Double): Boolean = value >= x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Byte): Long = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Short): Long = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Char): Long = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Int): Long = value | x /** * Returns the bitwise OR of this value and `x`. * @example {{{ * (0xf0 | 0xaa) == 0xfa * // in binary: 11110000 * // | 10101010 * // -------- * // 11111010 * }}} */ def |(x: Long): Long = value | x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Byte): Long = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Short): Long = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Char): Long = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Int): Long = value & x /** * Returns the bitwise AND of this value and `x`. * @example {{{ * (0xf0 & 0xaa) == 0xa0 * // in binary: 11110000 * // & 10101010 * // -------- * // 10100000 * }}} */ def &(x: Long): Long = value & x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Byte): Long = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Short): Long = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Char): Long = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Int): Long = value ^ x /** * Returns the bitwise XOR of this value and `x`. * @example {{{ * (0xf0 ^ 0xaa) == 0x5a * // in binary: 11110000 * // ^ 10101010 * // -------- * // 01011010 * }}} */ def ^(x: Long): Long = value ^ x /** Returns the sum of this value and `x`. */ def +(x: Byte): Long = value + x /** Returns the sum of this value and `x`. */ def +(x: Short): Long = value + x /** Returns the sum of this value and `x`. */ def +(x: Char): Long = value + x /** Returns the sum of this value and `x`. */ def +(x: Int): Long = value + x /** Returns the sum of this value and `x`. */ def +(x: Long): Long = value + x /** Returns the sum of this value and `x`. */ def +(x: Float): Float = value + x /** Returns the sum of this value and `x`. */ def +(x: Double): Double = value + x /** Returns the difference of this value and `x`. */ def -(x: Byte): Long = value - x /** Returns the difference of this value and `x`. */ def -(x: Short): Long = value - x /** Returns the difference of this value and `x`. */ def -(x: Char): Long = value - x /** Returns the difference of this value and `x`. */ def -(x: Int): Long = value - x /** Returns the difference of this value and `x`. */ def -(x: Long): Long = value - x /** Returns the difference of this value and `x`. */ def -(x: Float): Float = value - x /** Returns the difference of this value and `x`. */ def -(x: Double): Double = value - x /** Returns the product of this value and `x`. */ def *(x: Byte): Long = value * x /** Returns the product of this value and `x`. */ def *(x: Short): Long = value * x /** Returns the product of this value and `x`. */ def *(x: Char): Long = value * x /** Returns the product of this value and `x`. */ def *(x: Int): Long = value * x /** Returns the product of this value and `x`. */ def *(x: Long): Long = value * x /** Returns the product of this value and `x`. */ def *(x: Float): Float = value * x /** Returns the product of this value and `x`. */ def *(x: Double): Double = value * x /** Returns the quotient of this value and `x`. */ def /(x: Byte): Long = value / x /** Returns the quotient of this value and `x`. */ def /(x: Short): Long = value / x /** Returns the quotient of this value and `x`. */ def /(x: Char): Long = value / x /** Returns the quotient of this value and `x`. */ def /(x: Int): Long = value / x /** Returns the quotient of this value and `x`. */ def /(x: Long): Long = value / x /** Returns the quotient of this value and `x`. */ def /(x: Float): Float = value / x /** Returns the quotient of this value and `x`. */ def /(x: Double): Double = value / x /** Returns the remainder of the division of this value by `x`. */ def %(x: Byte): Long = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Short): Long = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Char): Long = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Int): Long = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Long): Long = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Float): Float = value % x /** Returns the remainder of the division of this value by `x`. */ def %(x: Double): Double = value % x // Stuff from RichLong: /** * Returns a string representation of this <code>PosLong</code>'s underlying <code>Long</code> * as an unsigned integer in base&nbsp;2. * * <p> * The unsigned <code>long</code> value is this <code>PosLong</code>'s underlying <code>Long</code> plus * 2<sup>64</sup> if the underlying <code>Long</code> is negative; otherwise, it is * equal to the underlying <code>Long</code>. This value is converted to a string of * ASCII digits in binary (base&nbsp;2) with no extra leading * <code>0</code>s. If the unsigned magnitude is zero, it is * represented by a single zero character <code>'0'</code> * (<code>'&#92;u0030'</code>); otherwise, the first character of * the representation of the unsigned magnitude will not be the * zero character. The characters <code>'0'</code> * (<code>'&#92;u0030'</code>) and <code>'1'</code> * (<code>'&#92;u0031'</code>) are used as binary digits. * </p> * * @return the string representation of the unsigned <code>long</code> * value represented by this <code>PosLong</code>'s underlying <code>Long</code> in binary (base&nbsp;2). */ def toBinaryString: String = java.lang.Long.toBinaryString(value) /** * Returns a string representation of this <code>PosLong</code>'s underlying <code>Long</code> * as an unsigned integer in base&nbsp;16. * * <p> * The unsigned <code>long</code> value is this <code>PosLong</code>'s underlying <code>Long</code> plus * 2<sup>64</sup> if the underlying <code>Long</code> is negative; otherwise, it is * equal to the underlying <code>Long</code>. This value is converted to a string of * ASCII digits in hexadecimal (base&nbsp;16) with no extra * leading <code>0</code>s. If the unsigned magnitude is zero, it * is represented by a single zero character <code>'0'</code> * (<code>'&#92;u0030'</code>); otherwise, the first character of * the representation of the unsigned magnitude will not be the * zero character. The following characters are used as * hexadecimal digits: * </p> * * <blockquote> * <code>0123456789abcdef</code> * </blockquote> * * <p> * These are the characters <code>'&#92;u0030'</code> through * <code>'&#92;u0039'</code> and <code>'&#92;u0061'</code> through * <code>'&#92;u0066'</code>. If uppercase letters are desired, * the <code>toUpperCase</code> method may be called * on the result. * </p> * * @return the string representation of the unsigned <code>long</code> * value represented by this <code>PosLong</code>'s underlying <code>Long</code> in hexadecimal * (base&nbsp;16). */ def toHexString: String = java.lang.Long.toHexString(value) def toOctalString: String = java.lang.Long.toOctalString(value) // No point to call abs on a PosZLong. def max(that: PosZLong): PosZLong = if (math.max(value, that.value) == value) this else that def min(that: PosZLong): PosZLong = if (math.min(value, that.value) == value) this else that // adapted from RichInt: /** * @param end The final bound of the range to make. * @return A [[scala.collection.immutable.NumericRange.Exclusive[Long]]] from `this` up to but * not including `end`. */ def until(end: Long): NumericRange.Exclusive[Long] = value.until(end) /** * @param end The final bound of the range to make. * @param step The number to increase by for each step of the range. * @return A [[scala.collection.immutable.NumericRange.Exclusive[Long]]] from `this` up to but * not including `end`. */ def until(end: Long, step: Long): NumericRange.Exclusive[Long] = value.until(end, step) /** * @param end The final bound of the range to make. * @return A [[scala.collection.immutable.NumericRange.Inclusive[Long]]] from `'''this'''` up to * and including `end`. */ def to(end: Long): NumericRange.Inclusive[Long] = value.to(end) /** * @param end The final bound of the range to make. * @param step The number to increase by for each step of the range. * @return A [[scala.collection.immutable.NumericRange.Inclusive[Long]]] from `'''this'''` up to * and including `end`. */ def to(end: Long, step: Long): NumericRange.Inclusive[Long] = value.to(end, step) } object PosZLong { def from(value: Long): Option[PosZLong] = if (value >= 0L) Some(new PosZLong(value)) else None import language.experimental.macros import scala.language.implicitConversions implicit def apply(value: Long): PosZLong = macro PosZLongMacro.apply implicit def widenToLong(poz: PosZLong): Long = poz.value implicit def widenToFloat(poz: PosZLong): Float = poz.value implicit def widenToDouble(poz: PosZLong): Double = poz.value implicit def widenToPosZFloat(poz: PosZLong): PosZFloat = PosZFloat.from(poz.value).get implicit def widenToPosZDouble(poz: PosZLong): PosZDouble = PosZDouble.from(poz.value).get }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/events/TestLocationFunctionServices.scala
/* * 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.events import org.scalatest.Assertions._ trait TestLocationFunctionServices { private[events] case class TestStartingPair(testName: String, fileName: String, lineNumber: Int, var checked: Boolean = false) import scala.language.existentials private[events] case class TestResultPair(clazz: Class[_], fileName: String, lineNumber: Int, var checked: Boolean = false) private[events] case class ScopeOpenedPair(testName: String, fileName: String, lineNumber: Int, var checked: Boolean = false) private[events] case class ScopeClosedPair(testName: String, fileName: String, lineNumber: Int, var checked: Boolean = false) val suiteTypeName: String val expectedStartingList: List[TestStartingPair] val expectedResultList: List[TestResultPair] val expectedScopeOpenedList: List[ScopeOpenedPair] val expectedScopeClosedList: List[ScopeClosedPair] def checkFileNameLineNumber(suiteName:String, expectedFileName: String, expectedLineNumber: Int, event: Event):Boolean = { event.location match { case Some(evt) => val lineInFile = event.location.get.asInstanceOf[LineInFile] assert(expectedFileName == lineInFile.fileName, "Suite " + suiteName + " - " + event + " expected LocationFunctionSuiteProp.scala, got " + lineInFile.fileName) assert(expectedLineNumber == lineInFile.lineNumber, "Suite " + suiteName + " - " + event + " expected " + expectedLineNumber + ", got " + lineInFile.lineNumber) true case None => fail("Suite " + suiteName + " - Event " + event.getClass.getName + " does not have location.") } } def checkFun(event: Event) { event match { case testStarting: TestStarting => val expectedStartingPairOpt = expectedStartingList.find { pair => pair.testName == testStarting.testName } expectedStartingPairOpt match { case Some(expectedStartingPair) => expectedStartingPair.checked = checkFileNameLineNumber(suiteTypeName, expectedStartingPair.fileName, expectedStartingPair.lineNumber, event) case None => fail("Unknown TestStarting for testName=" + testStarting.testName + " in " + suiteTypeName) } case scopeOpened: ScopeOpened => val expectedScopeOpenedPairOpt = expectedScopeOpenedList.find { pair => pair.testName == scopeOpened.message } expectedScopeOpenedPairOpt match { case Some(expectedScopeOpenedPair) => expectedScopeOpenedPair.checked = checkFileNameLineNumber(suiteTypeName, expectedScopeOpenedPair.fileName, expectedScopeOpenedPair.lineNumber, event) case None => fail("Unknown ScopeOpened for testName=" + scopeOpened.message + " in " + suiteTypeName) } case scopeClosed: ScopeClosed => val expectedScopeClosedPairOpt = expectedScopeClosedList.find { pair => pair.testName == scopeClosed.message } expectedScopeClosedPairOpt match { case Some(expectedScopeClosedPair) => expectedScopeClosedPair.checked = checkFileNameLineNumber(suiteTypeName, expectedScopeClosedPair.fileName, expectedScopeClosedPair.lineNumber, event) case None => fail("Unknown ScopeClosed for testName=" + scopeClosed.message + " in " + suiteTypeName) } case _ => val expectedResultPairOpt = expectedResultList.find { pair => pair.clazz == event.getClass() } expectedResultPairOpt match { case Some(expectedResultPair) => expectedResultPair.checked = checkFileNameLineNumber(suiteTypeName, expectedResultPair.fileName, expectedResultPair.lineNumber, event) case None => fail("Unexpected event:" + event.getClass.getName + " in " + suiteTypeName) } } } def allChecked = { expectedStartingList.foreach { pair => assert(pair.checked, suiteTypeName + ": TestStarting for " + pair.testName + " not fired.") } expectedResultList.foreach { pair => assert(pair.checked, suiteTypeName + ": " + pair.clazz.getName() + " event not fired.") } expectedScopeOpenedList.foreach { pair => assert(pair.checked, suiteTypeName + ": ScopedOpened for " + pair.testName + " not fired.") } expectedScopeClosedList.foreach { pair => assert(pair.checked, suiteTypeName + ": ScopedClosed for " + pair.testName + " not fired.") } } }
cquiroz/scalatest
project/GenDeprecatedShouldMatchersTests.scala
<filename>project/GenDeprecatedShouldMatchersTests.scala /* * Copyright 2001-2011 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. */ import java.io.File import java.io.FileWriter import java.io.BufferedWriter import scala.io.Source import scala.io.Codec object DeprecatedShouldMatcherTestsHelper { implicit val codec = Codec.default def translateShouldToDeprecatedShould(shouldLine: String): String = { shouldLine.replaceAll("Should", "DeprecatedShould") } def generateFile(targetDir: String, srcFileName: String, targetFileName: String) { val matchersDir = new File(targetDir + "/main/scala/org/scalatest/matchers") matchersDir.mkdirs() val writer = new BufferedWriter(new FileWriter(targetDir + "/main/scala/org/scalatest/" + targetFileName)) try { val shouldLines = Source.fromFile("src/main/scala/org/scalatest/" + srcFileName).getLines().toList for (shouldLine <- shouldLines) { val deprecatedShouldLine = translateShouldToDeprecatedShould(shouldLine) writer.write(deprecatedShouldLine) writer.newLine() } } finally { writer.close() } } } import DeprecatedShouldMatcherTestsHelper._ object GenDeprecatedShouldMatchersTests { def main(args: Array[String]) { val targetDir = args(0) val matchersDir = new File("gen/" + targetDir + "/test/scala/org/scalatest/matchers") matchersDir.mkdirs() val shouldFileNames = List( "ShouldBehaveLikeSpec.scala", "ShouldContainElementSpec.scala", "ShouldContainKeySpec.scala", "ShouldContainValueSpec.scala", "ShouldEqualSpec.scala", "ShouldHavePropertiesSpec.scala", "ShouldLengthSpec.scala", "ShouldOrderedSpec.scala", "ShouldSizeSpec.scala", "ShouldBeASymbolSpec.scala", "ShouldBeAnSymbolSpec.scala", "ShouldBeMatcherSpec.scala", "ShouldBePropertyMatcherSpec.scala", "ShouldBeSymbolSpec.scala", "ShouldEndWithRegexSpec.scala", "ShouldEndWithSubstringSpec.scala", "ShouldFullyMatchSpec.scala", "ShouldIncludeRegexSpec.scala", "ShouldIncludeSubstringSpec.scala", "ShouldLogicalMatcherExprSpec.scala", "ShouldMatcherSpec.scala", "ShouldPlusOrMinusSpec.scala", "ShouldSameInstanceAsSpec.scala", "ShouldStartWithRegexSpec.scala", "ShouldStartWithSubstringSpec.scala", "ShouldBeNullSpec.scala" ) for (shouldFileName <- shouldFileNames) { val deprecatedShouldFileName = shouldFileName.replace("Should", "DeprecatedShould") val writer = new BufferedWriter(new FileWriter("gen/" + targetDir + "/test/scala/org/scalatest/matchers/" + deprecatedShouldFileName)) try { val shouldLines = Source.fromFile("src/test/scala/org/scalatest/matchers/" + shouldFileName).getLines().toList // for 2.8 for (shouldLine <- shouldLines) { val deprecatedShouldLine = translateShouldToDeprecatedShould(shouldLine) writer.write(deprecatedShouldLine.toString) writer.newLine() // add for 2.8 } } finally { writer.close() } } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/tools/HtmlReporterSpec.scala
/* * 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.tools import org.scalatest._ import SharedHelpers._ import org.scalatest.events._ class HtmlReporterSpec extends Spec { object `HtmlReporter ` { def `should throw IllegalStateException when SuiteCompleted is received without any suite events` { val tempDir = createTempDirectory() val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, None, None) val suiteCompleted = SuiteCompleted(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite")) val e = intercept[IllegalStateException] { htmlRep(suiteCompleted) } assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteCompleted + " in the head of suite events, but we got no suite event at all") } def `should throw IllegalStateException when SuiteCompleted is received without a SuiteStarting` { val tempDir = createTempDirectory() val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, None, None) val testStarting = TestStarting(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite"), "A Test", "A Test") htmlRep(testStarting) val suiteCompleted = SuiteCompleted(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite")) val e = intercept[IllegalStateException] { htmlRep(suiteCompleted) } assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteCompleted + " in the head of suite events, but we got: " + testStarting) } def `should throw IllegalStateException when SuiteAborted is received without any suite events` { val tempDir = createTempDirectory() val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, None, None) val suiteAborted = SuiteAborted(new Ordinal(99), "Error", "TestSuite", "TestSuite", Some("TestSuite")) val e = intercept[IllegalStateException] { htmlRep(suiteAborted) } assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteAborted + " in the head of suite events, but we got no suite event at all") } def `should throw IllegalStateException when SuiteAborted is received without a SuiteStarting` { val tempDir = createTempDirectory() val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, None, None) val testStarting = TestStarting(new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite"), "A Test", "A Test") htmlRep(testStarting) val suiteAborted = SuiteAborted(new Ordinal(99), "Error", "TestSuite", "TestSuite", Some("TestSuite")) val e = intercept[IllegalStateException] { htmlRep(suiteAborted) } assert(e.getMessage === "Expected SuiteStarting for completion event: " + suiteAborted + " in the head of suite events, but we got: " + testStarting) } def `should take MarkupProvided with '&' in it without problem` { val tempDir = createTempDirectory() val htmlRep = new HtmlReporter(tempDir.getAbsolutePath, false, None, None) val suiteStarting = SuiteStarting( new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite") ) val markupProvided = MarkupProvided( new Ordinal(99), "<a href=\"http://XXX.xxx.com/stc?registerRandom=true&add_random_sku_to_wait_list_sku_available=true\">a link</a>", Some( NameInfo("TestSuite", "TestSuite", Some("TestSuite"), Some("test 1")) ) ) val suiteCompleted = SuiteCompleted( new Ordinal(99), "TestSuite", "TestSuite", Some("TestSuite") ) htmlRep(suiteStarting) htmlRep(markupProvided) htmlRep(suiteCompleted) htmlRep.dispose() } } object `HtmlReporter's convertSingleParaToDefinition method` { def `should leave strings that contain no <p> alone` { assert(HtmlReporter.convertSingleParaToDefinition("") === "") assert(HtmlReporter.convertSingleParaToDefinition("hello") === "hello") assert(HtmlReporter.convertSingleParaToDefinition(" hello") === " hello") } def `should transform something that is a single HTML paragraph to a definition` { val actual = HtmlReporter.convertSingleParaToDefinition("<p>This test finished with a <strong>bold</strong> statement!</p>") val expected = "<dl>\n<dt>This test finished with a <strong>bold</strong> statement!</dt>\n</dl>" assert(actual === expected) val actual2 = HtmlReporter.convertSingleParaToDefinition("<p>Whereas this test finished with an <em>emphatic</em> statement!</p>") val expected2 = "<dl>\n<dt>Whereas this test finished with an <em>emphatic</em> statement!</dt>\n</dl>" assert(actual2 === expected2) } def `should return unchanged strings with more than one <p>` { val original = "<p>This test finished with a <strong>bold</strong> statement!</p><p>second</p>" val actual = HtmlReporter.convertSingleParaToDefinition(original) assert(actual === original) } def `should return unchanged strings that have just one <p>, but which is not first` { val original = "other stuff<p>This test finished with a <strong>bold</strong> statement!</p>" val actual = HtmlReporter.convertSingleParaToDefinition(original) assert(actual === original) } def `should return unchanged strings that start with <p>, but don't end with </p>` { val original = "<p>This test finished with a <strong>bold</strong> statement!</p>extra" val actual = HtmlReporter.convertSingleParaToDefinition(original) assert(actual === original) } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/RandomTestOrder.scala
/* * 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 import scala.util.Random import java.util.concurrent.LinkedBlockingQueue import collection.JavaConverters._ import org.scalatest.events.Event import org.scalatest.time.Span import org.scalatest.tools.{TestSortingReporter, Runner} /** * Trait that causes tests to be run in pseudo-random order. * * <p> * Although the tests are run in pseudo-random order, events will be fired in the &ldquo;normal&rdquo; order for the <code>Suite</code> * that mixes in this trait, as determined by <code>runTests</code>. * </p> * * <p> * The purpose of this trait is to reduce the likelihood of unintentional order dependencies between tests * in the same test class. * </p> * * @author <NAME> */ trait RandomTestOrder extends OneInstancePerTest { this: Suite => private[scalatest] case class DeferredSuiteRun(suite: Suite with RandomTestOrder, testName: String, status: ScalaTestStatefulStatus) private val suiteRunQueue = new LinkedBlockingQueue[DeferredSuiteRun] /** * Modifies the behavior of <code>super.runTest</code> to facilitate pseudo-random order test execution. * * <p> * If <code>runTestInNewInstance</code> is <code>false</code>, this is the test-specific (distributed) * instance, so this trait's implementation of this method simply invokes <code>super.runTest</code>, * passing along the same <code>testName</code> and <code>args</code> object, delegating responsibility * for actually running the test to the super implementation. After <code>super.runTest</code> returns * (or completes abruptly by throwing an exception), it notifies <code>args.distributedTestSorter</code> * that it has completed running the test by invoking <code>completedTest</code> on it, * passing in the <code>testName</code>. * </p> * * <p> * If <code>runTestInNewInstance</code> is <code>true</code>, it notifies <code>args.distributedTestSorter</code> * that it is distributing the test by invoking <code>distributingTest</code> on it, * passing in the <code>testName</code>. The test execution will be deferred to be run in pseudo-random order later. * </p> * * <p> * Note: this trait's implementation of this method is <code>final</code> to ensure that * any other desired <code>runTest</code> behavior is executed by the same thread that executes * the test. For example, if you were to mix in <code>BeforeAndAfter</code> after * <code>RandomTestOrder</code>, the <code>before</code> and <code>after</code> code would * be executed by the general instance on the main test thread, rather than by the test-specific * instance on the distributed thread. Marking this method <code>final</code> ensures that * traits like <code>BeforeAndAfter</code> can only be &lquot;super&rquot; to <code>RandomTestOrder</code> * and, therefore, that its <code>before</code> and <code>after</code> code will be run * by the same distributed thread that runs the test itself. * </p> * * @param testName the name of one test to execute. * @param args the <code>Args</code> for this run * @return a <code>Status</code> object that indicates when the test started by this method has completed, and whether or not it failed . */ final protected abstract override def runTest(testName: String, args: Args): Status = { if (args.runTestInNewInstance) { // Tell the TSR that the test is being distributed for (sorter <- args.distributedTestSorter) sorter.distributingTest(testName) // defer the suite execution val status = new ScalaTestStatefulStatus suiteRunQueue.put(DeferredSuiteRun(newInstance, testName, status)) status } else { // In test-specific (distributed) instance, so just run the test. (RTINI was // removed by OIPT's implementation of runTests.) try { super.runTest(testName, args) } finally { // Tell the TSR that the distributed test has completed for (sorter <- args.distributedTestSorter) sorter.completedTest(testName) } } } /** * Construct a new instance of this <code>Suite</code>. * * <p> * This trait's implementation of <code>runTests</code> invokes this method to create * a new instance of this <code>Suite</code> for each test. This trait's implementation * of this method uses reflection to call <code>this.getClass.newInstance</code>. This * approach will succeed only if this <code>Suite</code>'s class has a public, no-arg * constructor. In most cases this is likely to be true, because to be instantiated * by ScalaTest's <code>Runner</code> a <code>Suite</code> needs a public, no-arg * constructor. However, this will not be true of any <code>Suite</code> defined as * an inner class of another class or trait, because every constructor of an inner * class type takes a reference to the enclosing instance. In such cases, and in * cases where a <code>Suite</code> class is explicitly defined without a public, * no-arg constructor, you will need to override this method to construct a new * instance of the <code>Suite</code> in some other way. * </p> * * <p> * Here's an example of how you could override <code>newInstance</code> to construct * a new instance of an inner class: * </p> * * <pre class="stHighlight"> * import org.scalatest._ * * class Outer { * class InnerSuite extends Suite with RandomTestOrder { * def testOne() {} * def testTwo() {} * override def newInstance = new InnerSuite * } * } * </pre> */ override def newInstance: Suite with RandomTestOrder = this.getClass.newInstance.asInstanceOf[Suite with RandomTestOrder] /** * A maximum amount of time to wait for out-of-order events generated by running the tests * of this <code>Suite</code> in parallel while sorting the events back into a more * user-friendly, sequential order. * * <p> * The default implementation of this method returns the value specified via <code>-T</code> to * <a href="tools/Runner$.html"></code>Runner</code></a>, or 2 seconds, if no <code>-T</code> was supplied. * </p> * * @return a maximum amount of time to wait for events while resorting them into sequential order */ protected def sortingTimeout: Span = Suite.testSortingReporterTimeout /** * Modifies the behavior of <code>super.run</code> to facilitate pseudo-random order test execution. * * <p> * If both <code>testName</code> and <code>args.distributedTestSorter</code> are defined, * this trait's implementation of this method will create a "test-specific reporter" whose <code>apply</code> * method will invoke the <code>apply</code> method of the <code>DistributedTestSorter</code>, which takes * a test name as well as the event. It will then invoke <code>super.run</code> passing along * the same <code>testName</code> and an <code>Args</code> object that is the same except with the * original reporter replaced by the test-specific reporter. * </p> * * <p> * If either <code>testName</code> or <code>args.distributedTestSorter</code> is empty, it will create <code>TestSortingReporter</code> * and override <code>args</code>'s <code>reporter</code> and <code>distributedTestSorter</code> with it. It then call <code>super.run</code> * to delegate the run to super's implementation, and to collect all children suites in <code>suiteRunQueue</code>. After <code>super.run</code> * completed, it then shuffle the order of the suites collected in <code>suiteRunQueue</code> and run them. * </p> * * @param testName an optional name of one test to execute. If <code>None</code>, all relevant tests should be executed. * I.e., <code>None</code> acts like a wildcard that means execute all relevant tests in this <code>Suite</code>. * @param args the <code>Args</code> for this run * @return a <code>Status</code> object that indicates when all tests and nested suites started by this method have completed, and whether or not a failure occurred. */ abstract override def run(testName: Option[String], args: Args): Status = { (testName, args.distributedTestSorter) match { case (Some(name), Some(sorter)) => super.run(testName, args.copy(reporter = createTestSpecificReporter(sorter, name))) case _ => val testSortingReporter = new TestSortingReporter(suiteId, args.reporter, sortingTimeout, testNames.size, args.distributedSuiteSorter, System.err) val newArgs = args.copy(reporter = testSortingReporter, distributedTestSorter = Some(testSortingReporter)) val status = super.run(testName, newArgs) // Random shuffle the deferred suite list, before executing them. Random.shuffle(suiteRunQueue.asScala.toList).map { case DeferredSuiteRun(suite, testName, statefulStatus) => val status = suite.run(Some(testName), newArgs.copy(runTestInNewInstance = true)) status.whenCompleted { result => if (!result) statefulStatus.setFailed() statefulStatus.setCompleted() } } status } } private[scalatest] def createTestSpecificReporter(testSorter: DistributedTestSorter, testName: String): Reporter = { class TestSpecificReporter(testSorter: DistributedTestSorter, testName: String) extends Reporter { def apply(event: Event) { testSorter.apply(testName, event) } } new TestSpecificReporter(testSorter, testName) } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/prop/Configuration.scala
/* * 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.prop import org.scalacheck.Test.Parameters import org.scalacheck.Test.TestCallback import org.scalacheck.Gen import org.scalactic.anyvals.{PosZInt, PosZDouble, PosInt} /** * Trait providing methods and classes used to configure property checks provided by the * the <code>forAll</code> methods of trait <code>GeneratorDrivenPropertyChecks</code> (for ScalaTest-style * property checks) and the <code>check</code> methods of trait <code>Checkers</code> (for ScalaCheck-style property checks). * * @author <NAME> */ trait Configuration { /** * Configuration object for property checks. * * <p> * The default values for the parameters are: * </p> * * <table style="border-collapse: collapse; border: 1px solid black"> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * minSuccessful * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * 100 * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * maxDiscarded * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * 500 * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * minSize * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * 0 * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * maxSize * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * 100 * </td> * </tr> * <tr> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * workers * </td> * <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"> * 1 * </td> * </tr> * </table> * * @param minSuccessful the minimum number of successful property evaluations required for the property to pass. * @param maxDiscarded the maximum number of discarded property evaluations allowed during a property check * @param minSize the minimum size parameter to provide to ScalaCheck, which it will use when generating objects for which size matters (such as strings or lists). * @param maxSize the maximum size parameter to provide to ScalaCheck, which it will use when generating objects for which size matters (such as strings or lists). * @param workers specifies the number of worker threads to use during property evaluation * @throws IllegalArgumentException if the specified <code>minSuccessful</code> value is less than or equal to zero, * the specified <code>maxDiscarded</code> value is less than zero, * the specified <code>minSize</code> value is less than zero, * the specified <code>maxSize</code> value is less than zero, * the specified <code>minSize</code> is greater than the specified or default value of <code>maxSize</code>, or * the specified <code>workers</code> value is less than or equal to zero. * * @author <NAME> */ @deprecated("Use PropertyCheckConfiguration instead") case class PropertyCheckConfig( minSuccessful: Int = 100, maxDiscarded: Int = 500, minSize: Int = 0, maxSize: Int = 100, workers: Int = 1 ) extends PropertyCheckConfigurable { require(minSuccessful > 0, "minSuccessful had value " + minSuccessful + ", but must be greater than zero") require(maxDiscarded >= 0, "maxDiscarded had value " + maxDiscarded + ", but must be greater than or equal to zero") require(minSize >= 0, "minSize had value " + minSize + ", but must be greater than or equal to zero") require(maxSize >= 0, "maxSize had value " + maxSize + ", but must be greater than or equal to zero") require(minSize <= maxSize, "minSize had value " + minSize + ", which must be less than or equal to maxSize, which had value " + maxSize) require(workers > 0, "workers had value " + workers + ", but must be greater than zero") private [prop] def asPropertyCheckConfiguration = this } import scala.language.implicitConversions /** * Implicitly converts <code>PropertyCheckConfig</code>s to <code>PropertyCheckConfiguration</code>, * which enables a smoother upgrade path. */ implicit def PropertyCheckConfig2PropertyCheckConfiguration(p: PropertyCheckConfig): PropertyCheckConfiguration = { val maxDiscardedFactor = PropertyCheckConfiguration.calculateMaxDiscardedFactor(p.minSuccessful, p.maxDiscarded) new PropertyCheckConfiguration( minSuccessful = PosInt.from(p.minSuccessful).get, maxDiscardedFactor = PosZDouble.from(maxDiscardedFactor).get, minSize = PosZInt.from(p.minSize).get, sizeRange = PosZInt.from(p.maxSize - p.minSize).get, workers = PosInt.from(p.workers).get) { override private [scalatest] val legacyMaxDiscarded = Some(p.maxDiscarded) override private [scalatest] val legacyMaxSize = Some(p.maxSize) } } case class PropertyCheckConfiguration(minSuccessful: PosInt = PosInt(100), maxDiscardedFactor: PosZDouble = PosZDouble(5.0), minSize: PosZInt = PosZInt(0), sizeRange: PosZInt = PosZInt(100), workers: PosInt = PosInt(1)) extends PropertyCheckConfigurable { @deprecated("Transitional value to ensure upgrade compatibility when mixing PropertyCheckConfig and minSuccessful parameters. Remove with PropertyCheckConfig class") private [scalatest] val legacyMaxDiscarded: Option[Int] = None @deprecated("Transitional value to ensure upgrade compatibility when mixing PropertyCheckConfig and minSize parameters. Remove with PropertyCheckConfig class") private [scalatest] val legacyMaxSize: Option[Int] = None private [prop] def asPropertyCheckConfiguration = this } /** * Internal transitional trait for upgrade compatibility when mixing * <code>PropertyCheckConfig</code> and <code>PropertyCheckConfiguration</code> implicit variables. * * When <code>PropertyCheckConfig</code> is removed, this trait will be removed as well. * * For example, see ConfigImplicitOverrideInClassTest. */ @deprecated("Use PropertyCheckConfiguration directly instead.") trait PropertyCheckConfigurable { private [prop] def asPropertyCheckConfiguration: PropertyCheckConfiguration } object PropertyCheckConfiguration { private[scalatest] def calculateMaxDiscardedFactor(minSuccessful: Int, maxDiscarded: Int): Double = ((maxDiscarded + 1): Double) / (minSuccessful: Double) } /** * Abstract class defining a family of configuration parameters for property checks. * * <p> * The subclasses of this abstract class are used to pass configuration information to * the <code>forAll</code> methods of traits <code>PropertyChecks</code> (for ScalaTest-style * property checks) and <code>Checkers</code>(for ScalaCheck-style property checks). * </p> * * @author <NAME> */ sealed abstract class PropertyCheckConfigParam /** * A <code>PropertyCheckConfigParam</code> that specifies the minimum number of successful * property evaluations required for the property to pass. * * @author <NAME> */ case class MinSuccessful(value: PosInt) extends PropertyCheckConfigParam /** * A <code>PropertyCheckConfigParam</code> that specifies the maximum number of discarded * property evaluations allowed during property evaluation. * * <p> * In <code>GeneratorDrivenPropertyChecks</code>, a property evaluation is discarded if it throws * <code>DiscardedEvaluationException</code>, which is produce by <code>whenever</code> clause that * evaluates to false. For example, consider this ScalaTest property check: * </p> * * <pre class="stHighlight"> * // forAll defined in <code>GeneratorDrivenPropertyChecks</code> * forAll { (n: Int) => * whenever (n > 0) { * doubleIt(n) should equal (n * 2) * } * } * * </pre> * * <p> * In the above code, whenever a non-positive <code>n</code> is passed, the property function will complete abruptly * with <code>DiscardedEvaluationException</code>. * </p> * * <p> * Similarly, in <code>Checkers</code>, a property evaluation is discarded if the expression to the left * of ScalaCheck's <code>==></code> operator is false. Here's an example: * </p> * * <pre class="stHighlight"> * // forAll defined in <code>Checkers</code> * forAll { (n: Int) => * (n > 0) ==> doubleIt(n) == (n * 2) * } * * </pre> * * <p> * For either kind of property check, <code>MaxDiscarded</code> indicates the maximum number of discarded * evaluations that will be allowed. As soon as one past this number of evaluations indicates it needs to be discarded, * the property check will fail. * </p> * * @throws IllegalArgumentException if specified <code>value</code> is less than zero. * * @author <NAME> */ @deprecated case class MaxDiscarded(value: Int) extends PropertyCheckConfigParam { require(value >= 0) } case class MaxDiscardedFactor(value: PosZDouble) extends PropertyCheckConfigParam /** * A <code>PropertyCheckConfigParam</code> that specifies the minimum size parameter to * provide to ScalaCheck, which it will use when generating objects for which size matters (such as * strings or lists). * * @author <NAME> */ case class MinSize(value: PosZInt) extends PropertyCheckConfigParam /** * A <code>PropertyCheckConfigParam</code> that specifies the maximum size parameter to * provide to ScalaCheck, which it will use when generating objects for which size matters (such as * strings or lists). * * <p> * Note that the maximum size should be greater than or equal to the minimum size. This requirement is * enforced by the <code>PropertyCheckConfig</code> constructor and the <code>forAll</code> methods of * traits <code>PropertyChecks</code> and <code>Checkers</code>. In other words, it is enforced at the point * both a maximum and minimum size are provided together. * </p> * * @throws IllegalArgumentException if specified <code>value</code> is less than zero. * * @author <NAME> */ @deprecated("use SizeRange instead") case class MaxSize(value: Int) extends PropertyCheckConfigParam { require(value >= 0) } /** * A <code>PropertyCheckConfigParam</code> that (with minSize) specifies the maximum size parameter to * provide to ScalaCheck, which it will use when generating objects for which size matters (such as * strings or lists). * * <p> * Note that the size range is added to minSize in order to calculate the maximum size passed to ScalaCheck. * Using a range allows compile-time checking of a non-negative number being specified. * </p> * * @author <NAME> */ case class SizeRange(value: PosZInt) extends PropertyCheckConfigParam /** * A <code>PropertyCheckConfigParam</code> that specifies the number of worker threads * to use when evaluating a property. * * @throws IllegalArgumentException if specified <code>value</code> is less than or equal to zero. * * @author <NAME> */ case class Workers(value: PosInt) extends PropertyCheckConfigParam /** * Returns a <code>MinSuccessful</code> property check configuration parameter containing the passed value, which specifies the minimum number of successful * property evaluations required for the property to pass. * * @throws IllegalArgumentException if specified <code>value</code> is less than or equal to zero. */ def minSuccessful(value: PosInt): MinSuccessful = new MinSuccessful(value) /** * Returns a <code>MaxDiscarded</code> property check configuration parameter containing the passed value, which specifies the maximum number of discarded * property evaluations allowed during property evaluation. * * @throws IllegalArgumentException if specified <code>value</code> is less than zero. */ @deprecated("use maxDiscardedFactor instead") def maxDiscarded(value: Int): MaxDiscarded = new MaxDiscarded(value) /** * Returns a <code>MaxDiscardedFactor</code> property check configuration parameter containing the passed value, which specifies the factor of discarded * property evaluations allowed during property evaluation. * */ def maxDiscardedFactor(value: PosZDouble): MaxDiscardedFactor = MaxDiscardedFactor(value) /** * Returns a <code>MinSize</code> property check configuration parameter containing the passed value, which specifies the minimum size parameter to * provide to ScalaCheck, which it will use when generating objects for which size matters (such as * strings or lists). * * @throws IllegalArgumentException if specified <code>value</code> is less than zero. */ def minSize(value: PosZInt): MinSize = new MinSize(value) /** * Returns a <code>MaxSize</code> property check configuration parameter containing the passed value, which specifies the maximum size parameter to * provide to ScalaCheck, which it will use when generating objects for which size matters (such as * strings or lists). * * <p> * Note that the maximum size should be greater than or equal to the minimum size. This requirement is * enforced by the <code>PropertyCheckConfig</code> constructor and the <code>forAll</code> methods of * traits <code>PropertyChecks</code> and <code>Checkers</code>. In other words, it is enforced at the point * both a maximum and minimum size are provided together. * </p> * * @throws IllegalArgumentException if specified <code>value</code> is less than zero. */ @deprecated("use SizeRange instead") def maxSize(value: Int): MaxSize = new MaxSize(value) /** * Returns a <code>SizeRange</code> property check configuration parameter containing the passed value, that (with minSize) specifies the maximum size parameter to * provide to ScalaCheck, which it will use when generating objects for which size matters (such as * strings or lists). * * <p> * Note that the size range is added to minSize in order to calculate the maximum size passed to ScalaCheck. * Using a range allows compile-time checking of a non-negative number being specified. * </p> * * @author <NAME> */ def sizeRange(value: PosZInt): SizeRange = SizeRange(value) /** * Returns a <code>Workers</code> property check configuration parameter containing the passed value, which specifies the number of worker threads * to use when evaluating a property. * * @throws IllegalArgumentException if specified <code>value</code> is less than or equal to zero. */ def workers(value: PosInt): Workers = new Workers(value) private[prop] def getParams( configParams: Seq[PropertyCheckConfigParam], c: PropertyCheckConfigurable ): Parameters = { val config: PropertyCheckConfiguration = c.asPropertyCheckConfiguration var minSuccessful: Option[Int] = None var maxDiscarded: Option[Int] = None var maxDiscardedFactor: Option[Double] = None var pminSize: Option[Int] = None var psizeRange: Option[Int] = None var pmaxSize: Option[Int] = None var pworkers: Option[Int] = None var minSuccessfulTotalFound = 0 var maxDiscardedTotalFound = 0 var maxDiscardedFactorTotalFound = 0 var minSizeTotalFound = 0 var sizeRangeTotalFound = 0 var maxSizeTotalFound = 0 var workersTotalFound = 0 for (configParam <- configParams) { configParam match { case param: MinSuccessful => minSuccessful = Some(param.value) minSuccessfulTotalFound += 1 case param: MaxDiscarded => maxDiscarded = Some(param.value) maxDiscardedTotalFound += 1 case param: MaxDiscardedFactor => maxDiscardedFactor = Some(param.value) maxDiscardedFactorTotalFound += 1 case param: MinSize => pminSize = Some(param.value) minSizeTotalFound += 1 case param: SizeRange => psizeRange = Some(param.value) sizeRangeTotalFound += 1 case param: MaxSize => pmaxSize = Some(param.value) maxSizeTotalFound += 1 case param: Workers => pworkers = Some(param.value) workersTotalFound += 1 } } if (minSuccessfulTotalFound > 1) throw new IllegalArgumentException("can pass at most one MinSuccessful config parameters, but " + minSuccessfulTotalFound + " were passed") val maxDiscardedAndFactorTotalFound = maxDiscardedTotalFound + maxDiscardedFactorTotalFound if (maxDiscardedAndFactorTotalFound > 1) throw new IllegalArgumentException("can pass at most one MaxDiscarded or MaxDiscardedFactor config parameters, but " + maxDiscardedAndFactorTotalFound + " were passed") if (minSizeTotalFound > 1) throw new IllegalArgumentException("can pass at most one MinSize config parameters, but " + minSizeTotalFound + " were passed") val maxSizeAndSizeRangeTotalFound = maxSizeTotalFound + sizeRangeTotalFound if (maxSizeAndSizeRangeTotalFound > 1) throw new IllegalArgumentException("can pass at most one SizeRange or MaxSize config parameters, but " + maxSizeAndSizeRangeTotalFound + " were passed") if (workersTotalFound > 1) throw new IllegalArgumentException("can pass at most one Workers config parameters, but " + workersTotalFound + " were passed") new Parameters { val minSuccessfulTests: Int = minSuccessful.getOrElse(config.minSuccessful) val minSize: Int = pminSize.getOrElse(config.minSize) val maxSize: Int = { (psizeRange, pmaxSize, config.legacyMaxSize) match { case (None, None, Some(legacyMaxSize)) => legacyMaxSize case (None, Some(maxSize), _) => maxSize case _ => psizeRange.getOrElse(config.sizeRange.value) + minSize } } val rng: scala.util.Random = Gen.Parameters.default.rng val workers: Int = pworkers.getOrElse(config.workers) val testCallback: TestCallback = new TestCallback {} val maxDiscardRatio: Float = { (maxDiscardedFactor, maxDiscarded, config.legacyMaxDiscarded, minSuccessful) match { case (None, None, Some(legacyMaxDiscarded), Some(specifiedMinSuccessful)) => PropertyCheckConfiguration.calculateMaxDiscardedFactor(specifiedMinSuccessful, legacyMaxDiscarded).toFloat case (None, Some(md), _, _) => if (md < 0) Parameters.default.maxDiscardRatio else PropertyCheckConfiguration.calculateMaxDiscardedFactor(minSuccessfulTests, md).toFloat case _ => maxDiscardedFactor.getOrElse(config.maxDiscardedFactor.value).toFloat } } val customClassLoader: Option[ClassLoader] = None } } /** * Implicit <code>PropertyCheckConfiguration</code> value providing default configuration values. */ implicit val generatorDrivenConfig = PropertyCheckConfiguration() } /** * Companion object that facilitates the importing of <code>Configuration</code> members as * an alternative to mixing it in. One use case is to import <code>Configuration</code> members so you can use * them in the Scala interpreter. */ object Configuration extends Configuration
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/TaggingScopesSpec.scala
<filename>scalatest-test/src/test/scala/org/scalatest/TaggingScopesSpec.scala<gh_stars>1-10 /* * 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 import tagobjects._ import SharedHelpers._ import Matchers._ /* This just tests a trait, TagGroups, that I created to answer a user query about tagging scopes. I probably won't put this into ScalaTest proper to keep tagging simple, but I'll leave this in the repo as an example for folks who want to do something like this. - bv */ class TaggingScopesSpec extends Spec { class ExampleSpec extends FreeSpec { override lazy val tags: Map[String, Set[String]] = super.tags.transform { case (testName, tagsSet) if testName startsWith "scope1" => tagsSet + "Scope1" case (testName, tagsSet) if testName startsWith "scope2" => tagsSet + "Scope2" case (_, existingSet) => existingSet } "scope1" - { "slow" taggedAs Slow in { 1 + 1 shouldEqual 2 } "disk" taggedAs Disk in { 1 + 1 shouldEqual 2 } } "scope2" - { "network" taggedAs Network in { 1 + 1 shouldEqual 2 } "cpu" taggedAs CPU in { 1 + 1 shouldEqual 2 } } } object `A Suite with TagGroups` { def `should run all tests if default Filter is used` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep)) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope1 slow", "scope1 disk", "scope2 network", "scope2 cpu") } def `should run non-excluded tests if Filter containing tags-to-exclude is passed in` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep, filter = Filter(tagsToExclude = Set("org.scalatest.tags.Disk")))) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope1 slow", "scope2 network", "scope2 cpu") } def `should run included tests if Filter containing tags-to-include is passed in` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep, filter = Filter(tagsToInclude = Some(Set("org.scalatest.tags.Disk"))))) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope1 disk") } def `should run non-excluded tests if Filter containing Scope1 tags-to-exclude is passed in` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep, filter = Filter(tagsToExclude = Set("Scope1")))) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope2 network", "scope2 cpu") } def `should run included tests if Filter containing Scope1 tags-to-include is passed in` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep, filter = Filter(tagsToInclude = Some(Set("Scope1"))))) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope1 slow", "scope1 disk") } def `should run non-excluded tests if Filter containing Scope2 tags-to-exclude is passed in` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep, filter = Filter(tagsToExclude = Set("Scope2")))) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope1 slow", "scope1 disk") } def `should run included tests if Filter containing Scope2 tags-to-include is passed in` { val es = new ExampleSpec val rep = new EventRecordingReporter es.run(None, Args(rep, filter = Filter(tagsToInclude = Some(Set("Scope2"))))) rep.testSucceededEventsReceived.map(_.testName) shouldEqual Vector("scope2 network", "scope2 cpu") } } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/algebra/Commutative.scala
<reponame>cquiroz/scalatest /* * Copyright 2001-2015 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.scalactic.algebra import scala.language.higherKinds import scala.language.implicitConversions /** * Typeclass trait representing a binary operation that obeys the commutative law. * * <p> * The commutative law states that changing the order of the operands to a binary operation * does not change the result, i.e. given values <code>a</code>, <code>b</code> * </p> * * <pre> * (a op b) === (b op a) * </pre> * */ trait Commutative[A] { /** * A binary operation that obeys the commutative law. * * See the main documentation for this trait for more detail. */ def op(a1: A, a2: A): A } /** * Companion object for <code>Commutative</code>. * an implicit conversion method from <code>A</code> to <code>Commutative.Adapter[A]</code> */ object Commutative { /** * Adapter class for <a href="Commutative.html"><code>Commutative</code></a> * that wraps a value of type <code>A</code> given an * implicit <code>Commutative[A]</code>. * * @param underlying The value of type <code>A</code> to wrap. * @param commutative The captured <code>Commutative[A]</code> whose behavior * is used to implement this class's methods. */ class Adapter[A](val underlying: A)(implicit val commutative: Commutative[A]) { /** * A binary operation that obeys the commutative law. * * See the main documentation for trait <a href="Commutative.html"><code>Commutative</code></a> for more detail. */ def op(a2: A): A = commutative.op(underlying, a2) } /** * Implicitly wraps an object in an <code>Commutative.Adapter[A]</code> * so long as an implicit <code>Commutative[A]</code> is available. */ implicit def adapters[A](a: A)(implicit ev: Commutative[A]): Commutative.Adapter[A] = new Adapter(a)(ev) /** * Summons an implicitly available <code>Commutative[A]</code>. * * <p> * This method allows you to write expressions like <code>Commutative[String]</code> instead of * <code>implicitly[Commutative[String]]</code>. * </p> */ def apply[A](implicit ev: Commutative[A]): Commutative[A] = ev }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/words/MatcherWordsSpec.scala
/* * 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.words import org.scalatest._ import Matchers._ class MatcherWordsSpec extends Spec with MatcherWords { object `MatcherWords ` { object `equal(Any) method returns MatcherFactory1` { val mtf: matchers.MatcherFactory1[Any, enablers.EvidenceThat[String]#CanEqual] = equal ("tommy") val mt = mtf.matcher[String] def `should have pretty toString` { mtf.toString should be ("equal (\"tommy\")") mt.toString should be ("equal (\"tommy\")") } val mr = mt("tomy") def `should have correct MatcherResult` { mr should have ( 'matches (false), 'failureMessage ("\"tom[]y\" did not equal \"tom[m]y\""), 'negatedFailureMessage ("\"tomy\" equaled \"tommy\""), 'midSentenceFailureMessage ("\"tom[]y\" did not equal \"tom[m]y\""), 'midSentenceNegatedFailureMessage ("\"tomy\" equaled \"tommy\""), 'rawFailureMessage ("{0} did not equal {1}"), 'rawNegatedFailureMessage ("{0} equaled {1}"), 'rawMidSentenceFailureMessage ("{0} did not equal {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} equaled {1}"), 'failureMessageArgs(Vector("tom[]y", "tom[m]y")), 'negatedFailureMessageArgs(Vector("tomy", "tommy")), 'midSentenceFailureMessageArgs(Vector("tom[]y", "tom[m]y")), 'midSentenceNegatedFailureMessageArgs(Vector("tomy", "tommy")) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (true), 'failureMessage ("\"tomy\" equaled \"tommy\""), 'negatedFailureMessage ("\"tom[]y\" did not equal \"tom[m]y\""), 'midSentenceFailureMessage ("\"tomy\" equaled \"tommy\""), 'midSentenceNegatedFailureMessage ("\"tom[]y\" did not equal \"tom[m]y\""), 'rawFailureMessage ("{0} equaled {1}"), 'rawNegatedFailureMessage ("{0} did not equal {1}"), 'rawMidSentenceFailureMessage ("{0} equaled {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} did not equal {1}"), 'failureMessageArgs(Vector("tomy", "tommy")), 'negatedFailureMessageArgs(Vector("tom[]y", "tom[m]y")), 'midSentenceFailureMessageArgs(Vector("tomy", "tommy")), 'midSentenceNegatedFailureMessageArgs(Vector("tom[]y", "tom[m]y")) ) } } } }
cquiroz/scalatest
examples/src/main/scala/org/scalatest/examples/propspec/SetSpec.scala
/* * 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.examples.propspec import org.scalatest._ import prop._ import scala.collection.immutable._ import java.util.NoSuchElementException class SetSpec extends PropSpec with TableDrivenPropertyChecks with ShouldMatchers { val examples = Table( "set", BitSet.empty, HashSet.empty[Int], TreeSet.empty[Int] ) property("an empty Set should have size 0") { forAll(examples) { set => set.size should be (0) } } property("invoking head on an empty set should produce NoSuchElementException") { forAll(examples) { set => evaluating { set.head } should produce [NoSuchElementException] } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/testng/TestNGWrapperSuite.scala
<reponame>cquiroz/scalatest /* * 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.testng import org.scalatest._ import org.testng.TestNG import org.testng.TestListenerAdapter /** * <p> * Suite that wraps existing TestNG test suites, described by TestNG XML config files. This class allows * existing TestNG tests written in Java to be run by ScalaTest. * </p> * * <p> * One way to use this class is to extend it and provide a list of one or more * names of TestNG XML config file names to run. Here's an example: * </p> * * <pre class="stHighlight"> * class MyWrapperSuite extends TestNGWrapperSuite( * List("oneTest.xml", "twoTest.xml", "redTest.xml", "blueTest.xml") * ) * </pre> * * <p> * You can also specify TestNG XML config files on <code>Runner</code>'s command line with <code>-t</code> parameters. See * the documentation for <code>Runner</code> for more information. * </p> * * <p> * To execute <code>TestNGWrapperSuite</code>s with ScalaTest's <code>Runner</code>, you must include TestNG's jar file on the class path or runpath. * This version of <code>TestNGSuite</code> was tested with TestNG version 6.3.1. * </p> * * @author <NAME> */ class TestNGWrapperSuite(xmlSuiteFilenames: List[String]) extends TestNGSuite { // Probably mention FileNotFoundException here // If any files contained in the property cannot be found, a FileNotFoundException will be thrown. /** * Runs TestNG with the XML config file or files provided to the primary constructor, passing reports to the specified <code>Reporter</code>. * * @param testName If present (Some), then only the method with the supplied name is executed and groups will be ignored. * @param args the <code>Args</code> for this run */ override def run(testName: Option[String], args: Args): Status = { import args._ val tagsToInclude = filter.tagsToInclude match { case None => Set[String]() case Some(tti) => tti } val tagsToExclude = filter.tagsToExclude val status = new ScalaTestStatefulStatus runTestNG(reporter, tagsToInclude, tagsToExclude, tracker, status) status.setCompleted() status } /** * Runs all tests in the xml suites. * @param reporter the reporter to be notified of test events (success, failure, etc) */ override private[testng] def runTestNG(reporter: Reporter, tracker: Tracker, status: ScalaTestStatefulStatus) { runTestNG(reporter, Set[String](), Set[String](), tracker, status) } /** * Executes the following: * * 1) Calls the super class to set up groups with the given groups Sets. * 2) Adds the xml suites to TestNG * 3) Runs TestNG * * @param reporter the reporter to be notified of test events (success, failure, etc) * @param groupsToInclude contains the names of groups to run. only tests in these groups will be executed * @param groupsToExclude tests in groups in this Set will not be executed * @param status Run status. */ private[testng] def runTestNG(reporter: Reporter, groupsToInclude: Set[String], groupsToExclude: Set[String], tracker: Tracker, status: ScalaTestStatefulStatus) { val testng = new TestNG handleGroups(groupsToInclude, groupsToExclude, testng) addXmlSuitesToTestNG(testng) run(testng, reporter, tracker, status) } // TODO: We should probably do this checking in the constructor. /** * TestNG allows users to programmatically tell it which xml suites to run via the setTestSuites method. * This method takes a java.util.List containing java.io.File objects, where each file is a TestNG xml suite. * TestNGWrapperSuite takes xmlSuitesPropertyName in its constructor. This property should contain * the full paths of one or more xml suites, comma seperated. This method simply creates a java.util.List * containing each xml suite contained in xmlSuitesPropertyName and calls the setTestSuites method on the * given TestNG object. * * @param testng the TestNG object to set the suites on * * @throws FileNotFoundException if a file in xmlSuitesPropertyName does not exist. * */ private def addXmlSuitesToTestNG(testng: TestNG) { import java.io.File import java.io.FileNotFoundException val files = new java.util.ArrayList[String] xmlSuiteFilenames.foreach( { name => val f = new File( name ) if( ! f.exists ) throw new FileNotFoundException( f.getAbsolutePath ) files add name } ) testng.setTestSuites(files) } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/laws/FunctorLaws.scala
/* * Copyright 2001-2014 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.laws import org.scalacheck._ import org.scalactic._ import org.scalactic.algebra._ import org.scalatest._ import org.scalatest.prop.GeneratorDrivenPropertyChecks._ import Matchers._ import Functor.adapters import scala.language.higherKinds class FunctorLaws[Context[_]](implicit functor: Functor[Context], val arbCa: Arbitrary[Context[Int]], val shrCa: Shrink[Context[Int]]) extends Laws("functor") { override val laws = Every( law("identity") { () => forAll { (ca: Context[Int]) => (ca map identity[Int]) shouldEqual ca } }, law("composition") { () => forAll { (ca: Context[Int], f: Int => Int, g: Int => Int) => ((ca map f) map g) shouldEqual (ca map (g compose f)) } } ) }
cquiroz/scalatest
scalatest-test.js/src/test/scala/test/fixture/ExampleFunSuite.scala
package test.fixture import org.scalatest._ class ExampleFunSuite extends fixture.FunSuite { type FixtureParam = String def withFixture(test: OneArgTest): Outcome = { test("hi") } test("An empty Set should have size 0") { f => assert(Set.empty.size == 0) } test("Invoking head on an empty Set should produce NoSuchElementException") { f => intercept[NoSuchElementException] { Set.empty.head } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldIncludeRegexSpec.scala
<reponame>cquiroz/scalatest<filename>scalatest-test/src/test/scala/org/scalatest/ShouldIncludeRegexSpec.scala /* * 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 import org.scalatest.prop.Checkers import org.scalacheck._ import Arbitrary._ import Prop._ import org.scalatest.exceptions.TestFailedException import SharedHelpers._ import Matchers._ class ShouldIncludeRegexSpec extends Spec with Checkers with ReturnsNormallyThrowsAssertion { /* s should include substring t s should include regex t s should startWith substring t s should startWith regex t s should endWith substring t s should endWith regex t s should fullyMatch regex t */ object `The include regex syntax` { val decimal = """(-)?(\d+)(\.\d*)?""" val decimalRegex = """(-)?(\d+)(\.\d*)?""".r object `(when the regex is specified by a string)` { def `should do nothing if the string includes substring that matched regex specified as a string` { "1.78" should include regex ("1.7") "21.7" should include regex ("1.7") "21.78" should include regex ("1.7") "1.7" should include regex (decimal) "21.7" should include regex (decimal) "1.78" should include regex (decimal) "a -1.8 difference" should include regex (decimal) "b8" should include regex (decimal) "8x" should include regex (decimal) "1.x" should include regex (decimal) // The remaining are full matches, which should also work with "include" "1.7" should include regex ("1.7") "1.7" should include regex (decimal) "-1.8" should include regex (decimal) "8" should include regex (decimal) "1." should include regex (decimal) } def `should do nothing if the string includes substring that matched regex specified as a string and withGroup` { "abccde" should include regex("b(c*)d" withGroup "cc") "bccde" should include regex("b(c*)d" withGroup "cc") "abccd" should include regex("b(c*)d" withGroup "cc") // full matches, which should also work with "include" "bccd" should include regex("b(c*)d" withGroup "cc") } def `should do nothing if the string includes substring that matched regex specified as a string and withGroups` { "abccdde" should include regex("b(c*)(d*)" withGroups ("cc", "dd")) "bccdde" should include regex("b(c*)(d*)" withGroups ("cc", "dd")) "abccdd" should include regex("b(c*)(d*)" withGroups ("cc", "dd")) // full matches, which should also work with "include" "bccdd" should include regex("b(c*)(d*)" withGroups ("cc", "dd")) } def `should do nothing if the string does not include substring that matched regex specified as a string when used with not` { "eight" should not { include regex (decimal) } "one.eight" should not { include regex (decimal) } "eight" should not include regex (decimal) "one.eight" should not include regex (decimal) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used with not` { "bccde" should not { include regex ("b(c*)d" withGroup "c") } "abccde" should not { include regex ("b(c*)d" withGroup "c") } "bccde" should not include regex ("b(c*)d" withGroup "c") "abccde" should not include regex ("b(c*)d" withGroup "c") } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used with not` { "bccdde" should not { include regex ("b(c*)(d*)" withGroups ("cc", "d")) } "abccdde" should not { include regex ("b(c*)(d*)" withGroups ("cc", "d")) } "bccdde" should not include regex ("b(c*)(d*)" withGroups ("cc", "d")) "abccdde" should not include regex ("b(c*)(d*)" withGroups ("cc", "d")) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-and expression` { "a1.7" should (include regex (decimal) and (include regex (decimal))) "a1.7" should (include regex (decimal) and (include regex (decimal))) "a1.7" should (include regex (decimal) and (include regex (decimal))) "1.7b" should ((include regex (decimal)) and (include regex (decimal))) "1.7b" should ((include regex (decimal)) and (include regex (decimal))) "1.7b" should ((include regex (decimal)) and (include regex (decimal))) "a1.7b" should (include regex (decimal) and include regex (decimal)) "a1.7b" should (include regex (decimal) and include regex (decimal)) "a1.7b" should (include regex (decimal) and include regex (decimal)) "1.7" should (include regex (decimal) and (include regex (decimal))) "1.7" should ((include regex (decimal)) and (include regex (decimal))) "1.7" should (include regex (decimal) and include regex (decimal)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-and expression` { "abccd" should (include regex ("b(c*)d" withGroup "cc") and (include regex ("b(c*)d" withGroup "cc"))) "abccd" should (include regex ("b(c*)d" withGroup "cc") and (include regex ("b(c*)d" withGroup "cc"))) "abccd" should (include regex ("b(c*)d" withGroup "cc") and (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((include regex ("b(c*)d" withGroup "cc")) and (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((include regex ("b(c*)d" withGroup "cc")) and (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((include regex ("b(c*)d" withGroup "cc")) and (include regex ("b(c*)d" withGroup "cc"))) "abccde" should (include regex ("b(c*)d" withGroup "cc") and include regex ("b(c*)d" withGroup "cc")) "abccde" should (include regex ("b(c*)d" withGroup "cc") and include regex ("b(c*)d" withGroup "cc")) "abccde" should (include regex ("b(c*)d" withGroup "cc") and include regex ("b(c*)d" withGroup "cc")) "bccd" should (include regex ("b(c*)d" withGroup "cc") and (include regex ("b(c*)d" withGroup "cc"))) "bccd" should ((include regex ("b(c*)d" withGroup "cc")) and (include regex ("b(c*)d" withGroup "cc"))) "bccd" should (include regex ("b(c*)d" withGroup "cc") and include regex ("b(c*)d" withGroup "cc")) "abccd" should (equal ("abccd") and (include regex ("b(c*)d" withGroup "cc"))) "abccd" should (equal ("abccd") and (include regex ("b(c*)d" withGroup "cc"))) "abccd" should (equal ("abccd") and (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((equal ("bccde")) and (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((equal ("bccde")) and (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((equal ("bccde")) and (include regex ("b(c*)d" withGroup "cc"))) "abccde" should (equal ("abccde") and include regex ("b(c*)d" withGroup "cc")) "abccde" should (equal ("abccde") and include regex ("b(c*)d" withGroup "cc")) "abccde" should (equal ("abccde") and include regex ("b(c*)d" withGroup "cc")) "bccd" should (equal ("bccd") and (include regex ("b(c*)d" withGroup "cc"))) "bccd" should ((equal ("bccd")) and (include regex ("b(c*)d" withGroup "cc"))) "bccd" should (equal ("bccd") and include regex ("b(c*)d" withGroup "cc")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-and expression` { "abccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "bccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should ((include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "abccdd" should (equal ("abccdd") and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdd" should (equal ("abccdd") and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdd" should (equal ("abccdd") and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((equal ("bccdde")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((equal ("bccdde")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((equal ("bccdde")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdde" should (equal ("abccdde") and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "abccdde" should (equal ("abccdde") and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "abccdde" should (equal ("abccdde") and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "bccdd" should (equal ("bccdd") and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should ((equal ("bccdd")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should (equal ("bccdd") and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-or expression` { "a1.7" should (include regex ("hello") or (include regex (decimal))) "a1.7" should (include regex ("hello") or (include regex (decimal))) "a1.7" should (include regex ("hello") or (include regex (decimal))) "1.7b" should ((include regex ("hello")) or (include regex (decimal))) "1.7b" should ((include regex ("hello")) or (include regex (decimal))) "a1.7b" should ((include regex ("hello")) or (include regex (decimal))) "a1.7b" should (include regex ("hello") or include regex (decimal)) "a1.7b" should (include regex ("hello") or include regex (decimal)) "a1.7b" should (include regex ("hello") or include regex (decimal)) "1.7" should (include regex ("hello") or (include regex (decimal))) "1.7" should ((include regex ("hello")) or (include regex (decimal))) "1.7" should (include regex ("hello") or include regex (decimal)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-or expression` { "abccd" should (include regex ("b(c*)d" withGroup "c") or (include regex ("b(c*)d" withGroup "cc"))) "abccd" should ((include regex ("b(c*)d" withGroup "c")) or (include regex ("b(c*)d" withGroup "cc"))) "abccd" should (include regex ("b(c*)d" withGroup "c") or (include regex ("b(c*)d" withGroup "cc"))) "bccde" should (include regex ("b(c*)d" withGroup "c") or (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((include regex ("b(c*)d" withGroup "c")) or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should ((include regex ("b(c*)d" withGroup "c")) or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should (include regex ("b(c*)d" withGroup "c") or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should ((include regex ("b(c*)d" withGroup "c")) or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should (include regex ("b(c*)d" withGroup "c") or include regex ("b(c*)d" withGroup "cc")) "bccd" should (include regex ("b(c*)d" withGroup "c") or (include regex ("b(c*)d" withGroup "cc"))) "bccd" should ((include regex ("b(c*)d" withGroup "c")) or (include regex ("b(c*)d" withGroup "cc"))) "bccd" should (include regex ("b(c*)d" withGroup "c") or include regex ("b(c*)d" withGroup "cc")) "abccd" should (equal ("abcd") or (include regex ("b(c*)d" withGroup "cc"))) "abccd" should ((equal ("abcd")) or (include regex ("b(c*)d" withGroup "cc"))) "abccd" should (equal ("abcd") or include regex ("b(c*)d" withGroup "cc")) "bccde" should (equal ("bcde") or (include regex ("b(c*)d" withGroup "cc"))) "bccde" should ((equal ("bcde")) or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should ((equal ("bcde")) or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should (equal ("abcde") or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should ((equal ("abcde")) or (include regex ("b(c*)d" withGroup "cc"))) "abccde" should (equal ("abcde") or include regex ("b(c*)d" withGroup "cc")) "bccd" should (equal ("bcd") or (include regex ("b(c*)d" withGroup "cc"))) "bccd" should ((equal ("bcd")) or (include regex ("b(c*)d" withGroup "cc"))) "bccd" should (equal ("bcd") or include regex ("b(c*)d" withGroup "cc")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-or expression` { "abccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) or include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "bccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should ((include regex ("b(c*)(d*)" withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) or include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "abccdd" should (equal ("abccd") or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdde" should ((equal ("bccde")) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdde" should ((equal ("bccde")) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "abccdde" should (equal ("abccde") or include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) "bccdd" should (equal ("bccd") or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should ((equal ("bccd")) or (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) "bccdd" should (equal ("bccd") or include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-and expression with not` { "fred" should (not (include regex ("bob")) and not (include regex (decimal))) "fred" should ((not include regex ("bob")) and (not include regex (decimal))) "fred" should (not include regex ("bob") and not include regex (decimal)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-and expression with not` { "abccde" should (not (include regex ("b(c*)d" withGroup "c")) and not (include regex ("b(c*)d" withGroup "c"))) "abccde" should ((not include regex ("b(c*)d" withGroup "c")) and (not include regex ("b(c*)d" withGroup "c"))) "abccde" should (not include regex ("b(c*)d" withGroup "c") and not include regex ("b(c*)d" withGroup "c")) "abccde" should (not (equal ("abcde")) and not (include regex ("b(c*)d" withGroup "c"))) "abccde" should ((not equal ("abcde")) and (not include regex ("b(c*)d" withGroup "c"))) "abccde" should (not equal ("abcde") and not include regex ("b(c*)d" withGroup "c")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-and expression with not` { "abccdde" should (not (include regex ("b(c*)(d*)" withGroups ("cc", "d"))) and not (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should ((not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) and (not include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should (not include regex ("b(c*)(d*)" withGroups ("cc", "d")) and not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) "abccdde" should (not (equal ("abccde")) and not (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should ((not equal ("abccde")) and (not include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should (not equal ("abccde") and not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-or expression with not` { "fred" should (not (include regex ("fred")) or not (include regex (decimal))) "fred" should ((not include regex ("fred")) or (not include regex (decimal))) "fred" should (not include regex ("fred") or not include regex (decimal)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-or expression with not` { "abccde" should (not (include regex ("b(c*)d" withGroup "cc")) or not (include regex ("b(c*)d" withGroup "c"))) "abccde" should ((not include regex ("b(c*)d" withGroup "cc")) or (not include regex ("b(c*)d" withGroup "c"))) "abccde" should (not include regex ("b(c*)d" withGroup "cc") or not include regex ("b(c*)d" withGroup "c")) "abccde" should (not (equal ("abccde")) or not (include regex ("b(c*)d" withGroup "c"))) "abccde" should ((not equal ("abccde")) or (not include regex ("b(c*)d" withGroup "c"))) "abccde" should (not equal ("abccde") or not include regex ("b(c*)d" withGroup "c")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-or expression with not` { "abccdde" should (not (include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) or not (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should ((not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) or (not include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")) or not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) "abccdde" should (not (equal ("abccdde")) or not (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should ((not equal ("abccdde")) or (not include regex ("b(c*)(d*)" withGroups ("cc", "d")))) "abccdde" should (not equal ("abccdde") or not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) } def `should throw TestFailedException if the string does not match substring that matched regex specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should include regex ("1.78") } assert(caught1.getMessage === "\"1.7\" did not include substring that matched regex 1.78") val caught2 = intercept[TestFailedException] { "1.7" should include regex ("21.7") } assert(caught2.getMessage === "\"1.7\" did not include substring that matched regex 21.7") val caught3 = intercept[TestFailedException] { "-one.eight" should include regex (decimal) } assert(caught3.getMessage === "\"-one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should include regex (decimal) } assert(caught6.getMessage === "\"eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught7 = intercept[TestFailedException] { "one.eight" should include regex (decimal) } assert(caught7.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught8 = intercept[TestFailedException] { "onedoteight" should include regex (decimal) } assert(caught8.getMessage === "\"onedoteight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught9 = intercept[TestFailedException] { "***" should include regex (decimal) } assert(caught9.getMessage === "\"***\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string does not match substring that matched regex specified as a string and withGroup` { val caught1 = intercept[TestFailedException] { "abccde" should include regex ("b(c*)d" withGroup "c") } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does not match substring that matched regex specified as a string and withGroups` { val caught1 = intercept[TestFailedException] { "abccdde" should include regex ("b(c*)(d*)" withGroups ("cc", "d")) } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { include regex ("1.7") } } assert(caught1.getMessage === "\"1.7\" included substring that matched regex 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { include regex (decimal) } } assert(caught2.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { include regex (decimal) } } assert(caught3.getMessage === "\"-1.8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { include regex (decimal) } } assert(caught4.getMessage === "\"8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { include regex (decimal) } } assert(caught5.getMessage === "\"1.\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not include regex ("1.7") } assert(caught11.getMessage === "\"1.7\" included substring that matched regex 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not include regex (decimal) } assert(caught12.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not include regex (decimal) } assert(caught13.getMessage === "\"-1.8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not include regex (decimal) } assert(caught14.getMessage === "\"8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not include regex (decimal) } assert(caught15.getMessage === "\"1.\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") // The rest are non-exact matches val caught21 = intercept[TestFailedException] { "a1.7" should not { include regex ("1.7") } } assert(caught21.getMessage === "\"a1.7\" included substring that matched regex 1.7") val caught22 = intercept[TestFailedException] { "1.7b" should not { include regex (decimal) } } assert(caught22.getMessage === "\"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught23 = intercept[TestFailedException] { "a-1.8b" should not { include regex (decimal) } } assert(caught23.getMessage === "\"a-1.8b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string and withGroup when used with not` { val caught1 = intercept[TestFailedException] { "abccde" should not { include regex ("b(c*)d" withGroup "cc") } } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccde" should not include regex ("b(c*)d" withGroup "cc") } assert(caught2.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string and withGroups when used with not` { val caught1 = intercept[TestFailedException] { "abccdde" should not { include regex ("b(c*)(d*)" withGroups ("cc", "dd")) } } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccdde" should not include regex ("b(c*)(d*)" withGroups ("cc", "dd")) } assert(caught2.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (include regex (decimal) and (include regex ("1.8"))) } assert(caught1.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not include substring that matched regex 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((include regex (decimal)) and (include regex ("1.8"))) } assert(caught2.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not include substring that matched regex 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (include regex (decimal) and include regex ("1.8")) } assert(caught3.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not include substring that matched regex 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "one.eight" should (include regex (decimal) and (include regex ("1.8"))) } assert(caught4.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "one.eight" should ((include regex (decimal)) and (include regex ("1.8"))) } assert(caught5.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "one.eight" should (include regex (decimal) and include regex ("1.8")) } assert(caught6.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d" withGroup "cc") and (include regex ("b(c*)d" withGroup "c"))) } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccde" should ((include regex ("b(c*)d" withGroup "cc")) and (include regex ("b(c*)d" withGroup "c"))) } assert(caught2.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d" withGroup "cc") and include regex ("b(c*)d" withGroup "c")) } assert(caught3.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d" withGroup "c") and (include regex ("b(c*)d" withGroup "cc"))) } assert(caught4.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccde" should ((include regex ("b(c*)d" withGroup "c")) and (include regex ("b(c*)d" withGroup "cc"))) } assert(caught5.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d" withGroup "c") and include regex ("b(c*)d" withGroup "cc")) } assert(caught6.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccde" should (equal ("abccde") and (include regex ("b(c*)d" withGroup "c"))) } assert(caught7.getMessage === "\"abccde\" equaled \"abccde\", but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccde" should ((equal ("abccde")) and (include regex ("b(c*)d" withGroup "c"))) } assert(caught8.getMessage === "\"abccde\" equaled \"abccde\", but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abccde" should (equal ("abccde") and include regex ("b(c*)d" withGroup "c")) } assert(caught9.getMessage === "\"abccde\" equaled \"abccde\", but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abccde" should (equal ("abcde") and (include regex ("b(c*)d" withGroup "cc"))) } assert(caught10.getMessage === "\"abc[c]de\" did not equal \"abc[]de\"") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abccde" should ((equal ("abcde")) and (include regex ("b(c*)d" withGroup "cc"))) } assert(caught11.getMessage === "\"abc[c]de\" did not equal \"abc[]de\"") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccde" should (equal ("abcde") and include regex ("b(c*)d" withGroup "cc")) } assert(caught12.getMessage === "\"abc[c]de\" did not equal \"abc[]de\"") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught2.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "dd")) and include regex ("b(c*)(d*)" withGroups ("cc", "d"))) } assert(caught3.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught4.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "d"))) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught5.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught6.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccdde" should (equal ("abccdde") and (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught7.getMessage === "\"abccdde\" equaled \"abccdde\", but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccdde" should ((equal ("abccdde")) and (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught8.getMessage === "\"abccdde\" equaled \"abccdde\", but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abccdde" should (equal ("abccdde") and include regex ("b(c*)(d*)" withGroups ("cc", "d"))) } assert(caught9.getMessage === "\"abccdde\" equaled \"abccdde\", but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught10.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\"") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abccdde" should ((equal ("abccde")) and (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught11.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\"") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") and include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught12.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\"") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "one.seven" should (include regex (decimal) or (include regex ("1.8"))) } assert(caught1.getMessage === "\"one.seven\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"one.seven\" did not include substring that matched regex 1.8") val caught2 = intercept[TestFailedException] { "one.seven" should ((include regex (decimal)) or (include regex ("1.8"))) } assert(caught2.getMessage === "\"one.seven\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"one.seven\" did not include substring that matched regex 1.8") val caught3 = intercept[TestFailedException] { "one.seven" should (include regex (decimal) or include regex ("1.8")) } assert(caught3.getMessage === "\"one.seven\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"one.seven\" did not include substring that matched regex 1.8") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d" withGroup "c") or (include regex ("b(c*)d" withGroup "c"))) } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccde" should ((include regex ("b(c*)d" withGroup "c")) or (include regex ("b(c*)d" withGroup "c"))) } assert(caught2.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d" withGroup "c") or include regex ("b(c*)d" withGroup "c")) } assert(caught3.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccde" should (equal ("abcde") or (include regex ("b(c*)d" withGroup "c"))) } assert(caught4.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccde" should ((equal ("abcde")) or (include regex ("b(c*)d" withGroup "c"))) } assert(caught5.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccde" should (equal ("abcde") or include regex ("b(c*)d" withGroup "c")) } assert(caught6.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) or (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccdde" should ((include regex ("b(c*)(d*)" withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught2.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)" withGroups ("cc", "d")) or include regex ("b(c*)(d*)" withGroups ("cc", "d"))) } assert(caught3.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") or (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught4.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccdde" should ((equal ("abccde")) or (include regex ("b(c*)(d*)" withGroups ("cc", "d")))) } assert(caught5.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") or include regex ("b(c*)(d*)" withGroups ("cc", "d"))) } assert(caught6.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not include regex ("1.8") and (not include regex (decimal))) } assert(caught1.getMessage === "\"1.7\" did not include substring that matched regex 1.8, but \"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not include regex ("1.8")) and (not include regex (decimal))) } assert(caught2.getMessage === "\"1.7\" did not include substring that matched regex 1.8, but \"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not include regex ("1.8") and not include regex (decimal)) } assert(caught3.getMessage === "\"1.7\" did not include substring that matched regex 1.8, but \"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught4 = intercept[TestFailedException] { "a1.7" should (not include regex ("1.8") and (not include regex (decimal))) } assert(caught4.getMessage === "\"a1.7\" did not include substring that matched regex 1.8, but \"a1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1.7b" should ((not include regex ("1.8")) and (not include regex (decimal))) } assert(caught5.getMessage === "\"1.7b\" did not include substring that matched regex 1.8, but \"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "a1.7b" should (not include regex ("1.8") and not include regex (decimal)) } assert(caught6.getMessage === "\"a1.7b\" did not include substring that matched regex 1.8, but \"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d" withGroup "c") and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught1.getMessage === "\"bccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccd" should ((not include regex ("b(c*)d" withGroup "c")) and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught2.getMessage === "\"bccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d" withGroup "c") and not include regex ("b(c*)d" withGroup "cc")) } assert(caught3.getMessage === "\"bccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccd" should (not include regex ("b(c*)d" withGroup "c") and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught4.getMessage === "\"abccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "bccde" should ((not include regex ("b(c*)d" withGroup "c")) and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught5.getMessage === "\"bccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccde" should (not include regex ("b(c*)d" withGroup "c") and not include regex ("b(c*)d" withGroup "cc")) } assert(caught6.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "bccd" should (not equal ("bcd") and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught7.getMessage === "\"bc[c]d\" did not equal \"bc[]d\", but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "bccd" should ((not equal ("bcd")) and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught8.getMessage === "\"bc[c]d\" did not equal \"bc[]d\", but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccd" should (not equal ("bcd") and not include regex ("b(c*)d" withGroup "cc")) } assert(caught9.getMessage === "\"bc[c]d\" did not equal \"bc[]d\", but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abccd" should (not equal ("abcd") and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught10.getMessage === "\"abc[c]d\" did not equal \"abc[]d\", but \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccde" should ((not equal ("bcde")) and (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught11.getMessage === "\"bc[c]de\" did not equal \"bc[]de\", but \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccde" should (not equal ("abcde") and not include regex ("b(c*)d" withGroup "cc")) } assert(caught12.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", but \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)" withGroups ("cc", "d")) and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught1.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccdd" should ((not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught2.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)" withGroups ("cc", "d")) and not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught3.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccdd" should (not include regex ("b(c*)(d*)" withGroups ("cc", "d")) and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught4.getMessage === "\"abccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "bccdde" should ((not include regex ("b(c*)(d*)" withGroups ("cc", "d"))) and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught5.getMessage === "\"bccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccdde" should (not include regex ("b(c*)(d*)" withGroups ("cc", "d")) and not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught6.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "bccdd" should (not equal ("bccd") and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught7.getMessage === "\"bccd[d]\" did not equal \"bccd[]\", but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "bccdd" should ((not equal ("bccd")) and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught8.getMessage === "\"bccd[d]\" did not equal \"bccd[]\", but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccdd" should (not equal ("bccd") and not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught9.getMessage === "\"bccd[d]\" did not equal \"bccd[]\", but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abccdd" should (not equal ("abccd") and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught10.getMessage === "\"abccd[d]\" did not equal \"abccd[]\", but \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccdde" should ((not equal ("bccde")) and (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught11.getMessage === "\"bccd[d]e\" did not equal \"bccd[]e\", but \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccdde" should (not equal ("abccde") and not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught12.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", but \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not include regex (decimal) or (not include regex ("1.7"))) } assert(caught1.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "1.7" should ((not include regex (decimal)) or (not include regex ("1.7"))) } assert(caught2.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "1.7" should (not include regex (decimal) or not include regex ("1.7")) } assert(caught3.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "1.7" should (not (include regex (decimal)) or not (include regex ("1.7"))) } assert(caught4.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "a1.7" should (not include regex (decimal) or (not include regex ("1.7"))) } assert(caught5.getMessage === "\"a1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7\" included substring that matched regex 1.7") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "1.7b" should ((not include regex (decimal)) or (not include regex ("1.7"))) } assert(caught6.getMessage === "\"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7b\" included substring that matched regex 1.7") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "a1.7b" should (not include regex (decimal) or not include regex ("1.7")) } assert(caught7.getMessage === "\"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7b\" included substring that matched regex 1.7") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "a1.7b" should (not (include regex (decimal)) or not (include regex ("1.7"))) } assert(caught8.getMessage === "\"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7b\" included substring that matched regex 1.7") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d" withGroup "cc") or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught1.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccd" should ((not include regex ("b(c*)d" withGroup "cc")) or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught2.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d" withGroup "cc") or not include regex ("b(c*)d" withGroup "cc")) } assert(caught3.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "bccd" should (not (include regex ("b(c*)d" withGroup "cc")) or not (include regex ("b(c*)d" withGroup "cc"))) } assert(caught4.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccd" should (not include regex ("b(c*)d" withGroup "cc") or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught5.getMessage === "\"abccd\" included substring that matched regex b(c*)d and group cc, and \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "bccde" should ((not include regex ("b(c*)d" withGroup "cc")) or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught6.getMessage === "\"bccde\" included substring that matched regex b(c*)d and group cc, and \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccde" should (not include regex ("b(c*)d" withGroup "cc") or not include regex ("b(c*)d" withGroup "cc")) } assert(caught7.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccde" should (not (include regex ("b(c*)d" withGroup "cc")) or not (include regex ("b(c*)d" withGroup "cc"))) } assert(caught8.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccd" should (not equal ("bccd") or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught9.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "bccd" should ((not equal ("bccd")) or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught10.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccd" should (not equal ("bccd") or not include regex ("b(c*)d" withGroup "cc")) } assert(caught11.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "bccd" should (not (equal ("bccd")) or not (include regex ("b(c*)d" withGroup "cc"))) } assert(caught12.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abccd" should (not equal ("abccd") or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught13.getMessage === "\"abccd\" equaled \"abccd\", and \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught13.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "bccde" should ((not equal ("bccde")) or (not include regex ("b(c*)d" withGroup "cc"))) } assert(caught14.getMessage === "\"bccde\" equaled \"bccde\", and \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught14.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abccde" should (not equal ("abccde") or not include regex ("b(c*)d" withGroup "cc")) } assert(caught15.getMessage === "\"abccde\" equaled \"abccde\", and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught15.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abccde" should (not (equal ("abccde")) or not (include regex ("b(c*)d" withGroup "cc"))) } assert(caught16.getMessage === "\"abccde\" equaled \"abccde\", and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught16.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")) or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught1.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccdd" should ((not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught2.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")) or not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught3.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "bccdd" should (not (include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) or not (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught4.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccdd" should (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")) or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught5.getMessage === "\"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "bccdde" should ((not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught6.getMessage === "\"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccdde" should (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")) or not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught7.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccdde" should (not (include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) or not (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught8.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccdd" should (not equal ("bccdd") or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught9.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "bccdd" should ((not equal ("bccdd")) or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught10.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccdd" should (not equal ("bccdd") or not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught11.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "bccdd" should (not (equal ("bccdd")) or not (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught12.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abccdd" should (not equal ("abccdd") or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught13.getMessage === "\"abccdd\" equaled \"abccdd\", and \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught13.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "bccdde" should ((not equal ("bccdde")) or (not include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught14.getMessage === "\"bccdde\" equaled \"bccdde\", and \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught14.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abccdde" should (not equal ("abccdde") or not include regex ("b(c*)(d*)" withGroups ("cc", "dd"))) } assert(caught15.getMessage === "\"abccdde\" equaled \"abccdde\", and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught15.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abccdde" should (not (equal ("abccdde")) or not (include regex ("b(c*)(d*)" withGroups ("cc", "dd")))) } assert(caught16.getMessage === "\"abccdde\" equaled \"abccdde\", and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught16.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) } } object `(when the regex is specified by an actual Regex)` { def `should do nothing if the string includes substring that matched regex specified as a string` { "1.78" should include regex ("1.7") "21.7" should include regex ("1.7") "21.78" should include regex ("1.7") "1.7" should include regex (decimalRegex) "21.7" should include regex (decimalRegex) "1.78" should include regex (decimalRegex) "a -1.8 difference" should include regex (decimalRegex) "b8" should include regex (decimalRegex) "8x" should include regex (decimalRegex) "1.x" should include regex (decimalRegex) // The remaining are full matches, which should also work with "include" "1.7" should include regex ("1.7") "1.7" should include regex (decimalRegex) "-1.8" should include regex (decimalRegex) "8" should include regex (decimalRegex) "1." should include regex (decimalRegex) } def `should do nothing if the string includes substring that matched regex specified as a string and withGroup` { "abccde" should include regex("b(c*)d".r withGroup "cc") "bccde" should include regex("b(c*)d".r withGroup "cc") "abccd" should include regex("b(c*)d".r withGroup "cc") // full matches, which should also work with "include" "bccd" should include regex("b(c*)d".r withGroup "cc") } def `should do nothing if the string includes substring that matched regex specified as a string and withGroups` { "abccdde" should include regex("b(c*)(d*)".r withGroups ("cc", "dd")) "bccdde" should include regex("b(c*)(d*)".r withGroups ("cc", "dd")) "abccdd" should include regex("b(c*)(d*)".r withGroups ("cc", "dd")) // full matches, which should also work with "include" "bccdd" should include regex("b(c*)(d*)".r withGroups ("cc", "dd")) } def `should do nothing if the string does not include substring that matched regex specified as a string when used with not` { "eight" should not { include regex (decimalRegex) } "one.eight" should not { include regex (decimalRegex) } "eight" should not include regex (decimalRegex) "one.eight" should not include regex (decimalRegex) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used with not` { "bccde" should not { include regex ("b(c*)d".r withGroup "c") } "abccde" should not { include regex ("b(c*)d".r withGroup "c") } "bccde" should not include regex ("b(c*)d".r withGroup "c") "abccde" should not include regex ("b(c*)d".r withGroup "c") } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used with not` { "bccdde" should not { include regex ("b(c*)(d*)".r withGroups ("cc", "d")) } "abccdde" should not { include regex ("b(c*)(d*)".r withGroups ("cc", "d")) } "bccdde" should not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) "abccdde" should not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-and expression` { "a1.7" should (include regex (decimalRegex) and (include regex (decimalRegex))) "1.7b" should (include regex (decimalRegex) and (include regex (decimalRegex))) "a1.7b" should (include regex (decimalRegex) and (include regex (decimalRegex))) "a1.7" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "1.7b" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "a1.7b" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "a1.7" should (include regex (decimalRegex) and include regex (decimalRegex)) "1.7b" should (include regex (decimalRegex) and include regex (decimalRegex)) "a1.7b" should (include regex (decimalRegex) and include regex (decimalRegex)) "1.7" should (include regex (decimalRegex) and (include regex (decimalRegex))) "1.7" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "1.7" should (include regex (decimalRegex) and include regex (decimalRegex)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-and expression` { "abccd" should (include regex ("b(c*)d".r withGroup "cc") and (include regex ("b(c*)d".r withGroup "cc"))) "bccde" should ((include regex ("b(c*)d".r withGroup "cc")) and (include regex ("b(c*)d".r withGroup "cc"))) "abccde" should (include regex ("b(c*)d".r withGroup "cc") and include regex ("b(c*)d".r withGroup "cc")) "bccd" should (include regex ("b(c*)d".r withGroup "cc") and (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should ((include regex ("b(c*)d".r withGroup "cc")) and (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should (include regex ("b(c*)d".r withGroup "cc") and include regex ("b(c*)d".r withGroup "cc")) "abccd" should (equal ("abccd") and (include regex ("b(c*)d".r withGroup "cc"))) "bccde" should ((equal ("bccde")) and (include regex ("b(c*)d".r withGroup "cc"))) "abccde" should (equal ("abccde") and include regex ("b(c*)d".r withGroup "cc")) "bccd" should (equal ("bccd") and (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should ((equal ("bccd")) and (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should (equal ("bccd") and include regex ("b(c*)d".r withGroup "cc")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-and expression` { "abccdd" should (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdde" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) and include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) "bccdd" should (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) and include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) "abccdd" should (equal ("abccdd") and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdde" should ((equal ("bccdde")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "abccdde" should (equal ("abccdde") and include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) "bccdd" should (equal ("bccdd") and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should ((equal ("bccdd")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should (equal ("bccdd") and include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-or expression` { "a1.7" should (include regex ("hello") or (include regex (decimalRegex))) "1.7b" should (include regex ("hello") or (include regex (decimalRegex))) "a1.7b" should (include regex ("hello") or (include regex (decimalRegex))) "a1.7" should ((include regex ("hello")) or (include regex (decimalRegex))) "1.7b" should ((include regex ("hello")) or (include regex (decimalRegex))) "a1.7b" should ((include regex ("hello")) or (include regex (decimalRegex))) "a1.7" should (include regex ("hello") or include regex (decimalRegex)) "1.7b" should (include regex ("hello") or include regex (decimalRegex)) "a1.7b" should (include regex ("hello") or include regex (decimalRegex)) "1.7" should (include regex ("hello") or (include regex (decimalRegex))) "1.7" should ((include regex ("hello")) or (include regex (decimalRegex))) "1.7" should (include regex ("hello") or include regex (decimalRegex)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-or expression` { "abccd" should (include regex ("b(c*)d".r withGroup "c") or (include regex ("b(c*)d".r withGroup "cc"))) "bccde" should ((include regex ("b(c*)d".r withGroup "c")) or (include regex ("b(c*)d".r withGroup "cc"))) "abccde" should ((include regex ("b(c*)d".r withGroup "c")) or (include regex ("b(c*)d".r withGroup "cc"))) "abccde" should (include regex ("b(c*)d".r withGroup "c") or include regex ("b(c*)d".r withGroup "cc")) "bccd" should (include regex ("b(c*)d".r withGroup "c") or (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should ((include regex ("b(c*)d".r withGroup "c")) or (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should (include regex ("b(c*)d".r withGroup "c") or include regex ("b(c*)d".r withGroup "cc")) "abccd" should (equal ("abcd") or (include regex ("b(c*)d".r withGroup "cc"))) "bccde" should ((equal ("bcde")) or (include regex ("b(c*)d".r withGroup "cc"))) "abccde" should ((equal ("abcde")) or (include regex ("b(c*)d".r withGroup "cc"))) "abccde" should (equal ("abcde") or include regex ("b(c*)d".r withGroup "cc")) "bccd" should (equal ("bcd") or (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should ((equal ("bcd")) or (include regex ("b(c*)d".r withGroup "cc"))) "bccd" should (equal ("bcd") or include regex ("b(c*)d".r withGroup "cc")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-or expression` { "abccdd" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdde" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "abccdde" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) or include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) "bccdd" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) or include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) "abccdd" should (equal ("abccd") or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdde" should ((equal ("bccde")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "abccdde" should ((equal ("abccde")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "abccdde" should (equal ("abccde") or include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) "bccdd" should (equal ("bccd") or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should ((equal ("bccd")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) "bccdd" should (equal ("bccd") or include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-and expression with not` { "fred" should (not (include regex ("bob")) and not (include regex (decimalRegex))) "fred" should ((not include regex ("bob")) and (not include regex (decimalRegex))) "fred" should (not include regex ("bob") and not include regex (decimalRegex)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-and expression with not` { "abccde" should (not (include regex ("b(c*)d".r withGroup "c")) and not (include regex ("b(c*)d".r withGroup "c"))) "abccde" should ((not include regex ("b(c*)d".r withGroup "c")) and (not include regex ("b(c*)d".r withGroup "c"))) "abccde" should (not include regex ("b(c*)d".r withGroup "c") and not include regex ("b(c*)d".r withGroup "c")) "abccde" should (not (equal ("abcde")) and not (include regex ("b(c*)d".r withGroup "c"))) "abccde" should ((not equal ("abcde")) and (not include regex ("b(c*)d".r withGroup "c"))) "abccde" should (not equal ("abcde") and not include regex ("b(c*)d".r withGroup "c")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-and expression with not` { "abccdde" should (not (include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) and not (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should ((not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) "abccdde" should (not (equal ("abccde")) and not (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should ((not equal ("abccde")) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should (not equal ("abccde") and not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-or expression with not` { "fred" should (not (include regex ("fred")) or not (include regex (decimalRegex))) "fred" should ((not include regex ("fred")) or (not include regex (decimalRegex))) "fred" should (not include regex ("fred") or not include regex (decimalRegex)) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroup when used in a logical-or expression with not` { "abccde" should (not (include regex ("b(c*)d".r withGroup "cc")) or not (include regex ("b(c*)d".r withGroup "c"))) "abccde" should ((not include regex ("b(c*)d".r withGroup "cc")) or (not include regex ("b(c*)d".r withGroup "c"))) "abccde" should (not include regex ("b(c*)d".r withGroup "cc") or not include regex ("b(c*)d".r withGroup "c")) "abccde" should (not (equal ("abccde")) or not (include regex ("b(c*)d".r withGroup "c"))) "abccde" should ((not equal ("abccde")) or (not include regex ("b(c*)d".r withGroup "c"))) "abccde" should (not equal ("abccde") or not include regex ("b(c*)d".r withGroup "c")) } def `should do nothing if the string does not include substring that matched regex specified as a string and withGroups when used in a logical-or expression with not` { "abccdde" should (not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) or not (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should ((not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) or not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) "abccdde" should (not (equal ("abccdde")) or not (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should ((not equal ("abccdde")) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) "abccdde" should (not equal ("abccdde") or not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) } def `should throw TestFailedException if the string does not match substring that matched regex specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should include regex ("1.78") } assert(caught1.getMessage === "\"1.7\" did not include substring that matched regex 1.78") val caught2 = intercept[TestFailedException] { "1.7" should include regex ("21.7") } assert(caught2.getMessage === "\"1.7\" did not include substring that matched regex 21.7") val caught3 = intercept[TestFailedException] { "-one.eight" should include regex (decimalRegex) } assert(caught3.getMessage === "\"-one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should include regex (decimalRegex) } assert(caught6.getMessage === "\"eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught7 = intercept[TestFailedException] { "one.eight" should include regex (decimalRegex) } assert(caught7.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught8 = intercept[TestFailedException] { "onedoteight" should include regex (decimalRegex) } assert(caught8.getMessage === "\"onedoteight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught9 = intercept[TestFailedException] { "***" should include regex (decimalRegex) } assert(caught9.getMessage === "\"***\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string does not match substring that matched regex specified as a string and withGroup` { val caught1 = intercept[TestFailedException] { "abccde" should include regex ("b(c*)d".r withGroup "c") } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does not match substring that matched regex specified as a string and withGroups` { val caught1 = intercept[TestFailedException] { "abccdde" should include regex ("b(c*)(d*)".r withGroups ("cc", "d")) } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { include regex ("1.7") } } assert(caught1.getMessage === "\"1.7\" included substring that matched regex 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { include regex (decimalRegex) } } assert(caught2.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { include regex (decimalRegex) } } assert(caught3.getMessage === "\"-1.8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { include regex (decimalRegex) } } assert(caught4.getMessage === "\"8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { include regex (decimalRegex) } } assert(caught5.getMessage === "\"1.\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not include regex ("1.7") } assert(caught11.getMessage === "\"1.7\" included substring that matched regex 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not include regex (decimalRegex) } assert(caught12.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not include regex (decimalRegex) } assert(caught13.getMessage === "\"-1.8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not include regex (decimalRegex) } assert(caught14.getMessage === "\"8\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not include regex (decimalRegex) } assert(caught15.getMessage === "\"1.\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") // The rest are non-exact matches val caught21 = intercept[TestFailedException] { "a1.7" should not { include regex ("1.7") } } assert(caught21.getMessage === "\"a1.7\" included substring that matched regex 1.7") val caught22 = intercept[TestFailedException] { "1.7b" should not { include regex (decimalRegex) } } assert(caught22.getMessage === "\"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught23 = intercept[TestFailedException] { "a-1.8b" should not { include regex (decimalRegex) } } assert(caught23.getMessage === "\"a-1.8b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string and withGroup when used with not` { val caught1 = intercept[TestFailedException] { "abccde" should not { include regex ("b(c*)d".r withGroup "cc") } } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccde" should not include regex ("b(c*)d".r withGroup "cc") } assert(caught2.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string and withGroups when used with not` { val caught1 = intercept[TestFailedException] { "abccdde" should not { include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) } } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccdde" should not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) } assert(caught2.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (include regex (decimalRegex) and (include regex ("1.8"))) } assert(caught1.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not include substring that matched regex 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((include regex (decimalRegex)) and (include regex ("1.8"))) } assert(caught2.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not include substring that matched regex 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (include regex (decimalRegex) and include regex ("1.8")) } assert(caught3.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not include substring that matched regex 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "one.eight" should (include regex (decimalRegex) and (include regex ("1.8"))) } assert(caught4.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "one.eight" should ((include regex (decimalRegex)) and (include regex ("1.8"))) } assert(caught5.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "one.eight" should (include regex (decimalRegex) and include regex ("1.8")) } assert(caught6.getMessage === "\"one.eight\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d".r withGroup "cc") and (include regex ("b(c*)d".r withGroup "c"))) } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccde" should ((include regex ("b(c*)d".r withGroup "cc")) and (include regex ("b(c*)d".r withGroup "c"))) } assert(caught2.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d".r withGroup "cc") and include regex ("b(c*)d".r withGroup "c")) } assert(caught3.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d".r withGroup "c") and (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught4.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccde" should ((include regex ("b(c*)d".r withGroup "c")) and (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught5.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d".r withGroup "c") and include regex ("b(c*)d".r withGroup "cc")) } assert(caught6.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccde" should (equal ("abccde") and (include regex ("b(c*)d".r withGroup "c"))) } assert(caught7.getMessage === "\"abccde\" equaled \"abccde\", but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccde" should ((equal ("abccde")) and (include regex ("b(c*)d".r withGroup "c"))) } assert(caught8.getMessage === "\"abccde\" equaled \"abccde\", but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abccde" should (equal ("abccde") and include regex ("b(c*)d".r withGroup "c")) } assert(caught9.getMessage === "\"abccde\" equaled \"abccde\", but \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abccde" should (equal ("abcde") and (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught10.getMessage === "\"abc[c]de\" did not equal \"abc[]de\"") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abccde" should ((equal ("abcde")) and (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught11.getMessage === "\"abc[c]de\" did not equal \"abc[]de\"") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccde" should (equal ("abcde") and include regex ("b(c*)d".r withGroup "cc")) } assert(caught12.getMessage === "\"abc[c]de\" did not equal \"abc[]de\"") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccdde" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) and (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught2.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) and include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) } assert(caught3.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught4.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccdde" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught5.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught6.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccdde" should (equal ("abccdde") and (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught7.getMessage === "\"abccdde\" equaled \"abccdde\", but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccdde" should ((equal ("abccdde")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught8.getMessage === "\"abccdde\" equaled \"abccdde\", but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abccdde" should (equal ("abccdde") and include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) } assert(caught9.getMessage === "\"abccdde\" equaled \"abccdde\", but \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught10.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\"") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abccdde" should ((equal ("abccde")) and (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught11.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\"") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") and include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught12.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\"") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "one.seven" should (include regex (decimalRegex) or (include regex ("1.8"))) } assert(caught1.getMessage === "\"one.seven\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"one.seven\" did not include substring that matched regex 1.8") val caught2 = intercept[TestFailedException] { "one.seven" should ((include regex (decimalRegex)) or (include regex ("1.8"))) } assert(caught2.getMessage === "\"one.seven\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"one.seven\" did not include substring that matched regex 1.8") val caught3 = intercept[TestFailedException] { "one.seven" should (include regex (decimalRegex) or include regex ("1.8")) } assert(caught3.getMessage === "\"one.seven\" did not include substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"one.seven\" did not include substring that matched regex 1.8") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d".r withGroup "c") or (include regex ("b(c*)d".r withGroup "c"))) } assert(caught1.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccde" should ((include regex ("b(c*)d".r withGroup "c")) or (include regex ("b(c*)d".r withGroup "c"))) } assert(caught2.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccde" should (include regex ("b(c*)d".r withGroup "c") or include regex ("b(c*)d".r withGroup "c")) } assert(caught3.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccde" should (equal ("abcde") or (include regex ("b(c*)d".r withGroup "c"))) } assert(caught4.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccde" should ((equal ("abcde")) or (include regex ("b(c*)d".r withGroup "c"))) } assert(caught5.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccde" should (equal ("abcde") or include regex ("b(c*)d".r withGroup "c")) } assert(caught6.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", and \"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught1.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abccdde" should ((include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) or (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught2.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abccdde" should (include regex ("b(c*)(d*)".r withGroups ("cc", "d")) or include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) } assert(caught3.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") or (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught4.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccdde" should ((equal ("abccde")) or (include regex ("b(c*)(d*)".r withGroups ("cc", "d")))) } assert(caught5.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccdde" should (equal ("abccde") or include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) } assert(caught6.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", and \"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not include regex ("1.8") and (not include regex (decimalRegex))) } assert(caught1.getMessage === "\"1.7\" did not include substring that matched regex 1.8, but \"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not include regex ("1.8")) and (not include regex (decimalRegex))) } assert(caught2.getMessage === "\"1.7\" did not include substring that matched regex 1.8, but \"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not include regex ("1.8") and not include regex (decimalRegex)) } assert(caught3.getMessage === "\"1.7\" did not include substring that matched regex 1.8, but \"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught4 = intercept[TestFailedException] { "a1.7" should (not include regex ("1.8") and (not include regex (decimalRegex))) } assert(caught4.getMessage === "\"a1.7\" did not include substring that matched regex 1.8, but \"a1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1.7b" should ((not include regex ("1.8")) and (not include regex (decimalRegex))) } assert(caught5.getMessage === "\"1.7b\" did not include substring that matched regex 1.8, but \"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "a1.7b" should (not include regex ("1.8") and not include regex (decimalRegex)) } assert(caught6.getMessage === "\"a1.7b\" did not include substring that matched regex 1.8, but \"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d".r withGroup "c") and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught1.getMessage === "\"bccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccd" should ((not include regex ("b(c*)d".r withGroup "c")) and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught2.getMessage === "\"bccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d".r withGroup "c") and not include regex ("b(c*)d".r withGroup "cc")) } assert(caught3.getMessage === "\"bccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccd" should (not include regex ("b(c*)d".r withGroup "c") and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught4.getMessage === "\"abccd\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "bccde" should ((not include regex ("b(c*)d".r withGroup "c")) and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught5.getMessage === "\"bccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccde" should (not include regex ("b(c*)d".r withGroup "c") and not include regex ("b(c*)d".r withGroup "cc")) } assert(caught6.getMessage === "\"abccde\" included substring that matched regex b(c*)d, but \"cc\" did not match group c, but \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "bccd" should (not equal ("bcd") and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught7.getMessage === "\"bc[c]d\" did not equal \"bc[]d\", but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "bccd" should ((not equal ("bcd")) and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught8.getMessage === "\"bc[c]d\" did not equal \"bc[]d\", but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccd" should (not equal ("bcd") and not include regex ("b(c*)d".r withGroup "cc")) } assert(caught9.getMessage === "\"bc[c]d\" did not equal \"bc[]d\", but \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abccd" should (not equal ("abcd") and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught10.getMessage === "\"abc[c]d\" did not equal \"abc[]d\", but \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccde" should ((not equal ("bcde")) and (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught11.getMessage === "\"bc[c]de\" did not equal \"bc[]de\", but \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccde" should (not equal ("abcde") and not include regex ("b(c*)d".r withGroup "cc")) } assert(caught12.getMessage === "\"abc[c]de\" did not equal \"abc[]de\", but \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught1.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccdd" should ((not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught2.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught3.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abccdd" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught4.getMessage === "\"abccdd\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "bccdde" should ((not include regex ("b(c*)(d*)".r withGroups ("cc", "d"))) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught5.getMessage === "\"bccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abccdde" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "d")) and not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught6.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*), but \"dd\" did not match group d at index 1, but \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "bccdd" should (not equal ("bccd") and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught7.getMessage === "\"bccd[d]\" did not equal \"bccd[]\", but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "bccdd" should ((not equal ("bccd")) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught8.getMessage === "\"bccd[d]\" did not equal \"bccd[]\", but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccdd" should (not equal ("bccd") and not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught9.getMessage === "\"bccd[d]\" did not equal \"bccd[]\", but \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abccdd" should (not equal ("abccd") and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught10.getMessage === "\"abccd[d]\" did not equal \"abccd[]\", but \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccdde" should ((not equal ("bccde")) and (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught11.getMessage === "\"bccd[d]e\" did not equal \"bccd[]e\", but \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abccdde" should (not equal ("abccde") and not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught12.getMessage === "\"abccd[d]e\" did not equal \"abccd[]e\", but \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not include regex (decimalRegex) or (not include regex ("1.7"))) } assert(caught1.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not include regex (decimalRegex)) or (not include regex ("1.7"))) } assert(caught2.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not include regex (decimalRegex) or not include regex ("1.7")) } assert(caught3.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (include regex (decimalRegex)) or not (include regex ("1.7"))) } assert(caught4.getMessage === "\"1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7\" included substring that matched regex 1.7") val caught5 = intercept[TestFailedException] { "a1.7" should (not include regex (decimalRegex) or (not include regex ("1.7"))) } assert(caught5.getMessage === "\"a1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7\" included substring that matched regex 1.7") val caught6 = intercept[TestFailedException] { "1.7b" should ((not include regex (decimalRegex)) or (not include regex ("1.7"))) } assert(caught6.getMessage === "\"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7b\" included substring that matched regex 1.7") val caught7 = intercept[TestFailedException] { "a1.7b" should (not include regex (decimalRegex) or not include regex ("1.7")) } assert(caught7.getMessage === "\"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7b\" included substring that matched regex 1.7") val caught8 = intercept[TestFailedException] { "a1.7b" should (not (include regex (decimalRegex)) or not (include regex ("1.7"))) } assert(caught8.getMessage === "\"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7b\" included substring that matched regex 1.7") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroup when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d".r withGroup "cc") or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught1.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccd" should ((not include regex ("b(c*)d".r withGroup "cc")) or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught2.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccd" should (not include regex ("b(c*)d".r withGroup "cc") or not include regex ("b(c*)d".r withGroup "cc")) } assert(caught3.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "bccd" should (not (include regex ("b(c*)d".r withGroup "cc")) or not (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught4.getMessage === "\"bccd\" included substring that matched regex b(c*)d and group cc, and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccd" should (not include regex ("b(c*)d".r withGroup "cc") or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught5.getMessage === "\"abccd\" included substring that matched regex b(c*)d and group cc, and \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "bccde" should ((not include regex ("b(c*)d".r withGroup "cc")) or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught6.getMessage === "\"bccde\" included substring that matched regex b(c*)d and group cc, and \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccde" should (not include regex ("b(c*)d".r withGroup "cc") or not include regex ("b(c*)d".r withGroup "cc")) } assert(caught7.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccde" should (not (include regex ("b(c*)d".r withGroup "cc")) or not (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught8.getMessage === "\"abccde\" included substring that matched regex b(c*)d and group cc, and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccd" should (not equal ("bccd") or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught9.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "bccd" should ((not equal ("bccd")) or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught10.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccd" should (not equal ("bccd") or not include regex ("b(c*)d".r withGroup "cc")) } assert(caught11.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "bccd" should (not (equal ("bccd")) or not (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught12.getMessage === "\"bccd\" equaled \"bccd\", and \"bccd\" included substring that matched regex b(c*)d and group cc") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abccd" should (not equal ("abccd") or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught13.getMessage === "\"abccd\" equaled \"abccd\", and \"abccd\" included substring that matched regex b(c*)d and group cc") assert(caught13.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "bccde" should ((not equal ("bccde")) or (not include regex ("b(c*)d".r withGroup "cc"))) } assert(caught14.getMessage === "\"bccde\" equaled \"bccde\", and \"bccde\" included substring that matched regex b(c*)d and group cc") assert(caught14.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abccde" should (not equal ("abccde") or not include regex ("b(c*)d".r withGroup "cc")) } assert(caught15.getMessage === "\"abccde\" equaled \"abccde\", and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught15.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abccde" should (not (equal ("abccde")) or not (include regex ("b(c*)d".r withGroup "cc"))) } assert(caught16.getMessage === "\"abccde\" equaled \"abccde\", and \"abccde\" included substring that matched regex b(c*)d and group cc") assert(caught16.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string includes substring that matched regex specified as a string and withGroups when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught1.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught1.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "bccdd" should ((not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught2.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught2.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "bccdd" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) or not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught3.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught3.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "bccdd" should (not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) or not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught4.getMessage === "\"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught4.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abccdd" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught5.getMessage === "\"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught5.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "bccdde" should ((not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught6.getMessage === "\"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught6.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abccdde" should (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")) or not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught7.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught7.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abccdde" should (not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) or not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught8.getMessage === "\"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd, and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught8.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "bccdd" should (not equal ("bccdd") or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught9.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught9.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "bccdd" should ((not equal ("bccdd")) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught10.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught10.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "bccdd" should (not equal ("bccdd") or not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught11.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught11.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "bccdd" should (not (equal ("bccdd")) or not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught12.getMessage === "\"bccdd\" equaled \"bccdd\", and \"bccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught12.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abccdd" should (not equal ("abccdd") or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught13.getMessage === "\"abccdd\" equaled \"abccdd\", and \"abccdd\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught13.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "bccdde" should ((not equal ("bccdde")) or (not include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught14.getMessage === "\"bccdde\" equaled \"bccdde\", and \"bccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught14.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abccdde" should (not equal ("abccdde") or not include regex ("b(c*)(d*)".r withGroups ("cc", "dd"))) } assert(caught15.getMessage === "\"abccdde\" equaled \"abccdde\", and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught15.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abccdde" should (not (equal ("abccdde")) or not (include regex ("b(c*)(d*)".r withGroups ("cc", "dd")))) } assert(caught16.getMessage === "\"abccdde\" equaled \"abccdde\", and \"abccdde\" included substring that matched regex b(c*)(d*) and group cc, dd") assert(caught16.failedCodeFileName === Some("ShouldIncludeRegexSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) } } } } /* def `should do nothing if the string includes substring that matched regex specified as a string` { "1.78" should include regex ("1.7") "21.7" should include regex ("1.7") "21.78" should include regex ("1.7") "1.7" should include regex (decimalRegex) "21.7" should include regex (decimalRegex) "1.78" should include regex (decimalRegex) "a -1.8 difference" should include regex (decimalRegex) "b8" should include regex (decimalRegex) "8x" should include regex (decimalRegex) "1.x" should include regex (decimalRegex) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-and expression` { "a1.7" should (include regex (decimalRegex) and (include regex (decimalRegex))) "1.7b" should (include regex (decimalRegex) and (include regex (decimalRegex))) "a1.7b" should (include regex (decimalRegex) and (include regex (decimalRegex))) "a1.7" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "1.7b" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "a1.7b" should ((include regex (decimalRegex)) and (include regex (decimalRegex))) "a1.7" should (include regex (decimalRegex) and include regex (decimalRegex)) "1.7b" should (include regex (decimalRegex) and include regex (decimalRegex)) "a1.7b" should (include regex (decimalRegex) and include regex (decimalRegex)) } def `should do nothing if the string does not include substring that matched regex specified as a string when used in a logical-or expression` { "a1.7" should (include regex ("hello") or (include regex (decimalRegex))) "1.7b" should (include regex ("hello") or (include regex (decimalRegex))) "a1.7b" should (include regex ("hello") or (include regex (decimalRegex))) "a1.7" should ((include regex ("hello")) or (include regex (decimalRegex))) "1.7b" should ((include regex ("hello")) or (include regex (decimalRegex))) "a1.7b" should ((include regex ("hello")) or (include regex (decimalRegex))) "a1.7" should (include regex ("hello") or include regex (decimalRegex)) "1.7b" should (include regex ("hello") or include regex (decimalRegex)) "a1.7b" should (include regex ("hello") or include regex (decimalRegex)) } def `should throw TestFailedException if the string does matches substring that matched regex specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "a1.7" should not { include regex ("1.7") } } assert(caught1.getMessage === "\"a1.7\" included substring that matched regex 1.7") val caught2 = intercept[TestFailedException] { "1.7b" should not { include regex (decimalRegex) } } assert(caught2.getMessage === "\"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "a-1.8b" should not { include regex (decimalRegex) } } assert(caught3.getMessage === "\"a-1.8b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "a1.7" should (not include regex ("1.8") and (not include regex (decimalRegex))) } assert(caught1.getMessage === "\"a1.7\" did not include substring that matched regex 1.8, but \"a1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught2 = intercept[TestFailedException] { "1.7b" should ((not include regex ("1.8")) and (not include regex (decimalRegex))) } assert(caught2.getMessage === "\"1.7b\" did not include substring that matched regex 1.8, but \"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "a1.7b" should (not include regex ("1.8") and not include regex (decimalRegex)) } assert(caught3.getMessage === "\"a1.7b\" did not include substring that matched regex 1.8, but \"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string includes substring that matched regex specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "a1.7" should (not include regex (decimalRegex) or (not include regex ("1.7"))) } assert(caught1.getMessage === "\"a1.7\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7\" included substring that matched regex 1.7") val caught2 = intercept[TestFailedException] { "1.7b" should ((not include regex (decimalRegex)) or (not include regex ("1.7"))) } assert(caught2.getMessage === "\"1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"1.7b\" included substring that matched regex 1.7") val caught3 = intercept[TestFailedException] { "a1.7b" should (not include regex (decimalRegex) or not include regex ("1.7")) } assert(caught3.getMessage === "\"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7b\" included substring that matched regex 1.7") val caught4 = intercept[TestFailedException] { "a1.7b" should (not (include regex (decimalRegex)) or not (include regex ("1.7"))) } assert(caught4.getMessage === "\"a1.7b\" included substring that matched regex (-)?(\\d+)(\\.\\d*)?, and \"a1.7b\" included substring that matched regex 1.7") } */
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/exceptions/TableDrivenPropertyCheckFailedExceptionSpec.scala
<reponame>cquiroz/scalatest /* * 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.exceptions import org.scalatest.FunSpec import org.scalatest.Matchers import org.scalatest.SharedHelpers.thisLineNumber import org.scalatest.prop._ /* Uncomment this after removing the deprecated type aliases in the org.scalatest.prop package object import org.scalatest.exceptions.TableDrivenPropertyCheckFailedException */ class TableDrivenPropertyCheckFailedExceptionSpec extends FunSpec with Matchers with TableDrivenPropertyChecks { describe("The TableDrivenPropertyCheckFailedException") { it("should give the proper line on a table-driven property check") { val examples = Table( ("a", "b"), (1, 2), (3, 4), (6, 5), (7, 8) ) try { forAll (examples) { (a, b) => a should be < b } } catch { case e: TableDrivenPropertyCheckFailedException => e.failedCodeFileNameAndLineNumberString match { case Some(s) => s should equal ("TableDrivenPropertyCheckFailedExceptionSpec.scala:" + (thisLineNumber - 5)) case None => fail("A table-driven property check didn't produce a file name and line number string", e) } case e: Throwable => fail("forAll (examples) { (a, b) => a should be < b } didn't produce a TableDrivenPropertyCheckFailedException", e) } } describe("even when it is nested in another describe") { it("should give the proper line on a table-driven property check") { val examples = Table( ("a", "b"), (1, 2), (3, 4), (6, 5), (7, 8) ) try { forAll (examples) { (a, b) => a should be < b } } catch { case e: TableDrivenPropertyCheckFailedException => e.failedCodeFileNameAndLineNumberString match { case Some(s) => s should equal ("TableDrivenPropertyCheckFailedExceptionSpec.scala:" + (thisLineNumber - 5)) case None => fail("A table-driven property check didn't produce a file name and line number string", e) } case e: Throwable => fail("forAll (examples) { (a, b) => a should be < b } didn't produce a TableDrivenPropertyCheckFailedException", e) } } } it("should return the cause in both cause and getCause") { val theCause = new IllegalArgumentException("howdy") val tfe = new TableDrivenPropertyCheckFailedException(sde => "doody", Some(theCause), sde => 3, None, "howdy", List(1, 2, 3), List("a", "b", "c"), 7) assert(tfe.cause.isDefined) assert(tfe.cause.get === theCause) assert(tfe.getCause == theCause) } it("should return None in cause and null in getCause if no cause") { val tfe = new TableDrivenPropertyCheckFailedException(sde => "doody", None, sde => 3, None, "howdy", List(1, 2, 3), List("a", "b", "c"), 7) assert(tfe.cause.isEmpty) assert(tfe.getCause == null) } it("should be equal to itself") { val tfe = new TableDrivenPropertyCheckFailedException(sde => "doody", None, sde => 3, None, "howdy", List(1, 2, 3), List("a", "b", "c"), 7) assert(tfe == tfe) } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/DispatchReporter.scala
<gh_stars>1-10 /* * 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 import java.util.concurrent.CountDownLatch import java.io.PrintStream import org.scalatest.events._ import DispatchReporter.propagateDispose import java.util.concurrent.LinkedBlockingQueue import java.util.TimerTask import java.util.Timer import time.Now._ import java.util.concurrent.atomic.AtomicReference import tools.StringReporter.makeDurationString /** * A <code>Reporter</code> that dispatches test results to other <code>Reporter</code>s. * Attempts to dispatch each method invocation to each contained <code>Reporter</code>, * even if some <code>Reporter</code> methods throw <code>Exception</code>s. Catches * <code>Exception</code>s thrown by <code>Reporter</code> methods and prints error * messages to the standard error stream. * * The primary constructor creates a new <code>DispatchReporter</code> with specified <code>Reporter</code>s list. * Each object in the <code>reporters</code> list must implement <code>Reporter</code>. * * @param reporters the initial <code>Reporter</code>s list for this * <code>DispatchReporter</code> * @throws NullPointerException if <code>reporters</code> is <code>null</code>. * @author <NAME> */ private[scalatest] class DispatchReporter( val reporters: List[Reporter], val out: PrintStream = Console.err, detectSlowpokes: Boolean = false, slowpokeDetectionDelay: Long = 60000, slowpokeDetectionPeriod: Long = 60000 ) extends CatchReporter { thisDispatchReporter => private case object Dispose private final val latch = new CountDownLatch(1) // We keep track of the highest ordinal seen, allowing some to be skipped. private final val highestOrdinalSeenSoFar: AtomicReference[Ordinal] = new AtomicReference[Ordinal](new Ordinal(0)) // Can be either Event or Dispose.type. Be nice to capture that in the type param. private final val queue: LinkedBlockingQueue[AnyRef] = new LinkedBlockingQueue[AnyRef] private final val slowpokeItems: Option[(SlowpokeDetector, Timer)] = if (detectSlowpokes) { val slowpokeDetector = new SlowpokeDetector(slowpokeDetectionDelay, out) val timer = new Timer val task = new TimerTask { override def run(): Unit = { val slowpokes = slowpokeDetector.detectSlowpokes(now()) if (!slowpokes.isEmpty) { val msgs = for (slowpoke <- slowpokes) yield Resources.slowpokeDetected(makeDurationString(slowpoke.duration.millisPart), slowpoke.suiteName, slowpoke.testName) val fullMessage = msgs.mkString("\n") val dispatch = thisDispatchReporter thisDispatchReporter.apply( new AlertProvided( ordinal = highestOrdinalSeenSoFar.get, message = fullMessage, nameInfo = None, // Don't include name info. suiteName and testName for all slowpokes are included in fullMessage already. throwable = None, formatter = Some(IndentedText(Resources.alertFormattedText(fullMessage), fullMessage, 0)) ) ) } } } timer.schedule(task, slowpokeDetectionPeriod, slowpokeDetectionPeriod) Some((slowpokeDetector, timer)) } else None private def fireTestFinishedIfNecessary(suiteName: String, suiteId: String, testName: String): Unit = { slowpokeItems match { case Some((slowpokeDetector, _)) => slowpokeDetector.testFinished(suiteName, suiteId, testName) case None => } } class Propagator extends Runnable { def run() { var alive = true // local variable. Only used by the Propagator's thread, so no need for synchronization class Counter { var testsSucceededCount = 0 var testsFailedCount = 0 var testsIgnoredCount = 0 var testsCanceledCount = 0 var testsPendingCount = 0 var suitesCompletedCount = 0 var suitesAbortedCount = 0 var scopesPendingCount = 0 } val counterMap = scala.collection.mutable.Map[Int, Counter]() def incrementCount(event: Event, f: (Counter) => Unit) { val runStamp = event.ordinal.runStamp if (counterMap.contains(runStamp)) { val counter = counterMap(runStamp) f(counter) } else { val counter = new Counter f(counter) counterMap(runStamp) = counter } } // If None, that means don't update the summary so forward the old event. If Some, // create a new event with everything the same except the old summary replaced by the new one def updatedSummary(oldSummary: Option[Summary], ordinal: Ordinal): Option[Summary] = { oldSummary match { case None if (counterMap.contains(ordinal.runStamp)) => { // Update the RunAborted so that it is the same except it has a new Some(Summary) val counter = counterMap(ordinal.runStamp) Some( Summary( counter.testsSucceededCount, counter.testsFailedCount, counter.testsIgnoredCount, counter.testsPendingCount, counter.testsCanceledCount, counter.suitesCompletedCount, counter.suitesAbortedCount, counter.scopesPendingCount ) ) } case _ => None // Also pass the old None summary through if it isn't in the counterMap } } while (alive) { queue.take() match { case event: Event => val highestSoFar = highestOrdinalSeenSoFar.get if (event.ordinal > highestSoFar) highestOrdinalSeenSoFar.compareAndSet(highestSoFar, event.ordinal) // Ignore conflicts. Just let first one win and move on. // The reason is that this is used to send AlertProvided events for slowpoke notifications, and these need not have the // exactly the latest ordinal. So long as it is in the ballpark, that's is good enough. try { // The event will only actually be updated if it it is a RunCompleted/Aborted/Stopped event with None // as its summary and its runstamp has a counter entry. In that case, it will be given a Summary taken // from the counter. (And the counter will be removed from the counterMap.) These are counted here, because // they need to be counted on this side of any FilterReporters that may be in place. (In early versions of // ScalaTest, these were wrongly being counted by the reporters themselves, so if a FilterReporter filtered // out TestSucceeded events, then they just weren't being counted. val updatedEvent = event match { case _: RunStarting => counterMap(event.ordinal.runStamp) = new Counter; event case ts: TestSucceeded => incrementCount(event, _.testsSucceededCount += 1) fireTestFinishedIfNecessary(ts.suiteName, ts.suiteId, ts.testName) event case tf: TestFailed => incrementCount(event, _.testsFailedCount += 1) fireTestFinishedIfNecessary(tf.suiteName, tf.suiteId, tf.testName) event case _: TestIgnored => incrementCount(event, _.testsIgnoredCount += 1); event case tc: TestCanceled => incrementCount(event, _.testsCanceledCount += 1) fireTestFinishedIfNecessary(tc.suiteName, tc.suiteId, tc.testName) event case tp: TestPending => incrementCount(event, _.testsPendingCount += 1) fireTestFinishedIfNecessary(tp.suiteName, tp.suiteId, tp.testName) event case _: SuiteCompleted => incrementCount(event, _.suitesCompletedCount += 1); event case _: SuiteAborted => incrementCount(event, _.suitesAbortedCount += 1); event case _: ScopePending => incrementCount(event, _.scopesPendingCount += 1); event case oldRunCompleted @ RunCompleted(ordinal, duration, summary, formatter, location, payload, threadName, timeStamp) => updatedSummary(summary, ordinal) match { case None => oldRunCompleted case newSummary @ Some(_) => counterMap.remove(ordinal.runStamp) // Update the RunCompleted so that it is the same except it has a new Some(Summary) RunCompleted(ordinal, duration, newSummary, formatter, location, payload, threadName, timeStamp) } case oldRunStopped @ RunStopped(ordinal, duration, summary, formatter, location, payload, threadName, timeStamp) => updatedSummary(summary, ordinal) match { case None => oldRunStopped case newSummary @ Some(_) => counterMap.remove(ordinal.runStamp) // Update the RunStopped so that it is the same except it has a new Some(Summary) RunStopped(ordinal, duration, newSummary, formatter, location, payload, threadName, timeStamp) } case oldRunAborted @ RunAborted(ordinal, message, throwable, duration, summary, formatter, location, payload, threadName, timeStamp) => updatedSummary(summary, ordinal) match { case None => oldRunAborted case newSummary @ Some(_) => counterMap.remove(ordinal.runStamp) // Update the RunAborted so that it is the same except it has a new Some(Summary) RunAborted(ordinal, message, throwable, duration, newSummary, formatter, location, payload, threadName, timeStamp) } case ts: TestStarting => slowpokeItems match { case Some((slowpokeDetector, _)) => slowpokeDetector.testStarting( suiteName = ts.suiteName, suiteId = ts.suiteId, testName = ts.testName, now() ) case None => } event case _ => event } for (report <- reporters) report(updatedEvent) } catch { case e: Exception => val stringToPrint = Resources.reporterThrew(event) out.println(stringToPrint) e.printStackTrace(out) } case Dispose => try { for (reporter <- reporters) propagateDispose(reporter) } catch { case e: Exception => val stringToPrint = Resources.reporterDisposeThrew out.println(stringToPrint) e.printStackTrace(out) } finally { alive = false latch.countDown() } } } } } private val propagator = new Propagator (new Thread(propagator, "ScalaTest-dispatcher")).start() // Invokes dispose on each Reporter in this DispatchReporter's reporters list. // This method puts an event in the queue that is being used to serialize // events, and at some time later the propagator's thread will attempt to invoke // dispose on each contained Reporter, even if some Reporter's dispose methods throw // Exceptions. This method catches any Exception thrown by // a dispose method and handles it by printing an error message to the // standard error stream. Once finished with that, the propagator's thread will return. // // This method will not return until the propagator's thread has exited. // def dispatchDisposeAndWaitUntilDone() { queue.put(Dispose) latch.await() slowpokeItems match { case Some((_, timer)) => timer.cancel() case None => } } override def apply(event: Event) { queue.put(event) } def doApply(event: Event) {} def doDispose() { dispatchDisposeAndWaitUntilDone() } def isDisposed = latch.getCount == 0 } // TODO: Not a real problem, but if a DispatchReporter ever got itself in // its list of reporters, this would end up being an infinite loop. But // That first part, a DispatchReporter getting itself in there would be the real // bug. private[scalatest] object DispatchReporter { def propagateDispose(reporter: Reporter) { reporter match { case dispatchReporter: DispatchReporter => dispatchReporter.dispatchDisposeAndWaitUntilDone() case resourcefulReporter: ResourcefulReporter => resourcefulReporter.dispose() case _ => } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/laws/ApplicativeLaws.scala
/* * Copyright 2001-2014 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.laws import org.scalacheck.{Arbitrary, Shrink} import org.scalactic._ import org.scalactic.algebra._ import org.scalatest._ import org.scalatest.Matchers._ import org.scalatest.prop.GeneratorDrivenPropertyChecks._ import Applicative.adapters import scala.language.higherKinds class ApplicativeLaws[Context[_]](implicit ap: Applicative[Context], arbCa: Arbitrary[Context[Int]], shrCa: Shrink[Context[Int]], arbAb: Arbitrary[Int => String], shrAb: Shrink[Int => String], arbBc: Arbitrary[String => Double], shrBc: Shrink[String => Double], arbCab: Arbitrary[Context[Int => String]], shrCab: Shrink[Context[Int => String]], arbCbc: Arbitrary[Context[String => Double]], shrCbc: Shrink[Context[String => Double]]) extends Laws("applicative") { /* "applicative" laws { "composition" law { forAll { (ca: Context[Int], cf: Context[Int => String], cg: Context[String => Double]) => ((ca applying cf) applying cg) shouldEqual (ca applying (cf applying (cg map ( (g: String => Double) => (f: Int => String) => g compose f)))) } } "identity" law { } } } */ override val laws = Every( law("composition") { () => forAll { (ca: Context[Int], cf: Context[Int => String], cg: Context[String => Double]) => ((ca applying cf) applying cg) shouldEqual (ca applying (cf applying (cg map ( (g: String => Double) => (f: Int => String) => g compose f)))) } }, // ca ap (a => a) should be the same as ca law("identity") { () => forAll { (ca: Context[Int]) => (ca applying ap.insert((a: Int) => a)) shouldEqual ca } }, // (insert(a) ap insert(ab)) should be the same as insert(ab(a)) law("homomorphism") { () => forAll { (a: Int, f: Int => String) => (ap.insert(a) applying ap.insert(f)) shouldEqual ap.insert(f(a)) } }, law("interchange") { () => forAll { (a: Int, cf: Context[Int => String]) => (ap.insert(a) applying cf) shouldEqual (cf applying ap.insert((f: Int => String) => f(a))) } } ) }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/Uniformity.scala
<reponame>cquiroz/scalatest<gh_stars>1-10 /* * 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.scalactic /** * Defines a custom way to normalize instances of a type that can also handle normalization of that type when passed as <code>Any</code>. * * <p> * For example, to normalize <code>Double</code>s by truncating off any decimal part, * you might write: * </p> * * <pre class="stHighlight"> * import org.scalactic._ * * val truncated = * new Uniformity[Double] { * def normalized(d: Double) = d.floor * def normalizedCanHandle(o: Any) = o.isInstanceOf[Double] * def normalizedOrSame(o: Any): Any = * o match { * case d: Double =&gt; normalized(d) * case _ =&gt; o * } * } * </pre> * * <p> * Given this definition you could use it with the <a href="Explicitly.html"><code>Explicitly</code></a> DSL like this: * </p> * * <pre class="stHighlight"> * import org.scalatest._ * import Matchers._ * * 2.1 should equal (2.0) (after being truncated) * </pre> * * <p> * If you make the <code>truncated</code> <code>val</code> implicit and import or mix in the members of <a href="NormMethods.html"><code>NormMethods</code></a>, * you can access the behavior by invoking <code>.norm</code> on <code>Double</code>s. * </p> * * <pre class="stHighlight"> * implicit val doubleUniformity = truncated * import NormMethods._ * * val d = 2.1 * d.norm // returns 2.0 * </pre> * * <p> * Note that by creating a <code>Uniformity</code> rather than just an instance of its supertype, <a href="Normalization.html"><code>Normalization</code></a>, * it can be used more generally. For example, <code>Uniformity</code>s allow you to the <code>Explicitly</code> DSL with * <a href="TripleEquals.html"><code>TripleEquals</code></a>, whereas <code>Normalization</code>s require * <a href="TypeCheckedTripleEquals.html"><code>TypeCheckedTripleEquals</code></a> or * <a href="ConversionCheckedTripleEquals.html"><code>ConversionCheckedTripleEquals</code></a>. * <code>Uniformity</code>s also enable you to use the <code>Explicitly</code> DSL with ScalaTest's <code>should</code> <code>===</code>, <code>equal</code>, * and <code>contain</code> matcher syntax, whereas a plain <code>Normalization</code> can only be used with <code>should</code> <code>===</code>, and only * under either <code>TypeCheckedTripleEquals</code> or <code>ConversionCheckedTripleEquals</code>. * </p> * * @tparam A the type whose uniformity is being defined */ trait Uniformity[A] extends Normalization[A] { thisUniformity => /** * Returns either the result of passing this object to <code>normalized</code>, if appropriate, or the same object. * * <p> * Implementations can decide what &ldquo;appropriate&rdquo; means, but the intent is that it will usually mean the * value passed is of the type <code>A</code>. For example, if this is a <code>Uniformity[String]</code>, appropriate means * that the value (of type <code>Any</code>) passed is actually an instance of <code>String</code>. Because of erasure, * however, a <code>Uniformity[List[String]]</code> will only be able to tell whether a value is a <code>List[_]</code>, * so it might declare any <code>List[_]</code> that contains only <code>String</code>s (determined by invoking * <code>isInstanceOf[String]</code> on each element) to be appropriate. This means a <code>Uniformity[List[String]]</code> might normalize * a <code>List[AnyRef]</code> that happens to contain only <code>Strings</code>. * </p> * * @param b the object to normalize, if appropriate * @return a normalized form of the passed object, if this <code>Uniformity</code> was able to normalize it, else the same object passed */ def normalizedOrSame(b: Any): Any /** * Indicates whether this <code>Uniformity</code>'s <code>normalized</code> method can &ldquo;handle&rdquo; the passed object, if cast to the * appropriate type <code>A</code>. * * <p> * If this method returns true for a particular passed object, it means that if the object is passed * to <code>normalizedOrSame</code>, that method will return the result of passing it to <code>normalized</code>. * It does not mean that the object will necessarily be <em>modified</em> when passed to <code>normalizedOrSame</code> or <code>normalized</code>. * For example, the <code>lowerCased</code> field of <code>StringNormalizations</code> is a <code>Uniformity[String]</code> * that normalizes strings by forcing all characters to lower case: * </p> * * <pre class="stREPL"> * scala&gt; import org.scalactic._ * import org.scalactic._ * * scala&gt; import StringNormalizations._ * import StringNormalizations._ * * scala&gt; lowerCased * res0: org.scalactic.Uniformity[String] = lowerCased * * scala&gt; lowerCased.normalized("HALLOOO!") * res1: String = hallooo! * </pre> * * <p> * Now consider two strings held from variables of type <code>AnyRef</code>: * </p> * * <pre class="stREPL"> * scala&gt; val yell: AnyRef = "HOWDY" * yell: AnyRef = HOWDY * * scala&gt; val whisper: AnyRef = "howdy" * whisper: AnyRef = howdy * </pre> * * <p> * As you would expect, when <code>yell</code> is passed to <code>normalizedCanHandle</code>, it returns true, and when * <code>yell</code> is passed to <code>normalizedOrSame</code>, it returns a lower-cased (normal) form: * </p> * * <pre class="stREPL"> * scala&gt; lowerCased.normalizedCanHandle(yell) * res2: Boolean = true * * scala&gt; lowerCased.normalizedOrSame(yell) * res3: Any = howdy * </pre> * * <p> * A similar thing happens, however, when <code>whisper</code> is passed to <code>normalizedCanHandle</code> and <code>normalizedOrSame</code>, * even though in this case the string is already in normal form according to the <code>lowerCased</code> <code>Uniformity</code>: * </p> * * <pre class="stREPL"> * scala&gt; lowerCased.normalizedCanHandle(whisper) * res4: Boolean = true * * scala&gt; lowerCased.normalizedOrSame(whisper) * res5: Any = howdy * </pre> * * <p> * This illustrates that <code>normalizedCanHandle</code> does <em>not</em> indicate that the passed object is not in normalized form already, just that * it can be be handled by the <code>normalized</code> method. This further means that the <code>normalized</code> method itself * simply ensures that objects are returned in normal form. It need not necessarily change them: if a passed object is already in * normal form, <code>normalized</code> can (and usually should) return the exact same object. That is in fact what happened when we normalized * <code>whisper</code>. Since <code>whisper</code>'s value of <code>"hello"</code> was already in normal form (all lower-cased), <code>normalized</code> ( * invoked by the <code>normalizedOrSame</code> method) returned the exact same object passed: * </p> * * <pre class="stREPL"> * scala&gt; val whisperNormed = res5.asInstanceOf[AnyRef] * whisperNormed: AnyRef = howdy * * scala&gt; whisperNormed eq whisper * res8: Boolean = true * </pre> */ def normalizedCanHandle(b: Any): Boolean /** * Returns a new <code>Uniformity</code> that combines this and the passed <code>Uniformity</code>. * * <p> * The <code>normalized</code> and <code>normalizedOrSame</code> methods * of the <code>Uniformity</code> returned by this method return a result * obtained by forwarding the passed value first to this <code>Uniformity</code>'s implementation of the method, * then passing that result to the other <code>Uniformity</code>'s implementation of the method, respectively. * Essentially, the body of the composed <code>normalized</code> method is: * </p> * * <pre class="stHighlight"> * uniformityPassedToAnd.normalized(uniformityOnWhichAndWasInvoked.normalized(a)) * </pre> * * <p> * And the body of the composed <code>normalizedOrSame</code> method is: * </p> * * <pre class="stHighlight"> * uniformityPassedToAnd.normalizedOrSame(uniformityOnWhichAndWasInvoked.normalizedOrSame(a)) * </pre> * * <p> * The <code>normalizeCanHandle</code> method of the <code>Uniformity</code> returned by this method returns a result * obtained by anding the result of forwarding the passed value to this <code>Uniformity</code>'s implementation of the method * with the result of forwarding it to the passed <code>Uniformity</code>'s implementation. * Essentially, the body of the composed <code>normalizeCanHandle</code> method is: * </p> * * <pre class="stHighlight"> * uniformityOnWhichAndWasInvoked.normalizeCanHandle(a) &amp;&amp; uniformityPassedToAnd.normalizeCanHandle(a) * </pre> * * @param other a <code>Uniformity</code> to 'and' with this one * @return a <code>Uniformity</code> representing the composition of this and the passed <code>Uniformity</code> */ final def and(other: Uniformity[A]): Uniformity[A] = new Uniformity[A] { // Note in Scaladoc what order, and recommend people don't do side effects anyway. // By order, I mean left's normalized gets called first then right's normalized gets called on that result, for "left and right" def normalized(a: A): A = other.normalized(thisUniformity.normalized(a)) def normalizedCanHandle(b: Any): Boolean = other.normalizedCanHandle(b) && thisUniformity.normalizedCanHandle(b) def normalizedOrSame(b: Any): Any = other.normalizedOrSame(thisUniformity.normalizedOrSame(b)) } /** * Converts this <code>Uniformity</code> to a <code>NormalizingEquality[A]</code> whose <code>normalized</code>, * <code>normalizedCanHandle</code>, and <code>normalizedOrSame</code> methods delegate * to this <code>Uniformity[A]</code> and whose <code>afterNormalizationEquality</code> field returns the * implicitly passed <code>Equality[A]</code>. * * @param equality the <code>Equality</code> that the returned <code>NormalizingEquality</code> * will delegate to determine equality after normalizing both left and right (if appropriate) sides. */ final def toEquality(implicit equality: Equality[A]): NormalizingEquality[A] = new NormalizingEquality[A] { override val afterNormalizationEquality = equality def normalized(a: A): A = thisUniformity.normalized(a) def normalizedCanHandle(b: Any): Boolean = thisUniformity.normalizedCanHandle(b) def normalizedOrSame(b: Any): Any = thisUniformity.normalizedOrSame(b) } final def toHashingEquality(implicit equality: Equality[A]): NormalizingHashingEquality[A] = new NormalizingHashingEquality[A] { override val afterNormalizationEquality = equality def normalized(a: A): A = thisUniformity.normalized(a) def normalizedCanHandle(b: Any): Boolean = thisUniformity.normalizedCanHandle(b) def normalizedOrSame(b: Any): Any = thisUniformity.normalizedOrSame(b) override def toString: String = s"NormalizingHashingEquality(${thisUniformity})" } final def toOrderingEquality(implicit orderingEquality: OrderingEquality[A]): NormalizingOrderingEquality[A] = new NormalizingOrderingEquality[A](orderingEquality) { def normalized(a: A): A = thisUniformity.normalized(a) def normalizedCanHandle(b: Any): Boolean = thisUniformity.normalizedCanHandle(b) def normalizedOrSame(b: Any): Any = thisUniformity.normalizedOrSame(b) override def toString: String = s"NormalizingOrderingEquality(${thisUniformity})" } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/OutcomeOf.scala
<gh_stars>1-10 /* * 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 /** * Trait that contains the <code>outcomeOf</code> method, which executes a passed code block and * transforms the outcome into an <a href="Outcome.html"><code>Outcome</code></a>, using the * same mechanism used by ScalaTest to produce an <code>Outcome</code> when executing * a test. * * <p> * For an example of <code>outcomeOf</code> in action, see the documentation for * class <a href="prop/TableFor2.html"><code>TableFor2</code></a>. * </p> * * @author <NAME> */ trait OutcomeOf { /** * Executes the supplied code (a by-name parameter) and returns an <code>Outcome</code>. * * <p> * Because <code>Error</code>s are used to denote serious errors, ScalaTest does not always treat a test that completes abruptly with * an <code>Error</code> as a test failure, but sometimes as * an indication that serious problems have arisen that should cause the run to abort, and the <code>outcomeOf</code> method exhibits * the same behavior. For example, if a test completes abruptly * with an <code>OutOfMemoryError</code>, it will not be reported as a test failure, but will instead cause the run to abort. * Because not everyone uses <code>Error</code>s only to represent serious problems, however, ScalaTest only behaves this way * for the following exception types (and their subclasses): * </p> * * <ul> * <li><code>java.lang.annotation.AnnotationFormatError</code></li> * <li><code>java.awt.AWTError</code></li> * <li><code>java.nio.charset.CoderMalfunctionError</code></li> * <li><code>javax.xml.parsers.FactoryConfigurationError</code></li> * <li><code>java.lang.LinkageError</code></li> * <li><code>java.lang.ThreadDeath</code></li> * <li><code>javax.xml.transform.TransformerFactoryConfigurationError</code></li> * <li><code>java.lang.VirtualMachineError</code></li> * </ul> * * <p> * The previous list includes all <code>Error</code>s that exist as part of Java 1.5 API, excluding <code>java.lang.AssertionError</code>. * If the code supplied to <code>outcomeOf</code> completes abruptly in one of the errors in the previous list, <code>outcomeOf</code> * will not return an <code>Outcome</code>, but rather will complete abruptly with the same exception. * will wrap any other exception thrown by the supplied code in a <code>Some</code> and return it. * </p> * * <p> * The <code>outcomeOf</code> method (and ScalaTest in general) does treat a thrown <code>AssertionError</code> as an indication of a test failure and therefore * returns a <code>Failed</code> wrapping the <code>AssertionError</code>. In addition, any other <code>Error</code> that is not an instance of a * type mentioned in the previous list will be caught by the <code>outcomeOf</code> and transformed as follows: * * <ul> * <li><a href="exceptions/TestPendingException.html"><code>TestPendingException</code></a></li>: <a href="Pending$.html"><code>Pending</code></a> * <li><a href="exceptions/TestCanceledException.html"><code>TestCanceledException</code></a></li>: <a href="Canceled.html"><code>Canceled</code></a> * <li>otherwise: <a href="Failed.html"><code>Failed</code></a> * </ul> * </p> * * <p> * If the code block completes normally (<em>i.e.</em>, it doesn't throw any exception), <code>outcomeOf</code> results in <a href="Succeeded$.html"><code>Succeeded</code></a>. * </p> * * @param f a block of code to execute * @return an <code>Outcome</code> representing the outcome of executing the block of code */ def outcomeOf(f: => Unit): Outcome = { try { f Succeeded } catch { case ex: exceptions.TestCanceledException => Canceled(ex) case _: exceptions.TestPendingException => Pending case tfe: exceptions.TestFailedException => Failed(tfe) case ex: Throwable if !Suite.anExceptionThatShouldCauseAnAbort(ex) => Failed(ex) } } } /** * Companion object that facilitates the importing of <code>OutcomeOf</code>'s method as * an alternative to mixing it in. One use case is to import <code>OutcomeOf</code>'s method so you can use * it in the Scala interpreter. * * @author <NAME> */ object OutcomeOf extends OutcomeOf
cquiroz/scalatest
scalactic-test/src/test/scala/org/scalactic/NormalizingEqualitySpec.scala
<gh_stars>1-10 /* * 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.scalactic import org.scalatest._ import scala.collection.GenSeq import scala.collection.GenMap import scala.collection.GenSet import scala.collection.GenIterable import scala.collection.GenTraversable import scala.collection.GenTraversableOnce class NormalizedEqualitySpec extends FunSpec with NonImplicitAssertions { final case class StringWrapper(var value: String, var isNormalized: Boolean = false, var equalsWasCalled: Boolean = false) { override def equals(other: Any): Boolean = { equalsWasCalled = true other match { case that: StringWrapper => value == that.value case _ => false } } } class NormalizedStringWrapperEquality extends NormalizingEquality[StringWrapper] { def normalized(sw: StringWrapper): StringWrapper = { sw.value = sw.value.toLowerCase sw.isNormalized = true sw } def normalizedCanHandle(b: Any) = b match { case s: StringWrapper => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case s: StringWrapper => normalized(s) case _ => b } } describe("A NormalizingEquality type class") { it("should call .equals on the left hand object (and not on the right hand object)") { val a = StringWrapper("HowDy") val b = StringWrapper("hoWdY") assert(!a.equalsWasCalled) assert(!b.equalsWasCalled) assert((new NormalizedStringWrapperEquality).areEqual(a, b)) assert(a.equalsWasCalled) assert(!b.equalsWasCalled) } it("should normalize both sides when areEqual is called") { val a = StringWrapper("HowDy") val b = StringWrapper("hoWdY") assert(!a.isNormalized) assert(!b.isNormalized) assert((new NormalizedStringWrapperEquality).areEqual(a, b)) assert(a.isNormalized) assert(b.isNormalized) } it("should call .deep first if left side, right side, or both are Arrays") { class NormalizedArrayOfStringEquality extends NormalizingEquality[Array[String]] { def normalized(arr: Array[String]): Array[String] = arr.map(_.trim.toLowerCase) def normalizedCanHandle(b: Any) = b match { case arr: Array[_] => if (arr.forall(_.isInstanceOf[String])) true else false case _ => false } def normalizedOrSame(b: Any): Any = b match { case arr: Array[_] => if (arr.forall(_.isInstanceOf[String])) normalized(arr.asInstanceOf[Array[String]]) else b case _ => b } } val a = Array(" hi", "ThErE ", "DuDeS ") val b = Array("HI", "there", " dUdEs") val v = Vector("hi", "there", "dudes") assert((new NormalizedArrayOfStringEquality).areEqual(a, v)) assert((new NormalizedArrayOfStringEquality).areEqual(a, b)) } } describe("Normalizations") { it("should be composable with and") { import StringNormalizations._ assert(lowerCased.normalized("HowdY") == "howdy") assert(lowerCased.normalized("HowdY") != "howdy padna!") assert(trimmed.normalized("\nhowdy ") == "howdy") assert(trimmed.normalized("\nHowdY ") != "howdy") assert((trimmed and lowerCased).normalized("\nHowdY ") == "howdy") assert((trimmed and lowerCased).normalized("\nHowdY ") != "rowdy") } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/time/DurationSpec.scala
/* * 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.time import org.scalatest._ import scala.concurrent.duration._ class DurationSpec extends Spec with Matchers { def span(passed: Span): Span = passed def duration(passed: Duration): Duration = passed object `A Span` { def `can be specified with a finite scala.concurrent.Duration via an implicit conversion` { span(100 millis) shouldEqual Span(100, Millis) span(100 nanos) shouldEqual Span(100, Nanoseconds) } def `can be specified with an infinite scala.concurrent.Duration via an implicit conversion` { span(Duration.Inf) shouldEqual Span.Max span(Duration.MinusInf) shouldEqual Span.Zero } def `can be specified with an undefined scala.concurrent.Duration via an implicit conversion` { span(Duration.Undefined) shouldEqual Span.Max } } object `A Duration` { def `can be specified with a Span via an implicit conversion` { duration(Span(100, Millis)) shouldEqual (100 millis) duration(Span(100, Nanoseconds)) shouldEqual (100 nanos) } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/junit/JUnitRunnerSuite.scala
/* * 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.junit { import org.scalatest._ // Put fixture suites in a subpackage, so they won't be discovered by // -m org.scalatest.junit when running the test target for this project. package helpers { import org.junit.runner.RunWith @RunWith(classOf[JUnitRunner]) class EasySuite extends FunSuite { val runCount = 3 val failedCount = 2 val ignoreCount = 1 test("JUnit ran this OK!") { assert(1 === 1) } test("JUnit ran this OK!, but it had a failure we hope") { assert(1 === 2) } test("bla bla bla") { assert(1 === 2) } ignore("I should be ignored") { assert(1 === 2) } } // // Blows up in beforeAll before any tests can be run. // @RunWith(classOf[JUnitRunner]) class KerblooeySuite extends FunSuite with BeforeAndAfterAll { override def beforeAll() { throw new RuntimeException("kerblooey") } val runCount = 0 val failedCount = 1 val ignoreCount = 0 test("JUnit ran this OK!") { assert(1 === 1) } test("JUnit ran this OK!, but it had a failure we hope") { assert(1 === 2) } ignore("I should be ignored") { assert(1 === 2) } } } import org.junit.runner.JUnitCore import org.junit.runner.Description import org.junit.runner.notification.Failure import org.junit.runner.notification.RunNotifier import org.scalatest.junit.helpers.EasySuite import org.scalatest.junit.helpers.KerblooeySuite class JUnitRunnerSuite extends FunSuite { test("That EasySuite gets run by JUnit given its RunWith annotation") { val result = JUnitCore.runClasses(classOf[EasySuite]) val easySuite = new EasySuite assert(result.getRunCount === easySuite.runCount) // EasySuite has 3 tests (excluding the ignored one) assert(result.getFailureCount === easySuite.failedCount) // EasySuite has 2 tests that blow up assert(result.getIgnoreCount === easySuite.ignoreCount) // EasySuite has 1 ignored test } // // This is a regression test for a problem where a failure was // sometimes not reported in Jenkins when a beforeAll method threw // an exception. // // The fix was to catch and report the exception as a failure // from JUnitRunner.run, instead of allowing the exception to // propagate up. // test("a test failure is reported due to an exception thrown from " + "beforeAll when JUnitRunner.run is called directly") { val runNotifier = new RunNotifier { var methodInvocationCount = 0 var passed: Option[Failure] = None override def fireTestFailure(failure: Failure) { methodInvocationCount += 1 passed = Some(failure) } } (new JUnitRunner(classOf[KerblooeySuite])).run(runNotifier) import scala.language.reflectiveCalls assert(runNotifier.methodInvocationCount === 1) assert(runNotifier.passed.get.getDescription.getDisplayName === "org.scalatest.junit.helpers.KerblooeySuite") } // // This test verifies that the fix tested above didn't break the // behavior seen when JUnit calls the JUnitRunner. // test("That a test failure is reported due to an exception thrown from " + "beforeAll when JUnitRunner is called from JUnit") { val result = JUnitCore.runClasses(classOf[KerblooeySuite]) val kerblooeySuite = new KerblooeySuite assert(result.getRunCount === kerblooeySuite.runCount) assert(result.getFailureCount === kerblooeySuite.failedCount) assert(result.getIgnoreCount === kerblooeySuite.ignoreCount) } } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/Equivalence.scala
/* * 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.scalactic /** * Defines a custom way to determine equality for a type when compared with another value of the same type. * * <p> * <code>Equivalence</code> enables you to define alternate notions of equality for types that can be used * with ScalaUtil's <a href="TypeCheckedTripleEquals.html"><code>TypeCheckedTripleEquals</code></a> and * <a href="ConversionCheckedTripleEquals.html"><code>ConversionCheckedTripleEquals</code></a> * traits. These traits can be used to perform equality comparisons with type constraints enforced at * compile time using ScalaUtil's <code>===</code> and <code>!==</code> syntax * and ScalaTest's <code>should</code> <code>===</code> syntax of <code>Matchers</code> trait. * </p> * * <a name="equivalanceLaws"></a> * <h2>Equivalence laws</h2> * * <p> * Instances of <code>Equivalence[T]</code> define an equivalence relation on non-<code>null</code> instance of type <code>T</code> * that must adhere to the following laws (which are consistent with those of <code>equals</code> on <code>java.lang.Object</code>): * </p> * * <ul> * <li><em>reflexivity</em>: for any non-<code>null</code> value <code>x</code>, <code>areEqual(x, x)</code> must return <code>true.</code></li> * <li><em>symmetry</em>: for any non-<code>null</code> values <code>x</code> and <code>y</code>, <code>areEqual(x, y)</code> must return <code>true</code> if and only if <code>areEqual(y, x)</code> returns <code>true</code>.</li> * <li><em>transitivity</em>: for any non-<code>null</code> values <code>x</code>, <code>y</code>, and <code>z</code>, if <code>areEqual(x, y)</code> returns <code>true</code> and <code>areEqual(y, z)</code> returns <code>true</code>, then <code>areEqual(x, z)</code> must return <code>true</code>.</li> * <li><em>consistency</em>: for any non-<code>null</code> values <code>x</code> and <code>y</code>, multiple invocations of <code>areEqual(x, y)</code> consistently return <code>true</code> or consistently return <code>false</code>, provided no information used in the equality comparison on the objects is modified.</li> * <li><em>right-null</em>: For any non-<code>null</code> value <code>x</code>, <code>areEqual(x, null)</code> must return <code>false</code>.</li> * <li><em>left-null</em>: For any non-<code>null</code> value <code>x</code>, <code>areEqual(null, x)</code> must return <code>false</code>.</li> * <li><em>both-null</em>: <code>areEqual(null, null)</code> must return <code>true</code>.</li> * </ul> * * <a name="equivalenceAndEquality"></a> * <h2>Equivalence and equality</h2> * * <p> * Because <a href="Equality.html"><code>Equality</code></a> extends <code>Equivalence</code>, you automatically * define an <code>Equivalence[T]</code> when you define an <code>Equality[T]</code>. Most often you will usually * want to define custom <code>Equality</code>s, because they will be more generally useful: they are also * used by Scalactic's <a href="TripleEquals.html"><code>TripleEquals</code></a> trait and ScalaTest's * <code>equal</code>, <code>be</code>, and <code>contain</code> matcher syntax. However, if you really want * just an <code>Equivalence</code>, and writing an <code>Equality</code> is inconvenient, you can write * an <code>Equivalence</code> directly for a type. * </p> * * <p> * For example, say you have a case class that includes a <code>Double</code> value: * </p> * * <pre class="stREPL"> * scala&gt; case class Person(name: String, age: Double) * defined class Person * </pre> * * <p> * Imagine you are calculating the <code>age</code> values in such as way that occasionally tests * are failing because of rounding differences that you actually don't care about. For example, you * expect an age of 29.0, but you're sometimes seeing 29.0001: * </p> * * <pre class="stREPL"> * scala&gt; import org.scalactic._ * import org.scalactic._ * * scala&gt; import TypeCheckedTripleEquals._ * import TypeCheckedTripleEquals._ * * scala&gt; Person("Joe", 29.0001) === Person("Joe", 29.0) * res0: Boolean = false * </pre> * * <p> * The <code>===</code> operator of <code>TypeCheckedTripleEquals</code> looks for an implicit * <code>Equivalence[SUPER]</code>, where <code>SUPER</code> is either the left-hand or right-hand type, whichever * one is a supertype of the other. In this case, both sides are <code>Person</code> (which is considered a supertype of * itself), so the compiler will look for an <code>Equivalence[Person]</code>. * Because you didn't specifically provide an implicit <code>Equivalence[Person]</code>, <code>===</code> will fall back on * <a href="Equality.html#defaultEquality">default equality</a>, because an <code>Equality[Person]</code> <em>is-an</em> * <code>Equivalence[Person]</code>. The default <code>Equality[Person]</code> will call <code>Person</code>'s * <code>equals</code> method. That <code>equals</code> method, provided by the Scala compiler * because <code>Person</code> is a case class, will declare these two objects unequal because 29.001 does not * exactly equal 29.0. * </p> * * <p> * To make the equality check more forgiving, you could define an implicit <code>Equivalence[Person]</code> that compares * the <code>age</code> <code>Double</code>s with a tolerance, like this: * </p> * * <pre class="stREPL"> * scala&gt; import Tolerance._ * import Tolerance._ * * scala&gt; implicit val personEq = * | new Equivalence[Person] { * | def areEquivalent(a: Person, b: Person): Boolean = * | a.name == b.name &amp;&amp; a.age === b.age +- 0.0002 * | } * personEq: org.scalactic.Equivalence[Person] = $anon$1@7892bd8 * </pre> * * <p> * Now the <code>===</code> operator will use your more forgiving <code>Equivalence[Person]</code> for the * equality check instead of default equality: * </p> * * <pre class="stREPL"> * scala&gt; Person("Joe", 29.0001) === Person("Joe", 29.0) * res1: Boolean = true * </pre> * */ trait Equivalence[T] { /** * Indicates whether the objects passed as <code>a</code> and <code>b</code> are equal. * * <p> * Note: this <code>areEquivalent</code> method means essentially the same thing as the <code>areEqual</code> method * of trait <a href="Equality.html"><code>Equality</code></a>, the difference only being the static type of the * right-hand value. This method is named <code>areEquivalent</code> instead * of <code>areEqual</code> so that it can be implemented in terms of <code>areEqual</code> in trait * <code>Equality</code> (which extends <code>Equivalence</code>). * </p> * * @param a a left-hand-side object being compared with another (right-hand-side one) for equality (<em>e.g.</em>, <code>a == b</code>) * @param b a right-hand-side object being compared with another (left-hand-side one) for equality (<em>e.g.</em>, <code>a == b</code>) * @return true if the passed objects are "equal," as defined by this <code>Equivalence</code> instance */ def areEquivalent(a: T, b: T): Boolean } /** * Companion object for trait <code>Equivalence</code> that provides a factory method for producing * default <code>Equivalence</code> instances. */ object Equivalence { /** * Provides default <code>Equivalence</code> implementations for the specified type whose * <code>areEqual</code> method first calls <code>.deep</code> on any <code>Array</code> (on either the left or right side), * then compares the resulting objects with <code>==</code>. * * @return a default <code>Equivalence[T]</code> */ implicit def default[T]: Equivalence[T] = Equality.default[T] }
cquiroz/scalatest
scalactic-test/src/test/scala/org/scalactic/CooperativeEqualitySpec.scala
/* * Copyright 2001-2014 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.scalactic import org.scalatest._ class CooperativeEqualitySpec extends Spec with Matchers with NonImplicitAssertions { object `Two Options` { object `when cooperative Equality instances are defined for both element types` { implicit val intEquality = new Equality[Int] { def areEqual(a: Int, b: Any): Boolean = b match { case complex: Complex => complex.imaginary == 0 && complex.real == a case simple => simple == a } } implicit val complexEquality = new Equality[Complex] { def areEqual(a: Complex, b: Any): Boolean = b match { case int: Int => a.imaginary == 0 && a.real == int case other => other == a } } implicit val enabler = EnabledEqualityBetween[Int, Complex] // This is a sanity check, a test to make sure the test is testing what // I think it is testing def `should be comparable under Checked- and EnabledEquality outside of Options` { // New policies // Both sides Some new UncheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new CheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new EnabledEquality { 42 shouldEqual Complex(42.0, 0.0) } // Both sides Option new UncheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new CheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new EnabledEquality { 42 shouldEqual Complex(42.0, 0.0) } // Left side Some, right side Option new UncheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new CheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new EnabledEquality { 42 shouldEqual Complex(42.0, 0.0) } // Left side Option, right side Some new UncheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new CheckedEquality { 42 shouldEqual Complex(42.0, 0.0) } new EnabledEquality { 42 shouldEqual Complex(42.0, 0.0) } // Deprecated policies // Both sides Some new TripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new TypeCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new ConversionCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } // Both sides Option new TripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new TypeCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new ConversionCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } // Left side Some, right side Option new TripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new TypeCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new ConversionCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } // Left side Option, right side Some new TripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new TypeCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } new ConversionCheckedTripleEquals { 42 shouldEqual Complex(42.0, 0.0) } } def `should not by default be comparable under Checked- and EnabledEquality` { // New policies // Both sides Some new UncheckedEquality { Some(42) should not equal Some(Complex(42.0, 0.0)) } "new CheckedEquality { Some(42) shouldEqual Some(Complex(42.0, 0.0)) }" shouldNot typeCheck "new EnabledEquality { Some(42) shouldEqual Some(Complex(42.0, 0.0)) }" shouldNot typeCheck // Both sides Option new UncheckedEquality { Option(42) should not equal Option(Complex(42.0, 0.0)) } "new CheckedEquality { Option(42) shouldEqual Option(Complex(42.0, 0.0)) }" shouldNot typeCheck "new EnabledEquality { Option(42) shouldEqual Option(Complex(42.0, 0.0)) }" shouldNot typeCheck // Left side Some, right side Option new UncheckedEquality { Some(42) should not equal Option(Complex(42.0, 0.0)) } "new CheckedEquality { Some(42) shouldEqual Option(Complex(42.0, 0.0)) }" shouldNot typeCheck "new EnabledEquality { Some(42) shouldEqual Option(Complex(42.0, 0.0)) }" shouldNot typeCheck // Left side Option, right side Some new UncheckedEquality { Option(42) should not equal Some(Complex(42.0, 0.0)) } "new CheckedEquality { Option(42) shouldEqual Some(Complex(42.0, 0.0)) }" shouldNot typeCheck "new EnabledEquality { Option(42) shouldEqual Some(Complex(42.0, 0.0)) }" shouldNot typeCheck import AsMethods._ new CheckedEquality { Option(42.as[Complex]) shouldEqual Some(Complex(42.0, 0.0)) } "new EnabledEquality { Option(42.as[Complex]) shouldEqual Some(Complex(42.0, 0.0)) }" shouldNot typeCheck implicit val enableComplexComparisons = EnabledEqualityFor[Complex] new EnabledEquality { Option(42.as[Complex]) shouldEqual Some(Complex(42.0, 0.0)) } // Deprecated policies // Both sides Some new TripleEquals { Some(42) should not equal Some(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Some(42) should not equal Some(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Some(42) should not equal Some(Complex(42.0, 0.0)) } // Both sides Option new TripleEquals { Option(42) should not equal Option(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Option(42) should not equal Option(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Option(42) should not equal Option(Complex(42.0, 0.0)) } // Left side Some, right side Option new TripleEquals { Some(42) should not equal Option(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Some(42) should not equal Option(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Some(42) should not equal Option(Complex(42.0, 0.0)) } // Left side Option, right side Some new TripleEquals { Option(42) should not equal Some(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Option(42) should not equal Some(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Option(42) should not equal Some(Complex(42.0, 0.0)) } } def `should be comparable under Checked- and EnabledEquality if also under RecursiveOptionEquality` { import RecursiveOptionEquality._ // New policies // Both sides Some new UncheckedEquality { Some(42) shouldEqual Some(Complex(42.0, 0.0)) } new CheckedEquality { Some(42) shouldEqual Some(Complex(42.0, 0.0)) } new EnabledEquality { Some(42) shouldEqual Some(Complex(42.0, 0.0)) } // Both sides Option new UncheckedEquality { Option(42) shouldEqual Option(Complex(42.0, 0.0)) } new CheckedEquality { Option(42) shouldEqual Option(Complex(42.0, 0.0)) } new EnabledEquality { Option(42) shouldEqual Option(Complex(42.0, 0.0)) } // Left side Some, right side Option new UncheckedEquality { Some(42) shouldEqual Option(Complex(42.0, 0.0)) } new CheckedEquality { Some(42) shouldEqual Option(Complex(42.0, 0.0)) } new EnabledEquality { Some(42) shouldEqual Option(Complex(42.0, 0.0)) } // Left side Option, right side Some new UncheckedEquality { Option(42) shouldEqual Some(Complex(42.0, 0.0)) } new CheckedEquality { Option(42) shouldEqual Some(Complex(42.0, 0.0)) } new EnabledEquality { Option(42) shouldEqual Some(Complex(42.0, 0.0)) } // Deprecated policies // Both sides Some new TripleEquals { Some(42) shouldEqual Some(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Some(42) shouldEqual Some(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Some(42) shouldEqual Some(Complex(42.0, 0.0)) } // Both sides Option new TripleEquals { Option(42) shouldEqual Option(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Option(42) shouldEqual Option(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Option(42) shouldEqual Option(Complex(42.0, 0.0)) } // Left side Some, right side Option new TripleEquals { Some(42) shouldEqual Option(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Some(42) shouldEqual Option(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Some(42) shouldEqual Option(Complex(42.0, 0.0)) } // Left side Option, right side Some new TripleEquals { Option(42) shouldEqual Some(Complex(42.0, 0.0)) } new TypeCheckedTripleEquals { Option(42) shouldEqual Some(Complex(42.0, 0.0)) } new ConversionCheckedTripleEquals { Option(42) shouldEqual Some(Complex(42.0, 0.0)) } } } } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/EnabledEqualityFor.scala
<reponame>cquiroz/scalatest /* * Copyright 2001-2014 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.scalactic import scala.language.higherKinds class EnabledEqualityFor[A] object EnabledEqualityFor { implicit val strEqEn: EnabledEqualityFor[String] = new EnabledEqualityFor[String] implicit def enabledEqualityForTuple2[A, B]: EnabledEqualityFor[Tuple2[A, B]] = EnabledEqualityFor[Tuple2[A, B]] /* implicit def enabledEqualityForJavaMapEntry[A, B]: EnabledEqualityFor[java.util.Map.Entry[A, B]] = EnabledEqualityFor[java.util.Map.Entry[A, B]] implicit def enabledEqualityForScalaTestJavaMapEntry[A, B]: EnabledEqualityFor[org.scalatest.Entry[A, B]] = EnabledEqualityFor[org.scalatest.Entry[A, B]] // implicit def enabledEqualityForJavaMapEntry[A, B, ENTRY[a, b] <: java.util.Map.Entry[a, b]]: EnabledEqualityFor[ENTRY[A, B]] = EnabledEqualityFor[ENTRY[A, B]] */ def apply[A]: EnabledEqualityFor[A] = new EnabledEqualityFor[A] }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/InOrderContainMatcherDeciderSpec.scala
/* * 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 import org.scalactic.Equality import org.scalactic.Explicitly import org.scalactic.StringNormalizations import org.scalactic.Uniformity import collection.GenTraversable import SharedHelpers._ import Matchers._ import StringNormalizations._ class InOrderContainMatcherDeciderSpec extends Spec with Explicitly { val mapTrimmed: Uniformity[(Int, String)] = new Uniformity[(Int, String)] { def normalized(s: (Int, String)): (Int, String) = (s._1, s._2.trim) def normalizedCanHandle(b: Any) = b match { case (_: Int, _: String) => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case (k: Int, v: String) => normalized((k, v)) case _ => b } } val incremented: Uniformity[Int] = new Uniformity[Int] { var count = 0 def normalized(s: Int): Int = { count += 1 s + count } def normalizedCanHandle(b: Any) = b.isInstanceOf[Int] def normalizedOrSame(b: Any): Any = b match { case i: Int => normalized(i) case _ => b } } val mapIncremented: Uniformity[(Int, String)] = new Uniformity[(Int, String)] { var count = 0 def normalized(s: (Int, String)): (Int, String) = { count += 1 (s._1 + count, s._2) } def normalizedCanHandle(b: Any) = b match { case (_: Int, _: String) => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case (k: Int, v: String) => normalized((k, v)) case _ => b } } val appended: Uniformity[String] = new Uniformity[String] { var count = 0 def normalized(s: String): String = { count += 1 s + count } def normalizedCanHandle(b: Any) = b match { case _: String => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case s: String => normalized(s) case _ => b } } class Translated(map: Map[String, String]) extends Uniformity[String] { def normalized(s: String): String = map.get(s) match { case Some(translated) => translated case None => s } def normalizedCanHandle(b: Any) = b match { case _: String => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case s: String => normalized(s) case _ => b } } val lowerCaseEquality = new Equality[String] { def areEqual(left: String, right: Any) = left.toLowerCase == (right match { case s: String => s.toLowerCase case other => other }) } val reverseEquality = new Equality[String] { def areEqual(left: String, right: Any) = left.reverse == (right match { case s: String => s.toLowerCase case other => other }) } object `inOrder ` { def checkShouldContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) { val leftText = FailureMessages.decorateToStringValue(left) e.message should be (Some(leftText + " did not contain all of (" + right.map(FailureMessages.decorateToStringValue).mkString(", ") + ") in order")) e.failedCodeFileName should be (Some("InOrderContainMatcherDeciderSpec.scala")) e.failedCodeLineNumber should be (Some(lineNumber)) } def checkShouldNotContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) { val leftText = FailureMessages.decorateToStringValue(left) e.message should be (Some(leftText + " contained all of (" + right.map(FailureMessages.decorateToStringValue).mkString(", ") + ") in order")) e.failedCodeFileName should be (Some("InOrderContainMatcherDeciderSpec.scala")) e.failedCodeLineNumber should be (Some(lineNumber)) } def `should take specified equality when 'should contain' is used` { (List("1 ", "2", "3 ") should contain inOrder ("1", "2 ", "3")) (after being trimmed) (Array("1 ", "2", "3 ") should contain inOrder ("1", "2 ", "3")) (after being trimmed) (javaList("1", "2 ", "3") should contain inOrder ("1", "2 ", "3")) (after being trimmed) } def `should take specified equality when 'should not contain' is used` { (List("1 ", "2", "3 ") should not contain inOrder ("1", "2 ", "3")) (after being appended) (Array("1 ", "2", "3 ") should not contain inOrder ("1", "2 ", "3")) (after being appended) (javaList("1 ", "2", "3 ") should not contain inOrder ("1", "2 ", "3")) (after being appended) } def `should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with specified normalization` { val left1 = List("1 ", "2", "3 ") val e1 = intercept[exceptions.TestFailedException] { (left1 should contain inOrder ("1", "2 ", "3")) (after being appended) } checkShouldContainStackDepth(e1, left1, Array("1", "2 ", "3").deep, thisLineNumber - 2) val left2 = Array("1 ", "2", "3 ") val e2 = intercept[exceptions.TestFailedException] { (left2 should contain inOrder ("1", "2 ", "3")) (after being appended) } checkShouldContainStackDepth(e2, left2, Array("1", "2 ", "3").deep, thisLineNumber - 2) val left3 = javaList("1 ", "2", "3 ") val e3 = intercept[exceptions.TestFailedException] { (left3 should contain inOrder ("1", "2 ", "3")) (after being appended) } checkShouldContainStackDepth(e3, left3, Array("1", "2 ", "3").deep, thisLineNumber - 2) } def `should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with specified normalization` { val translated = new Translated(Map("eno" -> "one")) val left1 = List("one", "two", "three") val e1 = intercept[exceptions.TestFailedException] { (left1 should not contain inOrder ("eno", "two", "three")) (after being translated) } checkShouldNotContainStackDepth(e1, left1, Array("eno", "two", "three").deep, thisLineNumber - 2) val left2 = Array("one", "two", "three") val e2 = intercept[exceptions.TestFailedException] { (left2 should not contain inOrder ("eno", "two", "three")) (after being translated) } checkShouldNotContainStackDepth(e2, left2, Array("eno", "two", "three").deep, thisLineNumber - 2) val left3 = javaList("one", "two", "three") val e3 = intercept[exceptions.TestFailedException] { (left3 should not contain inOrder ("eno", "two", "three")) (after being translated) } checkShouldNotContainStackDepth(e3, left3, Array("eno", "two", "three").deep, thisLineNumber - 2) } def `should take specified equality and normalization when 'should contain' is used` { (List("A ", "B", "C ") should contain inOrder ("a", "b ", "c")) (decided by lowerCaseEquality afterBeing trimmed) (Array("A ", "B", "C ") should contain inOrder ("a", "b ", "c")) (decided by lowerCaseEquality afterBeing trimmed) (javaList("A ", "B", "C ") should contain inOrder ("a", "b ", "c")) (decided by lowerCaseEquality afterBeing trimmed) } def `should take specified equality and normalization when 'should not contain' is used` { (List("one ", "two", "three ") should not contain inOrder ("one", "two ", "three")) (decided by reverseEquality afterBeing trimmed) (Array("one ", "two", "three ") should not contain inOrder ("one", "two ", "three")) (decided by reverseEquality afterBeing trimmed) (javaList("one ", "two", "three ") should not contain inOrder ("one", "two ", "three")) (decided by reverseEquality afterBeing trimmed) } def `should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with specified equality and normalization` { val left1 = List("one ", "two", "three ") val e1 = intercept[exceptions.TestFailedException] { (left1 should contain inOrder ("one", "two ", "three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e1, left1, Array("one", "two ", "three").deep, thisLineNumber - 2) val left2 = Array("one ", "two", "three ") val e2 = intercept[exceptions.TestFailedException] { (left2 should contain inOrder ("one", "two ", "three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e2, left2, Array("one", "two ", "three").deep, thisLineNumber - 2) val left3 = javaList("one ", "two", "three ") val e3 = intercept[exceptions.TestFailedException] { (left3 should contain inOrder ("one", "two ", "three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e3, left3, Array("one", "two ", "three").deep, thisLineNumber - 2) } def `should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with specified equality and normalization` { val left1 = List("one ", "two", "three ") val e1 = intercept[exceptions.TestFailedException] { (left1 should not contain inOrder ("eno ", "owt", "eerht ")) (decided by reverseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e1, left1, Array("eno ", "owt", "eerht ").deep, thisLineNumber - 2) val left2 = Array("one ", "two", "three ") val e2 = intercept[exceptions.TestFailedException] { (left2 should not contain inOrder ("eno ", "owt", "eerht ")) (decided by reverseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e2, left2, Array("eno ", "owt", "eerht ").deep, thisLineNumber - 2) val left3 = javaList("one ", "two", "three ") val e3 = intercept[exceptions.TestFailedException] { (left3 should not contain inOrder ("eno ", "owt", "eerht ")) (decided by reverseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e3, left3, Array("eno ", "owt", "eerht ").deep, thisLineNumber - 2) } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldFullyMatchSpec.scala
<filename>scalatest-test/src/test/scala/org/scalatest/ShouldFullyMatchSpec.scala /* * 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 import org.scalatest.prop.Checkers import org.scalacheck._ import Arbitrary._ import Prop._ import org.scalatest.exceptions.TestFailedException import SharedHelpers._ import Matchers._ class ShouldFullyMatchSpec extends Spec with Checkers with ReturnsNormallyThrowsAssertion { /* s should include substring t s should include regex t s should startWith substring t s should startWith regex t s should endWith substring t s should endWith regex t s should fullyMatch regex t */ object `The fullyMatch regex syntax` { val decimal = """(-)?(\d+)(\.\d*)?""" val decimalRegex = """(-)?(\d+)(\.\d*)?""".r object `(when the regex is specified by a string)` { def `should do nothing if the string fully matches the regular expression specified as a string` { "1.7" should fullyMatch regex ("1.7") "1.7" should fullyMatch regex (decimal) "-1.8" should fullyMatch regex (decimal) "8" should fullyMatch regex (decimal) "1." should fullyMatch regex (decimal) } def `should do nothing if the string does not fully match the regular expression specified as a string when used with not` { "eight" should not { fullyMatch regex (decimal) } "1.eight" should not { fullyMatch regex (decimal) } "one.8" should not { fullyMatch regex (decimal) } "eight" should not fullyMatch regex (decimal) "1.eight" should not fullyMatch regex (decimal) "one.8" should not fullyMatch regex (decimal) "1.8-" should not fullyMatch regex (decimal) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression` { "1.7" should (fullyMatch regex (decimal) and (fullyMatch regex (decimal))) "1.7" should ((fullyMatch regex (decimal)) and (fullyMatch regex (decimal))) "1.7" should (fullyMatch regex (decimal) and fullyMatch regex (decimal)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression` { "1.7" should (fullyMatch regex ("hello") or (fullyMatch regex (decimal))) "1.7" should ((fullyMatch regex ("hello")) or (fullyMatch regex (decimal))) "1.7" should (fullyMatch regex ("hello") or fullyMatch regex (decimal)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression with not` { "fred" should (not (fullyMatch regex ("bob")) and not (fullyMatch regex (decimal))) "fred" should ((not fullyMatch regex ("bob")) and (not fullyMatch regex (decimal))) "fred" should (not fullyMatch regex ("bob") and not fullyMatch regex (decimal)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression with not` { "fred" should (not (fullyMatch regex ("fred")) or not (fullyMatch regex (decimal))) "fred" should ((not fullyMatch regex ("fred")) or (not fullyMatch regex (decimal))) "fred" should (not fullyMatch regex ("fred") or not fullyMatch regex (decimal)) } def `should throw TestFailedException if the string does not match the regular expression specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("1.78") } assert(caught1.getMessage === "\"1.7\" did not fully match the regular expression 1.78") val caught2 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("21.7") } assert(caught2.getMessage === "\"1.7\" did not fully match the regular expression 21.7") val caught3 = intercept[TestFailedException] { "-1.eight" should fullyMatch regex (decimal) } assert(caught3.getMessage === "\"-1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should fullyMatch regex (decimal) } assert(caught6.getMessage === "\"eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught7 = intercept[TestFailedException] { "1.eight" should fullyMatch regex (decimal) } assert(caught7.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught8 = intercept[TestFailedException] { "one.8" should fullyMatch regex (decimal) } assert(caught8.getMessage === "\"one.8\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught9 = intercept[TestFailedException] { "1.8-" should fullyMatch regex (decimal) } assert(caught9.getMessage === "\"1.8-\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string does matches the regular expression specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex ("1.7") } } assert(caught1.getMessage === "\"1.7\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex (decimal) } } assert(caught2.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { fullyMatch regex (decimal) } } assert(caught3.getMessage === "\"-1.8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { fullyMatch regex (decimal) } } assert(caught4.getMessage === "\"8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { fullyMatch regex (decimal) } } assert(caught5.getMessage === "\"1.\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not fullyMatch regex ("1.7") } assert(caught11.getMessage === "\"1.7\" fully matched the regular expression 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not fullyMatch regex (decimal) } assert(caught12.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not fullyMatch regex (decimal) } assert(caught13.getMessage === "\"-1.8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not fullyMatch regex (decimal) } assert(caught14.getMessage === "\"8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not fullyMatch regex (decimal) } assert(caught15.getMessage === "\"1.\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimal) and (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((fullyMatch regex (decimal)) and (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimal) and fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not fully match the regular expression 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimal) and (fullyMatch regex ("1.8"))) } assert(caught4.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1.eight" should ((fullyMatch regex (decimal)) and (fullyMatch regex ("1.8"))) } assert(caught5.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimal) and fullyMatch regex ("1.8")) } assert(caught6.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimal) or (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\"1.seven\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.seven\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.seven" should ((fullyMatch regex (decimal)) or (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\"1.seven\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.seven\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimal) or fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\"1.seven\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.seven\" did not fully match the regular expression 1.8") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and (not fullyMatch regex (decimal))) } assert(caught1.getMessage === "\"1.7\" did not fully match the regular expression 1.8, but \"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex ("1.8")) and (not fullyMatch regex (decimal))) } assert(caught2.getMessage === "\"1.7\" did not fully match the regular expression 1.8, but \"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and not fullyMatch regex (decimal)) } assert(caught3.getMessage === "\"1.7\" did not fully match the regular expression 1.8, but \"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimal) or (not fullyMatch regex ("1.7"))) } assert(caught1.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex (decimal)) or (not fullyMatch regex ("1.7"))) } assert(caught2.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimal) or not fullyMatch regex ("1.7")) } assert(caught3.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (fullyMatch regex (decimal)) or not (fullyMatch regex ("1.7"))) } assert(caught4.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") } } object `(when the regex is specifed by a string and with group)` { object `(when used with should)` { def `should do nothing if the string fully matches the regular expression and with group as specified` { "abbc" should fullyMatch regex ("a(b*)c" withGroup "bb") "abbcc" should fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bb") and (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should ((fullyMatch regex ("a(b*)c" withGroup "bb")) and (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bb") and fullyMatch regex ("a(b*)c" withGroup "bb")) "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) and fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbc" should (equal ("abbc") and (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should ((equal ("abbc")) and (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should (equal ("abbc") and fullyMatch regex ("a(b*)c" withGroup "bb")) "abbcc" should (equal ("abbcc") and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((equal ("abbcc")) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (equal ("abbcc") and fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") or (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should ((fullyMatch regex ("a(b*)c" withGroup "bbb")) or (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") or fullyMatch regex ("a(b*)c" withGroup "bb")) "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bbb", "cc")) or (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((fullyMatch regex ("a(b*)(c*)" withGroups ("bbb", "cc"))) or (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bbb", "cc")) or fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbc" should (equal ("abbc") or (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should ((equal ("abbc")) or (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbc" should (equal ("abbc") or fullyMatch regex ("a(b*)c" withGroup "bb")) "abbcc" should (equal ("abbc") or (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((equal ("abbc")) or (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (equal ("abbc") or fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } def `should throw TestFailedException if the string fully matches the regular expression but does not match specified group` { val caught1 = intercept[TestFailedException] { "abbbc" should fullyMatch regex ("a(b*)c" withGroup "bb") } assert(caught1.message === Some("\"abbbc\" fully matched the regular expression a(b*)c, but \"bbb\" did not match group bb")) assert(caught1.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccc" should fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) } assert(caught2.message === Some("\"abbccc\" fully matched the regular expression a(b*)(c*), but \"ccc\" did not match group cc at index 1")) assert(caught2.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bb") and (fullyMatch regex ("a(b*)c" withGroup "bbb"))) } assert(caught3.getMessage === "\"abbc\" fully matched the regular expression a(b*)c and group bb, but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught3.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c" withGroup "bb")) and (fullyMatch regex ("a(b*)c" withGroup "bbb"))) } assert(caught4.getMessage === "\"abbc\" fully matched the regular expression a(b*)c and group bb, but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught4.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bb") and fullyMatch regex ("a(b*)c" withGroup "bbb")) } assert(caught5.getMessage === "\"abbc\" fully matched the regular expression a(b*)c and group bb, but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught5.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught6 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") and fullyMatch regex ("a(b*)c" withGroup "bbbb")) } assert(caught6.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught6.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c" withGroup "bbb")) and (fullyMatch regex ("a(b*)c" withGroup "bbb"))) } assert(caught7.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught7.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") and fullyMatch regex ("a(b*)c" withGroup "bbbb")) } assert(caught8.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught8.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught9.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc, but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught9.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught10.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc, but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught10.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) and fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught11.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc, but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught11.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught12 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc"))) } assert(caught12.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught12.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) } assert(caught13.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught13.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc"))) } assert(caught14.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught14.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") or (fullyMatch regex ("a(b*)c" withGroup "bbbb"))) } assert(caught15.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught15.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c" withGroup "bbb")) or (fullyMatch regex ("a(b*)c" withGroup "bbbb"))) } assert(caught16.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught16.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught17 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") or fullyMatch regex ("a(b*)c" withGroup "bbbb")) } assert(caught17.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught17.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught17.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught18 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) } assert(caught18.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught18.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught18.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught19 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) or (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) } assert(caught19.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught19.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught19.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught20 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc"))) } assert(caught20.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught20.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught20.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught21 = intercept[TestFailedException] { "abbc" should (equal ("abbc") and (fullyMatch regex ("a(b*)c" withGroup "bbb"))) } assert(caught21.getMessage === "\"abbc\" equaled \"abbc\", but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught21.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught21.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught22 = intercept[TestFailedException] { "abbc" should ((equal ("abbc")) and (fullyMatch regex ("a(b*)c" withGroup "bbb"))) } assert(caught22.getMessage === "\"abbc\" equaled \"abbc\", but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught22.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught22.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught23 = intercept[TestFailedException] { "abbc" should (equal ("abbc") and fullyMatch regex ("a(b*)c" withGroup "bbb")) } assert(caught23.getMessage === "\"abbc\" equaled \"abbc\", but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught23.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught23.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught24 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") and (equal ("abbc"))) } assert(caught24.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught24.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught24.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught25 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c" withGroup "bbb")) and (equal ("abbc"))) } assert(caught25.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught25.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught25.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught26 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c" withGroup "bbb") and equal ("abbc")) } assert(caught26.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught26.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught26.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught27 = intercept[TestFailedException] { "abbcc" should (equal ("abbcc") and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught27.getMessage === "\"abbcc\" equaled \"abbcc\", but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught27.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught27.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught28 = intercept[TestFailedException] { "abbcc" should ((equal ("abbcc")) and (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught28.getMessage === "\"abbcc\" equaled \"abbcc\", but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught28.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught28.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught29 = intercept[TestFailedException] { "abbcc" should (equal ("abbcc") and fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught29.getMessage === "\"abbcc\" equaled \"abbcc\", but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught29.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught29.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught30 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (equal ("abbcc"))) } assert(caught30.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught30.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught30.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught31 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (equal ("abbcc"))) } assert(caught31.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught31.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught31.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught32 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and equal ("abbcc")) } assert(caught32.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught32.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught32.failedCodeLineNumber === Some(thisLineNumber - 4)) } } object `(when used with should not)` { def `should do nothing if the string does not fully match the regular expression and with group as specified` { "abbbc" should not { fullyMatch regex ("a(b*)c" withGroup "bb") } "abbbc" should not fullyMatch regex ("a(b*)c" withGroup "bb") "abbccc" should not { fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) } "abbccc" should not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) "abbbc" should (not (fullyMatch regex ("a(b*)c" withGroup "bb")) and not (fullyMatch regex ("a(b*)c" withGroup "bbbb"))) "abbbc" should ((not fullyMatch regex ("a(b*)c" withGroup "bb")) and (not fullyMatch regex ("a(b*)c" withGroup "bbbb"))) "abbbc" should (not fullyMatch regex ("a(b*)c" withGroup "bb") and not fullyMatch regex ("a(b*)c" withGroup "bbbb")) "abbccc" should (not (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and not (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) "abbccc" should ((not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) "abbccc" should (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) and not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc"))) "abbbc" should (not (fullyMatch regex ("a(b*)c" withGroup "bbb")) or not (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbbc" should ((not fullyMatch regex ("a(b*)c" withGroup "bbb")) or (not fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbbc" should (not fullyMatch regex ("a(b*)c" withGroup "bbb") or not fullyMatch regex ("a(b*)c" withGroup "bb")) "abbbc" should (not (equal ("abbcc")) and not (fullyMatch regex ("a(b*)c" withGroup "bbbb"))) "abbbc" should ((not equal "abbcc") and (not fullyMatch regex ("a(b*)c" withGroup "bbbb"))) "abbbc" should (not equal "abbcc" and not fullyMatch regex ("a(b*)c" withGroup "bbbb")) "abbccc" should (not (equal ("abbcc")) and not (fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) "abbccc" should ((not equal ("abbcc")) and (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc")))) "abbccc" should (not equal ("abbcc") and not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cccc"))) "abbbc" should (not (equal ("abbbc")) or not (fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbbc" should ((not equal ("abbbc")) or (not fullyMatch regex ("a(b*)c" withGroup "bb"))) "abbbc" should (not equal ("abbbc") or not fullyMatch regex ("a(b*)c" withGroup "bb")) } def `should throw TestFailedException if the string fully matches the regular expression and with group as specified` { val caught1 = intercept[TestFailedException] { "abbc" should not { fullyMatch regex ("a(b*)c" withGroup "bb") } } assert(caught1.message === Some("\"abbc\" fully matched the regular expression a(b*)c and group bb")) assert(caught1.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbc" should not fullyMatch regex ("a(b*)c" withGroup "bb") } assert(caught2.message === Some("\"abbc\" fully matched the regular expression a(b*)c and group bb")) assert(caught2.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcc" should not { fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) } } assert(caught3.message === Some("\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc")) assert(caught3.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcc" should not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")) } assert(caught4.message === Some("\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc")) assert(caught4.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbc" should (not fullyMatch regex ("a(b*)c" withGroup "bbb") and (not fullyMatch regex ("a(b*)c" withGroup "bb"))) } assert(caught5.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught5.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbc" should ((not fullyMatch regex ("a(b*)c" withGroup "bbb")) and (not fullyMatch regex ("a(b*)c" withGroup "bb"))) } assert(caught6.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught6.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbc" should (not fullyMatch regex ("a(b*)c" withGroup "bbb") and not fullyMatch regex ("a(b*)c" withGroup "bb")) } assert(caught7.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught7.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbcc" should (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught8.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught8.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbcc" should ((not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught9.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught9.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abbcc" should (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught10.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught10.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbc" should (not equal ("abbcc") and (not fullyMatch regex ("a(b*)c" withGroup "bb"))) } assert(caught11.getMessage === "\"abbc[]\" did not equal \"abbc[c]\", but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught11.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abbc" should ((not equal ("abbcc")) and (not fullyMatch regex ("a(b*)c" withGroup "bb"))) } assert(caught12.getMessage === "\"abbc[]\" did not equal \"abbc[c]\", but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught12.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abbc" should (not equal ("abbcc") and not fullyMatch regex ("a(b*)c" withGroup "bb")) } assert(caught13.getMessage === "\"abbc[]\" did not equal \"abbc[c]\", but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught13.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "abbcc" should (not equal ("abbccc") and (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught14.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught14.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abbcc" should ((not equal "abbccc") and (not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught15.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught15.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abbcc" should (not equal "abbccc" and not fullyMatch regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught16.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught16.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) } } } object `(when the regex is specified by an actual Regex)` { def `should do nothing if the string fully matches the regular expression specified as a string` { "1.7" should fullyMatch regex ("1.7") "1.7" should fullyMatch regex (decimalRegex) "-1.8" should fullyMatch regex (decimalRegex) "8" should fullyMatch regex (decimalRegex) "1." should fullyMatch regex (decimalRegex) } def `should do nothing if the string does not fully match the regular expression specified as a string when used with not` { "eight" should not { fullyMatch regex (decimalRegex) } "1.eight" should not { fullyMatch regex (decimalRegex) } "one.8" should not { fullyMatch regex (decimalRegex) } "eight" should not fullyMatch regex (decimalRegex) "1.eight" should not fullyMatch regex (decimalRegex) "one.8" should not fullyMatch regex (decimalRegex) "1.8-" should not fullyMatch regex (decimalRegex) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression` { "1.7" should (fullyMatch regex (decimalRegex) and (fullyMatch regex (decimalRegex))) "1.7" should ((fullyMatch regex (decimalRegex)) and (fullyMatch regex (decimalRegex))) "1.7" should (fullyMatch regex (decimalRegex) and fullyMatch regex (decimalRegex)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression` { "1.7" should (fullyMatch regex ("hello") or (fullyMatch regex (decimalRegex))) "1.7" should ((fullyMatch regex ("hello")) or (fullyMatch regex (decimalRegex))) "1.7" should (fullyMatch regex ("hello") or fullyMatch regex (decimalRegex)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression with not` { "fred" should (not (fullyMatch regex ("bob")) and not (fullyMatch regex (decimalRegex))) "fred" should ((not fullyMatch regex ("bob")) and (not fullyMatch regex (decimalRegex))) "fred" should (not fullyMatch regex ("bob") and not fullyMatch regex (decimalRegex)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression with not` { "fred" should (not (fullyMatch regex ("fred")) or not (fullyMatch regex (decimalRegex))) "fred" should ((not fullyMatch regex ("fred")) or (not fullyMatch regex (decimalRegex))) "fred" should (not fullyMatch regex ("fred") or not fullyMatch regex (decimalRegex)) } def `should throw TestFailedException if the string does not match the regular expression specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("1.78") } assert(caught1.getMessage === "\"1.7\" did not fully match the regular expression 1.78") val caught2 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("21.7") } assert(caught2.getMessage === "\"1.7\" did not fully match the regular expression 21.7") val caught3 = intercept[TestFailedException] { "-1.eight" should fullyMatch regex (decimalRegex) } assert(caught3.getMessage === "\"-1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should fullyMatch regex (decimalRegex) } assert(caught6.getMessage === "\"eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught7 = intercept[TestFailedException] { "1.eight" should fullyMatch regex (decimalRegex) } assert(caught7.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught8 = intercept[TestFailedException] { "one.8" should fullyMatch regex (decimalRegex) } assert(caught8.getMessage === "\"one.8\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught9 = intercept[TestFailedException] { "1.8-" should fullyMatch regex (decimalRegex) } assert(caught9.getMessage === "\"1.8-\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string does matches the regular expression specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex ("1.7") } } assert(caught1.getMessage === "\"1.7\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex (decimalRegex) } } assert(caught2.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { fullyMatch regex (decimalRegex) } } assert(caught3.getMessage === "\"-1.8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { fullyMatch regex (decimalRegex) } } assert(caught4.getMessage === "\"8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { fullyMatch regex (decimalRegex) } } assert(caught5.getMessage === "\"1.\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not fullyMatch regex ("1.7") } assert(caught11.getMessage === "\"1.7\" fully matched the regular expression 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not fullyMatch regex (decimalRegex) } assert(caught12.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not fullyMatch regex (decimalRegex) } assert(caught13.getMessage === "\"-1.8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not fullyMatch regex (decimalRegex) } assert(caught14.getMessage === "\"8\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not fullyMatch regex (decimalRegex) } assert(caught15.getMessage === "\"1.\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimalRegex) and (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((fullyMatch regex (decimalRegex)) and (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimalRegex) and fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, but \"1.7\" did not fully match the regular expression 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimalRegex) and (fullyMatch regex ("1.8"))) } assert(caught4.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught5 = intercept[TestFailedException] { "1.eight" should ((fullyMatch regex (decimalRegex)) and (fullyMatch regex ("1.8"))) } assert(caught5.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") val caught6 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimalRegex) and fullyMatch regex ("1.8")) } assert(caught6.getMessage === "\"1.eight\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimalRegex) or (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\"1.seven\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.seven\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.seven" should ((fullyMatch regex (decimalRegex)) or (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\"1.seven\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.seven\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimalRegex) or fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\"1.seven\" did not fully match the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.seven\" did not fully match the regular expression 1.8") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and (not fullyMatch regex (decimalRegex))) } assert(caught1.getMessage === "\"1.7\" did not fully match the regular expression 1.8, but \"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex ("1.8")) and (not fullyMatch regex (decimalRegex))) } assert(caught2.getMessage === "\"1.7\" did not fully match the regular expression 1.8, but \"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and not fullyMatch regex (decimalRegex)) } assert(caught3.getMessage === "\"1.7\" did not fully match the regular expression 1.8, but \"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimalRegex) or (not fullyMatch regex ("1.7"))) } assert(caught1.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex (decimalRegex)) or (not fullyMatch regex ("1.7"))) } assert(caught2.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimalRegex) or not fullyMatch regex ("1.7")) } assert(caught3.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (fullyMatch regex (decimalRegex)) or not (fullyMatch regex ("1.7"))) } assert(caught4.getMessage === "\"1.7\" fully matched the regular expression (-)?(\\d+)(\\.\\d*)?, and \"1.7\" fully matched the regular expression 1.7") } } object `(when the regex is specifed by a actual Regex and with group)` { object `(when used with should)` { def `should do nothing if the string fully matches the regular expression and with group as specified` { "abbc" should fullyMatch regex ("a(b*)c".r withGroup "bb") "abbcc" should fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bb") and (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should ((fullyMatch regex ("a(b*)c".r withGroup "bb")) and (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bb") and fullyMatch regex ("a(b*)c".r withGroup "bb")) "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should ((fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bbb") or (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should ((fullyMatch regex ("a(b*)c".r withGroup "bbb")) or (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bbb") or fullyMatch regex ("a(b*)c".r withGroup "bb")) "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bbb", "cc")) or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should ((fullyMatch regex ("a(b*)(c*)".r withGroups ("bbb", "cc"))) or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bbb", "cc")) or fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) "abbc" should (equal ("abbc") and (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should ((equal ("abbc")) and (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should (equal ("abbc") and fullyMatch regex ("a(b*)c".r withGroup "bb")) "abbcc" should (equal ("abbcc") and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should ((equal ("abbcc")) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should (equal ("abbcc") and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) "abbc" should (equal ("abbbc") or (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should ((equal ("abbbc")) or (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbc" should (equal ("abbbc") or fullyMatch regex ("a(b*)c".r withGroup "bb")) "abbcc" should (equal ("abbbcc") or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should ((equal ("abbbcc")) or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) "abbcc" should (equal ("abbbcc") or fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) } def `should throw TestFailedException if the string fully matches the regular expression but does not match specified group` { val caught1 = intercept[TestFailedException] { "abbbc" should fullyMatch regex ("a(b*)c".r withGroup "bb") } assert(caught1.message === Some("\"abbbc\" fully matched the regular expression a(b*)c, but \"bbb\" did not match group bb")) assert(caught1.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccc" should fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } assert(caught2.message === Some("\"abbccc\" fully matched the regular expression a(b*)(c*), but \"ccc\" did not match group cc at index 1")) assert(caught2.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bb") and (fullyMatch regex ("a(b*)c".r withGroup "bbb"))) } assert(caught3.getMessage === "\"abbc\" fully matched the regular expression a(b*)c and group bb, but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught3.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c".r withGroup "bb")) and (fullyMatch regex ("a(b*)c".r withGroup "bbb"))) } assert(caught4.getMessage === "\"abbc\" fully matched the regular expression a(b*)c and group bb, but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught4.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bb") and fullyMatch regex ("a(b*)c".r withGroup "bbb")) } assert(caught5.getMessage === "\"abbc\" fully matched the regular expression a(b*)c and group bb, but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught5.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught6 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bbb") and fullyMatch regex ("a(b*)c".r withGroup "bbbb")) } assert(caught6.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught6.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c".r withGroup "bbb")) and (fullyMatch regex ("a(b*)c".r withGroup "bbb"))) } assert(caught7.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught7.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bbb") and fullyMatch regex ("a(b*)c".r withGroup "bbbb")) } assert(caught8.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught8.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")))) } assert(caught9.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc, but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught9.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")))) } assert(caught10.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc, but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught10.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc"))) } assert(caught11.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc, but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught11.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught12 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) } assert(caught12.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught12.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc"))) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) } assert(caught13.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught13.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) } assert(caught14.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught14.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bbb") or (fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) } assert(caught15.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught15.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abbc" should ((fullyMatch regex ("a(b*)c".r withGroup "bbb")) or (fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) } assert(caught16.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught16.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught17 = intercept[TestFailedException] { "abbc" should (fullyMatch regex ("a(b*)c".r withGroup "bbb") or fullyMatch regex ("a(b*)c".r withGroup "bbbb")) } assert(caught17.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught17.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught17.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught18 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) } assert(caught18.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught18.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught18.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught19 = intercept[TestFailedException] { "abbcc" should ((fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc"))) or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) } assert(caught19.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught19.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught19.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught20 = intercept[TestFailedException] { "abbcc" should (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) or fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) } assert(caught20.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught20.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught20.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught21 = intercept[TestFailedException] { "abbc" should (equal ("abbc") and (fullyMatch regex ("a(b*)c".r withGroup "bbb"))) } assert(caught21.getMessage === "\"abbc\" equaled \"abbc\", but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught21.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught21.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught22 = intercept[TestFailedException] { "abbc" should ((equal ("abbc")) and (fullyMatch regex ("a(b*)c".r withGroup "bbb"))) } assert(caught22.getMessage === "\"abbc\" equaled \"abbc\", but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught22.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught22.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught23 = intercept[TestFailedException] { "abbc" should (equal ("abbc") and fullyMatch regex ("a(b*)c".r withGroup "bbb")) } assert(caught23.getMessage === "\"abbc\" equaled \"abbc\", but \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb") assert(caught23.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught23.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught24 = intercept[TestFailedException] { "abbc" should (equal ("abbbc") and fullyMatch regex ("a(b*)c".r withGroup "bbbb")) } assert(caught24.getMessage === "\"abb[]c\" did not equal \"abb[b]c\"") assert(caught24.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught24.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught25 = intercept[TestFailedException] { "abbc" should ((equal ("abbbc")) and (fullyMatch regex ("a(b*)c".r withGroup "bbb"))) } assert(caught25.getMessage === "\"abb[]c\" did not equal \"abb[b]c\"") assert(caught25.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught25.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught26 = intercept[TestFailedException] { "abbc" should (equal ("abbbc") and fullyMatch regex ("a(b*)c".r withGroup "bbbb")) } assert(caught26.getMessage === "\"abb[]c\" did not equal \"abb[b]c\"") assert(caught26.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught26.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught27 = intercept[TestFailedException] { "abbcc" should (equal ("abbcc") and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")))) } assert(caught27.getMessage === "\"abbcc\" equaled \"abbcc\", but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught27.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught27.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught28 = intercept[TestFailedException] { "abbcc" should ((equal ("abbcc")) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")))) } assert(caught28.getMessage === "\"abbcc\" equaled \"abbcc\", but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught28.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught28.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught29 = intercept[TestFailedException] { "abbcc" should (equal ("abbcc") and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc"))) } assert(caught29.getMessage === "\"abbcc\" equaled \"abbcc\", but \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1") assert(caught29.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught29.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught30 = intercept[TestFailedException] { "abbcc" should (equal ("abbccc") and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) } assert(caught30.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\"") assert(caught30.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught30.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught31 = intercept[TestFailedException] { "abbcc" should ((equal ("abbccc")) and (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) } assert(caught31.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\"") assert(caught31.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught31.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught32 = intercept[TestFailedException] { "abbcc" should (equal ("abbccc") and fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) } assert(caught32.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\"") assert(caught32.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught32.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught33 = intercept[TestFailedException] { "abbc" should (equal ("abbbc") or (fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) } assert(caught33.getMessage === "\"abb[]c\" did not equal \"abb[b]c\", and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught33.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught33.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught34 = intercept[TestFailedException] { "abbc" should ((equal ("abbbc")) or (fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) } assert(caught34.getMessage === "\"abb[]c\" did not equal \"abb[b]c\", and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught34.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught34.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught35 = intercept[TestFailedException] { "abbc" should (equal ("abbbc") or fullyMatch regex ("a(b*)c".r withGroup "bbbb")) } assert(caught35.getMessage === "\"abb[]c\" did not equal \"abb[b]c\", and \"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbbb") assert(caught35.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught35.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught36 = intercept[TestFailedException] { "abbcc" should (equal ("abbccc") or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) } assert(caught36.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught36.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught36.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught37 = intercept[TestFailedException] { "abbcc" should ((equal ("abbccc")) or (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) } assert(caught37.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught37.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught37.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught38 = intercept[TestFailedException] { "abbcc" should (equal ("abbccc") or fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) } assert(caught38.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", and \"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group cccc at index 1") assert(caught38.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught38.failedCodeLineNumber === Some(thisLineNumber - 4)) } } object `(when used with should not)` { def `should do nothing if the string does not fully match the regular expression and with group as specified` { "abbbc" should not { fullyMatch regex ("a(b*)c".r withGroup "bb") } "abbbc" should not fullyMatch regex ("a(b*)c".r withGroup "bb") "abbccc" should not { fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } "abbccc" should not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) "abbbc" should (not (fullyMatch regex ("a(b*)c".r withGroup "bb")) and not (fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) "abbbc" should ((not fullyMatch regex ("a(b*)c".r withGroup "bb")) and (not fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) "abbbc" should (not fullyMatch regex ("a(b*)c".r withGroup "bb") and not fullyMatch regex ("a(b*)c".r withGroup "bbbb")) "abbccc" should (not (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) and not (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) "abbccc" should ((not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) and (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) "abbccc" should (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) and not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) "abbbc" should (not (fullyMatch regex ("a(b*)c".r withGroup "bbb")) or not (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbbc" should ((not fullyMatch regex ("a(b*)c".r withGroup "bbb")) or (not fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbbc" should (not fullyMatch regex ("a(b*)c".r withGroup "bbb") or not fullyMatch regex ("a(b*)c".r withGroup "bb")) "abbbc" should (not (equal ("abbc")) and not (fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) "abbbc" should ((not equal ("abbc")) and (not fullyMatch regex ("a(b*)c".r withGroup "bbbb"))) "abbbc" should (not equal ("abbc") and not fullyMatch regex ("a(b*)c".r withGroup "bbbb")) "abbccc" should (not (equal ("abbcc")) and not (fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) "abbccc" should ((not equal ("abbcc")) and (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc")))) "abbccc" should (not equal ("abbcc") and not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cccc"))) "abbbc" should (not (equal ("abbbc")) or not (fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbbc" should ((not equal ("abbbc")) or (not fullyMatch regex ("a(b*)c".r withGroup "bb"))) "abbbc" should (not equal ("abbbc") or not fullyMatch regex ("a(b*)c".r withGroup "bb")) } def `should throw TestFailedException if the string fully matches the regular expression and with group as specified` { val caught1 = intercept[TestFailedException] { "abbc" should not { fullyMatch regex ("a(b*)c".r withGroup "bb") } } assert(caught1.message === Some("\"abbc\" fully matched the regular expression a(b*)c and group bb")) assert(caught1.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbc" should not fullyMatch regex ("a(b*)c".r withGroup "bb") } assert(caught2.message === Some("\"abbc\" fully matched the regular expression a(b*)c and group bb")) assert(caught2.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcc" should not { fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } } assert(caught3.message === Some("\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc")) assert(caught3.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcc" should not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } assert(caught4.message === Some("\"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc")) assert(caught4.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbc" should (not fullyMatch regex ("a(b*)c".r withGroup "bbb") and (not fullyMatch regex ("a(b*)c".r withGroup "bb"))) } assert(caught5.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught5.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbc" should ((not fullyMatch regex ("a(b*)c".r withGroup "bbb")) and (not fullyMatch regex ("a(b*)c".r withGroup "bb"))) } assert(caught6.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught6.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbc" should (not fullyMatch regex ("a(b*)c".r withGroup "bbb") and not fullyMatch regex ("a(b*)c".r withGroup "bb")) } assert(caught7.getMessage === "\"abbc\" fully matched the regular expression a(b*)c, but \"bb\" did not match group bbb, but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught7.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbcc" should (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) and (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) } assert(caught8.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught8.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbcc" should ((not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc"))) and (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) } assert(caught9.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught9.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught10 = intercept[TestFailedException] { "abbcc" should (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) and not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) } assert(caught10.getMessage === "\"abbcc\" fully matched the regular expression a(b*)(c*), but \"cc\" did not match group ccc at index 1, but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught10.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbc" should (not equal ("abbbc") and (not fullyMatch regex ("a(b*)c".r withGroup "bb"))) } assert(caught11.getMessage === "\"abb[]c\" did not equal \"abb[b]c\", but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught11.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abbc" should ((not equal ("abbbc")) and (not fullyMatch regex ("a(b*)c".r withGroup "bb"))) } assert(caught12.getMessage === "\"abb[]c\" did not equal \"abb[b]c\", but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught12.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught13 = intercept[TestFailedException] { "abbc" should (not equal ("abbbc") and not fullyMatch regex ("a(b*)c".r withGroup "bb")) } assert(caught13.getMessage === "\"abb[]c\" did not equal \"abb[b]c\", but \"abbc\" fully matched the regular expression a(b*)c and group bb") assert(caught13.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught14 = intercept[TestFailedException] { "abbcc" should (not equal ("abbccc") and (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) } assert(caught14.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught14.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught15 = intercept[TestFailedException] { "abbcc" should ((not equal ("abbccc")) and (not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc")))) } assert(caught15.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught15.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught16 = intercept[TestFailedException] { "abbcc" should (not equal ("abbccc") and not fullyMatch regex ("a(b*)(c*)".r withGroups ("bb", "cc"))) } assert(caught16.getMessage === "\"abbcc[]\" did not equal \"abbcc[c]\", but \"abbcc\" fully matched the regular expression a(b*)(c*) and group bb, cc") assert(caught16.failedCodeFileName === Some("ShouldFullyMatchSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) } } } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/words/HaveWordSpec.scala
/* * 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.words import org.scalatest._ import matchers.{HavePropertyMatcher, HavePropertyMatchResult} class HaveWordSpec extends Spec with Matchers { object `HaveWord ` { def `should have pretty toString` { have.toString should be ("have") } object `length(Long) method returns MatcherFactory1` { val mtf = have length 3 val mt = mtf.matcher[Array[Int]] def `should have pretty toString` { mtf.toString should be ("have length 3") mt.toString should be ("have length 3") } val lhs = Array(1, 2, 3) val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (true), 'failureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'negatedFailureMessage ("Array(1, 2, 3) had length 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had length 3"), 'rawFailureMessage ("{0} had length {1} instead of expected length {2}"), 'rawNegatedFailureMessage ("{0} had length {1}"), 'rawMidSentenceFailureMessage ("{0} had length {1} instead of expected length {2}"), 'rawMidSentenceNegatedFailureMessage ("{0} had length {1}"), 'failureMessageArgs(Vector(lhs, 3, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3)) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (false), 'failureMessage ("Array(1, 2, 3) had length 3"), 'negatedFailureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had length 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'rawFailureMessage ("{0} had length {1}"), 'rawNegatedFailureMessage ("{0} had length {1} instead of expected length {2}"), 'rawMidSentenceFailureMessage ("{0} had length {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} had length {1} instead of expected length {2}"), 'failureMessageArgs(Vector(lhs, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3, 3)) ) } } object `size(Long) method returns MatcherFactory1` { val mtf = have size 3 val mt = mtf.matcher[Array[Int]] def `should have pretty toString` { mtf.toString should be ("have size 3") mt.toString should be ("have size 3") } val lhs = Array(1, 2, 3) val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (true), 'failureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'negatedFailureMessage ("Array(1, 2, 3) had size 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had size 3"), 'rawFailureMessage ("{0} had size {1} instead of expected size {2}"), 'rawNegatedFailureMessage ("{0} had size {1}"), 'rawMidSentenceFailureMessage ("{0} had size {1} instead of expected size {2}"), 'rawMidSentenceNegatedFailureMessage ("{0} had size {1}"), 'failureMessageArgs(Vector(lhs, 3, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3)) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (false), 'failureMessage ("Array(1, 2, 3) had size 3"), 'negatedFailureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had size 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'rawFailureMessage ("{0} had size {1}"), 'rawNegatedFailureMessage ("{0} had size {1} instead of expected size {2}"), 'rawMidSentenceFailureMessage ("{0} had size {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} had size {1} instead of expected size {2}"), 'failureMessageArgs(Vector(lhs, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3, 3)) ) } } object `message(String) method returns MatcherFactory1` { val mtf = have message "Message from Mars!" val mt = mtf.matcher[RuntimeException] def `should have pretty toString` { mtf.toString should be ("have message \"Message from Mars!\"") mt.toString should be ("have message \"Message from Mars!\"") } val lhs = new RuntimeException("Message from Mars!") val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (true), 'failureMessage (lhs + " had message \"Message from Mars!\" instead of expected message \"Message from Mars!\""), 'negatedFailureMessage (lhs + " had message \"Message from Mars!\""), 'midSentenceFailureMessage (lhs + " had message \"Message from Mars!\" instead of expected message \"Message from Mars!\""), 'midSentenceNegatedFailureMessage (lhs + " had message \"Message from Mars!\""), 'rawFailureMessage ("{0} had message {1} instead of expected message {2}"), 'rawNegatedFailureMessage ("{0} had message {1}"), 'rawMidSentenceFailureMessage ("{0} had message {1} instead of expected message {2}"), 'rawMidSentenceNegatedFailureMessage ("{0} had message {1}"), 'failureMessageArgs(Vector(lhs, "Message from Mars!", "Message from Mars!")), 'negatedFailureMessageArgs(Vector(lhs, "Message from Mars!")), 'midSentenceFailureMessageArgs(Vector(lhs, "Message from Mars!", "Message from Mars!")), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, "Message from Mars!")) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (false), 'failureMessage (lhs + " had message \"Message from Mars!\""), 'negatedFailureMessage (lhs + " had message \"Message from Mars!\" instead of expected message \"Message from Mars!\""), 'midSentenceFailureMessage (lhs + " had message \"Message from Mars!\""), 'midSentenceNegatedFailureMessage (lhs + " had message \"Message from Mars!\" instead of expected message \"Message from Mars!\""), 'rawFailureMessage ("{0} had message {1}"), 'rawNegatedFailureMessage ("{0} had message {1} instead of expected message {2}"), 'rawMidSentenceFailureMessage ("{0} had message {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} had message {1} instead of expected message {2}"), 'failureMessageArgs(Vector(lhs, "Message from Mars!")), 'negatedFailureMessageArgs(Vector(lhs, "Message from Mars!", "Message from Mars!")), 'midSentenceFailureMessageArgs(Vector(lhs, "Message from Mars!")), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, "Message from Mars!", "Message from Mars!")) ) } } object `apply(ResultOfLengthWordApplication) method returns MatcherFactory1` { val mtf: matchers.MatcherFactory1[Any, enablers.Length] = have (new ResultOfLengthWordApplication(3)) val mt = mtf.matcher[Array[Int]] def `should have pretty toString` { mtf.toString should be ("have length 3") mt.toString should be ("have length 3") } val lhs = Array(1, 2, 3) val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (true), 'failureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'negatedFailureMessage ("Array(1, 2, 3) had length 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had length 3"), 'rawFailureMessage ("{0} had length {1} instead of expected length {2}"), 'rawNegatedFailureMessage ("{0} had length {1}"), 'rawMidSentenceFailureMessage ("{0} had length {1} instead of expected length {2}"), 'rawMidSentenceNegatedFailureMessage ("{0} had length {1}"), 'failureMessageArgs(Vector(lhs, 3, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3)) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (false), 'failureMessage ("Array(1, 2, 3) had length 3"), 'negatedFailureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had length 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had length 3 instead of expected length 3"), 'rawFailureMessage ("{0} had length {1}"), 'rawNegatedFailureMessage ("{0} had length {1} instead of expected length {2}"), 'rawMidSentenceFailureMessage ("{0} had length {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} had length {1} instead of expected length {2}"), 'failureMessageArgs(Vector(lhs, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3, 3)) ) } } object `size(ResultOfSizeWordApplication) method returns MatcherFactory1` { val mtf: matchers.MatcherFactory1[Any, enablers.Size] = have (new ResultOfSizeWordApplication(3)) val mt = mtf.matcher[Array[Int]] def `should have pretty toString` { mtf.toString should be ("have size 3") mt.toString should be ("have size 3") } val lhs = Array(1, 2, 3) val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (true), 'failureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'negatedFailureMessage ("Array(1, 2, 3) had size 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had size 3"), 'rawFailureMessage ("{0} had size {1} instead of expected size {2}"), 'rawNegatedFailureMessage ("{0} had size {1}"), 'rawMidSentenceFailureMessage ("{0} had size {1} instead of expected size {2}"), 'rawMidSentenceNegatedFailureMessage ("{0} had size {1}"), 'failureMessageArgs(Vector(lhs, 3, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3)) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (false), 'failureMessage ("Array(1, 2, 3) had size 3"), 'negatedFailureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'midSentenceFailureMessage ("Array(1, 2, 3) had size 3"), 'midSentenceNegatedFailureMessage ("Array(1, 2, 3) had size 3 instead of expected size 3"), 'rawFailureMessage ("{0} had size {1}"), 'rawNegatedFailureMessage ("{0} had size {1} instead of expected size {2}"), 'rawMidSentenceFailureMessage ("{0} had size {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} had size {1} instead of expected size {2}"), 'failureMessageArgs(Vector(lhs, 3)), 'negatedFailureMessageArgs(Vector(lhs, 3, 3)), 'midSentenceFailureMessageArgs(Vector(lhs, 3)), 'midSentenceNegatedFailureMessageArgs(Vector(lhs, 3, 3)) ) } } object `apply(HavePropertyMatcher) method returns MatcherFactory1` { def name(expectedName: String) = { HavePropertyMatcher { (person: Person) => HavePropertyMatchResult( person.name == expectedName, "name", expectedName, person.name ) } } val nameBob = name("Bob") val mt = have (nameBob) case class Person(name: String) def `should have pretty toString` { mt.toString should be ("have (" + nameBob + ")") } object `when evaluate to true` { val lhs = Person("Bob") val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (true), 'failureMessage ("The name property had its expected value \"Bob\", on object " + lhs), 'negatedFailureMessage ("The name property had its expected value \"Bob\", on object " + lhs), 'midSentenceFailureMessage ("the name property had its expected value \"Bob\", on object " + lhs), 'midSentenceNegatedFailureMessage ("the name property had its expected value \"Bob\", on object " + lhs), 'rawFailureMessage ("The {0} property had its expected value {1}, on object {2}"), 'rawNegatedFailureMessage ("The {0} property had its expected value {1}, on object {2}"), 'rawMidSentenceFailureMessage ("the {0} property had its expected value {1}, on object {2}"), 'rawMidSentenceNegatedFailureMessage ("the {0} property had its expected value {1}, on object {2}"), 'failureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)), 'negatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)), 'midSentenceFailureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)), 'midSentenceNegatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (false), 'failureMessage ("The name property had its expected value \"Bob\", on object " + lhs), 'negatedFailureMessage ("The name property had its expected value \"Bob\", on object " + lhs), 'midSentenceFailureMessage ("the name property had its expected value \"Bob\", on object " + lhs), 'midSentenceNegatedFailureMessage ("the name property had its expected value \"Bob\", on object " + lhs), 'rawFailureMessage ("The {0} property had its expected value {1}, on object {2}"), 'rawNegatedFailureMessage ("The {0} property had its expected value {1}, on object {2}"), 'rawMidSentenceFailureMessage ("the {0} property had its expected value {1}, on object {2}"), 'rawMidSentenceNegatedFailureMessage ("the {0} property had its expected value {1}, on object {2}"), 'failureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)), 'negatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)), 'midSentenceFailureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)), 'midSentenceNegatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", lhs)) ) } } object `when evaluate to false` { val lhs = Person("Alice") val mr = mt(lhs) def `should have correct MatcherResult` { mr should have ( 'matches (false), 'failureMessage ("The name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'negatedFailureMessage ("The name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'midSentenceFailureMessage ("the name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'midSentenceNegatedFailureMessage ("the name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'rawFailureMessage ("The {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'rawNegatedFailureMessage ("The {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'rawMidSentenceFailureMessage ("the {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'rawMidSentenceNegatedFailureMessage ("the {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'failureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)), 'negatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)), 'midSentenceFailureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)), 'midSentenceNegatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)) ) } val nmr = mr.negated def `should have correct negated MatcherResult` { nmr should have ( 'matches (true), 'failureMessage ("The name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'negatedFailureMessage ("The name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'midSentenceFailureMessage ("the name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'midSentenceNegatedFailureMessage ("the name property had value \"Alice\", instead of its expected value \"Bob\", on object " + lhs), 'rawFailureMessage ("The {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'rawNegatedFailureMessage ("The {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'rawMidSentenceFailureMessage ("the {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'rawMidSentenceNegatedFailureMessage ("the {0} property had value {2}, instead of its expected value {1}, on object {3}"), 'failureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)), 'negatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)), 'midSentenceFailureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)), 'midSentenceNegatedFailureMessageArgs(Vector(UnquotedString("name"), "Bob", "Alice", lhs)) ) } } } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/junit/JUnitSuiteSpec.scala
<reponame>cquiroz/scalatest /* * 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.junit import org.scalatest._ import SharedHelpers._ import scala.collection.immutable.TreeSet import org.scalatest.junit.junit4helpers._ import org.junit.Test import org.junit.Ignore class JUnitSuiteSpec extends FunSpec { describe("A JUnitSuite") { it("should return the test names in alphabetical order from testNames") { val a = new JUnitSuite { @Test def doThis() {} @Test def doThat() {} } assertResult(List("doThat", "doThis")) { a.testNames.iterator.toList } val b = new JUnitSuite {} assertResult(List[String]()) { b.testNames.iterator.toList } val c = new JUnitSuite { @Test def doThat() {} @Test def doThis() {} } assertResult(List("doThat", "doThis")) { c.testNames.iterator.toList } } it("should return the proper testNames for test methods whether or not they take an Informer") { val a = new JUnitSuite { @Test def doThis() = () @Test def doThat(info: Informer) = () } assert(a.testNames === TreeSet("doThis")) val b = new JUnitSuite {} assert(b.testNames === TreeSet[String]()) } it("should return names of methods that are annotated with Test, take no params, but have a return type " + "other than Unit from testNames") { val a = new TestWithNonUnitMethod assert(a.testNames === TreeSet("doThat", "doTheOtherThing", "doThis")) } it("should return a tags map from the tags method that contains only methods marked with org.junit.Ignore") { val a = new JUnitSuite { @Ignore @Test def testThis() = () @Test def testThat() = () } assert(a.tags === Map("testThis" -> Set("org.scalatest.Ignore"))) val b = new JUnitSuite { @Test def testThis() = () @Ignore @Test def testThat() = () } assert(b.tags === Map("testThat" -> Set("org.scalatest.Ignore"))) val c = new JUnitSuite { @Ignore @Test def testThis() = () @Ignore @Test def testThat() = () } assert(c.tags === Map("testThis" -> Set("org.scalatest.Ignore"), "testThat" -> Set("org.scalatest.Ignore"))) val d = new JUnitSuite { @SlowAsMolasses @Test def testThis() = () @SlowAsMolasses @Ignore @Test def testThat() = () } assert(d.tags === Map("testThat" -> Set("org.scalatest.Ignore"))) val e = new JUnitSuite {} assert(e.tags === Map()) } it("should execute all tests when run is called with testName None") { TestWasCalledSuite.reinitialize() val b = new TestWasCalledSuite b.run(None, Args(SilentReporter)) assert(TestWasCalledSuite.theDoThisCalled) assert(TestWasCalledSuite.theDoThatCalled) } it("should execute one test when run is called with a defined testName") { TestWasCalledSuite.reinitialize() val a = new TestWasCalledSuite a.run(Some("doThis"), Args(SilentReporter)) assert(TestWasCalledSuite.theDoThisCalled) assert(!TestWasCalledSuite.theDoThatCalled) } it("should throw IllegalArgumentException if run is passed a testName that does not exist") { val a = new TestWasCalledSuite intercept[IllegalArgumentException] { // Here, they forgot that the name is actually doThis(Fixture) a.run(Some("misspelled"), Args(SilentReporter)) } } it("should run no tests if tags to include is non-empty") { TestWasCalledSuite.reinitialize() val a = new TestWasCalledSuite a.run(None, Args(SilentReporter, Stopper.default, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), ConfigMap.empty, None, new Tracker, Set.empty)) assert(!TestWasCalledSuite.theDoThisCalled) assert(!TestWasCalledSuite.theDoThatCalled) } it("should return the correct test count from its expectedTestCount method") { val a = new ASuite assert(a.expectedTestCount(Filter()) === 1) val b = new BSuite assert(b.expectedTestCount(Filter()) === 0) val c = new org.scalatest.junit.junit4helpers.CSuite assert(c.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 0) assert(c.expectedTestCount(Filter(None, Set("org.scalatest.FastAsLight"))) === 1) val d = new DSuite assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 0) assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 0) assert(d.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 6) assert(d.expectedTestCount(Filter()) === 6) val e = new ESuite assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 0) assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 0) assert(e.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 1) assert(e.expectedTestCount(Filter()) === 1) } it("should generate a test failure if a Throwable, or an Error other than direct Error subtypes " + "known in JDK 1.5, excluding AssertionError") { val a = new ShouldFailSuite val rep = new EventRecordingReporter a.run(None, Args(rep)) val tf = rep.testFailedEventsReceived assert(tf.size === 3) } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/matchers/MatchResultSpec.scala
<filename>scalatest-test/src/test/scala/org/scalatest/matchers/MatchResultSpec.scala /* * 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.matchers import org.scalatest._ import Inside._ import org.scalactic.{PrettyMethods, Prettifier} class MatchResultSpec extends FreeSpec with Matchers with PrettyMethods { "A MatchResult" - { val mr = MatchResult(false, "1 did not equal 2", "1 equaled 2", "1 did not equal 2", "1 equaled 2") "can be negated" in { mr should equal (MatchResult(false, "1 did not equal 2", "1 equaled 2", "1 did not equal 2", "1 equaled 2")) mr.negated should equal (MatchResult(true, "1 equaled 2", "1 did not equal 2", "1 equaled 2", "1 did not equal 2")) val mr2 = MatchResult(false, "{0} did not equal null", "The reference equaled null", "{0} did not equal null", "the reference equaled null", Vector("howdy"), Vector.empty) mr2 should have ( 'matches (false), 'failureMessage ("\"howdy\" did not equal null"), 'negatedFailureMessage ("The reference equaled null"), 'midSentenceFailureMessage ("\"howdy\" did not equal null"), 'midSentenceNegatedFailureMessage ("the reference equaled null"), 'rawFailureMessage ("{0} did not equal null"), 'rawNegatedFailureMessage ("The reference equaled null"), 'rawMidSentenceFailureMessage ("{0} did not equal null"), 'rawMidSentenceNegatedFailureMessage ("the reference equaled null"), 'failureMessageArgs(Vector("howdy")), 'negatedFailureMessageArgs(Vector.empty), 'midSentenceFailureMessageArgs(Vector("howdy")), 'midSentenceNegatedFailureMessageArgs(Vector.empty) ) val mr2Negated = mr2.negated mr2Negated should equal (MatchResult(true, "The reference equaled null", "{0} did not equal null", "the reference equaled null", "{0} did not equal null", Vector.empty, Vector("howdy"))) mr2Negated should have ( 'matches (true), 'failureMessage ("The reference equaled null"), 'negatedFailureMessage ("\"howdy\" did not equal null"), 'midSentenceFailureMessage ("the reference equaled null"), 'midSentenceNegatedFailureMessage ("\"howdy\" did not equal null"), 'rawFailureMessage ("The reference equaled null"), 'rawNegatedFailureMessage ("{0} did not equal null"), 'rawMidSentenceFailureMessage ("the reference equaled null"), 'rawMidSentenceNegatedFailureMessage ("{0} did not equal null"), 'failureMessageArgs(Vector.empty), 'negatedFailureMessageArgs(Vector("howdy")), 'midSentenceFailureMessageArgs(Vector.empty), 'midSentenceNegatedFailureMessageArgs(Vector("howdy")) ) } "can be pattern matched via an extractor for the failureMessage if it doesn't match" in { inside (mr) { case MatchFailed(failureMessage) => failureMessage should be ("1 did not equal 2") } } "can be pattern matched via an extractor for the negatedFailureMessage if it does match" in { inside (mr.negated) { case MatchSucceeded(negatedFailureMessage) => negatedFailureMessage should be ("1 did not equal 2") } } "should construct localized strings from the raw strings and args" in { val mr = MatchResult(false, "{0} did not equal {1}", "{0} equaled {1}", "{0} did not equal {1}", "{0} equaled {1}", Vector(1, 2), Vector(1, 2)) mr should have ( 'matches (false), 'failureMessage ("1 did not equal 2"), 'negatedFailureMessage ("1 equaled 2"), 'midSentenceFailureMessage ("1 did not equal 2"), 'midSentenceNegatedFailureMessage ("1 equaled 2"), 'rawFailureMessage ("{0} did not equal {1}"), 'rawNegatedFailureMessage ("{0} equaled {1}"), 'rawMidSentenceFailureMessage ("{0} did not equal {1}"), 'rawMidSentenceNegatedFailureMessage ("{0} equaled {1}"), 'failureMessageArgs(Vector(1, 2)), 'negatedFailureMessageArgs(Vector(1, 2)), 'midSentenceFailureMessageArgs(Vector(1, 2)), 'midSentenceNegatedFailureMessageArgs(Vector(1, 2)) ) } "should use midSentenceFailureMessageArgs to construct midSentenceFailureMessage" in { val mr = MatchResult(false, "{0} did not equal {1}", "{0} equaled {1}", "{0} did not equal {1}", "{0} equaled {1}", Vector.empty, Vector.empty, Vector(1, 2), Vector.empty, Prettifier.default) mr.midSentenceFailureMessage should be ("1 did not equal 2") } "should use midSentenceNegatedFailureMessageArgs to construct midSentenceNegatedFailureMessage" in { val mr = MatchResult(false, "{0} did not equal {1}", "{0} equaled {1}", "{0} did not equal {1}", "{0} equaled {1}", Vector.empty, Vector.empty, Vector.empty, Vector(1, 2), Prettifier.default) mr.midSentenceNegatedFailureMessage should be ("1 equaled 2") } } "The MatchResult companion object factory method" - { "that takes two strings should work correctly" in { val mr = MatchResult(true, "one", "two") mr should have ( 'matches (true), 'failureMessage ("one"), 'negatedFailureMessage ("two"), 'midSentenceFailureMessage ("one"), 'midSentenceNegatedFailureMessage ("two"), 'rawFailureMessage ("one"), 'rawNegatedFailureMessage ("two"), 'rawMidSentenceFailureMessage ("one"), 'rawMidSentenceNegatedFailureMessage ("two"), 'failureMessageArgs(Vector.empty), 'negatedFailureMessageArgs(Vector.empty), 'midSentenceFailureMessageArgs(Vector.empty), 'midSentenceNegatedFailureMessageArgs(Vector.empty) ) val ms = MatchResult(false, "aaa", "bbb") ms should have ( 'matches (false), 'failureMessage ("aaa"), 'negatedFailureMessage ("bbb"), 'midSentenceFailureMessage ("aaa"), 'midSentenceNegatedFailureMessage ("bbb"), 'rawFailureMessage ("aaa"), 'rawNegatedFailureMessage ("bbb"), 'rawMidSentenceFailureMessage ("aaa"), 'rawMidSentenceNegatedFailureMessage ("bbb"), 'failureMessageArgs(Vector.empty), 'negatedFailureMessageArgs(Vector.empty), 'midSentenceFailureMessageArgs(Vector.empty), 'midSentenceNegatedFailureMessageArgs(Vector.empty) ) } "that takes four strings should work correctly" in { val mr = MatchResult(true, "one", "two", "three", "four") mr should have ( 'matches (true), 'failureMessage ("one"), 'negatedFailureMessage ("two"), 'midSentenceFailureMessage ("three"), 'midSentenceNegatedFailureMessage ("four"), 'rawFailureMessage ("one"), 'rawNegatedFailureMessage ("two"), 'rawMidSentenceFailureMessage ("three"), 'rawMidSentenceNegatedFailureMessage ("four"), 'failureMessageArgs(Vector.empty), 'negatedFailureMessageArgs(Vector.empty), 'midSentenceFailureMessageArgs(Vector.empty), 'midSentenceNegatedFailureMessageArgs(Vector.empty) ) val ms = MatchResult(false, "aaa", "bbb", "ccc", "ddd") ms should have ( 'matches (false), 'failureMessage ("aaa"), 'negatedFailureMessage ("bbb"), 'midSentenceFailureMessage ("ccc"), 'midSentenceNegatedFailureMessage ("ddd"), 'rawFailureMessage ("aaa"), 'rawNegatedFailureMessage ("bbb"), 'rawMidSentenceFailureMessage ("ccc"), 'rawMidSentenceNegatedFailureMessage ("ddd"), 'failureMessageArgs(Vector.empty), 'negatedFailureMessageArgs(Vector.empty), 'midSentenceFailureMessageArgs(Vector.empty), 'midSentenceNegatedFailureMessageArgs(Vector.empty) ) } "that takes four strings and two IndexedSeqs should work correctly" in { val mr = MatchResult(true, "one", "two", "three", "four", Vector(42), Vector(42.0)) mr should have ( 'matches (true), 'failureMessage ("one"), 'negatedFailureMessage ("two"), 'midSentenceFailureMessage ("three"), 'midSentenceNegatedFailureMessage ("four"), 'rawFailureMessage ("one"), 'rawNegatedFailureMessage ("two"), 'rawMidSentenceFailureMessage ("three"), 'rawMidSentenceNegatedFailureMessage ("four"), 'failureMessageArgs(Vector(42)), 'negatedFailureMessageArgs(Vector(42.0)), 'midSentenceFailureMessageArgs(Vector(42)), 'midSentenceNegatedFailureMessageArgs(Vector(42.0)) ) val ms = MatchResult(false, "aaa", "bbb", "ccc", "ddd", Vector("ho", "he"), Vector("foo", "fie")) ms should have ( 'matches (false), 'failureMessage ("aaa"), 'negatedFailureMessage ("bbb"), 'midSentenceFailureMessage ("ccc"), 'midSentenceNegatedFailureMessage ("ddd"), 'rawFailureMessage ("aaa"), 'rawNegatedFailureMessage ("bbb"), 'rawMidSentenceFailureMessage ("ccc"), 'rawMidSentenceNegatedFailureMessage ("ddd"), 'failureMessageArgs(Vector("ho", "he")), 'negatedFailureMessageArgs(Vector("foo", "fie")), 'midSentenceFailureMessageArgs(Vector("ho", "he")), 'midSentenceNegatedFailureMessageArgs(Vector("foo", "fie")) ) } "that takes two strings and one IndexedSeq should work correctly" in { val mr = MatchResult(true, "one", "two", Vector(42)) mr should have ( 'matches (true), 'failureMessage ("one"), 'negatedFailureMessage ("two"), 'midSentenceFailureMessage ("one"), 'midSentenceNegatedFailureMessage ("two"), 'rawFailureMessage ("one"), 'rawNegatedFailureMessage ("two"), 'rawMidSentenceFailureMessage ("one"), 'rawMidSentenceNegatedFailureMessage ("two"), 'failureMessageArgs(Vector(42)), 'negatedFailureMessageArgs(Vector(42)), 'midSentenceFailureMessageArgs(Vector(42)), 'midSentenceNegatedFailureMessageArgs(Vector(42)) ) val ms = MatchResult(false, "aaa", "bbb", Vector("ho", "he")) ms should have ( 'matches (false), 'failureMessage ("aaa"), 'negatedFailureMessage ("bbb"), 'midSentenceFailureMessage ("aaa"), 'midSentenceNegatedFailureMessage ("bbb"), 'rawFailureMessage ("aaa"), 'rawNegatedFailureMessage ("bbb"), 'rawMidSentenceFailureMessage ("aaa"), 'rawMidSentenceNegatedFailureMessage ("bbb"), 'failureMessageArgs(Vector("ho", "he")), 'negatedFailureMessageArgs(Vector("ho", "he")), 'midSentenceFailureMessageArgs(Vector("ho", "he")), 'midSentenceNegatedFailureMessageArgs(Vector("ho", "he")) ) } "that takes two strings and two IndexedSeqs should work correctly" in { val mr = MatchResult(true, "one", "two", Vector(42), Vector(42.0)) mr should have ( 'matches (true), 'failureMessage ("one"), 'negatedFailureMessage ("two"), 'midSentenceFailureMessage ("one"), 'midSentenceNegatedFailureMessage ("two"), 'rawFailureMessage ("one"), 'rawNegatedFailureMessage ("two"), 'rawMidSentenceFailureMessage ("one"), 'rawMidSentenceNegatedFailureMessage ("two"), 'failureMessageArgs(Vector(42)), 'negatedFailureMessageArgs(Vector(42.0)), 'midSentenceFailureMessageArgs(Vector(42)), 'midSentenceNegatedFailureMessageArgs(Vector(42.0)) ) val ms = MatchResult(false, "aaa", "bbb", Vector("ho", "he"), Vector("foo", "fie")) ms should have ( 'matches (false), 'failureMessage ("aaa"), 'negatedFailureMessage ("bbb"), 'midSentenceFailureMessage ("aaa"), 'midSentenceNegatedFailureMessage ("bbb"), 'rawFailureMessage ("aaa"), 'rawNegatedFailureMessage ("bbb"), 'rawMidSentenceFailureMessage ("aaa"), 'rawMidSentenceNegatedFailureMessage ("bbb"), 'failureMessageArgs(Vector("ho", "he")), 'negatedFailureMessageArgs(Vector("foo", "fie")), 'midSentenceFailureMessageArgs(Vector("ho", "he")), 'midSentenceNegatedFailureMessageArgs(Vector("foo", "fie")) ) } "that takes four strings and four IndexedSeqs should work correctly" in { val mr = MatchResult(true, "one", "two", "three", "four", Vector(1), Vector(2), Vector(3), Vector(4)) mr should have ( 'matches (true), 'failureMessage ("one"), 'negatedFailureMessage ("two"), 'midSentenceFailureMessage ("three"), 'midSentenceNegatedFailureMessage ("four"), 'rawFailureMessage ("one"), 'rawNegatedFailureMessage ("two"), 'rawMidSentenceFailureMessage ("three"), 'rawMidSentenceNegatedFailureMessage ("four"), 'failureMessageArgs(Vector(1)), 'negatedFailureMessageArgs(Vector(2)), 'midSentenceFailureMessageArgs(Vector(3)), 'midSentenceNegatedFailureMessageArgs(Vector(4)) ) val ms = MatchResult(false, "aaa", "bbb", "ccc", "ddd", Vector('A'), Vector('B'), Vector('C'), Vector('D')) ms should have ( 'matches (false), 'failureMessage ("aaa"), 'negatedFailureMessage ("bbb"), 'midSentenceFailureMessage ("ccc"), 'midSentenceNegatedFailureMessage ("ddd"), 'rawFailureMessage ("aaa"), 'rawNegatedFailureMessage ("bbb"), 'rawMidSentenceFailureMessage ("ccc"), 'rawMidSentenceNegatedFailureMessage ("ddd"), 'failureMessageArgs(Vector('A')), 'negatedFailureMessageArgs(Vector('B')), 'midSentenceFailureMessageArgs(Vector('C')), 'midSentenceNegatedFailureMessageArgs(Vector('D')) ) } } "The MatchResult obtained from ScalaTest matchers should have localized raw strings and args" - { "for be > 'b'" in { val m = be > 'b' m('a') should have ( 'matches (false), 'rawFailureMessage (Resources.rawWasNotGreaterThan), 'rawNegatedFailureMessage (Resources.rawWasGreaterThan), 'rawMidSentenceFailureMessage (Resources.rawWasNotGreaterThan), 'rawMidSentenceNegatedFailureMessage (Resources.rawWasGreaterThan), 'failureMessageArgs(Vector('a', 'b')), 'negatedFailureMessageArgs(Vector('a', 'b')) ) } "for be < 'b'" in { val m = be < 'b' m('c') should have ( 'matches (false), 'rawFailureMessage (Resources.rawWasNotLessThan), 'rawNegatedFailureMessage (Resources.rawWasLessThan), 'rawMidSentenceFailureMessage (Resources.rawWasNotLessThan), 'rawMidSentenceNegatedFailureMessage (Resources.rawWasLessThan), 'failureMessageArgs(Vector('c', 'b')), 'negatedFailureMessageArgs(Vector('c', 'b')) ) } } "The MatchResult obtained from and-ing two Matchers" - { /* scala> be > 'b' and be > 'd' res0: org.scalatest.matchers.Matcher[Char] = <function1> */ "should be lazy about constructing strings" - { /* scala> res0('a') res1: org.scalatest.matchers.MatchResult = MatchResult(false,'a' was not greater than 'b','a' was greater than 'b','a' was not greater than 'b','a' was greater than 'b',Vector(),Vector()) */ "for false and false" in { val m = be > 'b' and be > 'd' val mr = m('a') mr.matches shouldBe false mr.rawFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.failureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty)) mr.negatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty)) mr.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty)) mr.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty)) mr.failureMessageArgs should be (Vector('a', 'b')) mr.negatedFailureMessageArgs should be (Vector('a', 'b')) } /* scala> be > 'b' and be < 'd' res4: org.scalatest.matchers.Matcher[Char] = <function1> scala> res4('a') res5: org.scalatest.matchers.MatchResult = MatchResult(false,'a' was not greater than 'b','a' was greater than 'b','a' was not greater than 'b','a' was greater than 'b',Vector(),Vector()) */ "for false and true" in { val m = be > 'b' and be < 'd' val mr = m('a') mr.matches shouldBe false mr.rawFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.failureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty)) mr.negatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty)) mr.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty)) mr.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty)) mr.failureMessageArgs should be (Vector('a', 'b')) mr.negatedFailureMessageArgs should be (Vector('a', 'b')) } /* scala> res0('c') res2: org.scalatest.matchers.MatchResult = MatchResult(false,'c' was greater than 'b', but 'c' was not greater than 'd','c' was greater than 'b', and 'c' was greater than 'd','c' was greater than 'b', but 'c' was not greater than 'd','c' was greater than 'b', and 'c' was greater than 'd',Vector(),Vector()) */ "for true and false" in { val left = be > 'b' val right = be > 'd' val m = left and right val mr = m('c') mr.matches shouldBe false mr.rawFailureMessage should be (Resources.rawCommaBut) mr.rawNegatedFailureMessage should be (Resources.rawCommaAnd) mr.rawMidSentenceFailureMessage should be (Resources.rawCommaBut) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd) mr.failureMessage should be (Resources.commaBut(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('c'.pretty, 'd'.pretty))) mr.negatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasGreaterThan('c'.pretty, 'd'.pretty))) mr.midSentenceFailureMessage should be (Resources.commaBut(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('c'.pretty, 'd'.pretty))) mr.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasGreaterThan('c'.pretty, 'd'.pretty))) mr.failureMessageArgs should be (Vector(NegatedFailureMessage(left('c')), MidSentenceFailureMessage(right('c')))) mr.negatedFailureMessageArgs should be (Vector(NegatedFailureMessage(left('c')), MidSentenceNegatedFailureMessage(right('c')))) mr.midSentenceFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(left('c')), MidSentenceFailureMessage(right('c')))) mr.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(left('c')), MidSentenceNegatedFailureMessage(right('c')))) } /* scala> res0('e') res3: org.scalatest.matchers.MatchResult = MatchResult(true,'e' was greater than 'b', but 'e' was not greater than 'd','e' was greater than 'b', and 'e' was greater than 'd','e' was greater than 'b', but 'e' was not greater than 'd','e' was greater than 'b', and 'e' was greater than 'd',Vector(),Vector()) */ "for true and true" in { val left = be > 'b' val right = be > 'd' val m = left and right val mr = m('e') mr.matches shouldBe true mr.rawFailureMessage should be (Resources.rawCommaBut) mr.rawNegatedFailureMessage should be (Resources.rawCommaAnd) mr.rawMidSentenceFailureMessage should be (Resources.rawCommaBut) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd) mr.failureMessage should be (Resources.commaBut(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('e'.pretty, 'd'.pretty))) mr.negatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasGreaterThan('e'.pretty, 'd'.pretty))) mr.midSentenceFailureMessage should be (Resources.commaBut(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('e'.pretty, 'd'.pretty))) mr.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasGreaterThan('e'.pretty, 'd'.pretty))) mr.failureMessageArgs should be (Vector(NegatedFailureMessage(left('e')), MidSentenceFailureMessage(right('e')))) mr.negatedFailureMessageArgs should be (Vector(NegatedFailureMessage(left('e')), MidSentenceNegatedFailureMessage(right('e')))) mr.midSentenceFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(left('e')), MidSentenceFailureMessage(right('e')))) mr.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(left('e')), MidSentenceNegatedFailureMessage(right('e')))) } } } "The MatchResult obtained from or-ing two Matchers" - { /* scala> be > 'b' or be > 'd' res0: org.scalatest.matchers.Matcher[Char] = <function1> */ "should be lazy about constructing strings" - { /* scala> res0('a') res1: org.scalatest.matchers.MatchResult = MatchResult(false,'a' was not greater than 'b', and 'a' was not greater than 'd','a' was not greater than 'b', and 'a' was greater than 'd','a' was not greater than 'b', and 'a' was not greater than 'd','a' was not greater than 'b', and 'a' was greater than 'd',Vector(),Vector()) */ "for false or false" in { val left = be > 'b' val right = be > 'd' val m = left or right val mr = m('a') mr.matches shouldBe false mr.rawFailureMessage should be (Resources.rawCommaAnd) mr.rawNegatedFailureMessage should be (Resources.rawCommaAnd) mr.rawMidSentenceFailureMessage should be (Resources.rawCommaAnd) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd) mr.failureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('a'.pretty, 'd'.pretty))) mr.negatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasGreaterThan('a'.pretty, 'd'.pretty))) mr.midSentenceFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('a'.pretty, 'd'.pretty))) mr.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasGreaterThan('a'.pretty, 'd'.pretty))) mr.failureMessageArgs should be (Vector(FailureMessage(left('a')), MidSentenceFailureMessage(right('a')))) mr.negatedFailureMessageArgs should be (Vector(FailureMessage(left('a')), MidSentenceNegatedFailureMessage(right('a')))) mr.midSentenceFailureMessageArgs should be (Vector(MidSentenceFailureMessage(left('a')), MidSentenceFailureMessage(right('a')))) mr.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceFailureMessage(left('a')), MidSentenceNegatedFailureMessage(right('a')))) } /* scala> be > 'b' or be < 'd' res4: org.scalatest.matchers.Matcher[Char] = <function1> scala> res4('a') res5: org.scalatest.matchers.MatchResult = MatchResult(true,'a' was not greater than 'b', and 'a' was not less than 'd','a' was not greater than 'b', and 'a' was less than 'd','a' was not greater than 'b', and 'a' was not less than 'd','a' was not greater than 'b', and 'a' was less than 'd',Vector(),Vector()) */ "for false or true" in { val left = be > 'b' val right = be < 'd' val m = left or right val mr = m('a') mr.matches shouldBe true mr.rawFailureMessage should be (Resources.rawCommaAnd) mr.rawNegatedFailureMessage should be (Resources.rawCommaAnd) mr.rawMidSentenceFailureMessage should be (Resources.rawCommaAnd) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd) mr.failureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotLessThan('a'.pretty, 'd'.pretty))) mr.negatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasLessThan('a'.pretty, 'd'.pretty))) mr.midSentenceFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotLessThan('a'.pretty, 'd'.pretty))) mr.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasLessThan('a'.pretty, 'd'.pretty))) mr.failureMessageArgs should be (Vector(FailureMessage(left('a')), MidSentenceFailureMessage(right('a')))) mr.negatedFailureMessageArgs should be (Vector(FailureMessage(left('a')), MidSentenceNegatedFailureMessage(right('a')))) mr.midSentenceFailureMessageArgs should be (Vector(MidSentenceFailureMessage(left('a')), MidSentenceFailureMessage(right('a')))) mr.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceFailureMessage(left('a')), MidSentenceNegatedFailureMessage(right('a')))) } /* scala> res0('c') res2: org.scalatest.matchers.MatchResult = MatchResult(true,'c' was greater than 'b','c' was not greater than 'b','c' was greater than 'b','c' was not greater than 'b',Vector(),Vector()) */ "for true or false" in { val m = be > 'b' or be > 'd' val mr = m('c') mr.matches shouldBe true mr.rawFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.failureMessage should be (Resources.wasNotGreaterThan('c'.pretty, 'b'.pretty)) mr.negatedFailureMessage should be (Resources.wasGreaterThan('c'.pretty, 'b'.pretty)) mr.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('c'.pretty, 'b'.pretty)) mr.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('c'.pretty, 'b'.pretty)) mr.failureMessageArgs should be (Vector('c', 'b')) mr.negatedFailureMessageArgs should be (Vector('c', 'b')) } /* scala> res0('e') res3: org.scalatest.matchers.MatchResult = MatchResult(true,'e' was greater than 'b','e' was not greater than 'b','e' was greater than 'b','e' was not greater than 'b',Vector(),Vector()) */ "for true or true" in { val m = be > 'b' or be > 'd' val mr = m('e') mr.matches shouldBe true mr.rawFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan) mr.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan) mr.failureMessage should be (Resources.wasNotGreaterThan('e'.pretty, 'b'.pretty)) mr.negatedFailureMessage should be (Resources.wasGreaterThan('e'.pretty, 'b'.pretty)) mr.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('e'.pretty, 'b'.pretty)) mr.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('e'.pretty, 'b'.pretty)) mr.failureMessageArgs should be (Vector('e', 'b')) mr.negatedFailureMessageArgs should be (Vector('e', 'b')) } } } }
cquiroz/scalatest
scalactic-test/src/test/scala/org/scalactic/OrderingEqualitySpec.scala
<filename>scalactic-test/src/test/scala/org/scalactic/OrderingEqualitySpec.scala /* * Copyright 2001-2014 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.scalactic import org.scalatest._ import scala.collection.GenSeq import scala.collection.GenMap import scala.collection.GenSet import scala.collection.GenIterable import scala.collection.GenTraversable import scala.collection.GenTraversableOnce class OrderingEqualitySpec extends Spec with MustMatchers { object `A Normalization` { def `can be converted to a OrderingEquality via toOrderingEquality` { /* scala> val ord = implicitly[Ordering[String]] ord: Ordering[String] = scala.math.Ordering$String$@f634763 scala> ord.compare("happy", "happy") res2: Int = 0 scala> ord.compare("happy", "dappy") res3: Int = 4 scala> ord.compare("dappy", "happy") res4: Int = -4 */ val ordEq = StringNormalizations.lowerCased.toOrderingEquality ordEq.compare("HI", "hi") mustEqual 0 ordEq.compare("happy", "happy") mustEqual 0 ordEq.compare("hapPy", "hAPpy") mustEqual 0 ordEq.compare("happy", "dappy") must be > 0 ordEq.compare("dappy", "happy") must be < 0 } } }
cquiroz/scalatest
scalactic-test/src/test/scala/org/scalactic/anyvals/PercentSpec.scala
/* * Copyright 2001-2014 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.scalactic.anyvals import org.scalatest._ import scala.collection.mutable.WrappedArray import OptionValues._ import org.scalactic.CheckedEquality._ class PercentSpec extends FunSpec with Matchers { describe("A Percent") { describe("should offer a from factory method that") { it("returns Some[Percent] if the passed Int is between 0 and 100") { Percent.from(0).value.value shouldBe 0 Percent.from(50).value.value shouldBe 50 Percent.from(100).value.value shouldBe 100 } it("returns None if the passed Int is NOT between 0 and 100") { Percent.from(101) shouldBe None Percent.from(1000) shouldBe None Percent.from(-1) shouldBe None Percent.from(-99) shouldBe None } } it("should have a pretty toString") { Percent.from(42).value.toString shouldBe "Percent(42)" } describe("when created with apply method") { it("should compile when 8 is passed in") { "Percent(8)" should compile Percent(8).value shouldEqual 8 "Percent(0)" should compile Percent(0).value shouldEqual 0 "Percent(100)" should compile Percent(100).value shouldEqual 100 } it("should not compile when -1 is passed in") { "Percent(-1)" shouldNot compile } it("should not compile when 101 is passed in") { "Percent(101)" shouldNot compile } it("should not compile when -8 is passed in") { "Percent(-8)" shouldNot compile } it("should not compile when x is passed in") { val x: Int = -8 "Percent(x)" shouldNot compile } } } describe("An LPercent") { describe("should offer a from factory method that") { it("returns Some[LPercent] if the passed Long is between 0 and 100") { LPercent.from(0L).value.value shouldBe 0L LPercent.from(50L).value.value shouldBe 50L LPercent.from(100L).value.value shouldBe 100L } it("returns None if the passed Long is NOT between 0 and 100") { LPercent.from(101L) shouldBe None LPercent.from(1000L) shouldBe None LPercent.from(-1L) shouldBe None LPercent.from(-99L) shouldBe None } } it("should have a pretty toString") { LPercent.from(42L).value.toString shouldBe "LPercent(42)" } } describe("An FPercent") { describe("should offer a from factory method that") { it("returns Some[FPercent] if the passed Float is between 0 and 100") { FPercent.from(0.0F).value.value shouldBe 0.0F FPercent.from(50.0F).value.value shouldBe 50.0F FPercent.from(100.0F).value.value shouldBe 100.0F } it("returns None if the passed Float is NOT between 0 and 100") { FPercent.from(100.00001F) shouldBe None FPercent.from(1000.1F) shouldBe None FPercent.from(-.000001F) shouldBe None FPercent.from(-99.999F) shouldBe None } } it("should have a pretty toString") { // SKIP-SCALATESTJS-START FPercent.from(42.0F).value.toString shouldBe "FPercent(42.0)" // SKIP-SCALATESTJS-END //SCALATESTJS-ONLY FPercent.from(42.0F).value.toString shouldBe "FPercent(42)" // SKIP-SCALATESTJS-START FPercent.from(42.42F).value.toString shouldBe "FPercent(42.42)" // SKIP-SCALATESTJS-END //SCALATESTJS-ONLY FPercent.from(42.42F).value.toString shouldBe "FPercent(42.41999816894531)" } } describe("A DPercent") { describe("should offer a from factory method that") { it("returns Some[DPercent] if the passed Double is between 0 and 100") { DPercent.from(0.0).value.value shouldBe 0.0 DPercent.from(50.0).value.value shouldBe 50.0 DPercent.from(100.0).value.value shouldBe 100.0 } it("returns None if the passed Double is NOT between 0 and 100") { DPercent.from(100.000001) shouldBe None DPercent.from(1000.1) shouldBe None DPercent.from(-.000001) shouldBe None DPercent.from(-99.999) shouldBe None } } it("should have a pretty toString") { // SKIP-SCALATESTJS-START DPercent.from(42.0).value.toString shouldBe "DPercent(42.0)" // SKIP-SCALATESTJS-END //SCALATESTJS-ONLY DPercent.from(42.0).value.toString shouldBe "DPercent(42)" DPercent.from(42.42).value.toString shouldBe "DPercent(42.42)" } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/tools/SocketReporter.scala
/* * 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.tools import org.scalatest.events.Event import org.scalatest.ResourcefulReporter import java.net.Socket import java.io.ObjectOutputStream import java.io.BufferedOutputStream private[scalatest] class SocketReporter(host: String, port: Int) extends ResourcefulReporter { private val socket = new Socket(host, port) private val out = new ObjectOutputStream(socket.getOutputStream) def apply(event: Event) { synchronized { out.writeObject(event) out.flush() } } def dispose() { out.flush() out.close() socket.close() } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/tools/FriendlyParamsTranslator.scala
/* * 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.tools import collection.mutable.ListBuffer private[scalatest] object FriendlyParamsTranslator { private[scalatest] val validConfigMap = Map( "dropteststarting" -> "N", "droptestsucceeded" -> "C", "droptestignored" -> "X", "droptestpending" -> "E", "dropsuitestarting" -> "H", "dropsuitecompleted" -> "L", "dropinfoprovided" -> "O", "nocolor" -> "W", "shortstacks" -> "S", "fullstacks" -> "F", "durations" -> "D" ) private [scalatest] def extractContentInBracket(raw:String, it:Iterator[String], expected:String):String = { if(!raw.startsWith("(")) throw new IllegalArgumentException("Invalid configuration, example valid configuration: " + expected) val withBrackets = if(raw.endsWith(")")) raw else parseUntilFound(raw, ")", it) withBrackets.substring(1, withBrackets.length() - 1) } private[scalatest] def parseUntilFound(value:String, endsWith:String, it:Iterator[String]):String = { if(it.hasNext) { val next = it.next() if(next.endsWith(endsWith)) value + next else parseUntilFound(value + next, endsWith, it) } else throw new IllegalArgumentException("Unable to find '" + endsWith + "'") } private[scalatest] def parseCompoundParams(rawParamsStr:String, it:Iterator[String], expected:String):Array[String] = { val rawClassArr = extractContentInBracket(rawParamsStr, it, expected).split(",") for(rawClass <- rawClassArr) yield { val trimmed = rawClass.trim() if(trimmed.length() > 1 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) trimmed.substring(1, trimmed.length() - 1) else trimmed } } private[scalatest] def translateCompoundParams(rawParamsStr:String, it:Iterator[String], expected:String):String = { val paramsArr = parseCompoundParams(rawParamsStr, it, expected) paramsArr.mkString(" ") } private[scalatest] def parseParams(rawParamsStr:String, it:Iterator[String], validParamSet:Set[String], expected:String):Map[String, String] = { if(rawParamsStr.length() > 0) { val paramsStr = extractContentInBracket(rawParamsStr, it, expected) val configsArr:Array[String] = paramsStr.split(",") val tuples = for(configStr <- configsArr) yield { val keyValueArr = configStr.trim().split("=") if(keyValueArr.length == 2) { // Value config param val key:String = keyValueArr(0).trim() if(!validParamSet.contains(key)) throw new IllegalArgumentException("Invalid configuration: " + key) val rawValue = keyValueArr(1).trim() val value:String = if(rawValue.startsWith("\"") && rawValue.endsWith("\"") && rawValue.length() > 1) rawValue.substring(1, rawValue.length() - 1) else rawValue (key -> value) } else throw new IllegalArgumentException("Invalid configuration: " + configStr) } Map[String, String]() ++ tuples } else Map[String, String]() } private[scalatest] def translateConfigs(rawConfigs:String):String = { val configArr = rawConfigs.split(" ") val translatedArr = configArr.map {config => val translatedOpt:Option[String] = validConfigMap.get(config) translatedOpt match { case Some(translated) => translated case None => throw new IllegalArgumentException("Invalid config value: " + config) } } translatedArr.mkString } private[scalatest] def getTranslatedConfig(paramsMap:Map[String, String]):String = { val configOpt:Option[String] = paramsMap.get("config") configOpt match { case Some(configStr) => translateConfigs(configStr) case None => "" } } private[scalatest] def translateCompound(inputString:String, friendlyName:String, dash:String, it:Iterator[String]):List[String] = { val translatedList = new ListBuffer[String]() val elements:Array[String] = parseCompoundParams(inputString.substring(friendlyName.length()), it, friendlyName + "(a, b, c)") elements.foreach{ element => translatedList += dash translatedList += element } translatedList.toList } private[scalatest] def parseDashAndArgument(dash:String, replaceDeprecated:String, it:Iterator[String]):List[String] = { // Do not show deprecated message for now, until the friendly dsl is really ready //println(dash + " is deprecated, use " + replaceDeprecated + " instead.") val translatedList = new ListBuffer[String]() translatedList += dash if(it.hasNext) translatedList += it.next translatedList.toList } private[scalatest] def showDeprecated(inputString:String, replaceDeprecated:String):String = { // May be we can use a logger later // Do not show deprecated message for now, until the friendly dsl is really ready //println(inputString + " is deprecated, use " + replaceDeprecated + " instead.") inputString } private[scalatest] def translateKeyValue(value:String, elementName:String, translated:String, requiredAttrList:List[String], optionalAttrList:List[String], exampleValid:String, it:Iterator[String]):List[String] = { val paramsMap:Map[String, String] = parseParams(value.substring(elementName.length()), it, (requiredAttrList ::: optionalAttrList).toSet, exampleValid) val translatedList = new ListBuffer[String]() translatedList += translated + getTranslatedConfig(paramsMap) requiredAttrList.filter(attr => attr != "config").foreach { attr => val option:Option[String] = paramsMap.get(attr) option match { case Some(value) => translatedList += value case None => throw new IllegalArgumentException(elementName + " requires " + attr + " to be specified, example: " + exampleValid) } } optionalAttrList.filter(attr => attr != "config").foreach { attr => val option:Option[String] = paramsMap.get(attr) option match { case Some(value) => translatedList += value case None => // Do nothing since it's optional } } translatedList.toList } private[scalatest] def translateArguments(args: Array[String]): Array[String] = { val newArgs = new ListBuffer[String] val it = args.iterator while (it.hasNext) { val s = it.next if (s.startsWith("include")) { println("WARNING: Argument 'include' has been deprecated and will be removed in a future version of ScalaTest. Please use -n instead.") newArgs ++= List("-n", translateCompoundParams(s.substring("include".length()), it, "include(a, b, c)")) } else if (s.startsWith("exclude")) { println("WARNING: Argument 'exclude' has been deprecated and will be removed in a future version of ScalaTest. Please use -l instead.") newArgs ++= List("-l", translateCompoundParams(s.substring("exclude".length()), it, "exclude(a, b, c)")) } else if (s.startsWith("stdout")) { println("WARNING: Argument 'stdout' has been deprecated and will be removed in a future version of ScalaTest. Please use -o instead.") newArgs += "-o" + getTranslatedConfig(parseParams(s.substring("stdout".length()), it, Set("config"), "stdout")) } else if (s.startsWith("stderr")) { println("WARNING: Argument 'stderr' has been deprecated and will be removed in a future version of ScalaTest. Please use -e instead.") newArgs += "-e" + getTranslatedConfig(parseParams(s.substring("stderr".length()), it, Set("config"), "stderr")) } /*else if (s.startsWith("graphic")) { println("WARNING: Argument 'graphic' has been deprecated and will be removed in a future version of ScalaTest. Please use -g instead.") val paramsMap:Map[String, String] = parseParams(s.substring("graphic".length()), it, Set("config"), "graphic") val dashG = "-g" + getTranslatedConfig(paramsMap) if(dashG.indexOf("S") >= 0) throw new IllegalArgumentException("Cannot specify an 'shortstacks' (present short stack traces) configuration parameter for the graphic reporter (because it shows them anyway): ") if(dashG.indexOf("F") >= 0) throw new IllegalArgumentException("Cannot specify an 'fullstacks' (present full stack traces) configuration parameter for the graphic reporter (because it shows them anyway): ") if(dashG.indexOf("W") >= 0) throw new IllegalArgumentException("Cannot specify an 'nocolor' (present without color) configuration parameter for the graphic reporter") if(dashG.indexOf("D") >= 0 ) throw new IllegalArgumentException("Cannot specify an 'durations' (present all durations) configuration parameter for the graphic reporter (because it shows them all anyway)") newArgs += dashG }*/ else if (s.startsWith("file")) { println("WARNING: Argument 'file' has been deprecated and will be removed in a future version of ScalaTest. Please use -f instead.") newArgs ++= translateKeyValue(s, "file", "-f", List("filename"), List("config"), "file(directory=\"xxx\")", it) } else if(s.startsWith("junitxml")) { println("WARNING: Argument 'junitxml' has been deprecated and will be removed in a future version of ScalaTest. Please use -u instead.") newArgs ++= translateKeyValue(s, "junitxml", "-u", List("directory"), Nil, "junitxml(directory=\"xxx\")", it) } else if (s.startsWith("html")) { println("WARNING: Argument 'html' has been deprecated and will be removed in a future version of ScalaTest. Please use -h instead.") newArgs += "-h" val paramsMap:Map[String, String] = parseParams(s.substring("html".length), it, Set("directory", "css"), "html(directory=\"xxx\", css=\"xxx\")") val directoryOpt:Option[String] = paramsMap.get("directory") directoryOpt match { case Some(dir) => newArgs += dir case None => throw new IllegalArgumentException("html requires directory to be specified, example: html(directory=\"xxx\", css=\"xxx\")") } val cssOpt:Option[String] = paramsMap.get("css") cssOpt match { case Some(css) => if (css.length == 0) throw new IllegalArgumentException("html's css value cannot be empty string, example: html(directory=\"xxx\", css=\"xxx\")") newArgs += "-Y" newArgs += css case None => } } else if (s.startsWith("reporterclass")) { println("WARNING: Argument 'reporterclass' has been deprecated and will be removed in a future version of ScalaTest. Please use -g instead.") val paramsMap:Map[String, String] = parseParams(s.substring("reporterclass".length()), it, Set("classname", "config"), "reporterclass(classname=\"xxx\")") val classnameOpt:Option[String] = paramsMap.get("classname") val classname:String = classnameOpt match { case Some(clazzname) => clazzname case None => throw new IllegalArgumentException("reporterclass requires classname to be specified, example: reporterclass(classname=\"xxx\")") } val dashR = "-C" + getTranslatedConfig(paramsMap) if(dashR.indexOf("S") >= 0) throw new IllegalArgumentException("Cannot specify an 'shortstacks' (present short stack traces) configuration parameter for a custom reporter: " + dashR + " " + classname) if(dashR.indexOf("F") >= 0) throw new IllegalArgumentException("Cannot specify an 'fullstacks' (present full stack traces) configuration parameter for a custom reporter: " + dashR + " " + classname) if(dashR.indexOf("W") >= 0) throw new IllegalArgumentException("Cannot specify an 'nocolor' (present without color) configuration parameter for a custom reporter: " + dashR + " " + classname) if(dashR.indexOf("D") >= 0 ) throw new IllegalArgumentException("Cannot specify an 'durations' (present all durations) configuration parameter for a custom reporter: " + dashR + " " + classname) newArgs += dashR newArgs += classname } else if(s.startsWith("membersonly")) newArgs ++= translateCompound(s, "membersonly", "-m", it) else if(s.startsWith("wildcard")) newArgs ++= translateCompound(s, "wildcard", "-w", it) else newArgs += s } newArgs.toArray } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/concurrent/ScalaFutures.scala
/* * 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.concurrent import org.scalatest.time.Span import org.scalatest.exceptions.StackDepthExceptionHelper.getStackDepthFun import org.scalatest.Suite.anExceptionThatShouldCauseAnAbort import org.scalatest.Resources import org.scalatest.exceptions.{TestPendingException, TestFailedException, TimeoutField} import org.scalatest.exceptions.TestCanceledException import scala.util.Success import scala.util.Failure /** * Provides an implicit conversion from <code>scala.concurrent.Future[T]</code> to * <a href="Futures$FutureConcept.html"><code>FutureConcept[T]</code></a>. * * <p> * This trait enables you to invoke the methods defined on <code>FutureConcept</code> on a Scala <code>Future</code>, as well as to pass a Scala future * to the <code>whenReady</code> methods of supertrait <code>Futures</code>. * See the documentation for supertrait <a href="Futures.html"><code>Futures</code></a> for the details on the syntax this trait provides * for testing with Scala futures. * </p> * * @author <NAME> */ trait ScalaFutures extends Futures { import scala.language.implicitConversions /** * Implicitly converts a <code>scala.concurrent.Future[T]</code> to * <code>FutureConcept[T]</code>, allowing you to invoke the methods * defined on <code>FutureConcept</code> on a Scala <code>Future</code>, as well as to pass a Scala future * to the <code>whenReady</code> methods of supertrait <a href="Futures.html"><code>Futures</code></a>. * * <p> * See the documentation for supertrait <a href="Futures.html"><code>Futures</code></a> for the details on the syntax this trait provides * for testing with Java futures. * </p> * * <p> * If the <code>eitherValue</code> method of the underlying Scala future returns a <code>scala.Some</code> containing a * <code>scala.util.Failure</code> containing a <code>java.util.concurrent.ExecutionException</code>, and this * exception contains a non-<code>null</code> cause, that cause will be included in the <code>TestFailedException</code> as its cause. The * <code>ExecutionException</code> will be be included as the <code>TestFailedException</code>'s cause only if the * <code>ExecutionException</code>'s cause is <code>null</code>. * </p> * * <p> * The <code>isExpired</code> method of the returned <code>FutureConcept</code> will always return <code>false</code>, because * the underlying type, <code>scala.concurrent.Future</code>, does not support the notion of expiration. Likewise, the <code>isCanceled</code> * method of the returned <code>FutureConcept</code> will always return <code>false</code>, because * the underlying type, <code>scala.concurrent.Future</code>, does not support the notion of cancelation. * </p> * * @param scalaFuture a <code>scala.concurrent.Future[T]</code> to convert * @return a <code>FutureConcept[T]</code> wrapping the passed <code>scala.concurrent.Future[T]</code> */ implicit def convertScalaFuture[T](scalaFuture: scala.concurrent.Future[T]): FutureConcept[T] = new FutureConcept[T] { def eitherValue: Option[Either[Throwable, T]] = scalaFuture.value.map { case Success(o) => Right(o) case Failure(e) => Left(e) } def isExpired: Boolean = false // Scala Futures themselves don't support the notion of a timeout def isCanceled: Boolean = false // Scala Futures don't seem to be cancelable either /* def futureValue(implicit config: PatienceConfig): T = { try Await.ready(scalaFuture, Duration.fromNanos(config.timeout.totalNanos)) catch { case e: TimeoutException => } } */ } } /** * Companion object that facilitates the importing of <code>ScalaFutures</code> members as * an alternative to mixing in the trait. One use case is to import <code>ScalaFutures</code>'s members so you can use * them in the Scala interpreter. */ object ScalaFutures extends ScalaFutures
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/BigSuite.scala
/* * 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 import events._ import Suite.formatterForSuiteAborted import Suite.formatterForSuiteCompleted import Suite.formatterForSuiteStarting /* java -Dorg.scalatest.BigSuite.size=5 -Dorg.scalatest.SuiteCompletedStatusReporter.max=100 -classpath scalatest-1.0-CLICKDEMO.jar:/usr/artima/scala/lib/scala-library.jar org.scalatest.tools.Runner -c4 -p "scalatest-1.0-CLICKDEMO-tests.jar" -oNCXEHLO -r org.scalatest.SuiteCompletedStatusReporter -s org.scalatest.BigSuite -s org.scalatest.BigSuite -s org.scalatest.BigSuite -s org.scalatest.BigSuite -s org.scalatest.BigSuite BigSuite.size determines how many suites will be in each BigSuite tree. I haven't taken time to figure out the function, but it looks like this: size => number of suites in the tree 1 => 2 2 => 5 3 => 16 4 => 65 5 => 326 6 => 1957 7 => 13700 Each -s org.scalatest.BigSuite will create one BigSuite instance using the size specified by the property. By saying -r org.scalatest.SuiteCompletedStatusReporter, you get a custom reporter that prints out a duration note to the standard output for every <configurable number> of SuiteCompleted events it receives. It defaults to 10, and can be set via the -Dorg.scalatest.SuiteCompletedStatusReporter.max=100 setting. So the knobs we can turn are: -cN N is the number of threads in the thread pool -Dorg.scalatest.BigSuite.size=M, M determines the number of suites in the tree via some mysterious function -s org.scalatest.BigSuite..., repeating this gets you more instances of these trees sized by M -Dorg.scalatest.SuiteCompletedStatusReporter.max=X, where X is the number of SuiteCompleted events between duration notes */ class BigSuite(nestedSuiteCount: Option[Int]) extends Spec { thisSuite => override def nestedSuites: collection.immutable.IndexedSeq[Suite] = { def makeList(remaining: Int, soFar: List[Suite], nestedCount: Int): List[Suite] = { if (remaining == 0) soFar else makeList(remaining - 1, (new BigSuite(Some(nestedCount - 1)) :: soFar), nestedCount) } val nsList = nestedSuiteCount match { case None => val sizeString = System.getProperty("org.scalatest.BigSuite.size", "0") val size = try { sizeString.toInt } catch { case e: NumberFormatException => 0 } makeList(size, Nil, size) case Some(n) => if (n == 0) List() else { makeList(n, Nil, n) } } Vector.empty ++ nsList } def `test number 1` = { val someFailures = System.getProperty("org.scalatest.BigSuite.someFailures", "") nestedSuiteCount match { case Some(0) if someFailures == "true" => assert(1 + 1 === 3) case _ => assert(1 + 1 === 2) } } def `test number 2` = { assert(1 + 1 === 2) } def `test number 3` = { assert(1 + 1 === 2) } def `test number 4` = { assert(1 + 1 === 2) } def `test number 5` = { assert(1 + 1 === 2) } def `test number 6` = { assert(1 + 1 === 2) } def `test number 7` = { assert(1 + 1 === 2) } def `test number 8` = { assert(1 + 1 === 2) } def `test number 9` = { assert(1 + 1 === 2) } def `test number 10` = { assert(1 + 1 === 2) } def `test number 11` = { assert(1 + 1 === 2) } def `test number 12` = { assert(1 + 1 === 2) } def `test number 13` = { assert(1 + 1 === 2) } def `test number 14` = { assert(1 + 1 === 2) } def `test number 15` = { assert(1 + 1 === 2) } def `test number 16` = { assert(1 + 1 === 2) } def `test number 17` = { assert(1 + 1 === 2) } def `test number 18` = { assert(1 + 1 === 2) } def `test number 19` = { assert(1 + 1 === 2) } def `test number 20` = { assert(1 + 1 === 2) } def `test number 21` = { assert(1 + 1 === 2) } def `test number 22` = { assert(1 + 1 === 2) } def `test number 23` = { assert(1 + 1 === 2) } def `test number 24` = { assert(1 + 1 === 2) } def `test number 25` = { assert(1 + 1 === 2) } def `test number 26` = { assert(1 + 1 === 2) } def `test number 27` = { assert(1 + 1 === 2) } def `test number 28` = { assert(1 + 1 === 2) } def `test number 29` = { assert(1 + 1 === 2) } def `test number 30` = { assert(1 + 1 === 2) } def `test number 31` = { assert(1 + 1 === 2) } def `test number 32` = { assert(1 + 1 === 2) } def `test number 33` = { assert(1 + 1 === 2) } def `test number 34` = { assert(1 + 1 === 2) } def `test number 35` = { assert(1 + 1 === 2) } def `test number 36` = { assert(1 + 1 === 2) } def `test number 37` = { assert(1 + 1 === 2) } def `test number 38` = { assert(1 + 1 === 2) } def `test number 39` = { assert(1 + 1 === 2) } def `test number 40` = { assert(1 + 1 === 2) } def `test number 41` = { assert(1 + 1 === 2) } def `test number 42` = { assert(1 + 1 === 2) } def `test number 43` = { assert(1 + 1 === 2) } def `test number 44` = { assert(1 + 1 === 2) } def `test number 45` = { assert(1 + 1 === 2) } def `test number 46` = { assert(1 + 1 === 2) } def `test number 47` = { assert(1 + 1 === 2) } def `test number 48` = { assert(1 + 1 === 2) } def `test number 49` = { assert(1 + 1 === 2) } def `test number 50` = { assert(1 + 1 === 2) } def `test number 51` = { assert(1 + 1 === 2) } def `test number 52` = { assert(1 + 1 === 2) } def `test number 53` = { assert(1 + 1 === 2) } def `test number 54` = { assert(1 + 1 === 2) } def `test number 55` = { assert(1 + 1 === 2) } def `test number 56` = { assert(1 + 1 === 2) } def `test number 57` = { assert(1 + 1 === 2) } def `test number 58` = { assert(1 + 1 === 2) } def `test number 59` = { assert(1 + 1 === 2) } def `test number 60` = { assert(1 + 1 === 2) } def `test number 61` = { assert(1 + 1 === 2) } def `test number 62` = { assert(1 + 1 === 2) } def `test number 63` = { assert(1 + 1 === 2) } def `test number 64` = { assert(1 + 1 === 2) } def `test number 65` = { assert(1 + 1 === 2) } def `test number 66` = { assert(1 + 1 === 2) } def `test number 67` = { assert(1 + 1 === 2) } def `test number 68` = { assert(1 + 1 === 2) } def `test number 69` = { assert(1 + 1 === 2) } def `test number 70` = { assert(1 + 1 === 2) } def `test number 71` = { assert(1 + 1 === 2) } def `test number 72` = { assert(1 + 1 === 2) } def `test number 73` = { assert(1 + 1 === 2) } def `test number 74` = { assert(1 + 1 === 2) } def `test number 75` = { assert(1 + 1 === 2) } def `test number 76` = { assert(1 + 1 === 2) } def `test number 77` = { assert(1 + 1 === 2) } def `test number 78` = { assert(1 + 1 === 2) } def `test number 79` = { assert(1 + 1 === 2) } def `test number 80` = { assert(1 + 1 === 2) } def `test number 81` = { assert(1 + 1 === 2) } def `test number 82` = { assert(1 + 1 === 2) } def `test number 83` = { assert(1 + 1 === 2) } def `test number 84` = { assert(1 + 1 === 2) } def `test number 85` = { assert(1 + 1 === 2) } def `test number 86` = { assert(1 + 1 === 2) } def `test number 87` = { assert(1 + 1 === 2) } def `test number 88` = { assert(1 + 1 === 2) } def `test number 89` = { assert(1 + 1 === 2) } def `test number 90` = { assert(1 + 1 === 2) } def `test number 91` = { assert(1 + 1 === 2) } def `test number 92` = { assert(1 + 1 === 2) } def `test number 93` = { assert(1 + 1 === 2) } def `test number 94` = { assert(1 + 1 === 2) } def `test number 95` = { assert(1 + 1 === 2) } def `test number 96` = { assert(1 + 1 === 2) } def `test number 97` = { assert(1 + 1 === 2) } def `test number 98` = { assert(1 + 1 === 2) } def `test number 99` = { assert(1 + 1 === 2) } def `test number 100` = { assert(1 + 1 === 2) } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/BeforeAndAfterEachTestDataSuite.scala
<reponame>cquiroz/scalatest /* * 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 import scala.collection.mutable.ListBuffer import org.scalatest.events.Event import org.scalatest.events.Ordinal import org.scalatest.SharedHelpers.SilentReporter import org.scalatest.SharedHelpers.EventRecordingReporter import org.scalatest.events.InfoProvided class BeforeAndAfterEachTestDataSuite extends FunSuite { class TheSuper extends Spec { var runTestWasCalled = false var runWasCalled = false protected override def runTest(testName: String, args: Args): Status = { runTestWasCalled = true super.runTest(testName, args) } override def run(testName: Option[String], args: Args): Status = { runWasCalled = true super.run(testName, args) } } class MySuite extends TheSuper with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { var beforeEachTestDataCalledBeforeRunTest = false var afterEachTestDataCalledAfterRunTest = false var beforeAllConfigCalledBeforeExecute = false var afterAllConfigCalledAfterExecute = false var beforeEachTestDataGotTheGreeting = false var afterEachTestDataGotTheGreeting = false var beforeAllConfigGotTheGreeting = false var afterAllConfigGotTheGreeting = false def `test something` = () override def beforeAll(config: ConfigMap) { if (!runWasCalled) beforeAllConfigCalledBeforeExecute = true if (config.contains("hi") && config("hi") == "there") beforeAllConfigGotTheGreeting = true super.beforeAll(config) } override def beforeEach(td: TestData) { if (!runTestWasCalled) beforeEachTestDataCalledBeforeRunTest = true if (td.configMap.contains("hi") && td.configMap("hi") == "there") beforeEachTestDataGotTheGreeting = true super.beforeEach(td) } override def afterEach(td: TestData) { if (runTestWasCalled) afterEachTestDataCalledAfterRunTest = true if (td.configMap.contains("hi") && td.configMap("hi") == "there") afterEachTestDataGotTheGreeting = true super.afterEach(td) } override def afterAll(config: ConfigMap) { if (runWasCalled) afterAllConfigCalledAfterExecute = true if (config.contains("hi") && config("hi") == "there") afterAllConfigGotTheGreeting = true super.afterAll(config) } } test("super's runTest must be called") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.runTestWasCalled) } test("super's run must be called") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.runWasCalled) } test("beforeEach gets called before runTest") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.beforeEachTestDataCalledBeforeRunTest) } test("afterEach gets called after runTest") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.afterEachTestDataCalledAfterRunTest) } test("beforeAll gets called before run") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.beforeAllConfigCalledBeforeExecute) } test("afterAll gets called after run") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.afterAllConfigCalledAfterExecute) } test("beforeEach(config) gets the config passed to run") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.beforeEachTestDataGotTheGreeting) } test("afterEach(config) gets the config passed to run") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.afterEachTestDataGotTheGreeting) } test("beforeAll(config) gets the config passed to run") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.beforeAllConfigGotTheGreeting) } test("afterAll(config) gets the config passed to run") { val a = new MySuite a.run(None, Args(SilentReporter, Stopper.default, Filter(), ConfigMap("hi" -> "there"), None, new Tracker, Set.empty)) assert(a.afterAllConfigGotTheGreeting) } // test exceptions with runTest test("If any invocation of beforeEach completes abruptly with an exception, runTest " + "will complete abruptly with the same exception.") { class MySuite extends Suite with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { override def beforeEach(td: TestData) { throw new NumberFormatException } } intercept[NumberFormatException] { val a = new MySuite a.run(Some("july"), Args(StubReporter)) } } test("If any call to super.runTest completes abruptly with an exception, runTest " + "will complete abruptly with the same exception, however, before doing so, it will invoke afterEach") { trait FunkySuite extends Suite { protected override def runTest(testName: String, args: Args): Status = { throw new NumberFormatException } } class MySuite extends FunkySuite with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { var afterEachCalled = false override def afterEach(td: TestData) { afterEachCalled = true } } val a = new MySuite intercept[NumberFormatException] { a.run(Some("july"), Args(StubReporter)) } assert(a.afterEachCalled) } test("If both super.runTest and afterEach complete abruptly with an exception, runTest " + "will complete abruptly with the exception thrown by super.runTest.") { trait FunkySuite extends Suite { protected override def runTest(testName: String, args: Args): Status = { throw new NumberFormatException } } class MySuite extends FunkySuite with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { var afterEachCalled = false override def afterEach(td: TestData) { afterEachCalled = true throw new IllegalArgumentException } } val a = new MySuite intercept[NumberFormatException] { a.run(Some("july"), Args(StubReporter)) } assert(a.afterEachCalled) } test("If super.runTest returns normally, but afterEach completes abruptly with an " + "exception, runTest will complete abruptly with the same exception.") { class MySuite extends Spec with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { override def afterEach(td: TestData) { throw new NumberFormatException } def `test July` = () } intercept[NumberFormatException] { val a = new MySuite a.run(Some("test July"), Args(StubReporter)) } } // test exceptions with run test("If any invocation of beforeAll completes abruptly with an exception, run " + "will complete abruptly with the same exception.") { class MySuite extends Spec with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { override def beforeAll(cm: ConfigMap) { throw new NumberFormatException } def `test July` = () } intercept[NumberFormatException] { val a = new MySuite a.run(None, Args(StubReporter)) } } test("If any call to super.run completes abruptly with an exception, run " + "will complete abruptly with the same exception, however, before doing so, it will invoke afterAll") { trait FunkySuite extends Spec { override def run(testName: Option[String], args: Args): Status = { throw new NumberFormatException } } class MySuite extends FunkySuite with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { var afterAllCalled = false def `test 1` = {} def `test 2` = {} def `test 3` = {} override def afterAll(cm: ConfigMap) { afterAllCalled = true } } val a = new MySuite intercept[NumberFormatException] { a.run(None, Args(StubReporter)) } assert(a.afterAllCalled) } test("If both super.run and afterAll complete abruptly with an exception, run " + "will complete abruptly with the exception thrown by super.run.") { trait FunkySuite extends Spec { override def run(testName: Option[String], args: Args): Status = { throw new NumberFormatException } } class MySuite extends FunkySuite with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { var afterAllCalled = false def `test 1` = {} def `test 2` = {} def `test 3` = {} override def afterAll(cm: ConfigMap) { afterAllCalled = true throw new IllegalArgumentException } } val a = new MySuite intercept[NumberFormatException] { a.run(None, Args(StubReporter)) } assert(a.afterAllCalled) } test("If super.run returns normally, but afterAll completes abruptly with an " + "exception, run will complete abruptly with the same exception.") { class MySuite extends Spec with BeforeAndAfterEachTestData with BeforeAndAfterAllConfigMap { override def afterAll(cm: ConfigMap) { throw new NumberFormatException } def `test July` = () } intercept[NumberFormatException] { val a = new MySuite a.run(None, Args(StubReporter)) } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/OnlyContainMatcherDeciderSpec.scala
/* * 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 import org.scalactic.Equality import org.scalactic.Explicitly import org.scalactic.StringNormalizations._ import org.scalactic.Uniformity import org.scalactic.Entry import collection.GenTraversable import SharedHelpers._ import Matchers._ class OnlyContainMatcherDeciderSpec extends Spec with Explicitly { val mapTrimmed: Uniformity[(Int, String)] = new Uniformity[(Int, String)] { def normalized(s: (Int, String)): (Int, String) = (s._1, s._2.trim) def normalizedCanHandle(b: Any) = b match { case (_: Int, _: String) => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case (k: Int, v: String) => normalized((k, v)) case _ => b } } val javaMapTrimmed: Uniformity[java.util.Map.Entry[Int, String]] = new Uniformity[java.util.Map.Entry[Int, String]] { def normalized(s: java.util.Map.Entry[Int, String]): java.util.Map.Entry[Int, String] = Entry(s.getKey, s.getValue.trim) def normalizedCanHandle(b: Any) = b match { case entry: java.util.Map.Entry[_, _] => (entry.getKey, entry.getValue) match { case (_: Int, _: String) => true case _ => false } case _ => false } def normalizedOrSame(b: Any): Any = b match { case entry: java.util.Map.Entry[_, _] => (entry.getKey, entry.getValue) match { case (k: Int, v: String) => normalized(Entry(k, v)) case _ => b } case _ => b } } val incremented: Uniformity[Int] = new Uniformity[Int] { var count = 0 def normalized(s: Int): Int = { count += 1 s + count } def normalizedCanHandle(b: Any): Boolean = b.isInstanceOf[Int] def normalizedOrSame(b: Any): Any = b match { case i: Int => normalized(i) case _ => b } } val mapIncremented: Uniformity[(Int, String)] = new Uniformity[(Int, String)] { var count = 0 def normalized(s: (Int, String)): (Int, String) = { count += 1 (s._1 + count, s._2) } def normalizedCanHandle(b: Any) = b match { case (_: Int, _: String) => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case (k: Int, v: String) => normalized((k, v)) case _ => b } } val appended: Uniformity[String] = new Uniformity[String] { var count = 0 def normalized(s: String): String = { count += 1 s + count } def normalizedCanHandle(b: Any): Boolean = b.isInstanceOf[String] def normalizedOrSame(b: Any): Any = b match { case s: String => normalized(s) case _ => b } } val mapAppended: Uniformity[(Int, String)] = new Uniformity[(Int, String)] { var count = 0 def normalized(s: (Int, String)): (Int, String) = { count += 1 (s._1, s._2 + count) } def normalizedCanHandle(b: Any) = b match { case (_: Int, _: String) => true case _ => false } def normalizedOrSame(b: Any): Any = b match { case (k: Int, v: String) => normalized((k, v)) case _ => b } } val javaMapAppended: Uniformity[java.util.Map.Entry[Int, String]] = new Uniformity[java.util.Map.Entry[Int, String]] { var count = 0 def normalized(s: java.util.Map.Entry[Int, String]): java.util.Map.Entry[Int, String] = { count += 1 Entry(s.getKey, s.getValue + count) } def normalizedCanHandle(b: Any) = b match { case entry: java.util.Map.Entry[_, _] => (entry.getKey, entry.getValue) match { case (_: Int, _: String) => true case _ => false } case _ => false } def normalizedOrSame(b: Any): Any = b match { case entry: java.util.Map.Entry[_, _] => (entry.getKey, entry.getValue) match { case (k: Int, v: String) => normalized(Entry(k, v)) case _ => b } case _ => b } } val lowerCaseEquality = new Equality[String] { def areEqual(left: String, right: Any) = left.toLowerCase == (right match { case s: String => s.toLowerCase case other => other }) } val mapLowerCaseEquality = new Equality[(Int, String)] { def areEqual(left: (Int, String), right: Any) = right match { case t2: Tuple2[_, _] => left._1 == t2._1 && left._2.toLowerCase == (t2._2 match { case s: String => s.toLowerCase case other => other }) case right => left == right } } val javaMapLowerCaseEquality = new Equality[java.util.Map.Entry[Int, String]] { def areEqual(left: java.util.Map.Entry[Int, String], right: Any) = right match { case entry: java.util.Map.Entry[_, _] => left.getKey == entry.getKey && left.getValue.toLowerCase == (entry.getValue match { case s: String => s.toLowerCase case other => other }) case right => left == right } } val reverseEquality = new Equality[String] { def areEqual(left: String, right: Any) = left.reverse == (right match { case s: String => s.toLowerCase case other => other }) } val mapReverseEquality = new Equality[(Int, String)] { def areEqual(left: (Int, String), right: Any) = right match { case t2: Tuple2[_, _] => left._1 == t2._1 && left._2.reverse == (t2._2 match { case s: String => s.toLowerCase case other => other }) case right => left == right } } val javaMapReverseEquality = new Equality[java.util.Map.Entry[Int, String]] { def areEqual(left: java.util.Map.Entry[Int, String], right: Any) = right match { case entry: java.util.Map.Entry[_, _] => left.getKey == entry.getKey && left.getValue.reverse == (entry.getValue match { case s: String => s.toLowerCase case other => other }) case right => left == right } } object `only ` { def checkShouldContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) { val leftText = FailureMessages.decorateToStringValue(left) e.message should be (Some(leftText + " did not contain only (" + right.map(FailureMessages.decorateToStringValue).mkString(", ") + ")")) e.failedCodeFileName should be (Some("OnlyContainMatcherDeciderSpec.scala")) e.failedCodeLineNumber should be (Some(lineNumber)) } def checkShouldNotContainStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) { val leftText = FailureMessages.decorateToStringValue(left) e.message should be (Some(leftText + " contained only (" + right.map(FailureMessages.decorateToStringValue).mkString(", ") + ")")) e.failedCodeFileName should be (Some("OnlyContainMatcherDeciderSpec.scala")) e.failedCodeLineNumber should be (Some(lineNumber)) } def `should take specified normalization when 'should contain' is used` { (List("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed) (Set("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed) (Array("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed) (javaList("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed) (javaSet("1", " 2", "3") should contain only (" 1", "2 ", " 3")) (after being trimmed) (Map(1 -> "one", 2 -> " two", 3 -> "three") should contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (after being mapTrimmed) (javaMap(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")) should contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (after being javaMapTrimmed) } def `should take specified normalization when 'should not contain' is used` { (List("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended) (Set("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended) (Array("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended) (javaList("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended) (javaSet("1", "2", "3") should not contain only ("1", "2", "3")) (after being appended) (Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain only (1 -> "one", 2 -> "two", 3 -> "three")) (after being mapAppended) (javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain only (Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))) (after being javaMapAppended) } def `should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with specified normalization` { val left1 = List("1", "2", "3") val e1 = intercept[exceptions.TestFailedException] { (left1 should contain only ("1", "2", "3")) (after being appended) } checkShouldContainStackDepth(e1, left1, Array("1", "2", "3").deep, thisLineNumber - 2) val left2 = Set("1", "2", "3") val e2 = intercept[exceptions.TestFailedException] { (left2 should contain only ("1", "2", "3")) (after being appended) } checkShouldContainStackDepth(e2, left2, Array("1", "2", "3").deep, thisLineNumber - 2) val left3 = Array("1", "2", "3") val e3 = intercept[exceptions.TestFailedException] { (left3 should contain only ("1", "2", "3")) (after being appended) } checkShouldContainStackDepth(e3, left3, Array("1", "2", "3").deep, thisLineNumber - 2) val left4 = javaList("1", "2", "3") val e4 = intercept[exceptions.TestFailedException] { (left4 should contain only ("1", "2", "3")) (after being appended) } checkShouldContainStackDepth(e4, left4, Array("1", "2", "3").deep, thisLineNumber - 2) val left5 = Map(1 -> "one", 2 -> "two", 3 -> "three") val e5 = intercept[exceptions.TestFailedException] { (left5 should contain only (1 -> "one", 2 -> "two", 3 -> "three")) (after being mapAppended) } checkShouldContainStackDepth(e5, left5, Array(1 -> "one", 2 -> "two", 3 -> "three").deep, thisLineNumber - 2) val left6 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) val e6 = intercept[exceptions.TestFailedException] { (left6 should contain only (Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))) (after being javaMapAppended) } checkShouldContainStackDepth(e6, left6, Array(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")).deep, thisLineNumber - 2) } def `should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with specified normalization` { val left1 = List("1", " 2", "3") val e1 = intercept[exceptions.TestFailedException] { (left1 should not contain only (" 1", "2 ", " 3")) (after being trimmed) } checkShouldNotContainStackDepth(e1, left1, Array(" 1", "2 ", " 3").deep, thisLineNumber - 2) val left2 = Set("1", " 2", "3") val e2 = intercept[exceptions.TestFailedException] { (left2 should not contain only (" 1", "2 ", " 3")) (after being trimmed) } checkShouldNotContainStackDepth(e2, left2, Array(" 1", "2 ", " 3").deep, thisLineNumber - 2) val left3 = Array("1", " 2", "3") val e3 = intercept[exceptions.TestFailedException] { (left3 should not contain only (" 1", "2 ", " 3")) (after being trimmed) } checkShouldNotContainStackDepth(e3, left3, Array(" 1", "2 ", " 3").deep, thisLineNumber - 2) val left4 = javaList("1", " 2", "3") val e4 = intercept[exceptions.TestFailedException] { (left4 should not contain only (" 1", "2 ", " 3")) (after being trimmed) } checkShouldNotContainStackDepth(e4, left4, Array(" 1", "2 ", " 3").deep, thisLineNumber - 2) val left5 = Map(1 -> "one", 2 -> " two", 3 -> "three") val e5 = intercept[exceptions.TestFailedException] { (left5 should not contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (after being mapTrimmed) } checkShouldNotContainStackDepth(e5, left5, Array(1 -> " one", 2 -> "two ", 3 -> " three").deep, thisLineNumber - 2) val left6 = javaMap(Entry(1, "one"), Entry(2, " two"), Entry(3, "three")) val e6 = intercept[exceptions.TestFailedException] { (left6 should not contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (after being javaMapTrimmed) } checkShouldNotContainStackDepth(e6, left6, Array(Entry(1, " one"), Entry(2, "two "), Entry(3, " three")).deep, thisLineNumber - 2) } def `should take specified equality and normalization when 'should contain' is used` { (List("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) (Set("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) (Array("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) (javaList("ONE ", " TWO", "THREE ") should contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) (Map(1 -> "ONE ", 2 -> " TWO", 3 -> "THREE ") should contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (decided by mapLowerCaseEquality afterBeing mapTrimmed) (javaMap(Entry(1, "ONE "), Entry(2, " TWO"), Entry(3, "THREE ")) should contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapLowerCaseEquality afterBeing javaMapTrimmed) } def `should take specified equality and normalization when 'should not contain' is used` { (List("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) (Set("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) (Array("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) (javaList("one ", " two", "three ") should not contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) (Map(1 -> "one ", 2 -> " two", 3 -> "three ") should not contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (decided by mapReverseEquality afterBeing mapTrimmed) (javaMap(Entry(1, "one "), Entry(2, " two"), Entry(3, "three ")) should not contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapReverseEquality afterBeing javaMapTrimmed) } def `should throw TestFailedException with correct stack depth and message when 'should contain custom matcher' failed with specified equality and normalization` { val left1 = List("one ", " two", "three ") val e1 = intercept[exceptions.TestFailedException] { (left1 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e1, left1, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left2 = Set("one ", " two", "three ") val e2 = intercept[exceptions.TestFailedException] { (left2 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e2, left2, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left3 = Array("one ", " two", "three ") val e3 = intercept[exceptions.TestFailedException] { (left3 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e3, left3, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left4 = javaList("one ", " two", "three ") val e4 = intercept[exceptions.TestFailedException] { (left4 should contain only (" one", "two ", " three")) (decided by reverseEquality afterBeing trimmed) } checkShouldContainStackDepth(e4, left4, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left5 = Map(1 -> "one ", 2 -> " two", 3 -> "three ") val e5 = intercept[exceptions.TestFailedException] { (left5 should contain only (1 -> " one", 2 -> "two ", 3 -> " three")) (decided by mapReverseEquality afterBeing mapTrimmed) } checkShouldContainStackDepth(e5, left5, Array(1 -> " one", 2 -> "two ", 3 -> " three").deep, thisLineNumber - 2) val left6 = javaMap(Entry(1, "one "), Entry(2, " two"), Entry(3, "three ")) val e6 = intercept[exceptions.TestFailedException] { (left6 should contain only (Entry(1, " one"), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapReverseEquality afterBeing javaMapTrimmed) } checkShouldContainStackDepth(e6, left6, Array(Entry(1, " one"), Entry(2, "two "), Entry(3, " three")).deep, thisLineNumber - 2) } def `should throw TestFailedException with correct stack depth and message when 'should not contain custom matcher' failed with specified equality and normalization` { val left1 = List("ONE ", " TWO", "THREE ") val e1 = intercept[exceptions.TestFailedException] { (left1 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e1, left1, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left2 = Set("ONE ", " TWO", "THREE ") val e2 = intercept[exceptions.TestFailedException] { (left2 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e2, left2, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left3 = Array("ONE ", " TWO", "THREE ") val e3 = intercept[exceptions.TestFailedException] { (left3 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e3, left3, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left4 = javaList("ONE ", " TWO", "THREE ") val e4 = intercept[exceptions.TestFailedException] { (left4 should not contain only (" one", "two ", " three")) (decided by lowerCaseEquality afterBeing trimmed) } checkShouldNotContainStackDepth(e4, left4, Array(" one", "two ", " three").deep, thisLineNumber - 2) val left5 = Map(1 -> "ONE ", 2 -> " TWO", 3 -> "THREE ") val e5 = intercept[exceptions.TestFailedException] { (left5 should not contain only (1 -> " one ", 2 -> "two ", 3 -> " three")) (decided by mapLowerCaseEquality afterBeing mapTrimmed) } checkShouldNotContainStackDepth(e5, left5, Array(1 -> " one ", 2 -> "two ", 3 -> " three").deep, thisLineNumber - 2) val left6 = javaMap(Entry(1, "ONE "), Entry(2, " TWO"), Entry(3, "THREE ")) val e6 = intercept[exceptions.TestFailedException] { (left6 should not contain only (Entry(1, " one "), Entry(2, "two "), Entry(3, " three"))) (decided by javaMapLowerCaseEquality afterBeing javaMapTrimmed) } checkShouldNotContainStackDepth(e6, left6, Array(Entry(1, " one "), Entry(2, "two "), Entry(3, " three")).deep, thisLineNumber - 2) } } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/enablers/SafeSeqsConstraint.scala
/* * 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.scalactic.enablers import org.scalactic.{Equality, NormalizingEquality, Every, EqualityConstraint} import scala.collection.{GenTraversableOnce, GenTraversable} import org.scalactic.EqualityPolicy.BasicEqualityConstraint import annotation.implicitNotFound import scala.language.higherKinds @implicitNotFound(msg = "Could not find evidence that ${R} can be contained in ${C}; the missing implicit parameter is of type org.scalactic.enablers.SafeSeqsConstraint[${C},${R}]") trait SafeSeqsConstraint[-C, R] { def contains(container: C, element: R): Boolean def indexOf(container: C, element: R, from: Int): Int def lastIndexOf(container: C, element: R, end: Int): Int def indexOfSlice(container: C, slice: scala.collection.GenSeq[R], from: Int): Int def lastIndexOfSlice(container: C, slice: scala.collection.GenSeq[R], from: Int): Int } object SafeSeqsConstraint { implicit def containingNatureOfGenSeq[E, GENSEQ[e] <: scala.collection.GenSeq[e], R](implicit constraint: R <:< E): SafeSeqsConstraint[GENSEQ[E], R] = new SafeSeqsConstraint[GENSEQ[E], R] { def contains(genSeq: GENSEQ[E], ele: R): Boolean = { genSeq match { case seq: Seq[_] => seq.contains(ele) case _ => genSeq.exists(_ == ele) } } def indexOf(genSeq: GENSEQ[E], element: R, from: Int): Int = genSeq.indexOf(element, from) def lastIndexOf(genSeq: GENSEQ[E], element: R, end: Int): Int = genSeq.lastIndexOf(element, end) def indexOfSlice(genSeq: GENSEQ[E], slice: scala.collection.GenSeq[R], from: Int): Int = genSeq.toStream.indexOfSlice(slice, if (from < 0) 0 else from) def lastIndexOfSlice(genSeq: GENSEQ[E], slice: scala.collection.GenSeq[R], from: Int): Int = genSeq.toStream.lastIndexOfSlice(slice, if (from < 0) 0 else from) } implicit def containingNatureOfArray[E, ARRAY[e] <: Array[e], R](implicit constraint: R <:< E): SafeSeqsConstraint[ARRAY[E], R] = new SafeSeqsConstraint[ARRAY[E], R] { def contains(array: ARRAY[E], ele: R): Boolean = { array.contains(ele) } def indexOf(array: ARRAY[E], element: R, from: Int): Int = array.indexOf(element, from) def lastIndexOf(array: ARRAY[E], element: R, end: Int): Int = array.lastIndexOf(element, end) def indexOfSlice(array: ARRAY[E], slice: scala.collection.GenSeq[R], from: Int): Int = array.indexOfSlice(slice, if (from < 0) 0 else from) def lastIndexOfSlice(array: ARRAY[E], slice: scala.collection.GenSeq[R], from: Int): Int = array.lastIndexOfSlice(slice, if (from < 0) 0 else from) } implicit def containingNatureOfEvery[E, EVERY[e] <: Every[e], R](implicit constraint: R <:< E): SafeSeqsConstraint[EVERY[E], R] = new SafeSeqsConstraint[EVERY[E], R] { def contains(every: EVERY[E], ele: R): Boolean = { every.toVector.contains(ele) } def indexOf(every: EVERY[E], element: R, from: Int): Int = every.toVector.indexOf(element, from) def lastIndexOf(every: EVERY[E], element: R, end: Int): Int = every.toVector.lastIndexOf(element, end) def indexOfSlice(every: EVERY[E], slice: scala.collection.GenSeq[R], from: Int): Int = every.toStream.indexOfSlice(slice, if (from < 0) 0 else from) def lastIndexOfSlice(every: EVERY[E], slice: scala.collection.GenSeq[R], from: Int): Int = every.toStream.lastIndexOfSlice(slice, if (from < 0) 0 else from) } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/algebra/Functor.scala
<filename>scalactic/src/main/scala/org/scalactic/algebra/Functor.scala<gh_stars>1-10 /* * Copyright 2001-2014 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.scalactic.algebra import scala.language.higherKinds import scala.language.implicitConversions /** * Typeclass trait representing an algebraic structure defined by a <code>map</code> method that * obeys laws of <em>identity</em> and <em>composition</em>. * * <p> * The <em>identity law</em> states that given a value <code>ca</code> of type <code>Context[A]</code> and * the identity function, <code>(a: A) => a</code> (and implicit <code>Functor.adapters</code> imported): * </p> * * <pre> * ca.map((a: A) =&gt; a) === ca * </pre> * * <p> * The <em>composition law</em> states that given a value <code>ca</code> of type <code>Context[A]</code> and * two functions, <code>f</code> of type <code>A =&gt; B</code> and <code>g</code> of type <code>B =&gt; C</code> * (and implicit <code>Functor.adapters</code> imported): * </p> * * <pre> * ca.map(f).map(g) === ca.map(g compose f) * </pre> */ trait Functor[Context[_]] { /** * Applies the given function to the given value in context, returning the result in * the context. * * <p> * See the main documentation for this trait for more detail. * </p> */ def map[A, B](ca: Context[A])(f: A => B): Context[B] } /** * Companion object for trait <a href="Functor.html"><code>Functor</code></a>. */ object Functor { /** * Adapter class for <a href="Functor.html"><code>Functor</code></a> * that wraps a value of type <code>Context[A]</code> given an * implicit <code>Functor[Context]</code>. * * @param underlying The value of type <code>Context[A]</code> to wrap. * @param functor The captured <code>Functor[Context]</code> whose behavior * is used to implement this class's methods. */ class Adapter[Context[_], A](val underlying: Context[A])(implicit val functor: Functor[Context]) { /** * A mapping operation that obeys the identity and composition laws. * * See the main documentation for trait <a href="Functor.html"><code>Functor</code></a> for more detail. */ def map[B](f: A => B): Context[B] = functor.map(underlying)(f) } /** * Implicitly wraps an object in a <code>Functor.Adapter[Context, A]</code> * so long as an implicit <code>Functor[Context]</code> is available. */ implicit def adapters[Context[_], A](ca: Context[A])(implicit ev: Functor[Context]): Functor.Adapter[Context, A] = new Adapter(ca)(ev) /** * Summons an implicitly available Functor[Context]. * * <p> * This method allows you to write expressions like <code>Functor[List]</code> instead of * <code>implicitly[Functor[List]]</code>. * </p> */ def apply[Context[_]](implicit ev: Functor[Context]): Functor[Context] = ev }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/enablers/NoParamSpec.scala
/* * 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.enablers import org.scalatest._ import org.scalactic.Equality import scala.collection.immutable import org.scalatest.exceptions.TestFailedException class NoParamSpec extends Spec with Matchers with LoneElement { object `The implicit Containing providers` { def `should work with no-param collection types and default equality` { ConfigMap("hi" -> 1, "ho" -> "two") should contain ("hi" -> 1) } def `should be overridable with something that takes a specific equality` { implicit val inverseEquality = new Equality[(String, Any)] { def areEqual(a: (String, Any), b: Any): Boolean = a != b } ConfigMap("hi" -> 1) should not contain ("hi" -> 1) } } object `The implicit Aggregating providers` { def `should work with no-param collection types and default equality` { ConfigMap("hi" -> 1, "ho" -> "two") should contain allOf ("hi" -> 1, "ho" -> "two") } def `should be overridable with something that takes a specific equality` { implicit val inverseEquality = new Equality[(String, Any)] { def areEqual(a: (String, Any), b: Any): Boolean = a != b } ConfigMap("hi" -> 1) should not contain allOf ("hi" -> 1, "ho" -> "two") } } object `The implicit KeyMapping providers` { def `should work with no-param collection types and default equality` { ConfigMap("hi" -> 1, "ho" -> "two") should contain key ("hi") } def `should be overridable with something that takes a specific equality` { implicit val inverseEquality = new Equality[String] { def areEqual(a: String, b: Any): Boolean = a != b } ConfigMap("hi" -> 1) should not contain key ("hi") } } object `The implicit ValueMapping providers` { def `should work with no-param collection types and default equality` { ConfigMap("hi" -> 1, "ho" -> "two") should contain value (1) } def `should be overridable with something that takes a specific equality` { implicit val inverseEquality = new Equality[Any] { def areEqual(a: Any, b: Any): Boolean = a != b } ConfigMap("hi" -> 1) should not contain value (1) } } class MyStringSeq(underlying: immutable.Seq[String]) extends immutable.Seq[String] { def iterator: Iterator[String] = underlying.iterator def length: Int = underlying.length def apply(idx: Int): String = underlying(idx) } object MyStringSeq { def apply(args: String*): MyStringSeq = new MyStringSeq(immutable.Seq.empty[String] ++ args) } object `The implicit Sequencing providers` { def `should work with no-param collection types and default equality` { MyStringSeq("hi", "ho", "hey") should contain inOrder ("hi", "hey") } def `should be overridable with something that takes a specific equality` { implicit val inverseEquality = new Equality[String] { def areEqual(a: String, b: Any): Boolean = a != b } MyStringSeq("hi", "ho") should not contain inOrder ("hi", "ho") } } object `The implicit Collecting providers` { // I am not sure why this one already works without needing to make Collecting contravariant in C def `should work with no-param collection types` { MyStringSeq("hi").loneElement should be ("hi") intercept[TestFailedException] { MyStringSeq("hi", "ho").loneElement } ConfigMap("hi" -> 1).loneElement should be ("hi" -> 1) intercept[TestFailedException] { ConfigMap("hi" -> 1, "ho" -> 2).loneElement } } } object `The implicit Sortable providers` { def `should work with no-param collection types` { MyStringSeq("hey", "hi", "ho") should be (sorted) MyStringSeq("hi", "di", "ho") should not be sorted } } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/LazySeq.scala
/* * Copyright 2001-2015 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.scalactic trait LazySeq[+T] extends LazyBag[T] { def map[U](f: T => U): LazySeq[U] def flatMap[U](f: T => LazyBag[U]): LazySeq[U] def toEquaSet[U >: T](toPath: EquaPath[U]): toPath.EquaSet def toSortedEquaSet[U >: T](toPath: SortedEquaPath[U]): toPath.SortedEquaSet def toList: List[T] def size: Int def zip[U](that: LazyBag[U]): LazySeq[(T, U)] def zipAll[U, T1 >: T](that: LazyBag[U], thisElem: T1, thatElem: U): LazySeq[(T1, U)] def zipWithIndex: LazySeq[(T, Int)] } object LazySeq { private class BasicLazySeq[T](private val args: List[T]) extends LazySeq[T] { thisLazySeq => def map[U](f: T => U): LazySeq[U] = new MapLazySeq(thisLazySeq, f) def flatMap[U](f: T => LazyBag[U]): LazySeq[U] = new FlatMapLazySeq(thisLazySeq, f) def toEquaSet[U >: T](toPath: EquaPath[U]): toPath.FastEquaSet = toPath.FastEquaSet(args: _*) def toSortedEquaSet[U >: T](toPath: SortedEquaPath[U]): toPath.SortedEquaSet = toPath.TreeEquaSet(args: _*) def toList: List[T] = args def size: Int = args.size def zip[U](that: LazyBag[U]): LazySeq[(T, U)] = new ZipLazySeq(thisLazySeq, that) def zipAll[U, T1 >: T](that: LazyBag[U], thisElem: T1, thatElem: U): LazySeq[(T1, U)] = new ZipAllLazySeq(thisLazySeq, that, thisElem, thatElem) def zipWithIndex: LazySeq[(T, Int)] = new ZipWithIndex(thisLazySeq) override def toString = args.mkString("LazySeq(", ",", ")") override def equals(other: Any): Boolean = ??? override def hashCode: Int = ??? } private abstract class TransformLazySeq[T, U] extends LazySeq[U] { thisLazySeq => def map[V](g: U => V): LazySeq[V] = new MapLazySeq[U, V](thisLazySeq, g) def flatMap[V](f: U => LazyBag[V]): LazySeq[V] = new FlatMapLazySeq(thisLazySeq, f) def toEquaSet[V >: U](toPath: EquaPath[V]): toPath.FastEquaSet = { toPath.FastEquaSet(toList: _*) } def toSortedEquaSet[V >: U](toPath: SortedEquaPath[V]): toPath.SortedEquaSet = { toPath.TreeEquaSet(toList: _*) } def toList: List[U] def size: Int = toList.size def zip[V](that: LazyBag[V]): LazySeq[(U, V)] = new ZipLazySeq(thisLazySeq, that) def zipAll[V, U1 >: U](that: LazyBag[V], thisElem: U1, thatElem: V): LazySeq[(U1, V)] = new ZipAllLazySeq(thisLazySeq, that, thisElem, thatElem) def zipWithIndex: LazySeq[(U, Int)] = new ZipWithIndex(thisLazySeq) override def toString: String = toList.mkString("LazySeq(", ",", ")") override def equals(other: Any): Boolean = other match { case otherLazySeq: LazySeq[_] => thisLazySeq.toList == otherLazySeq.toList case _ => false } override def hashCode: Int = thisLazySeq.toList.hashCode } private class MapLazySeq[T, U](lazySeq: LazySeq[T], f: T => U) extends TransformLazySeq[T, U] { thisLazySeq => def toList: List[U] = lazySeq.toList.map(f) } private class FlatMapLazySeq[T, U](lazySeq: LazySeq[T], f: T => LazyBag[U]) extends TransformLazySeq[T, U] { thisLazySeq => def toList: List[U] = lazySeq.toList.flatMap(f.andThen(_.toList)) } private class ZipLazySeq[T, U](thisSeq: LazySeq[T], that: LazyBag[U]) extends TransformLazySeq[T, (T, U)] { def toList: List[(T, U)] = thisSeq.toList.zip(that.toList) } private class ZipAllLazySeq[T, U](thisSeq: LazySeq[T], thatBag: LazyBag[U], thisElem: T, thatElem: U) extends TransformLazySeq[T, (T, U)] { def toList: List[(T, U)] = thisSeq.toList.zipAll(thatBag.toList, thisElem, thatElem) } private class ZipWithIndex[T, U](thisSeq: LazySeq[T]) extends TransformLazySeq[T, (T, Int)] { def toList: List[(T, Int)] = thisSeq.toList.zipWithIndex } def apply[T](args: T*): LazySeq[T] = new BasicLazySeq(args.toList) }
cquiroz/scalatest
scalactic-test/src/test/scala/org/scalactic/TrySugarSpec.scala
/* * Copyright 2001-2014 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.scalactic import java.text._ import org.scalatest._ import scala.util.Try import scala.util.Success import scala.util.Failure import prop.TableDrivenPropertyChecks._ class TrySugarSpec extends UnitSpec with Accumulation with TrySugar { def isRound(i: Int): Validation[ErrorMessage] = if (i % 10 == 0) Pass else Fail(i + " was not a round number") def isDivBy3(i: Int): Validation[ErrorMessage] = if (i % 3 == 0) Pass else Fail(i + " was not divisible by 3") case class SomeException(msg: String) extends Exception(msg) "TrySugar" should "enable toOr to be invoked on Trys" in { Success(12).toOr shouldBe Good(12) (Success(12): Try[Int]).toOr shouldBe Good(12) val ex = new Exception("oops") Failure(ex).toOr shouldBe Bad(ex) (Failure(ex): Try[Int]).toOr shouldBe Bad(ex) } it should "offer a validating method that takes a T => Validation" in { Success(12).validating(isRound) shouldBe Failure(ValidationFailedException("12 was not a round number")) Success(10).validating(isRound) shouldBe Success(10) // Failure(SomeException("oops")).validating(isRound) shouldBe Failure(SomeException("oops")) Failure[Int](SomeException("oops")).validating(isRound) shouldBe Failure(SomeException("oops")) } it should "allow multiple validation functions to be passed to validating" in { Success(12).validating(isRound, isDivBy3) shouldBe Failure(ValidationFailedException("12 was not a round number")) Success(10).validating(isRound, isDivBy3) shouldBe Failure(ValidationFailedException("10 was not divisible by 3")) Success(30).validating(isRound, isDivBy3) shouldBe Success(30) // Failure(SomeException("oops")).validating(isRound, isDivBy3) shouldBe Failure(SomeException("oops")) Failure[Int](SomeException("oops")).validating(isRound, isDivBy3) shouldBe Failure(SomeException("oops")) } it should "require at least one parameter to be passed to validating" in { "Try(30).validating()" shouldNot compile } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/algebra/Distributive.scala
/* * Copyright 2001-2015 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.scalactic.algebra import scala.language.higherKinds import scala.language.implicitConversions /** * Typeclass trait representing two binary operations that obeys the distributive law: * one, <code>dop</code> that does the distributing, and the other <code>op</code> binary op that dop is applied to. * * <p> * The distributive law states that given values <code>a</code>, <code>b</code>, <code>c</code> * </p> * * <pre> * a dop (b op c) === (a dop b) op (a dop c) * </pre> * */ trait Distributive[A] { /** * A binary operation to be distributed over. */ def op(a1: A, a2: A): A /** * A binary operation that does the distributing, "distributing op." * * See the main documentation for this trait for more detail. */ def dop(a1: A, a2: A): A } /** * Companion object for <code>Distributive</code>. * an implicit conversion method from <code>A</code> to <code>Distributive.Adapter[A]</code> */ object Distributive { /** * Adapter class for <a href="Distributive.html"><code>Distributive</code></a> * that wraps a value of type <code>A</code> given an * implicit <code>Distributive[A]</code>. * * @param underlying The value of type <code>A</code> to wrap. * @param distributive The captured <code>Distributive[A]</code> whose behavior * is used to implement this class's methods. */ class Adapter[A](val underlying: A)(implicit val distributive: Distributive[A]) { /** * A binary operation to be distributed over: used with dop. * * See the main documentation for trait <a href="Distributive.html"><code>Distributive</code></a> for more detail. */ def op(a2: A): A = distributive.op(underlying, a2) /** * A binary operation that does the distributing. * * See the main documentation for trait <a href="Distributive.html"><code>Distributive</code></a> for more detail. */ def dop(a2: A): A = distributive.dop(underlying, a2) } /** * Implicitly wraps an object in an <code>Distributive.Adapter[A]</code> * so long as an implicit <code>Distributive[A]</code> is available. */ implicit def adapters[A](a: A)(implicit ev: Distributive[A]): Distributive.Adapter[A] = new Adapter(a)(ev) /** * Summons an implicitly available <code>Distributive[A]</code>. * * <p> * This method allows you to write expressions like <code>Distributive[Int]</code> instead of * <code>implicitly[Distributive[Ints]]</code>. * </p> */ def apply[A](implicit ev: Distributive[A]): Distributive[A] = ev }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/StreamlinedXmlNormMethodsSpec.scala
/* * Copyright 2001-2014 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 import scala.xml.{Node, Text, NodeSeq} class StreamlinedXmlNormMethodsSpec extends Spec with Matchers with StreamlinedXmlNormMethods { object `Xml Normalization of Elems` { def `should leave already-normalized XML alone` { <summer></summer>.norm == <summer></summer> shouldBe true } def `should zap text that is only whitespace` { <summer> </summer>.norm == <summer></summer> shouldBe true <summer> </summer>.norm == <summer></summer> shouldBe true <summer> <day></day> </summer>.norm == <summer><day></day></summer> shouldBe true <summer><day></day></summer> == <summer> <day></day> </summer>.norm shouldBe true <summer><day>Dude!</day></summer> == <summer> <day> Dude! </day> </summer>.norm shouldBe true <div>{Text("My name is ")}{Text("Harry")}</div>.norm shouldBe <div>My name is Harry</div> } } object `Xml Normalization of Nodes` { def `should leave already-normalized XML alone` { (<summer></summer>: Node).norm == <summer></summer> shouldBe true (Text("Bla"): Node).norm shouldBe Text("Bla") } def `should zap text that is only whitespace, unless it is already a Text` { (<summer> </summer>.norm: Node) == <summer></summer> shouldBe true (<summer> </summer>.norm: Node) == <summer></summer> shouldBe true (<summer> <day></day> </summer>.norm: Node) == <summer><day></day></summer> shouldBe true <summer><day></day></summer> == (<summer> <day></day> </summer>.norm: Node) shouldBe true <summer><day>Dude!</day></summer> == (<summer> <day> Dude! </day> </summer>.norm: Node) shouldBe true (Text(" "): Node).norm shouldBe Text(" ") (<div>{Text("My name is ")}{Text("Harry")}</div>: Node).norm shouldBe <div>My name is Harry</div> } } object `Xml Normalization of NodeSeq` { def `should leave already-normalized XML alone` { (<summer></summer>: NodeSeq).norm == <summer></summer> shouldBe true (Text("Bla"): NodeSeq).norm shouldBe Text("Bla") } def `should zap text that is only whitespace, unless it is already a Text` { (<summer> </summer>.norm: NodeSeq) == <summer></summer> shouldBe true (<summer> </summer>.norm: NodeSeq) == <summer></summer> shouldBe true (<summer> <day></day> </summer>.norm: NodeSeq) == <summer><day></day></summer> shouldBe true <summer><day></day></summer> == (<summer> <day></day> </summer>.norm: NodeSeq) shouldBe true <summer><day>Dude!</day></summer> == (<summer> <day> Dude! </day> </summer>.norm: NodeSeq) shouldBe true (Text(" "): NodeSeq).norm shouldBe Text(" ") (<div>{Text("My name is ")}{Text("Harry")}</div>: NodeSeq).norm shouldBe <div>My name is Harry</div> } } }
cquiroz/scalatest
scalactic/src/main/scala/org/scalactic/TrySugar.scala
/* * 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.scalactic import scala.util.Try import scala.util.Failure import annotation.tailrec /** * Trait providing an implicit class that adds a <code>toOr</code> method to * <code>Try</code>, which converts <code>Success</code> to <code>Good</code>, * and <code>Failure</code> to <code>Bad</code>. */ trait TrySugar { /** * Implicit class that adds a <code>toOr</code> method to * <code>Try</code>, which converts <code>Success</code> to <code>Good</code>, * and <code>Failure</code> to <code>Bad</code>. */ implicit class Tryizer[T](theTry: Try[T]) { def toOr: T Or Throwable = Or.from(theTry) def validating(hd: T => Validation[ErrorMessage], tl: (T => Validation[ErrorMessage])*): Try[T] = { theTry.flatMap { (o: T) => TrySugar.passOrFirstFail(o, hd :: tl.toList) match { case Pass => theTry case Fail(errorMessage) => Failure(ValidationFailedException(errorMessage)) } } } } } /** * Companion object for <code>TrySugar</code> enabling its members to be * imported as an alternative to mixing them in. */ object TrySugar extends TrySugar { @tailrec private[scalactic] def passOrFirstFail[T, E](o: T, fs: List[T => Validation[E]]): Validation[E] = { fs match { case Nil => Pass case head :: tail => head(o) match { case Pass => passOrFirstFail(o, tail) case firstFail => firstFail } } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/junit/helpers/TestWasCalledSuite.scala
/* * 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.junit.helpers import org.scalatest._ import org.scalatest.junit._ // This needs to be top level, not nested, because JUnit3 can't instantiate it // to run each test in its own instance if it is nested (no no-arg construtor). class TestWasCalledSuite extends JUnit3Suite { def testThis() { TestWasCalledSuite.theTestThisCalled = true } def testThat() { TestWasCalledSuite.theTestThatCalled = true } } object TestWasCalledSuite { def reinitialize() { theTestThisCalled = false theTestThatCalled = false } // Had to pull these out of the class, because JUnit makes a separate // instance for each test var theTestThisCalled = false var theTestThatCalled = false } class TestWithNonUnitMethod extends JUnit3Suite { def testThis() {} def testThat() {} // JUnit will not discover or run this, because its return type // is not Unit def testTheOtherThing(): String = "hi" } class TestWithMethodNamedTest extends JUnit3Suite { def testThis() {} def testThat() {} // JUnit will discover and run this method: def test() {} } class ASuite extends JUnit3Suite { def testThis() = () def testThat(info: Informer) = () } class BSuite extends JUnit3Suite { @Ignore def testThis() = () def testThat(info: Informer) = () } class CSuite extends JUnit3Suite { @FastAsLight def testThis() = () def testThat(info: Informer) = () } class DSuite extends JUnit3Suite { @FastAsLight @SlowAsMolasses def testThis() = () @SlowAsMolasses def testThat(info: Informer) = () def testTheOtherThing(info: Informer) = () def testOne() = () def testTwo() = () def test() = () // JUnit will discover and run this method simply named "test" def testFour(): String = "hi" // JUnit will not run these two because they don't def testFive(): Int = 5 // have result type Unit. } class ESuite extends JUnit3Suite { @FastAsLight @SlowAsMolasses def testThis() = () @SlowAsMolasses def testThat(info: Informer) = () @Ignore def testTheOtherThing(info: Informer) = () } class ShouldFailSuite extends JUnit3Suite { def testThrowsAssertionError() { throw new AssertionError } def testThrowsPlainOldError() { throw new Error } def testThrowsThrowable() { throw new Throwable } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/Reporter.scala
<reponame>cquiroz/scalatest /* * 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 import org.scalatest.events.Event /** * Trait whose instances collect the results of a running * suite of tests and presents those results in some way to the user. Instances of this trait can * be called "report functions" or "reporters." * * <p> * Reporters receive test results via fifteen events. * Each event is fired to pass a particular kind of information to * the reporter. The events are: * </p> * * <ul> * <li><a href="events/DiscoveryStarting.html"><code>DiscoveryStarting</code></a></li> * <li><a href="events/DiscoveryCompleted.html"><code>DiscoveryCompleted</code></a></li> * <li><a href="events/RunStarting.html"><code>RunStarting</code></a></li> * <li><a href="events/RunStopped.html"><code>RunStopped</code></a></li> * <li><a href="events/RunAborted.html"><code>RunAborted</code></a></li> * <li><a href="events/RunCompleted.html"><code>RunCompleted</code></a></li> * <li><a href="events/ScopeOpened.html"><code>ScopeOpened</code></a></li> * <li><a href="events/ScopeClosed.html"><code>ScopeClosed</code></a></li> * <li><a href="events/ScopePending.html"><code>ScopePending</code></a></li> * <li><a href="events/TestStarting.html"><code>TestStarting</code></a></li> * <li><a href="events/TestSucceeded.html"><code>TestSucceeded</code></a></li> * <li><a href="events/TestFailed.html"><code>TestFailed</code></a></li> * <li><a href="events/TestCanceled.html"><code>TestCanceled</code></a></li> * <li><a href="events/TestIgnored.html"><code>TestIgnored</code></a></li> * <li><a href="events/TestPending.html"><code>TestPending</code></a></li> * <li><a href="events/SuiteStarting.html"><code>SuiteStarting</code></a></li> * <li><a href="events/SuiteCompleted.html"><code>SuiteCompleted</code></a></li> * <li><a href="events/SuiteAborted.html"><code>SuiteAborted</code></a></li> * <li><a href="events/InfoProvided.html"><code>InfoProvided</code></a></li> * <li><a href="events/MarkupProvided.html"><code>MarkupProvided</code></a></li> * <li><a href="events/AlertProvided.html"><code>AlertProvided</code></a></li> * <li><a href="events/NoteProvided.html"><code>NoteProvided</code></a></li> * </ul> * * <p> * Reporters may be implemented such that they only present some of the reported events to the user. For example, you could * define a reporter class that does nothing in response to <code>SuiteStarting</code> events. * Such a class would always ignore <code>SuiteStarting</code> events. * </p> * * <p> * The term <em>test</em> as used in the <code>TestStarting</code>, <code>TestSucceeded</code>, * and <code>TestFailed</code> event names * is defined abstractly to enable a wide range of test implementations. * ScalaTest's style traits (subclasse of trait <a href="Suite.html"><code>Suite</code></a>) fire * <code>TestStarting</code> to indicate they are about to invoke one * of their tests, <code>TestSucceeded</code> to indicate a test returned normally, * and <code>TestFailed</code> to indicate a test completed abruptly with an exception. * Although the execution of a <code>Suite</code> subclass's tests will likely be a common event * reported via the * <code>TestStarting</code>, <code>TestSucceeded</code>, and <code>TestFailed</code> events, because * of the abstract definition of &ldquo;test&rdquo; used by the * the event classes, these events are not limited to this use. Information about any conceptual test * may be reported via the <code>TestStarting</code>, <code>TestSucceeded</code>, and * <code>TestFailed</code> events. * * <p> * Likewise, the term <em>suite</em> as used in the <code>SuiteStarting</code>, <code>SuiteAborted</code>, * and <code>SuiteCompleted</code> event names * is defined abstractly to enable a wide range of suite implementations. * Object <a href="tools/Runner$.html"><code>Runner</code></a> fires <code>SuiteStarting</code> to indicate it is about to invoke * <code>run</code> on a * <code>Suite</code>, <code>SuiteCompleted</code> to indicate a <code>Suite</code>'s * <code>run</code> method returned normally, * and <code>SuiteAborted</code> to indicate a <code>Suite</code>'s <code>run</code> * method completed abruptly with an exception. * Similarly, class <code>Suite</code> fires <code>SuiteStarting</code> to indicate it is about to invoke * <code>run</code> on a * nested <code>Suite</code>, <code>SuiteCompleted</code> to indicate a nested <code>Suite</code>'s * <code>run</code> method returned normally, * and <code>SuiteAborted</code> to indicate a nested <code>Suite</code>'s <code>run</code> * method completed abruptly with an exception. * Although the execution of a <code>Suite</code>'s <code>run</code> method will likely be a * common event reported via the * <code>SuiteStarting</code>, <code>SuiteAborted</code>, and <code>SuiteCompleted</code> events, because * of the abstract definition of "suite" used by the * event classes, these events are not limited to this use. Information about any conceptual suite * may be reported via the <code>SuiteStarting</code>, <code>SuiteAborted</code>, and * <code>SuiteCompleted</code> events. * * <h2>Extensibility</h2> * * <p> * You can create classes that extend <code>Reporter</code> to report test results in custom ways, and to * report custom information passed as an event "payload." * <code>Reporter</code> classes can handle events in any manner, including doing nothing. * </p> * * @author <NAME> */ trait Reporter { /** * Invoked to report an event that subclasses may wish to report in some way to the user. * * @param event the event being reported */ def apply(event: Event) } private[scalatest] object Reporter { private[scalatest] def indentStackTrace(stackTrace: String, level: Int): String = { val indentation = if (level > 0) " " * level else "" val withTabsZapped = stackTrace.replaceAll("\t", " ") val withInitialIndent = indentation + withTabsZapped withInitialIndent.replaceAll("\n", "\n" + indentation) // I wonder if I need to worry about alternate line endings. Probably. } // In the unlikely event that a message is blank, use the throwable's detail message private[scalatest] def messageOrThrowablesDetailMessage(message: String, throwable: Option[Throwable]): String = { val trimmedMessage = message.trim if (!trimmedMessage.isEmpty) trimmedMessage else throwable match { case Some(t) => t.getMessage.trim case None => "" } } } /* case RunStarting(ordinal, testCount, formatter, payload, threadName, timeStamp) => runStarting(testCount) case TestStarting(ordinal, suiteName, suiteClassName, testName, formatter, rerunnable, payload, threadName, timeStamp) => case TestSucceeded(ordinal, suiteName, suiteClassName, testName, duration, formatter, rerunnable, payload, threadName, timeStamp) => case TestFailed(ordinal, message, suiteName, suiteClassName, testName, throwable, duration, formatter, rerunnable, payload, threadName, timeStamp) => case TestIgnored(ordinal, suiteName, suiteClassName, testName, formatter, payload, threadName, timeStamp) => case TestPending(ordinal, suiteName, suiteClassName, testName, formatter, payload, threadName, timeStamp) => case SuiteStarting(ordinal, suiteName, suiteClassName, formatter, rerunnable, payload, threadName, timeStamp) => case SuiteCompleted(ordinal, suiteName, suiteClassName, duration, formatter, rerunnable, payload, threadName, timeStamp) => case SuiteAborted(ordinal, message, suiteName, suiteClassName, throwable, duration, formatter, rerunnable, payload, threadName, timeStamp) => case InfoProvided(ordinal, message, nameInfo, throwable, formatter, payload, threadName, timeStamp) => { case RunStopped(ordinal, duration, summary, formatter, payload, threadName, timeStamp) => runStopped() case RunAborted(ordinal, message, throwable, duration, summary, formatter, payload, threadName, timeStamp) => case RunCompleted(ordinal, duration, summary, formatter, payload, threadName, timeStamp) => runCompleted() */
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldEqualTypeCheckSpec.scala
<filename>scalatest-test/src/test/scala/org/scalatest/ShouldEqualTypeCheckSpec.scala<gh_stars>1-10 /* * 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 import scala.collection.GenSeq import scala.collection.GenMap import scala.collection.GenSet import scala.collection.GenIterable import scala.collection.GenTraversable import scala.collection.GenTraversableOnce import scala.collection.mutable import scala.collection.mutable.ListBuffer import org.scalactic.Equality import org.scalactic.CheckedEquality import Matchers._ class ShouldEqualTypeCheckSpec extends Spec with CheckedEquality { object `the should equal syntax should give a type error for suspicious types` { object `for values` { def `at the basic level` { """"hi" should equal ("hi")""" should compile """"hi" shouldEqual "hi"""" should compile """"hi" should not equal ("ho")""" should compile """"hi" shouldNot equal ("ho")""" should compile """1 should equal ("hi")""" shouldNot typeCheck """1 shouldEqual "hi"""" shouldNot typeCheck """1 should not equal ("ho")""" shouldNot typeCheck """1 shouldNot equal ("ho")""" shouldNot typeCheck """"hi" should equal (1)""" shouldNot typeCheck """"hi" shouldEqual 1""" shouldNot typeCheck """"hi" should not equal (1)""" shouldNot typeCheck """"hi" shouldNot equal (1)""" shouldNot typeCheck } def `when used solo in logical expressions` { "1 should (equal (1) and equal (2 - 1))" should compile "1 should (equal (1) or equal (2 - 1))" should compile "1 should (not equal (1) and equal (2 - 1))" should compile "1 should (not equal (1) or equal (2 - 1))" should compile "1 should (equal (1) and not equal (2 - 1))" should compile "1 should (equal (1) or not equal (2 - 1))" should compile "1 should (not equal (1) and not equal (2 - 1))" should compile "1 should (not equal (1) or not equal (2 - 1))" should compile """1 should (equal (1) and equal ("X"))""" shouldNot typeCheck """1 should (equal (1) or equal ("X"))""" shouldNot typeCheck """1 should (not equal (1) and equal ("X"))""" shouldNot typeCheck """1 should (not equal (1) or equal ("X"))""" shouldNot typeCheck """1 should (equal (1) and not equal ("X"))""" shouldNot typeCheck """1 should (equal (1) or not equal ("X"))""" shouldNot typeCheck """1 should (not equal (1) and not equal ("X"))""" shouldNot typeCheck """1 should (not equal (1) or not equal ("X"))""" shouldNot typeCheck """1 should (equal ("X") and equal (2 - 1))""" shouldNot typeCheck """1 should (equal ("X") or equal (2 - 1))""" shouldNot typeCheck """1 should (not equal ("X") and equal (2 - 1))""" shouldNot typeCheck """1 should (not equal ("X") or equal (2 - 1))""" shouldNot typeCheck """1 should (equal ("X") and not equal (2 - 1))""" shouldNot typeCheck """1 should (equal ("X") or not equal (2 - 1))""" shouldNot typeCheck """1 should (not equal ("X") and not equal (2 - 1))""" shouldNot typeCheck """1 should (not equal ("X") or not equal (2 - 1))""" shouldNot typeCheck """1 should (equal ("X") and equal ("Y"))""" shouldNot typeCheck """1 should (equal ("X") or equal ("Y"))""" shouldNot typeCheck """1 should (not equal ("X") and equal ("Y"))""" shouldNot typeCheck """1 should (not equal ("X") or equal ("Y"))""" shouldNot typeCheck """1 should (equal ("X") and not equal ("Y"))""" shouldNot typeCheck """1 should (equal ("X") or not equal ("Y"))""" shouldNot typeCheck """1 should (not equal ("X") and not equal ("Y"))""" shouldNot typeCheck """1 should (not equal ("X") or not equal ("Y"))""" shouldNot typeCheck } def `when used in larger logical expressions` { "List(1) should (have length (1) and equal (List(1, 2)))" should compile "List(1) should (have length (1) or equal (List(1, 2)))" should compile "List(1) should (not have length (1) and equal (List(1, 2)))" should compile "List(1) should (not have length (1) or equal (List(1, 2)))" should compile "List(1) should (have length (1) and not equal (List(1, 2)))" should compile "List(1) should (have length (1) or not equal (List(1, 2)))" should compile "List(1) should (not have length (1) and not equal (List(1, 2)))" should compile "List(1) should (not have length (1) or not equal (List(1, 2)))" should compile "List(1) should (equal (Vector(1)) and have length (1))" should compile "List(1) should (equal (Vector(1)) or have length (1))" should compile "List(1) should (not equal (Vector(1)) and have length (1))" should compile "List(1) should (not equal (Vector(1)) or have length (1))" should compile "List(1) should (equal (Vector(1)) and not have length (1))" should compile "List(1) should (equal (Vector(1)) or not have length (1))" should compile "List(1) should (not equal (Vector(1)) and not have length (1))" should compile "List(1) should (not equal (Vector(1)) or not have length (1))" should compile """List(1) should (have length (1) and equal ("X"))""" shouldNot typeCheck """List(1) should (have length (1) or equal ("X"))""" shouldNot typeCheck """List(1) should (not have length (1) and equal ("X"))""" shouldNot typeCheck """List(1) should (not have length (1) or equal ("X"))""" shouldNot typeCheck """List(1) should (have length (1) and not equal ("X"))""" shouldNot typeCheck """List(1) should (have length (1) or not equal ("X"))""" shouldNot typeCheck """List(1) should (not have length (1) and not equal ("X"))""" shouldNot typeCheck """List(1) should (not have length (1) or not equal ("X"))""" shouldNot typeCheck """List(1) should (equal ("X") and have length (1))""" shouldNot typeCheck """List(1) should (equal ("X") or have length (1))""" shouldNot typeCheck """List(1) should (not equal ("X") and have length (1))""" shouldNot typeCheck """List(1) should (not equal ("X") or have length (1))""" shouldNot typeCheck """List(1) should (equal ("X") and not have length (1))""" shouldNot typeCheck """List(1) should (equal ("X") or not have length (1))""" shouldNot typeCheck """List(1) should (not equal ("X") and not have length (1))""" shouldNot typeCheck """List(1) should (not equal ("X") or not have length (1))""" shouldNot typeCheck } def `when used in even larger multi-part logical expressions` { "1 should (equal (1) and equal (1) and equal (1) and equal (1))" should compile "1 should (equal (1) and equal (1) or equal (1) and equal (1) or equal (1))" should compile """1 should ( equal (1) and equal (1) or equal (1) and equal (1) or equal (1) )""" should compile "1 should (equal (1) and equal (1) and be >= (1) and equal (1))" should compile "1 should (equal (1) and equal (1) or be >= (1) and equal (1) or equal (1))" should compile """1 should ( equal (1) and equal (1) or be >= (1) and equal (1) or equal (1) )""" should compile "1 should (equal (1) and be >= (1) and equal (1) and be >= (1))" should compile "1 should (equal (1) and be >= (1) or equal (1) and be >= (1) or equal (1))" should compile """1 should ( equal (1) and be >= (1) or equal (1) and be >= (1) or equal (1) )""" should compile """1 should (equal (1) and equal ("hi") and equal (1) and equal (1))""" shouldNot typeCheck """1 should (equal (1) and equal (1) or equal (1) and equal ("hi") or equal (1))""" shouldNot typeCheck """1 should ( equal (1) and equal (1) or equal (1) and equal (1) or equal ("hi") )""" shouldNot typeCheck """1 should (equal ("hi") and equal (1) and be >= (1) and equal (1))""" shouldNot typeCheck """1 should (equal (1) and equal (1) or be >= (1) and equal ("hi") or equal (1))""" shouldNot typeCheck """1 should ( equal (1) and equal ("hi") or be >= (1) and equal (1) or equal (1) )""" shouldNot typeCheck """1 should (equal ("hi") and be >= (1) and equal (new java.util.Date) and be >= (1))""" shouldNot typeCheck """1 should (equal (1) and be >= (1) or equal (1) and be >= (1) or equal ("hi"))""" shouldNot typeCheck """1 should ( equal (1) and be >= (1) or equal (new java.util.Date) and be >= (1) or equal (1) )""" shouldNot typeCheck } def `when a wrongly typed explcit equality is provided` { import org.scalactic.Explicitly._ import org.scalactic.StringNormalizations._ implicit val strEq = after being lowerCased """"hi" should equal ("Hi")""" should compile """"hi" shouldNot equal ("Hi") (decided by defaultEquality[String])""" should compile """"hi" shouldNot equal ("Hi") (defaultEquality[String])""" should compile """1 shouldNot equal ("Hi") (defaultEquality[Int])""" shouldNot typeCheck """1 should equal ("Hi") (defaultEquality[Int])""" shouldNot typeCheck } } object `for collections` { def `at the basic level` { """all (List("hi")) should equal ("hi")""" should compile """all (List("hi")) shouldEqual "hi"""" should compile """all (List("hi")) should not equal ("ho")""" should compile """all (List("hi")) shouldNot equal ("ho")""" should compile """all (List(1)) should equal ("hi")""" shouldNot typeCheck """all (List(1)) shouldEqual "hi"""" shouldNot typeCheck """all (List(1)) should not equal ("ho")""" shouldNot typeCheck """all (List(1)) shouldNot equal ("ho")""" shouldNot typeCheck """all (List("hi")) should equal (1)""" shouldNot typeCheck """all (List("hi")) shouldEqual 1""" shouldNot typeCheck """all (List("hi")) should not equal (1)""" shouldNot typeCheck """all (List("hi")) shouldNot equal (1)""" shouldNot typeCheck } def `when used solo in logical expressions` { "all (List(1)) should (equal (1) and equal (2 - 1))" should compile "all (List(1)) should (equal (1) or equal (2 - 1))" should compile "all (List(1)) should (not equal (1) and equal (2 - 1))" should compile "all (List(1)) should (not equal (1) or equal (2 - 1))" should compile "all (List(1)) should (equal (1) and not equal (2 - 1))" should compile "all (List(1)) should (equal (1) or not equal (2 - 1))" should compile "all (List(1)) should (not equal (1) and not equal (2 - 1))" should compile "all (List(1)) should (not equal (1) or not equal (2 - 1))" should compile """all (List(1)) should (equal (1) and equal ("X"))""" shouldNot typeCheck """all (List(1)) should (equal (1) or equal ("X"))""" shouldNot typeCheck """all (List(1)) should (not equal (1) and equal ("X"))""" shouldNot typeCheck """all (List(1)) should (not equal (1) or equal ("X"))""" shouldNot typeCheck """all (List(1)) should (equal (1) and not equal ("X"))""" shouldNot typeCheck """all (List(1)) should (equal (1) or not equal ("X"))""" shouldNot typeCheck """all (List(1)) should (not equal (1) and not equal ("X"))""" shouldNot typeCheck """all (List(1)) should (not equal (1) or not equal ("X"))""" shouldNot typeCheck """all (List(1)) should (equal ("X") and equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (equal ("X") or equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") and equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") or equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (equal ("X") and not equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (equal ("X") or not equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") and not equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") or not equal (2 - 1))""" shouldNot typeCheck """all (List(1)) should (equal ("X") and equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (equal ("X") or equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") and equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") or equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (equal ("X") and not equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (equal ("X") or not equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") and not equal ("Y"))""" shouldNot typeCheck """all (List(1)) should (not equal ("X") or not equal ("Y"))""" shouldNot typeCheck } def `when used in larger logical expressions` { "all (List(List(1))) should (have length (1) and equal (List(1, 2)))" should compile "all (List(List(1)) )should (have length (1) or equal (List(1, 2)))" should compile "all (List(List(1))) should (not have length (1) and equal (List(1, 2)))" should compile "all (List(List(1))) should (not have length (1) or equal (List(1, 2)))" should compile "all (List(List(1))) should (have length (1) and not equal (List(1, 2)))" should compile "all (List(List(1))) should (have length (1) or not equal (List(1, 2)))" should compile "all (List(List(1))) should (not have length (1) and not equal (List(1, 2)))" should compile "all (List(List(1))) should (not have length (1) or not equal (List(1, 2)))" should compile "all (List(List(1))) should (equal (Vector(1)) and have length (1))" should compile "all (List(List(1))) should (equal (Vector(1)) or have length (1))" should compile "all (List(List(1))) should (not equal (Vector(1)) and have length (1))" should compile "all (List(List(1))) should (not equal (Vector(1)) or have length (1))" should compile "all (List(List(1))) should (equal (Vector(1)) and not have length (1))" should compile "all (List(List(1))) should (equal (Vector(1)) or not have length (1))" should compile "all (List(List(1))) should (not equal (Vector(1)) and not have length (1))" should compile "all (List(List(1))) should (not equal (Vector(1)) or not have length (1))" should compile """all (List(List(1))) should (have length (1) and equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (have length (1) or equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (not have length (1) and equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (not have length (1) or equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (have length (1) and not equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (have length (1) or not equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (not have length (1) and not equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (not have length (1) or not equal ("X"))""" shouldNot typeCheck """all (List(List(1))) should (equal ("X") and have length (1))""" shouldNot typeCheck """all (List(List(1))) should (equal ("X") or have length (1))""" shouldNot typeCheck """all (List(List(1))) should (not equal ("X") and have length (1))""" shouldNot typeCheck """all (List(List(1))) should (not equal ("X") or have length (1))""" shouldNot typeCheck """all (List(List(1))) should (equal ("X") and not have length (1))""" shouldNot typeCheck """all (List(List(1))) should (equal ("X") or not have length (1))""" shouldNot typeCheck """all (List(List(1))) should (not equal ("X") and not have length (1))""" shouldNot typeCheck """all (List(List(1))) should (not equal ("X") or not have length (1))""" shouldNot typeCheck } def `when used in even larger multi-part logical expressions` { "1 should (equal (1) and equal (1) and equal (1) and equal (1))" should compile "1 should (equal (1) and equal (1) or equal (1) and equal (1) or equal (1))" should compile """1 should ( equal (1) and equal (1) or equal (1) and equal (1) or equal (1) )""" should compile "all (List(1)) should (equal (1) and equal (1) and be >= (1) and equal (1))" should compile "all (List(1)) should (equal (1) and equal (1) or be >= (1) and equal (1) or equal (1))" should compile """all (List(1)) should ( equal (1) and equal (1) or be >= (1) and equal (1) or equal (1) )""" should compile "all (List(1)) should (equal (1) and be >= (1) and equal (1) and be >= (1))" should compile "all (List(1)) should (equal (1) and be >= (1) or equal (1) and be >= (1) or equal (1))" should compile """all (List(1)) should ( equal (1) and be >= (1) or equal (1) and be >= (1) or equal (1) )""" should compile """all (List(1)) should (equal (1) and equal ("hi") and equal (1) and equal (1))""" shouldNot typeCheck """all (List(1)) should (equal (1) and equal (1) or equal (1) and equal ("hi") or equal (1))""" shouldNot typeCheck """all (List(1)) should ( equal (1) and equal (1) or equal (1) and equal (1) or equal ("hi") )""" shouldNot typeCheck """all (List(1)) should (equal ("hi") and equal (1) and be >= (1) and equal (1))""" shouldNot typeCheck """all (List(1)) should (equal (1) and equal (1) or be >= (1) and equal ("hi") or equal (1))""" shouldNot typeCheck """all (List(1)) should ( equal (1) and equal ("hi") or be >= (1) and equal (1) or equal (1) )""" shouldNot typeCheck """all (List(1)) should (equal ("hi") and be >= (1) and equal (new java.util.Date) and be >= (1))""" shouldNot typeCheck """all (List(1)) should (equal (1) and be >= (1) or equal (1) and be >= (1) or equal ("hi"))""" shouldNot typeCheck """all (List(1)) should ( equal (1) and be >= (1) or equal (new java.util.Date) and be >= (1) or equal (1) )""" shouldNot typeCheck } } } }
cquiroz/scalatest
scalatest/src/main/scala/org/scalatest/prop/NonGeneratedTableDrivenPropertyChecks.scala
/* * Copyright 2001-2014 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 package prop import org.scalatest.FailureMessages._ import org.scalatest.exceptions.{TableDrivenPropertyCheckFailedException, StackDepth} import org.scalatest.exceptions.StackDepthExceptionHelper.getStackDepthFun import scala.annotation.tailrec import scala.collection.GenTraversable /** * Trait containing methods that facilitate property checks against tables of data. * * <p> * This trait contains one <code>forAll</code> method for each <code>TableForN</code> class, <code>TableFor1</code> * through <code>TableFor22</code>, which allow properties to be checked against the rows of a table. It also * contains a <code>wherever</code> method that can be used to indicate a property need only hold whenever some * condition is true. * </p> * * <p> * For an example of trait <code>TableDrivenPropertyChecks</code> in action, imagine you want to test this <code>Fraction</code> class: * </p> * * <pre class="stHighlight"> * class Fraction(n: Int, d: Int) { * * require(d != 0) * require(d != Integer.MIN_VALUE) * require(n != Integer.MIN_VALUE) * * val numer = if (d < 0) -1 * n else n * val denom = d.abs * * override def toString = numer + " / " + denom * } * </pre> * * <p> * <code>TableDrivenPropertyChecks</code> allows you to create tables with * between 1 and 22 columns and any number of rows. You create a table by passing * tuples to one of the factory methods of object <code>Table</code>. Each tuple must have the * same arity (number of members). The first tuple you pass must all be strings, because * it define names for the columns. Subsequent tuples define the data. After the initial tuple * that contains string column names, all tuples must have the same type. For example, * if the first tuple after the column names contains two <code>Int</code>s, all subsequent * tuples must contain two <code>Int</code> (<em>i.e.</em>, have type * <code>Tuple2[Int, Int]</code>). * </p> * * <p> * To test the behavior of <code>Fraction</code>, you could create a table * of numerators and denominators to pass to the constructor of the * <code>Fraction</code> class using one of the <code>apply</code> factory methods declared * in <code>Table</code>, like this: * </p> * * <pre class="stHighlight"> * import org.scalatest.prop.TableDrivenPropertyChecks._ * * val fractions = * Table( * ("n", "d"), // First tuple defines column names * ( 1, 2), // Subsequent tuples define the data * ( -1, 2), * ( 1, -2), * ( -1, -2), * ( 3, 1), * ( -3, 1), * ( -3, 0), * ( 3, -1), * ( 3, Integer.MIN_VALUE), * (Integer.MIN_VALUE, 3), * ( -3, -1) * ) * </pre> * * <p> * You could then check a property against each row of the table using a <code>forAll</code> method, like this: * </p> * * <pre class="stHighlight"> * import org.scalatest.Matchers._ * * forAll (fractions) { (n: Int, d: Int) => * * whenever (d != 0 && d != Integer.MIN_VALUE * && n != Integer.MIN_VALUE) { * * val f = new Fraction(n, d) * * if (n < 0 && d < 0 || n > 0 && d > 0) * f.numer should be > 0 * else if (n != 0) * f.numer should be < 0 * else * f.numer should be === 0 * * f.denom should be > 0 * } * } * </pre> * * <p> * Trait <code>TableDrivenPropertyChecks</code> provides 22 overloaded <code>forAll</code> methods * that allow you to check properties using the data provided by a table. Each <code>forAll</code> * method takes two parameter lists. The first parameter list is a table. The second parameter list * is a function whose argument types and number matches that of the tuples in the table. For * example, if the tuples in the table supplied to <code>forAll</code> each contain an * <code>Int</code>, a <code>String</code>, and a <code>List[Char]</code>, then the function supplied * to <code>forAll</code> must take 3 parameters, an <code>Int</code>, a <code>String</code>, * and a <code>List[Char]</code>. The <code>forAll</code> method will pass each row of data to * the function, and generate a <code>TableDrivenPropertyCheckFailedException</code> if the function * completes abruptly for any row of data with any exception that would <a href="../Suite.html#errorHandling">normally cause</a> a test to * fail in ScalaTest other than <code>DiscardedEvaluationException</code>. An * <code>DiscardedEvaluationException</code>, * which is thrown by the <code>whenever</code> method (also defined in this trait) to indicate * a condition required by the property function is not met by a row * of passed data, will simply cause <code>forAll</code> to skip that row of data. * <p> * * <a name="testingStatefulFunctions"></a><h2>Testing stateful functions</h2> * * <p> * One way to use a table with one column is to test subsequent return values * of a stateful function. Imagine, for example, you had an object named <code>FiboGen</code> * whose <code>next</code> method returned the <em>next</em> fibonacci number, where next * means the next number in the series following the number previously returned by <code>next</code>. * So the first time <code>next</code> was called, it would return 0. The next time it was called * it would return 1. Then 1. Then 2. Then 3, and so on. <code>FiboGen</code> would need to * maintain state, because it has to remember where it is in the series. In such a situation, * you could create a <code>TableFor1</code> (a table with one column, which you could alternatively * think of as one row), in which each row represents * the next value you expect. * </p> * * <pre class="stHighlight"> * val first14FiboNums = * Table("n", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233) * </pre> * * <p> * Then in your <code>forAll</code> simply call the function and compare it with the * expected return value, like this: * </p> * * <pre class="stHighlight"> * forAll (first14FiboNums) { n => * FiboGen.next should equal (n) * } * </pre> * * <a name="testingMutables"></a><h2>Testing mutable objects</h2> * * <p> * If you need to test a mutable object, one way you can use tables is to specify * state transitions in a table. For example, imagine you wanted to test this mutable * <code>Counter</code> class: * * <pre class="stHighlight"> class Counter { private var c = 0 def reset() { c = 0 } def click() { c += 1 } def enter(n: Int) { c = n } def count = c } * </pre> * * <p> * A <code>Counter</code> keeps track of how many times its <code>click</code> method * is called. The count starts out at zero and increments with each <code>click</code> * invocation. You can also set the count to a specific value by calling <code>enter</code> * and passing the value in. And the <code>reset</code> method returns the count back to * zero. You could define the actions that initiate state transitions with case classes, like this: * </p> * * <pre class="stHighlight"> abstract class Action case object Start extends Action case object Click extends Action case class Enter(n: Int) extends Action * </pre> * * <p> * Given these actions, you could define a state-transition table like this: * </p> * * <pre class="stHighlight"> val stateTransitions = Table( ("action", "expectedCount"), (Start, 0), (Click, 1), (Click, 2), (Click, 3), (Enter(5), 5), (Click, 6), (Enter(1), 1), (Click, 2), (Click, 3) ) * </pre> * * <p> * To use this in a test, simply do a pattern match inside the function you pass * to <code>forAll</code>. Make a pattern for each action, and have the body perform that * action when there's a match. Then check that the actual value equals the expected value: * </p> * * <pre class="stHighlight"> val counter = new Counter forAll (stateTransitions) { (action, expectedCount) => action match { case Start => counter.reset() case Click => counter.click() case Enter(n) => counter.enter(n) } counter.count should equal (expectedCount) } * </pre> * * <a name="invalidArgCombos"></a><h2>Testing invalid argument combinations</h2> * * <p> * A table-driven property check can also be helpful to ensure that the proper exception is thrown when invalid data is * passed to a method or constructor. For example, the <code>Fraction</code> constructor shown above should throw <code>IllegalArgumentException</code> * if <code>Integer.MIN_VALUE</code> is passed for either the numerator or denominator, or zero is passed for the denominator. This yields the * following five combinations of invalid data: * </p> * * <table style="border-collapse: collapse; border: 1px solid black"> * <tr><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><code>n</code></th><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><code>d</code></th></tr> * <tr><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"><code>Integer.MIN_VALUE</code></td><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"><code>Integer.MIN_VALUE</code></td></tr> * <tr><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">a valid value</td><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"><code>Integer.MIN_VALUE</code></td></tr> * <tr><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"><code>Integer.MIN_VALUE</code></td><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">a valid value</td></tr> * <tr><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center"><code>Integer.MIN_VALUE</code></td><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">zero</td></tr> * <tr><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">a valid value</td><td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">zero</td></tr> * </table> * * <p> * You can express these combinations in a table: * </p> * * <pre class="stHighlight"> * val invalidCombos = * Table( * ("n", "d"), * (Integer.MIN_VALUE, Integer.MIN_VALUE), * (1, Integer.MIN_VALUE), * (Integer.MIN_VALUE, 1), * (Integer.MIN_VALUE, 0), * (1, 0) * ) * </pre> * * <p> * Given this table, you could check that all invalid combinations produce <code>IllegalArgumentException</code>, like this: * </p> * * <pre class="stHighlight"> * forAll (invalidCombos) { (n: Int, d: Int) => * evaluating { * new Fraction(n, d) * } should produce [IllegalArgumentException] * } * </pre> * * </p> * @author <NAME> */ private[prop] trait NonGeneratedTableDrivenPropertyChecks extends Whenever with Tables { /* * Evaluates the passed code block if the passed boolean condition is true, else throws <code>DiscardedEvaluationException</code>. * * <p> * The <code>whenever</code> method can be used inside property check functions to skip invocations of the function with * data for which it is known the property would fail. For example, given the following <code>Fraction</code> class: * </p> * * <pre class="stHighlight"> * class Fraction(n: Int, d: Int) { * * require(d != 0) * require(d != Integer.MIN_VALUE) * require(n != Integer.MIN_VALUE) * * val numer = if (d < 0) -1 * n else n * val denom = d.abs * * override def toString = numer + " / " + denom * } * </pre> * * <p> * You could create a table of numerators and denominators to pass to the constructor of the * <code>Fraction</code> class like this: * </p> * * <pre class="stHighlight"> * import org.scalatest.prop.TableDrivenPropertyChecks._ * * val fractions = * Table( * ("n", "d"), * ( 1, 2), * ( -1, 2), * ( 1, -2), * ( -1, -2), * ( 3, 1), * ( -3, 1), * ( -3, 0), * ( 3, -1), * ( 3, Integer.MIN_VALUE), * (Integer.MIN_VALUE, 3), * ( -3, -1) * ) * </pre> * * <p> * Imagine you wanted to check a property against this class with data that includes some * value that are rejected by the constructor, such as a denominator of zero, which should * result in an <code>IllegalArgumentException</code>. You could use <code>whenever</code> * to skip any rows in the <code>fraction</code> that represent illegal arguments, like this: * </p> * * <pre class="stHighlight"> * import org.scalatest.Matchers._ * * forAll (fractions) { (n: Int, d: Int) => * * whenever (d != 0 && d != Integer.MIN_VALUE * && n != Integer.MIN_VALUE) { * * val f = new Fraction(n, d) * * if (n < 0 && d < 0 || n > 0 && d > 0) * f.numer should be > 0 * else if (n != 0) * f.numer should be < 0 * else * f.numer should be === 0 * * f.denom should be > 0 * } * } * </pre> * * <p> * In this example, rows 6, 8, and 9 have values that would cause a false to be passed * to <code>whenever</code>. (For example, in row 6, <code>d</code> is 0, which means <code>d</code> <code>!=</code> <code>0</code> * will be false.) For those rows, <code>whenever</code> will throw <code>DiscardedEvaluationException</code>, * which will cause the <code>forAll</code> method to skip that row. * </p> * * @param condition the boolean condition that determines whether <code>whenever</code> will evaluate the * <code>fun</code> function (<code>condition<code> is true) or throws <code>DiscardedEvaluationException</code> (<code>condition<code> is false) * @param fun the function to evaluate if the specified <code>condition</code> is true */ /* def whenever(condition: Boolean)(fun: => Unit) { if (!condition) throw new DiscardedEvaluationException fun } */ /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor1</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A](table: TableFor1[A])(fun: (A) => Unit) { table(fun) } case class ForResult[T](passedCount: Int = 0, discardedCount: Int = 0, messageAcc: IndexedSeq[String] = IndexedSeq.empty, passedElements: IndexedSeq[(Int, T)] = IndexedSeq.empty, failedElements: IndexedSeq[(Int, T, Throwable)] = IndexedSeq.empty) def runAndCollectResult[T <: Product](namesOfArgs: List[String], rows: Seq[T], sourceFileName: String, methodName: String, stackDepthAdjustment: Int)(fun: T => Unit) = { import InspectorsHelper.{shouldPropagate, indentErrorMessages} @tailrec def innerRunAndCollectResult[T <: Product](itr: Iterator[T], result: ForResult[T], index: Int)(fun: T => Unit): ForResult[T] = { if (itr.hasNext) { val head = itr.next val newResult = try { fun(head) result.copy(passedCount = result.passedCount + 1, passedElements = result.passedElements :+ (index, head)) } catch { case _: exceptions.DiscardedEvaluationException => result.copy(discardedCount = result.discardedCount + 1) // discard this evaluation and move on to the next case ex if !shouldPropagate(ex) => result.copy(failedElements = result.failedElements :+ (index, head, new exceptions.TableDrivenPropertyCheckFailedException( (sde => FailureMessages.propertyException(UnquotedString(ex.getClass.getSimpleName)) + (sde.failedCodeFileNameAndLineNumberString match { case Some(s) => " (" + s + ")"; case scala.None => "" }) + "\n" + " " + FailureMessages.thrownExceptionsMessage(if (ex.getMessage == null) "None" else UnquotedString(ex.getMessage)) + "\n" + ( ex match { case sd: StackDepth if sd.failedCodeFileNameAndLineNumberString.isDefined => " " + FailureMessages.thrownExceptionsLocation(UnquotedString(sd.failedCodeFileNameAndLineNumberString.get)) + "\n" case _ => "" } ) + " " + FailureMessages.occurredAtRow(index) + "\n" + indentErrorMessages(namesOfArgs.zip(head.productIterator.toSeq).map { case (name, value) => name + " = " + value }.toIndexedSeq).mkString("\n") + " )"), Some(ex), getStackDepthFun(sourceFileName, methodName, stackDepthAdjustment), scala.None, FailureMessages.undecoratedPropertyCheckFailureMessage, head.productIterator.toList, namesOfArgs, index ) ) ) } innerRunAndCollectResult(itr, newResult, index + 1)(fun) } else result } innerRunAndCollectResult(rows.toIterator, ForResult(), 0)(fun) } private[scalatest] def doForEvery[T <: Product](namesOfArgs: List[String], rows: Seq[T], messageFun: Any => String, sourceFileName: String, methodName: String, stackDepthAdjustment: Int)(fun: T => Unit): Unit = { import InspectorsHelper.indentErrorMessages val result = runAndCollectResult(namesOfArgs, rows, sourceFileName, methodName, stackDepthAdjustment + 2)(fun) val messageList = result.failedElements.map(_._3) if (messageList.size > 0) throw new exceptions.TestFailedException( sde => Some(messageFun(UnquotedString(indentErrorMessages(messageList.map(_.toString)).mkString(", \n")))), messageList.headOption, getStackDepthFun(sourceFileName, methodName, stackDepthAdjustment) ) } private[scalatest] def doExists[T <: Product](namesOfArgs: List[String], rows: Seq[T], messageFun: Any => String, sourceFileName: String, methodName: String, stackDepthAdjustment: Int)(fun: T => Unit): Unit = { import InspectorsHelper.indentErrorMessages val result = runAndCollectResult(namesOfArgs, rows, sourceFileName, methodName, stackDepthAdjustment + 2)(fun) if (result.passedCount == 0) { val messageList = result.failedElements.map(_._3) throw new exceptions.TestFailedException( sde => Some(messageFun(UnquotedString(indentErrorMessages(messageList.map(_.toString)).mkString(", \n")))), messageList.headOption, getStackDepthFun(sourceFileName, methodName, stackDepthAdjustment) ) } } def exists[A](table: TableFor1[A])(fun: (A) => Unit): Unit = { doExists[Tuple1[A]](List(table.heading), table.map(Tuple1.apply), Resources.tableDrivenExistsFailed _, "NonGeneratedTableDrivenPropertyChecks.scala", "exists", 3){a => fun(a._1)} } def exists[A, B](table: TableFor2[A, B])(fun: (A, B) => Unit): Unit = { doExists[(A, B)](table.heading.productIterator.to[List].map(_.toString), table, Resources.tableDrivenExistsFailed _, "NonGeneratedTableDrivenPropertyChecks.scala", "exists", 3)(fun.tupled) } def forEvery[A](table: TableFor1[A])(fun: (A) => Unit): Unit = { doForEvery[Tuple1[A]](List(table.heading), table.map(Tuple1.apply), Resources.tableDrivenForEveryFailed _, "NonGeneratedTableDrivenPropertyChecks.scala", "forEvery", 3){a => fun(a._1)} } def forEvery[A, B](table: TableFor2[A, B])(fun: (A, B) => Unit): Unit = { doForEvery[(A, B)](table.heading.productIterator.to[List].map(_.toString), table, Resources.tableDrivenForEveryFailed _, "NonGeneratedTableDrivenPropertyChecks.scala", "forEvery", 3)(fun.tupled) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor2</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B](table: TableFor2[A, B])(fun: (A, B) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor3</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C](table: TableFor3[A, B, C])(fun: (A, B, C) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor4</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D](table: TableFor4[A, B, C, D])(fun: (A, B, C, D) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor5</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E](table: TableFor5[A, B, C, D, E])(fun: (A, B, C, D, E) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor6</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F](table: TableFor6[A, B, C, D, E, F])(fun: (A, B, C, D, E, F) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor7</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G](table: TableFor7[A, B, C, D, E, F, G])(fun: (A, B, C, D, E, F, G) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor8</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H](table: TableFor8[A, B, C, D, E, F, G, H])(fun: (A, B, C, D, E, F, G, H) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor9</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I](table: TableFor9[A, B, C, D, E, F, G, H, I])(fun: (A, B, C, D, E, F, G, H, I) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor10</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J](table: TableFor10[A, B, C, D, E, F, G, H, I, J])(fun: (A, B, C, D, E, F, G, H, I, J) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor11</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K](table: TableFor11[A, B, C, D, E, F, G, H, I, J, K])(fun: (A, B, C, D, E, F, G, H, I, J, K) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor12</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L](table: TableFor12[A, B, C, D, E, F, G, H, I, J, K, L])(fun: (A, B, C, D, E, F, G, H, I, J, K, L) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor13</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M](table: TableFor13[A, B, C, D, E, F, G, H, I, J, K, L, M])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor14</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N](table: TableFor14[A, B, C, D, E, F, G, H, I, J, K, L, M, N])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor15</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O](table: TableFor15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor16</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P](table: TableFor16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor17</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q](table: TableFor17[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor18</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R](table: TableFor18[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor19</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S](table: TableFor19[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor20</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T](table: TableFor20[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor21</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U](table: TableFor21[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U) => Unit) { table(fun) } /** * Performs a property check by applying the specified property check function to each row * of the specified <code>TableFor22</code>. * * @param table the table of data with which to perform the property check * @param fun the property check function to apply to each row of data in the table */ def forAll[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V](table: TableFor22[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V])(fun: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V) => Unit) { table(fun) } } /* * Companion object that facilitates the importing of <code>TableDrivenPropertyChecks</code> members as * an alternative to mixing it in. One use case is to import <code>TableDrivenPropertyChecks</code> members so you can use * them in the Scala interpreter: * * <pre> * Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22). * Type in expressions to have them evaluated. * Type :help for more information. * * scala> import org.scalatest.prop.TableDrivenPropertyChecks._ * import org.scalatest.prop.TableDrivenPropertyChecks._ * * scala> val examples = * | Table( * | ("a", "b"), * | ( 1, 2), * | ( 3, 4) * | ) * examples: org.scalatest.prop.TableFor2[Int,Int] = TableFor2((1,2), (3,4)) * * scala> import org.scalatest.Matchers._ * import org.scalatest.Matchers._ * * scala> forAll (examples) { (a, b) => a should be < b } * * scala> forAll (examples) { (a, b) => a should be > b } * org.scalatest.prop.TableDrivenPropertyCheckFailedException: TestFailedException (included as this exception's cause) was thrown during property evaluation. * Message: 1 was not greater than 2 * Location: <console>:13 * Occurred at table row 0 (zero based, not counting headings), which had values ( * a = 1, * b = 2 * ) * at org.scalatest.prop.TableFor2$$anonfun$apply$4.apply(Table.scala:355) * at org.scalatest.prop.TableFor2$$anonfun$apply$4.apply(Table.scala:346) * at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:57) * at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:43) * at org.scalatest.prop.TableFor2.apply(Table.scala:346) * at org.scalatest.prop.TableDrivenPropertyChecks$class.forAll(TableDrivenPropertyChecks.scala:133) * ... * </pre> * * @author <NAME> */ private[prop] object NonGeneratedTableDrivenPropertyChecks extends NonGeneratedTableDrivenPropertyChecks
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/PartialFunctionValuesSpec.scala
/* * 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 import org.scalatest.OptionValues._ import org.scalatest.PartialFunctionValues._ import org.scalatest.SharedHelpers.thisLineNumber import Matchers._ import exceptions.TestFailedException class PartialFunctionValuesSpec extends FunSpec { val pf = new PartialFunction[Int, Int]() { def isDefinedAt(x: Int): Boolean = x % 2 == 0 def apply(x: Int): Int = x * x } describe("values on PartialFunction") { it("should return correct value when is defined") { pf.isDefinedAt(8) should === (true) pf.valueAt(8) should === (64) } it("should throw TestFailedException when is not defined") { val caught = the [TestFailedException] thrownBy { pf.valueAt(5) should === (25) } caught.failedCodeLineNumber.value should equal (thisLineNumber - 2) caught.failedCodeFileName.value should be ("PartialFunctionValuesSpec.scala") caught.message.value should be (Resources.partialFunctionValueNotDefined("5")) } } }
cquiroz/scalatest
scalatest-test/src/test/scala/org/scalatest/matchers/HavePropertyMatcherSpec.scala
/* * 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.matchers import org.scalatest._ import Matchers._ import java.io.File class HavePropertyMatcherSpec extends Spec { object `HavePropertyMatcher ` { object `instance created by HavePropertyMatcher apply method` { val havePropertyMatcher = HavePropertyMatcher[File, String] { file => HavePropertyMatchResult(true, "name", "test", "test") } def `should have pretty toString` { havePropertyMatcher.toString should be ("HavePropertyMatcher[java.io.File, java.lang.String](java.io.File => HavePropertyMatchResult[java.lang.String])") } } } }